简体   繁体   English

尽管满足要求,Python单元测试仍失败

[英]Python unit test fails despite meeting requirement

I am doing an online python course that requires I complete some exercise to progress. 我正在做一个在线python课程,要求我完成一些练习才能进步。 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: 在这种情况下,probelem语句如下:

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. 编写一个称为handler_data的函数,该函数的作用如下:给定整数列表时,返回一个列表,其中第一个元素是正数的计数,第二个元素是负数的总和。 NB: Treat 0 as positive. 注意:将0视为正数。

I came up with this, which I believe passes the visible requirement except maybe line 6 of the unit test case 我想出了这一点,我相信它可以通过可见的要求,除了单元测试用例的第6行

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. 每次运行代码时,我总是收到此错误消息,表明我的代码通过了3个测试中的2个,我认为这是test_only_list_allowed(self)我对这种事情不是很有经验,我需要帮助。 在此处输入图片说明

单元测试

The test shows that the code expected a string to be returned . 测试表明该代码期望返回一个字符串。 assert raises an AssertionError exception instead. assert引发一个AssertionError异常。 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 ). 您想返回与assertEquals()测试所寻找相同的字符串,因此'Only lists allowed' ,而不是msg参数(测试失败时显示 )。

Instead of using assert use return , and return the expected string: 代替使用assert使用return ,并返回期望的字符串:

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

Note that normally you'd use isinstance() to test for types: 请注意,通常您会使用isinstance()测试类型:

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. 您甚至可能拥有不支持与0进行比较的类型,因此您想先进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM