Python unit test fails despite meeting requirement

78 views Asked by At

I am doing an online python course that requires I complete some exercise to progress. The orginisers of this course says they have visible and hidden requirements a user must meet pass each test. In this case, the probelem statement is as follows:

Write a function called manipulate_data which will act as follows: When given a list of integers, return a list, where the first element is the count of positives numbers and the second element is the sum of negative numbers. NB: Treat 0 as positive.

I came up with this, which I believe passes the visible requirement except maybe line 6 of the unit test case

def manipulate_data(listinput):
    report = [0,0]
    if type(listinput) != list:
    #I may need some work here.. see unit test line 6
        assert "invalid argument" 
    for digit in listinput:
    #is an even number so we increment it by 1
        if digit >= 0 and type(digit) == int: 
            report[0] += 1
    #number is less than zero, adds it sum
        elif digit < 0 and type(digit) == int:
            report[1] += digit
    return report

EveryTime I run the code, I always get this Error message Indicating that my code passes 2 test out of three, which I assume is test_only_list_allowed(self) I am not really experienced with this kind of things and I need help. enter image description here

Unit Test

1

There are 1 answers

3
Martijn Pieters On BEST ANSWER

The test shows that the code expected a string to be returned. assert raises an AssertionError exception instead. You want to return the same string as the assertEquals() test is looking for, so 'Only lists allowed', not the msg argument (which is shown when the test fails).

Instead of using assert use return, and return the expected string:

if type(listinput) != list:
    return "Only lists allowed" 

Note that normally you'd use isinstance() to test for types:

if not isinstance(listinput, list):
    return "Only lists allowed" 
for digit in listinput:
    if not isinstance(digit, int):
        continue
    if digit >= 0: 
        report[0] += 1
    elif digit < 0:
        report[1] += digit

I used a single test for integers instead of testing in each branch. You could even have a type that doesn't support comparison with 0 so you want to get that test out of the way first.