我正在尝试弄清楚如何为用 Python 编写的函数编写单元测试——下面是代码:
def num_buses(n): import math """ (int) -> int Precondition: n >= 0 Return the minimum number of buses required to transport n people. Each bus can hold 50 people. >>> num_buses(75) 2 """ bus = int() if(n>=0): bus = int(math.ceil(n/50.0)) return bus
我正在尝试编写测试代码,但它们给出了失败的结果 - 以下是我开始的代码:
import a1 import unittest class TestNumBuses(unittest.TestCase): """ Test class for function a1.num_buses. """ def test_numbuses_1(self): actual = num_buses(75) expected = 2 self.assertEqual(actual, expected) # Add your test methods for a1.num_buses here. if __name__ == '__main__': unittest.main(exit=False)
当我按 F5 运行模块时 - 这就是我得到的 -
E ====================================================================== ERROR: test_numbuses_1 (__main__.TestNumBuses) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\1-blog-cacher\TestNumBuses.py", line 8, in test_numbuses_1 actual = num_buses(75) NameError: global name 'num_buses' is not defined ---------------------------------------------------------------------- Ran 1 test in 0.050s FAILED (errors=1)
所以我的测试失败了 - 虽然它应该通过,因为乘客人数是 75 人,每辆巴士最多可容纳 50 人 - 但超过这个数字就会导致数字四舍五入。
有人能看到我如何使测试用例工作以及我编写的测试代码哪里出了问题吗?
您看到的错误 ( ) 是因为您在测试中NameError: global name 'num_buses' is not defined没有正确引用该函数。在您的测试代码中,您直接调用,但由于您正在导入模块,因此您应该通过该模块访问该函数。num_buses``num_buses(75)``a1``num_buses
NameError: global name 'num_buses' is not defined
num_buses``num_buses(75)``a1``num_buses
为了修复这个问题,您需要修改测试以调用a1.num_buses(75)而不是num_buses(75)。
a1.num_buses(75)
num_buses(75)
这是更正后的测试代码:
import a1 import unittest class TestNumBuses(unittest.TestCase): """ Test class for function a1.num_buses. """ def test_numbuses_1(self): actual = a1.num_buses(75) # Access the function through the 'a1' module expected = 2 self.assertEqual(actual, expected) # Add your test methods for a1.num_buses here. if __name__ == '__main__': unittest.main(exit=False)
解释:
a1
num_buses``a1.num_buses
NameError
一旦您做出此更改,您的测试应该可以正确运行,并且它将检查函数是否num_buses(75)返回预期值2。
2
请让我知道这是否对你有用!