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 , There are mainly

The following features :

  • 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

  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

   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

   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"])

adopt python Code execution pytest.main()
1. 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 】
2. 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
============================= 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

   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"])

2. Run all use cases in the current folder, including subfolders

if __name__ == '__main__':
pytest.main(["-v","-s","./"])

3. Run the specified folder (code All use cases in the directory )

if __name__ == '__main__':
pytest.main(["-v","-s","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"])

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 .

 1 # -*- coding: utf-8 -*-
2 import pytest
3 import requests
4
5 def test_agent():
6 r = requests.post(
7 url="http://127.0.0.1:9000/get_user",
8 data={
9 "name": " Wu lei ",
10 "sex": 1
11 },
12 headers={"Content-Type": "application/json"}
13 )
14 print(r.text)
15 assert r.json()['data']['retCode'] == "00" and r.json()['data']['retMsg'] == " Successful call "
16
17 if __name__ == "__main__":
18 pytest.main(["-v","test_api.py"])

Python The test framework pytest More articles on the basics of getting started

  1. Python The test framework pytest Command line parameter usage

    stay Shell perform pytest -h You can see pytest The command line arguments for have this 10 Categories: , common 132 individual Serial number Category Chinese name Contains the number of command line arguments 1 positional arguments Shape parameter 1 2 gene ...

  2. Xiaobaixue Python Reptiles (35): The crawler frame Scrapy Fundamentals of entry ( 3、 ... and ) Selector Selectors

    Life is too short , I use Python Previous portal : Xiaobaixue Python Reptiles (1): The opening Xiaobaixue Python Reptiles (2): Lead to ( One ) Basic class library installation Xiaobaixue Python Reptiles (3): Lead to ( Two )Li ...

  3. Full function Python The test framework :pytest

    python Common test framework most people use unittest+HTMLTestRunner, I've seen it all this time pytest file , Discover this framework and rich plugins useful , So let's learn pytest.   imag ...

  4. May be Python The hottest third-party open source testing framework in pytest

    author :HelloGitHub-Prodesire HelloGitHub Of < Explain open source projects > series , Project address :https://github.com/HelloGitHub-Team/Arti ...

  5. Xiaobaixue Python Reptiles (34): The crawler frame Scrapy Fundamentals of entry ( Two )

    Life is too short , I use Python Previous portal : Xiaobaixue Python Reptiles (1): The opening Xiaobaixue Python Reptiles (2): Lead to ( One ) Basic class library installation Xiaobaixue Python Reptiles (3): Lead to ( Two )Li ...

  6. Xiaobaixue Python Reptiles (36): The crawler frame Scrapy Fundamentals of entry ( Four ) Downloader Middleware

    Life is too short , I use Python Previous portal : Xiaobaixue Python Reptiles (1): The opening Xiaobaixue Python Reptiles (2): Lead to ( One ) Basic class library installation Xiaobaixue Python Reptiles (3): Lead to ( Two )Li ...

  7. Xiaobaixue Python Reptiles (37): The crawler frame Scrapy Fundamentals of entry ( 5、 ... and ) Spider Middleware

    Life is too short , I use Python Previous portal : Xiaobaixue Python Reptiles (1): The opening Xiaobaixue Python Reptiles (2): Lead to ( One ) Basic class library installation Xiaobaixue Python Reptiles (3): Lead to ( Two )Li ...

  8. Xiaobaixue Python Reptiles (38): The crawler frame Scrapy Fundamentals of entry ( 6、 ... and ) Item Pipeline

    Life is too short , I use Python Previous portal : Xiaobaixue Python Reptiles (1): The opening Xiaobaixue Python Reptiles (2): Lead to ( One ) Basic class library installation Xiaobaixue Python Reptiles (3): Lead to ( Two )Li ...

  9. Xiaobaixue Python Reptiles (40): The crawler frame Scrapy Fundamentals of entry ( 7、 ... and ) docking Selenium actual combat

    Life is too short , I use Python Previous portal : Xiaobaixue Python Reptiles (1): The opening Xiaobaixue Python Reptiles (2): Lead to ( One ) Basic class library installation Xiaobaixue Python Reptiles (3): Lead to ( Two )Li ...

  10. Xiaobaixue Python Reptiles (41): The crawler frame Scrapy Fundamentals of entry ( 8、 ... and ) docking Splash actual combat

    Life is too short , I use Python Previous portal : Xiaobaixue Python Reptiles (1): The opening Xiaobaixue Python Reptiles (2): Lead to ( One ) Basic class library installation Xiaobaixue Python Reptiles (3): Lead to ( Two )Li ...

Random recommendation

  1. iOS_ Imitation QQ Emoticon keyboard

    When UITextFiled and UITextView When this kind of text input control becomes the first responder , The keyboard pops up by one of their UIView Class inputView Attribute to control , When inputView by nil The keyboard of the system will pop up , Want to ...

  2. Study OpenStack And (0): Basic knowledge of

    vi Direction key letter problem solution Carry out orders sudo apt-get remove vim-common Carry out orders sudo apt-get install vim The mouse is virtualbox Capture cannot ...

  3. WPF More than one of them RadioButton Bind to a property

    Like a pattern : stay View in : <RadioButton IsChecked="{Binding Option, Converter={cvt:EnumToBooleanConverter} ...

  4. Row to column String concatenation MSSQL A super problem

    By data ThreeLevelSortID KeyWordID KeyWordName key1 key2 key3 key4 Get big data ThreeLevelSortID KeyWordName ke ...

  5. Use Ratpack and Spring Boot Build high-performance JVM Microservice application

    Use Ratpack and Spring Boot Build high-performance JVM Microservice application This is what I do for InfoQ Translated articles , Original address :Build High Performance JVM Microservices wit ...

  6. mongodb ( One )

    #mongodb install (3.4.0) # Download installation package , decompression mkdir /data/mongodb cd /data/mongodb mkdir log conf data bin vim conf/mo ...

  7. PAT (Advanced Level) 1112. Stucked Keyboard (20)

    Find the characters that must be OK ( That is, a series of forehead characters x The number can be k Divisible ), The rest of the characters are probably problematic . #include<cstdio> #include<cstring> #include ...

  8. Hack Programming

    The computer consists of ROM(instruction memory).RAM(data memory).CPU form , The relationship is as follows Exist in calculation 3 A register :D.A.M. among D yes data register,A yes addr ...

  9. MySQL Caught tools :MySQL Sniffer【 turn 】

    This article is from :https://github.com/Qihoo360/mysql-sniffer brief introduction MySQL Sniffer It's based on MySQL Protocol capture tool , Grab in real time MySQLServer ...

  10. Java Floating point data in Float and Double The problem of making accurate calculations

    Java Floating point data in Float and Double The problem of making accurate calculations source   https://www.cnblogs.com/banxian/p/3781130.html One . Precision loss in floating point computation      ...