Rūdolfs Bērziņš
Rūdolfs Bērziņš

Reputation: 13

Should you test primitive functions in Python?

I am currently rewriting a large data framework for my company. My company has a basically nonexistent testing policy and I want to change that, but I am very new to testing software. Thus I wanted to ask the following question -

If I have the following function:

def read_attributes(annotation_file=IMPORTED_PATH):
    attributes = {}
    with open(annotation_file) as ga:
        for idx, line in enumerate(ga):
            fields = [field.strip() for field in line.split('\t')]
            if idx == 0:
                continue
            else:
                attributes[fields[0]] = fields[6] #0 - sample, 6 - tissue

    return attributes

I don't see the point in actually unit-testing it, if I have a previous test that checks if file at IMPORTED_PATH actually exists.

I have tried to test whether certain keys are present in the resulting attributes dictionary, but I see that as volatile because file at IMPORTED_PATH can change it's values. I could also write an if statement checking whether fields variable has the necessary amount of entries, but that is more of an internal check than a test.

Should I test this and how would I go about it?

Upvotes: 0

Views: 74

Answers (1)

Saar Buchnik
Saar Buchnik

Reputation: 126

I think you are mixing 2 different tests.

  1. A file in IMPORTED_PATH exists (You already have a unit-test for this one).

  2. read_attributes works as expected.

To check that read_attributes works as expected, I would create an annotation_file in a known location (maybe some test_resources folder).

This file should not be changed.

Since you know the contents of the file, the test should run something similar to the following:

def test_read_attributes():
    KNOWN_ANNOTATION_FILE = "path\to\constant\annotation\file"
    expected_attributes = <expected_values> # can also be read from a file

    attributes = read_attributes(annotation_file=KNOWN_ANNOTATION_FILE)

    assert attributes == expected_attributes 

I hope I understand your concerns correctly and it answers your question :-)

PS

If you are new to testing in python, I recommend pytest (it has a native plugin in PyCharm)

Upvotes: 1

Related Questions