当前位置:网站首页>It's no exaggeration to say that this is the most user-friendly basic tutorial of pytest I've ever seen
It's no exaggeration to say that this is the most user-friendly basic tutorial of pytest I've ever seen
2022-07-07 22:56:00 【Xiaowu knock code】
Pytest brief introduction
Pytest is a mature full-featured Python testing tool that helps you write better programs.The pytest framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries.
Through the introduction of the official website, we can learn ,Pytest Is a very mature full-featured python The test framework , It mainly has the following characteristics :
Simple, flexible and easy to use
Support parameterization
Support simple unit testing and complex functional testing , It can also be used for automated testing
There are many third-party plug-ins , And you can customize the extension
Of test cases skip and xfail Handle
It can be very good and Jenkins Integrate
Support run by Nose、UnitTest Test cases written
Pytest install
1. Use it directly pip Command to install :
pip install -U pytest # -U Yes, if installed, it will automatically upgrade to the latest version
2. Verify installation results :
pytest --version # Show the currently installed version
C:\Users\edison>pytest --version
pytest 6.2.5
( Slide left and right to see the full code )
3. stay pytest In the test framework , The following constraints apply :
The test file name should conform to test_.py or _test.py Format ( for example test_min.py)
The test class should be Test start , And cannot have init Method
In a single test class , Can contain one or more test_ Initial function
Pytest The test execution
pytest Testing is relatively simple , Let's look at an example :
import pytest # Import pytest package
def test_001(): # Function to test_ start
print("test_01")
def test_002():
print("test_02")
if __name__ == '__main__':
pytest.main(["-v","test_1214.py"]) # call pytest Of main Function execution test
( Slide left and right to see the full code )
Here we define two test functions , Print the result directly , Now perform the test :
============================= test session starts =============================
platform win32 -- Python 3.8.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- D:\Code\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\Code
collecting ... collected 2 items
test_1214.py::test_001 PASSED [ 50%]
test_1214.py::test_002 PASSED [100%]
============================== 2 passed in 0.11s ==============================
Process finished with exit code 0
( Slide left and right to see the full code )
The output shows how many cases have been executed 、 Corresponding test module 、 Number of passes and execution time .
Test class main function
pytest.main(["-v","test_1214.py"])
( Slide left and right to see the full code )
adopt python Code execution pytest.main():
Direct execution pytest.main() 【 Automatically find the current directory , With test_ A document that begins with or with _test At the end of the py file 】;
Set up pytest The execution parameters of pytest.main([‘–html=./report.html’,‘test_login.py’])【 perform test_login.py file , And generate html Report in format 】.
main() Execution parameters and plug-in parameters can be passed in parentheses , adopt [] Segmentation ,[] Multiple parameters in the pass through ‘ comma ,’ Segmentation :
Run all use cases under the directory and sub packages pytest.main([‘ Directory name ’])
Run all use cases of the specified module pytest.main([‘test_reg.py’])
Run the specified module, specified class, specified use case pytest.main([‘test_reg.py::TestClass::test_method’]) Colon division
-m=xxx: Run tagged use cases
-reruns=xxx: Failed to rerun
-q: Quiet mode , Do not output environment information
-v: Rich information mode , Output more detailed use case execution information
-s: Displays the... In the program print/logging Output
–resultlog=./log.txt Generate log
–junitxml=./log.xml Generate xml The report
assert methods
pytest Assertions mainly use Python Native assertion methods , There are mainly the following :
== The content and type must be equal at the same time
in Actual results include expected results
is Assert that the two values before and after are equal
import pytest # Import pytest package
def add(x,y): # Define to test_ Start function
return x + y
def test_add():
assert add(1,2) == 3 # Assert success
str1 = "Python,Java,Ruby"
def test_in():
assert "PHP" in str1 # Assertion failed
if __name__ == '__main__':
pytest.main(["-v","test_pytest.py"]) # call main Function execution test
( Slide left and right to see the full code )
============================= test session starts =============================
platform win32 -- Python 3.8.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- D:\Code\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\Code
collecting ... collected 2 items
test_pytest.py::test_add PASSED [ 50%]
test_pytest.py::test_in FAILED [100%]
================================== FAILURES ===================================
___________________________________ test_in ___________________________________
def test_in():
> assert "PHP" in str1
E AssertionError: assert 'PHP' in 'Python,Java,Ruby'
test_pytest.py:11: AssertionError
=========================== short test summary info ===========================
FAILED test_pytest.py::test_in - AssertionError: assert 'PHP' in 'Python,Java...
========================= 1 failed, 1 passed in 0.18s =========================
Process finished with exit code 0
( Slide left and right to see the full code )
You can see that the reason for the error is clearly pointed out in the operation result “AssertionError”, because PHP be not in str1 in .
A detailed explanation of common orders
1. Run the specified case :
if __name__ == '__main__':
pytest.main(["-v","-s","test_1214.py"])
( Slide left and right to see the full code )
2. Run all use cases in the current folder, including subfolders :
if __name__ == '__main__':
pytest.main(["-v","-s","./"])
( Slide left and right to see the full code )
3. Run the specified folder (code All use cases in the directory ):
if __name__ == '__main__':
pytest.main(["-v","-s","code/"])
( Slide left and right to see the full code )
4. Use cases are specified in the run module ( In the running module test_add Use cases ):
if __name__ == '__main__':
pytest.main(["-v","-s","test_pytest.py::test_add"])
( Slide left and right to see the full code )
5. Maximum number of execution failures .
Use expressions "–maxfail=num" To achieve ( Be careful : There can be no spaces in the expression ), Indicates that the total number of use case failures is equal to num Stop running when .
6. The error message is displayed on one line .
In the actual project, if many use cases fail to execute , Checking the error message will be troublesome . Use "–tb=line" command , It can solve this problem very well .
Interface call
Write an interface to query user information locally , adopt pytest To call , And make interface assertions .
# -*- coding: utf-8 -*-
import pytest
import requests
def test_agent():
r = requests.post(
url="http://127.0.0.1:9000/get_user",
data={
"name": " Wu lei ",
"sex": 1
},
headers={
"Content-Type": "application/json"}
)
print(r.text)
assert r.json()['data']['retCode'] == "00" and r.json()['data']['retMsg'] == " Successful call "
if __name__ == "__main__":
pytest.main(["-v","test_api.py"])
Finally, thank everyone who reads my article carefully , The following online link is also a very comprehensive one that I spent a few days sorting out , I hope it can also help you in need !
These materials , For those who want to change careers 【 software test 】 For our friends, it should be the most comprehensive and complete war preparation warehouse , This warehouse also accompanied me through the most difficult journey , I hope it can help you ! Everything should be done as soon as possible , Especially in the technology industry , We must improve our technical skills . I hope that's helpful ……
If you don't want to grow up alone , Unable to find the information of the system , The problem is not helped , If you insist on giving up after a few days , You can click the small card below to join our group , We can discuss and exchange , There will be various software testing materials and technical exchanges .
Click the small card at the end of the document to receive it |
Typing is not easy , If this article is helpful to you , Click a like, collect a hide and pay attention , Give the author an encouragement . It's also convenient for you to find it quickly next time .
Self study recommendation B Stop video :
Zero basis transition software testing : Self taught software testing , Got the byte test post offer, Is the B The best video station !
Advanced automation testing : Huawei has landed , Salary increase 20K,2022 Most suitable for self-study python Automated test tutorial , Spend it yourself 16800 Bought , Free sharing
边栏推荐
- Debezium series: set role statement supporting mysql8
- 0-5VAC转4-20mA交流电流隔离变送器/转换模块
- Revit secondary development - project file to family file
- 行测-图形推理-7-相异图形类
- 行测-图形推理-4-字母类
- Redis official ORM framework is more elegant than redistemplate
- php 获取图片信息的方法
- Variables and constants
- 一次搞明白 Session、Cookie、Token,面试问题全稿定
- Leetcode206. Reverse linked list
猜你喜欢
Microbial health network, how to restore microbial communities
数字藏品加速出圈,MarsNFT助力多元化文旅经济!
安踏DTC | 安踏转型,构建不只有FILA的增长飞轮
微服务远程Debug,Nocalhost + Rainbond微服务开发第二弹
php 获取图片信息的方法
Knowledge drop - PCB manufacturing process flow
LeetCode144. Preorder traversal of binary tree
Digital transformation: five steps to promote enterprise progress
苹果在iOS 16中通过'虚拟卡'安全功能进一步进军金融领域
Microbial Health Network, How to restore Microbial Communities
随机推荐
Unity local coordinates and world coordinates
Nx10.0 installation tutorial
Debezium系列之:支持 mysql8 的 set role 語句
Ni9185 and ni9234 hardware settings in Ni Max
Line test - graphic reasoning - 2 - black and white lattice class
7-18 simple simulation of banking business queue
Yarn开启ACL用户认证之后无法查看Yarn历史任务日志解决办法
How to close eslint related rules
Sword finger offer 28 Symmetric binary tree
不夸张地说,这是我见过最通俗易懂的,pytest入门基础教程
Digital transformation: five steps to promote enterprise progress
Revit secondary development - intercept project error / warning pop-up
C development - interprocess communication - named pipeline
Debezium系列之: 支持在 KILL 命令中使用变量
行测-图形推理-6-相似图形类
The PHP source code of the new website + remove authorization / support burning goose instead of pumping
PHP records the pitfalls encountered in the complete docking of Tencent cloud live broadcast and im live group chat
Early childhood education industry of "screwing bar": trillion market, difficult to be a giant
Revit secondary development - link file collision detection
0-5vac to 4-20mA AC current isolated transmitter / conversion module