[英]How do I write tests correctly using unittest?
I am trying to figure out how to write unit tests for functions that I have written in Python - here's the code written below: 我试图弄清楚如何为我用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
I am attempting to write test code but they are giving me fail results - here's code I started with: 我正在尝试编写测试代码,但是他们给了我失败的结果 - 这是我开始的代码:
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)
When I run the module by pressing F5 - this is what I get - 当我按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)
So my test Failed - although it should pass since the number of passengers are 75 and each bus can hold a maximum of 50 people - anything more than that will result in a rounding up of the figures. 所以我的测试失败 - 虽然它应该通过,因为乘客的数量是75,每辆公共汽车最多可以容纳50人 - 任何超过这个将导致数字的四舍五入。
Can anyone see how I can get the test cases to work and where my writing the test code went wrong? 任何人都可以看到我如何让测试用例工作以及我在哪里编写测试代码出错?
In your unittest file you have to import num_buses
. 在您的unittest文件中,您必须
import num_buses
。
This fixes your immediate problem, but if you have defined num_buses
in a1
then you have to do a1.num_buses
otherwise Python will think that num_buses
is a global function. 这可以解决您的问题,但是如果您在
a1
定义了num_buses
,那么您必须执行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)
Check this out: Cyber-Dojo Test - just press resume and then in test_untitled.py
press the TEST button. 看看这个: Cyber-Dojo测试 - 只需按下resume,然后在
test_untitled.py
按下TEST按钮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.