如何使用unittest正确编写测试?

时间:2013-04-06 05:00:31

标签: python math testing import numbers

我试图弄清楚如何为我用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人 - 除此之外的任何事情都会导致数据的四舍五入。

任何人都可以看到我如何让测试用例工作以及我在哪里编写测试代码出错了?

1 个答案:

答案 0 :(得分:2)

在您的unittest文件中,您必须import num_buses

这可以解决您的问题,但是如果您在num_buses中定义了a1,那么您必须执行a1.num_buses,否则Python会认为num_buses是一个全局函数。

import a1
import unittest
import num_buses

class TestNumBuses(unittest.TestCase):
    """ Test class for function a1.num_buses. """
    def test_numbuses_1(self):
        actual = num_buses(75) #a1.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)

检查出来:Cyber-Dojo Test - 只需按简历,然后在test_untitled.py按下TEST按钮。