一、
Python 的单元测试中,一般一个测试程序文件负责测试 Python 的一个模块,或者一个模块中的一个代码文件。它们经常以 test_somemodule.py 或 testSomeModule.py 的名字命名;一般保存在被测试模块的一个子目录 tests 中,也有就保存在该模块的根目录的。
如果要编写一个测试程序,需要以 unittest.TestCase 为基类派生,这样 unittest 就可以自动找到这些测试类了。这样的一个测试类中,凡是以“test”开头的方法,都是一个测试用例。
unittest 会自动统计测试用例的个数,并在最后的测试报告中指出测试成功了几个,有那些失败。TestCase 还有两个很有用的方法:在每个测试用例执行之前,写在 setUp 中的代码都会被执行,用来初始化测试环境;而 tearDown 中的代码则负责清除每个测试用例遗留的垃圾,恢复现场。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
import
unittest
import
commands
class
TSCache(
object
):
def
__init__(
self
):
# suit initial
print
"case %s"
%
self
def
doRequest(
self
):
comm
=
"curl -I -s -x localhost:8080 http://111111.cn/index.html"
output
=
commands.getoutput(comm)
rt
=
output.split(
"\r\n"
)[
0
]
return
rt
class
TestTSCache(unittest.TestCase):
#run before every test method
def
setUp(
self
):
print
'test before'
def
test_200Code(
self
):
active
=
TSCache().doRequest()
expect
=
'HTTP/1.1 200 OK'
self
.assertEquals(expect,active)
def
test_not404(
self
):
active
=
TSCache().doRequest()
expect
=
'HTTP/1.1 404 OK'
self
.assertNotEquals(expect,active)
#run after every test mehtod
def
tearDown(
self
):
print
'test after'
if
__name__
=
=
'__main__'
:
#print dir(TestTSCache)
unittest.main()
|
二、运行
python xxxx.py
python xxxx.py -v
三、结果
OK
Fail
Error
四、assert
类型 | 功能 |
assertEqual | |
assertEquals | |
assertNotEqual | |
assertNotEquals | |
assertAlmostEqual | |
assertAlmostEquals | |
assertNotAlmostEqual | |
assertNotAlmostEquals | |
assertTrue | |
assertFalse | |
assertRaises |
说明: #当assertEquals失败时,会把第一个和第二个参数的值打印出来;#assertFalse和assertTrue不会打印值
三、testsuit
程序的开头把当前目录、上一级目录和子目录 tests 都放入系统搜寻路径中。这是为了 Python 程序 import 模块代码和测试代码时更容易找到它们。紧接着,在当前目录和子目录 tests 中搜寻所有测试程序,把它们的列表加入到 modules_to_test 中。suite 方法根据前面定义的列表把所有测试用例都找出来。最后通过调用 unittest 的 testrunner 就可以启动我们的所有测试了,我们只要稍等一会儿,它就会把最终的测试报告放到我们面前
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
import
unittest
import
sys
import
os
import
getopt
"""
path = "/home/wb-yinlu/Beryl/study/Module/Cache/123457_cachexample.py"
path = "/home/wb-yinlu/Beryl/study/Module/Cache/*.py"
path = "/home/wb-yinlu/Beryl/study/Module/Cache/"
"""
def
getcase(path):
testfiles
=
[]
if
os.path.isdir(path):
# curdir and subdir insert to suite
for
root, dirs, files
in
os.walk(path):
files
=
[f[:
-
3
]
for
f
in
files
if
f.startswith(
'1'
)
and
f.endswith(
'.py'
)]
if
len
(files):
sys.path.append(root)
testfiles
=
testfiles
+
files
elif
os.path.splitext(path)[
1
]
=
=
".py"
:
root
=
os.path.dirname(path)
sys.path.append(root)
if
path[
-
4
:]
=
=
"*.py"
:
# curdir and subdir insert to suite,not inculde subdir
testfiles
=
testfiles
+
[f[:
-
3
]
for
f
in
os.listdir(root)
if
f.startswith(
'1'
)
and
f.endswith(
'.py'
)]
else
:
if
os.path.isfile(path):
# single py file insert to suite
testfiles
=
testfiles
+
[os.path.basename(path)[:
-
3
]]
else
:
print
"the python file is not exist"
sys.exit(
1
)
else
:
print
"it is not a dir or a effective python file path"
sys.exit(
1
)
return
testfiles
def
suite(path):
print
"path = %s"
%
path
alltests
=
unittest.TestSuite()
for
module
in
map
(
__import__
, getcase(path)):
alltests.addTest(unittest.findTestCases(module))
return
alltests
def
usage():
print
"help help help"
if
__name__
=
=
'__main__'
:
path
=
os.curdir
ver
=
1
opts, args
=
getopt.getopt(sys.argv[
1
:],
"p:hv"
,[
"path="
,
"help"
])
for
op, value
in
opts:
if
op
=
=
'-p'
:
path
=
value
elif
op
=
=
'-v'
:
ver
=
value
elif
op
=
=
'-h'
:
usage()
sys.exit(
1
)
else
:
pass
#unittest.main(defaultTest='suite')
runner
=
unittest.TextTestRunner(verbosity
=
ver)
runner.run(suite(path))
|
四、
运行测试套
1、命令模式
python -m unittest test_module1 test_module2 python -m unittest test_module.TestClass python -m unittest test_module.TestClass.test_method2、main设置
# unittest.main() # 用这个是最简单的,下面的用法可以同时测试多个类 # unittest.TextTestRunner(verbosity=2).run(suite1) # 这个等价于上述但可设置verbosity=2,省去了运行时加-v suite1 = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions) suite2 = unittest.TestLoader().loadTestsFromTestCase(TestDictValueFormatFunctions) suite1 = module1.TheTestSuite() suite2 = module2.TheTestSuite() alltests = unittest.TestSuite([suite1, suite2]) unittest.TextTestRunner(verbosity=2).run(suite)