当前位置:网站首页>Pytest unit test framework: simple and easy to use parameterization and multiple operation modes
Pytest unit test framework: simple and easy to use parameterization and multiple operation modes
2022-07-04 00:23:00 【Xiaowu knock code】
Unit test framework , You are familiar with Unittest、Nose(unittest An extension of ).Pytest It's unknown , But since I used it , I can't put it down , As it describes itself :simple powerful testing with Python. Easy to use parameterization and various operation modes , Make the test script simple and clear , Debugging and operation are more convenient .
One 、 A parameterized
For example, we are doing automated testing , When different parameters are passed , Expected return status code by 200. If you use Unittest It is complicated to do this parameterization , and pytest It's a lot easier . stay pytest There is pytest.mark.parametrize Decorator , Easy problem solving . We take the sogo As an example .
Use case description :
Step one 、 Turn on Sogou search (http://www.sogou.com/)
Step two 、 Input tesla Click the magnifying glass to search
expect : Return to normal
If you use interfaces , It's equivalent to query Parameters are passed later tesla that will do , The verification status code is 200
If you use interfaces , It's equivalent to query Parameters are passed later tesla that will do , The verification status code is 200
Import requests
Session = requests.session()
url = ‘https://www.sogou.com/web?’
para = {‘query’: ‘tesla’}
r = session.get(url, params=para, verify=False, allow_redirects=False)
assert r.status_code == 200
in fact , If only one search term is passed, the interface is considered normal , Then it is likely to be a big basket . So we may need to pass n Search terms to verify . in other words ,para Medium query In the following content, we need to pass many different search terms . For example, we want to search VR,BITCOIN Wait for more words , What needs to be done ?
This is the time to use pytest There is pytest.mark.parametrize Decorator , The code is as follows 8 That's ok , Just add a decorator outside the method .
Import pytest
Import requests
Session = requests.session()
url = https://www.sogou.com/web?’
search= [‘tesla’,‘VR’,‘BITCOIN’]
@pytest.mark.parametrize(‘test_input’,search)
def test_status_code(test_input):
para = {‘query’:test_input}
r= session.get(url,params=para, verify=False, allow_redirects=False)
assert r.status_code == 200
At this time, some students may ask questions , For multiple parameters, we use for Circulation can also be done , Why use this method . The reason is to use pytest Parameterization of , A parameter passed in is a case, In the above example, we passed in three parameters , Then there are three cases, Which parameter is passed in causing an error , We know at a glance . So what to do ? We are cmd Running scripts inside , Suppose the script file name is test_sogo_search.py, Place in C Under the plate :
C:>pytest test_sogo_search.py --html=./result/Report.html
stay pytest What you see in your report is this 
Through such a report , You can clearly know which search term is correct , Which search term verification result is wrong . Comparative use for In a circle , It's much clearer . In addition, there is the running time , It can also give additional information .
Two 、 Operation mode
Pytest A variety of operating modes , Make testing and debugging easier , Let's introduce 5 There are many modes used . Before the introduction, I need to remind you , function pytest I will find it when test Files beginning with test The first method or class, Otherwise, you will be prompted that you can't find a running case 了 .
1、 Generate result report after operation (htmlReport)
Operation mode :
pytest test_case.py --html=./result/test_caseReport.html
effect :

When a run error occurs , stay report You can intuitively see the cause of the error , Above picture , Expected status_code yes 302, But it is 200, So I made a mistake . Looking at the report, it becomes very easy to locate the problem . And the test results need not be sorted , Just submit the report directly .
2、 Run the specified Case
Code block (test_case.py)
class TestClassOne(object):
def test_one(self):
x = “this”
assert ‘h’ in x
def test_two(self):
x = “hello”
assert hasattr(x, ‘check’)
class TestClassTwo(object):
def test_one(self):
x = “this”
assert ‘h’ in x
def test_two(self):
x = “hello”
assert hasattr(x, ‘check’)
Operation mode :
Pattern 1:$ pytest test_case.py
Pattern 2:$ pytest test_case.py::TestClassTwo
Pattern 3:$ pytest test_case.py::TestClassTwo::test_one
explain :
Pattern 1: Directly execute the whole test_case File in all case
Pattern 2: function test_case In file TestClassTwo This class Of the two cases
Pattern 3: function test_case In file TestClassTwo This class Under the test_one
effect :
When we write more cases when , If you have to run it every time , It's undoubtedly a waste of time , In this simple way, we can easily specify any case Here we go .
Be careful :
Definition class when , Need to be T start , Otherwise pytest Is not going to run the class Of .
3、 Multi process running cases
pip install pytest-xdist
Operation mode :
$ pytest tes_case.py -n NUM
effect :
When case When it reaches a certain amount , The running time will become very long , If you want to shorten the running time of the script , Then you can use it to do .NUM Fill in the number of concurrent processes you want . Speed swish ~ Try it !
4、 Retry running cases
pip install pytest-rerunfailures
Operation mode :
$pytest tes_case.py --reruns NUM
effect :
When doing interface tests , Sometimes 503 Or short-term network fluctuations , Lead to case It will fail , In fact, it is not the result we want , At this time, you can run again case The way , Re execution . How many times to try again , Fill in with you NUM of .
5、 Show print Content
Operation mode :
$pytest tes_case.py -s
effect :
When running the test script , In order to debug or want to print something , We'll add some... To the code print Content , But it's running pytest when , These contents will not be displayed . If you bring it -s The mode of operation of , You can see that print The content of will be displayed .
in addition Pytest Multiple operation modes of can be superimposed , for instance , You want to run at the same time 4 Another process wants to print out print The content of , It can be used $pytest test_case.py -s -n 4
Finally, I also sorted out some software testing learning materials , It should be very helpful for small partners learning software testing . Friends who need information can pay attention to the official account. : Software testing tips dao, Free access ! Include , Software learning Roadmap ,50 Video of class for many days 、16 It's a real assault project ,80 More than one software for testing ,37 A test document ,70 A software testing related problem ,40 Test experience level article , Thousands of test questions to share , also 2021 Software testing interview Dictionary , There's also a selection of resumes for software testing jobs , I hope that's helpful ……
Learn not to fight alone , It's best to keep warm , Achieve each other and grow together , The effect of mass effect is very powerful , Let's learn together , Punch in together , Will be more motivated to learn , And you can stick to it .
Typing is not easy , If this article is helpful to you , I like it, I like it , Give the author an encouragement . It's also convenient for you to find it quickly next time .
边栏推荐
- The frost peel off the purple dragon scale, and the xiariba people will talk about database SQL optimization and the principle of indexing (primary / secondary / clustered / non clustered)
- A method to solve Bert long text matching
- Self study software testing. To what extent can you go out and find a job?
- Axure resources and prototype tool Axure RP 9 download
- How will the complete NFT platform work in 2022? How about its core functions and online time?
- It is forbidden to splice SQL in code
- Global and Chinese markets of distributed control system (DCS) consumption 2022-2028: Research Report on technology, participants, trends, market size and share
- Powerful blog summary
- [2021]NeRF in the Wild: Neural Radiance Fields for Unconstrained Photo Collections
- system. Exit (0) and system exit(1)
猜你喜欢
![Docking Alipay process [pay in person, QR code Payment]](/img/30/665580241020ee3adb872e725f0624.jpg)
Docking Alipay process [pay in person, QR code Payment]

URL (data:image/png; Base64, ivborw0k... Use case
![[source code] VB6 chat robot](/img/89/46b67f627c8257eaddc70a247c9ba5.jpg)
[source code] VB6 chat robot

Enter MySQL in docker container by command under Linux

STM32 GPIO CSDN creative punch in

Detailed explanation of the relationship between Zhongtai, wechat and DDD
![[MySQL] classification of multi table queries](/img/96/2e51ae8d52ea8184945e0540ce18f5.jpg)
[MySQL] classification of multi table queries

Zipper table in data warehouse (compressed storage)

Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?

ESP Arduino playing with peripherals (V) basic concept of interrupt and timer interrupt
随机推荐
NLP pre training technology development
Generic
Investment demand and income forecast report of China's building ceramics industry, 2022-2028
Alibaba cloud container service differentiation SLO hybrid technology practice
Iclr2022: how does AI recognize "things I haven't seen"?
Data storage - interview questions
[Mongodb] 2. Use mongodb --------- use compass
On the day when 28K joined Huawei testing post, I cried: everything I have done in these five months is worth it
What is the Valentine's Day gift given by the operator to the product?
Selenium library 4.5.0 keyword explanation (II)
Tencent interview: can you pour water?
MySQL is installed as a Windows Service
国元证券开户是真的安全可靠吗
[cloud native topic -48]:kubesphere cloud Governance - operation - overview of multi tenant concept
Celebrate the new year | Suihua fire rescue detachment has wonderful cultural activities during the Spring Festival
Is the account opening of Guoyuan securities really safe and reliable
Axure resources and prototype tool Axure RP 9 download
Tencent interview: can you find the number of 1 in binary?
Idea set class header comments
Gossip about redis source code 78