pytest之框架结构及运行方式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pytest之框架结构及运行方式相关的知识,希望对你有一定的参考价值。
参考技术Apytest的框架的测试结构相对unittest来说,更加灵活。比如从文件开始,各种前置、后置条件。
模块级:setup_module和teardown_module(开始于模块始末,全局的)
函数级:setup_function和teardown_function(只对函数用例生效(不在类中))、
类级:setup_class和teardown_class(只在类中前后运行一次(在类中))
方法级:setup_method和teardown_method(开始于方法始末(在类中))
类里面的(setup/teardown)运行在调用方法的前后
举例
返回结果显示如下:
test7.py::test_function1 整个模块.py 开始
不在类中的函数前
不在类中的函数1
PASSED不在类中的函数后
test7.py::test_function2 不在类中的函数前
不在类中的函数2
PASSED不在类中的函数后
test7.py::TestXase::test_method1 我是类开始执行
我是方法1和2开始执行
我是方法1
PASSED我是方法1和2结束执行
test7.py::TestXase::test_method2 我是方法1和2开始执行
我是方法2
PASSED我是方法1和2结束执行
我是类结束执行
整个模块.py 结束
============================== 4 passed in 0.02s ==============================
执行测试的方式有3种,平时我们用得比较多的方式就是main()方法的方式,其次就是命令行的方式。
1、main()方法:pytest.main([\'-v\',\'-s\',\'test01.py\']) ,如上述例子中显示。
2、命令行:pytest -s -v test.py,在命令行中,找到对应的目录。
3、调整pycharm中的值:Tools->Python Integrated tools -> Default test runner
pytest的执行原则注意事项:
1.pytest将在当前目录及其子目录中运行test_ .py或 test.py形式的所有文件。
2.以test 开头的函数 ,以Test开头的类,以test_开头的方法,所有package都要有 init _.py文件。
3.pytest可以执行unittest框架写的用例和方法。
pytest框架结构运行规则及命名方式
模块级 (setup_module/teardown_module) 不在类中的函数有用
函数级 (setup_function/teardown_function) 不在类中的函数有用
类级 (setup_class/teardown_class)只在 类中前后运行一次。
方法级 (setup_method/teardown_methond) 运行在类中方法始末
import pytest
def setup_module():
print(‘整个模块.py开始‘)
def teardown_module():
print(‘整个模块的.py结束‘)
def setup_function():
print(‘不在类中的函数前‘)
def teardown_function():
print(‘不在类中的函数后‘)
def test_w_one():
print(‘不在类中的方法1‘)
def test_w_two():
print(‘不在类中的方法2‘)
class TestClass:
def setup_class(self):
print(‘类前面‘)
def teardown_class(self):
print(‘类之后‘)
def setup_method(self):
print(‘方法前‘)
def teardown_method(self):
print(‘方法后‘)
def test_one(self):
x=‘this‘
assert ‘h‘ in x
def test_two(self):
x=‘hello‘
assert ‘h4‘==x
def test_three(self):
a=‘hello‘
b=‘hello world‘
assert a in b
if __name__ == ‘__main__‘:
pytest.main("-s -v","pytestDemo.py")
整个模块.py开始
不在类中的函数前
不在类中的方法1
不在类中的函数后
pytestDemo.py::test_w_one ? 20% ██ 不在类中的函数前
不在类中的方法2
不在类中的函数后
pytestDemo.py::test_w_two ? 40% ████ 类前面
方法前
方法后
pytestDemo.py::TestClass.test_one ? 60% ██████ 方法前
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― TestClass.test_two ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
self = <pytest_2.pytestDemo.TestClass object at 0x105b0f438>
def test_two(self):
x=‘hello‘
> assert ‘h4‘==x
E AssertionError: assert ‘h4‘ == ‘hello‘
E - h4
E + hello
pytestDemo.py:39: AssertionError
方法后
pytestDemo.py::TestClass.test_two ? 80% ████████ 方法前
方法后
类之后
整个模块的.py结束
pytestDemo.py::TestClass.test_three ? 100% ██████████
Results (0.14s):
4 passed
1 failed
- pytestDemo.py:37 TestClass.test_two
以上是关于pytest之框架结构及运行方式的主要内容,如果未能解决你的问题,请参考以下文章
pytest学习和使用3-对比unittest和pytest脚本在pycharm中运行的方式