0

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

4

2 回答 2

6

假设您的代码在模块中a1,请尝试num_busesa1, so开头a1.num_buses。问题是您的单元测试位于不同的模块中,并且该num_buses模块中的函数a1.num_buses在测试的命名空间中被引用,因此出现global错误。因此,将您的测试更改为:

class TestNumBuses(unittest.TestCase):
    """ Test class for function a1.num_buses. """
    def test_numbuses_1(self):
        actual = a1.num_buses(75)
        expected = 2
        self.assertEqual(actual, expected)
于 2013-04-06T07:35:20.213 回答
2

您的错误表明 num_buses 存在问题。尝试

actual = a1.num_buses(75)
于 2013-04-06T07:36:06.800 回答