用例设计原则
- 文件名以
test_*.py
文件和*_test.py
- 以
test_
开头的函数 - 以
Test
开头的类 - 以
test_
开头的方法 - 所有的包
pakege
必须要有__init__.py
文件
help帮助
1.查看pytest命令行参数,可以用pytest -h 或pytest --help查看
D:YOYO\
__init__.py
test_class.py
# content of test_class.py
class TestClass:
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
def test_three(self):
a = "hello"
b = "hello world"
assert a in b
test_sample.py
# content of test_sample.py
def func(x):
return x +1
def test_answer():
assert func(3)==5
执行测试用例
cmd
执行pytest
用例有三种方法,以下三种方法都可以,一般推荐第一个
pytest
py.test
python -m pytest
如果不带参数,在某个文件夹下执行时,它会查找该文件夹下所有的符合条件的用例(查看用例设计原则)
执行用例规则
1.执行某个目录下所有的用例
pytest 文件名/
2.执行某一个py文件下用例
pytest 脚本名称.py
3.-k 按关键字匹配
pytest -k "MyClass and not method"
这将运行包含与给定字符串表达式匹配的名称的测试,其中包括Python
使用文件名,类名和函数名作为变量的运算符。 上面的例子将运行
TestMyClass.test_something但不运行TestMyClass.test_method_simple
-x 遇到错误时停止测试
pytest -x test_class.py
从运行结果可以看出,本来有3个用例,第二个用例失败后就没继续往下执行了
class TestClass:
def test_one(self):
x = "wwj"
assert 'x' in x
def test_two(self):
x=4
assert 2+2 == x
运行结果:
E:\workspace\python\0510APIDemo\pytestDemo>pytest -x test_cl
ass.py
=================== test session starts ===================
platform win32 -- Python 3.7.4, pytest-5.4.3, py-1.9.0, plug
gy-0.13.1
rootdir: E:\workspace\python\0510APIDemo\pytestDemo
collected 2 items
test_class.py F
======================== FAILURES =========================
___________________ TestClass.test_one ____________________
self = <test_class.TestClass object at 0x000002B3B74B7648>
def test_one(self):
x = "wwj"
> assert 'x' in x
E AssertionError: assert 'x' in 'wwj'
test_class.py:4: AssertionError
================= short test summary info =================
FAILED test_class.py::TestClass::test_one - AssertionErro...
!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!
==================== 1 failed in 0.27s ====================
错误数量达到某个数量就停止执行
--maxfail=num