Application scenarios:
The pytest framework can solve the problem of executing multiple test scripts at the same time .
It provides detailed failure information of test cases, allowing developers to correct problems quickly and accurately. It is compatible with the latest versions of Python. It is also compatible with unittest, doctest and nose, out of the box. Next, let’s learn more about the pytest framework.
01. Installation and introduction
concept:
pytest is a unit testing framework for python. It is similar to the built-in Unittest testing framework. Compared with the Unittest framework, it is simpler to use and more efficient.
Official website: https://docs.pytest.org/en/latest/
Chinese document address: https://www.osgeo.cn/pytest/
01. Characteristics and writing rules
Features:
- Very easy to get started, simple to get started, rich documentation, there are many examples in the documentation for reference
- Supports simple unit testing and complex functional testing
- Support parameterization
- During test execution, you can skip certain tests, or mark certain cases that are expected to fail as failures. Support repeated execution of failed cases.
- Support running test cases written by Nose and Unittest
- Has many third-party plug-ins and can be customized and extended
- Convenient integration with continuous integration tools
Install:
Install the specified version through the pip command
pip3 install pytest==5.4.3
Pytest is a third-party testing framework for Python. It is an extension framework based on unittest, which is simpler and more efficient than unittest.
When writing use cases using pytest, you must comply with the following rules:
The test file name must start with "test" or end with "test" (such as: test_ab.py) and
the test method must start with "test". test*.py or *test.py
test class names start with "Test". Use case identification: Contains all test_* methods (the test class cannot have an init method)
to assert using basic assert.
使用 pytest 需要更改 pycharm 集成设置
Pytest 可以执行 uinttest 写的用例和方法
现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:110685036
02. Operation mode
There are two modes of operation:
- Command line mode [recommendation]
- Main function mode
Command line mode [recommendation]
命令行中执行 pytest -s test_demo01.py
Main function mode
import pytest
class Test:def test_case01(self):print(1)
def test_case02(self):print(2)# 主函数执行if __name__ == '__main__':pytest.main(['-s','test_demo01.py'])
Add the main function to the test_demo01.py file
-s indicates that console printing is supported. If not added, nothing will appear in print.
operation result
- . means success
- F means failure
Summary: It is recommended to use the command line to run, which is more convenient than the main function mode.
03. setup and teardown
pytest will execute two special methods before and after running the automation script, namely setup and teardown. The setup method will be executed before the script is executed, and the teardown method will be executed after the script is executed. We can obtain the driver object in setup. Close the driver object in teardown
Application scenarios:
function level approach
Run at the beginning and end of the test method, running the test function once will run setup and teardown once.
Sample code
import pytestclass Test:
def setup(self):print('test--->setup')def teardown(self):print('test--->teardown')def test_case01(self):print('test--->1')
def test_case02(self):print('test--->2')
# 主函数执行if __name__ == '__main__':pytest.main(['-s','test_demo01.py'])
Results of the
Sample code
import pytestclass Test:
def setup_class(cls):print('test--->setupcls')def teardown_class(cls):print('test--->teardowncls')def test_case01(self):print('test--->1')
def test_case02(self):print('test--->2')
# 主函数执行if __name__ == '__main__':pytest.main(['-s','test_demo01.py'])
Results of the
02. Pytest-commonly used plug-ins
The plug-in list URL: https://plugincompat.herokuapp.com contains many plug-in packages, which you can choose to use according to your work needs.
01. Pytest-html test report
Application scenarios
Whether the final execution of the automated test script passes or fails needs to be reflected in the test report
Use the command to install the specified version
pip install pytest-html=2.1.1
Excuting an order
pytest test_login.py --html=report.html
View report
Report display:
02. Control function execution sequence
Application scenarios:
In real life, if you want to place an order, you must log in first. We can control the order of function execution through plug-in installation.
使用命令 pip3 install pytest-ordering
- Mark the function under test, @pytest.mark.run(order=x)
- Solve the running order according to the parameters passed in by order
- When the order value is all positive or negative, the running order: the smaller the value, the higher the priority.
- Positive and negative numbers exist at the same time: positive numbers have higher priority
Sample code
import pytest
class Test:
def test_case01(self):print('test--->001')
@pytest.mark.run(order=2)def test_case02(self):print('test--->002')
@pytest.mark.run(order=1)def test_case03(self):print('test--->003')
Results of the
03. Retry after failure
Application scenarios:
Due to network reasons, automated scripts report errors. We can use the plug-in that fails and retry. When it fails, try to run it again. Generally, the final success can be regarded as success, but it is best to troubleshoot when it is a script problem.
使用命令pip3install pytest-rerunfailures 进行安装使用
Add --reruns n to the command line parameters in the configuration file
pytest -s test_demo2.py --reruns 3
Sample code
class Test:
def test_a(self):assert 1,1 # 断言成功
def test_b(self):print('失败')assert 0,1 # 断言失败
operation result
R means retry
Note that when retrying, if the script passes, it will not be retried later.
03. Advanced usage of pytest
01. Skip the test function
Application scenarios:
The same software may have different effects on different devices. For example, the 3D touch operation of iOS needs to be supported by devices above 6s. The same application can be installed on both 6s and 6s. If the device does not support it, there is no need to go there. Test this functionality. At this time, we can let this function skip
How to use:
Add the decorator @pytest.mark.skipif(condition, reason="xxx") on the test script that needs to be skipped | |
conditionreason | Conditions to be skipped, parameters must be passed. Reason, parameters must be passed. |
Sample code:
class Test:
def test_a(self):assert 1,1 # 断言成功@pytest.mark.skipif(condition=True,reason='x')def test_b(self):print('失败')assert 0,1 # 断言失败
Results of the
02. Expected failure
Application scenarios:
For example, the test mobile phone number input box is 11 digits long. If we pass in a 12 digit number, we can use expected failure at this time.
@pytest.mark.xfail(condition=None, reason=None, raises=None, run=True, strict=False)
- condition skip condition, required parameters
- reason Mark reason, required parameter
How to use:
Add a decorator example on top of a test script that needs to mark expected failures
Sample code:
class Test:
def test_a(self):print('-----testa')assert 1,1 # 断言成功
@pytest.mark.xfail(condition=True,reason='x')def test_b(self):print('-----testb')assert 0,1 # 断言失败
@pytest.mark.xfail(condition=True, reason='x')def test_c(self):print('-----testc')assert 0, 2 # 断言失败
Results of the:
x means that the expected failure result is not a bug, X means that the expected failure result is a success and is considered a bug
03. Data parameterization
Application scenarios:
The login function is to enter the user name, enter the password, and click to log in. However, if you want to test multiple values for the login username and password, there is no way to use ordinary operations. Data parameterization can help me achieve this effect.
Method name:
@pytest.mark.parametrize(argnames, argvalues, indirect=False, ids=None, scope=None)
- argnames parameter name
- argvalues parameter corresponds to the value. The type must be an iterable type. Generally, list is used.
How to use a parameter
- argnames is a string type, and the parameter name is determined according to the requirements.
- argvalues is a list type, and the contents of the list elements are determined according to requirements.
- In the test script, the parameters and names are consistent with argnames
- Used normally in test scripts
How many contents are there in the argvalues list, how many times will this script be run?
Sample code:
class Test:
@pytest.mark.parametrize('age',[18,19,23,21])def test_01(self,age):print(age)
Results of the:
Multiple parameters:
class Test:
@pytest.mark.parametrize(('name','age'),[('zhangsan',18),('lisi',19)]) def test_01(self,name,age):print(name,age)
Results of the:
04、Pytest-fixture
Application scenarios:
The fixture decorator is used to mark fixed factory functions. When other functions or classes call it, it will be activated and executed first. It is usually used to complete preset processing and repeated operations.
How to use:
- By function reference
Sample code:
class Testlogin:
@pytest.fixture()def test_login(self):print('登录操作')uname = 'lily'return uname
def test_a(self,test_login):print(f'test_a {test_login}')
def test_b(self):print('不需要登录操作')
operation result:
Finally, I would like to thank everyone who read my article carefully. Looking at the increase in fans and attention, there is always some courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly!
Software Testing Interview Document
We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.