我试图弄清楚如何在 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 人 - 超过此数量将导致数字四舍五入。