当前位置:网站首页>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 .
边栏推荐
- It is forbidden to splice SQL in code
- Zipper table in data warehouse (compressed storage)
- Collation of the most complete Chinese naturallanguageprocessing data sets, platforms and tools
- P1339 [USACO09OCT]Heat Wave G
- Idea a method for starting multiple instances of a service
- Global and Chinese market of glossometer 2022-2028: Research Report on technology, participants, trends, market size and share
- system. Exit (0) and system exit(1)
- 2020.2.14
- Generic tips
- 国元证券开户是真的安全可靠吗
猜你喜欢

Is user authentication really simple
![[complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!](/img/3f/75b3125f8779e6cf9467a30fd7eeb4.jpg)
[complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!

SPI based on firmware library

Bodong medical sprint Hong Kong stocks: a 9-month loss of 200million Hillhouse and Philips are shareholders

Similarities and differences of text similarity between Jaccard and cosine

Introducing Software Testing

Smart fan system based on stm32f407

Idea a method for starting multiple instances of a service

Kubedl hostnetwork: accelerating the efficiency of distributed training communication

Eight year test old bird, some suggestions for 1-3 year programmers
随机推荐
Report on prospects and future investment recommendations of China's assisted reproductive industry, 2022-2028 Edition
I would like to ask how the top ten securities firms open accounts? Is it safe to open an account online?
[complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!
Global and Chinese markets for coronary artery disease treatment devices 2022-2028: Research Report on technology, participants, trends, market size and share
Fudan 961 review
Similarities and differences of text similarity between Jaccard and cosine
Alibaba cloud container service differentiation SLO hybrid technology practice
[2021]NeRF in the Wild: Neural Radiance Fields for Unconstrained Photo Collections
Selenium library 4.5.0 keyword explanation (4)
P1339 [USACO09OCT]Heat Wave G
Version rollback revert don't reset better reset must be forced
Axure resources and prototype tool Axure RP 9 download
Analysis on the scale of China's smart health industry and prediction report on the investment trend of the 14th five year plan 2022-2028 Edition
Private project practice sharing populate joint query in mongoose makes the template unable to render - solve the error message: syntaxerror: unexpected token r in JSON at
Generic tips
What is the potential of pocket network, which is favored by well-known investors?
Selenium library 4.5.0 keyword explanation (III)
Is user authentication really simple
ITK learning notes (VII) the position of ITK rotation direction remains unchanged
国元证券开户是真的安全可靠吗