单元测试 - “NameError:未定义全局名称”

时间:2013-04-06 07:32:58

标签: python math import doctest

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

2 个答案:

答案 0 :(得分:5)

假设您的代码位于模块a1中,请尝试将num_busesa1对应,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)

答案 1 :(得分:2)

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

actual = a1.num_buses(75)