This article will mainly explain Python in pytest Explanation of the framework , Introduce what is pytest、 Why test 、 Why to use and reference and extend , In addition, there is a portal for a series of articles below , It's still being updated , Interested partners can also go to check , Don't talk much , Let's have a look ~
Series articles :
Series articles 1:【Python automated testing 1】 meet Python The beauty of the
Series articles 2:【Python automated testing 2】Python Installation configuration and PyCharm Basic use
Series articles 3:【Python automated testing 3】 First knowledge of data types and basic syntax
Series articles 4:【Python automated testing 4】 Summary of string knowledge
Series articles 5:【Python automated testing 5】 List and tuple knowledge summary
Series articles 6:【Python automated testing 6】 Dictionary and collective knowledge summary
Series articles 7:【Python automated testing 7】 Data operator knowledge collection
Series articles 8:【Python automated testing 8】 Explanation of process control statement
Series articles 9:【Python automated testing 9】 Function knowledge collection
Series articles 10:【Python automated testing 10】 File basic operation
Series articles 11:【Python automated testing 11】 modular 、 Package and path knowledge collection
Series articles 12:【Python automated testing 12】 Knowledge collection of exception handling mechanism
Series articles 13:【Python automated testing 13】 class 、 object 、 Collection of attribute and method knowledge
Series articles 14:【Python automated testing 14】Python Basic and advanced exercises of automatic test
Series articles 15:【Python automated testing 15】unittest The core concept and function of test framework
Series articles 16:【Python automated testing 16】 Test case data separation
Series articles 17:【Python automated testing 17】openpyxl Secondary packaging and data driven
Series articles 18:【Python automated testing 18】 Configuration file analysis and practical application
Series articles 19:【Python automated testing 19】 Log system logging Explain
Series articles 20:【Python automated testing 20】 Construction of interface automation test framework model
Series articles 21:【Python automated testing 21】 Interface automation test practice 1 _ Interface concept 、 Project introduction and test process Q & A
Series articles 22:【Python automated testing 22】 Interface automation test practice II _ Interface framework modification and use case optimization
Series articles 23:【Python automated testing 23】 Interface automation test practice III _ Dynamic parameterization and data forgery
Series articles 24:【Python automated testing 24】 Interface automation test practice IV _Python Operating the database
Series articles 25:【Python automated testing 25】 Interface automation test practice 5 _ Database assertion 、 Interface Association and related management optimization
pytest
Is a unit testing framework , During programming , A unit mainly refers to the smallest component of the code , For example, functions or classes , In object orientation , The smallest unit is the method under the class .
When we write a program , These functions and methods will be tested , Whether there is a program error , The process of testing the functions and methods of a program , It's called unit testing .pytest
The test framework for is similar to unittest
The frame is similar , but pytest
The test framework is better than unittest
More concise 、 Efficient , Concrete pytest
Basic introduction of , You can refer to :pytest Introduction
pytest
And unittest
similar , but pytest
There are still many advantages :
""" pytest advantage 1、pytest Compatible with unittest, If the previous use case is unittest Compiling , have access to pytest Direct use 2、pytest The assertion of directly uses assert Assertion , Not used self.asert And other kinds of assertions 3、pytest For failed test cases, very detailed error information is provided 4、pytest Test cases can be automatically discovered and collected 5、pytest There are very flexible fixture management 6、pytest Yes mark The tagging mechanism , Some use cases can be marked as smoke test cases 7、pytest It provides a very rich plug-in system 8、pytest No need to write classes ,unittest You need to write classes and inherit , here pytest More concise """
install pytest
Set the default runtime to pytest
:
def test_add():
assert True
The previous article mentioned , Framework means rules ,pytest
The use case rules are as follows :
""" pytest Use case rules : 1、 Module name test start .py ending , perhaps *_test.py 2、 The name of the test case function def test_XXX() 3、 You can leave the test class undefined """
""" pytest Mode of operation : 1、pycharm Run icon in ,pytest Start start run , If not pytest Can be in setting Search for pytest And set it to pytest Actuator 2、pytest Command line : To go to the root directory of the project and run pytest command ,pytest Command will automatically collect running instructions , Test cases that meet the requirements under all subdirectories , for example test_login.py, Module and test start , function test start , So is class 3、 adopt python Packages or python Module operation """
pytest
There are three modes of operation :
""" Mode one : Run directly through the triangle on the left side of the code (pycharm) """
""" Mode two : Run... From the command line -- pytest -- html=output.html """
""" Mode three : adopt python function """
from datetime import datetime
import pytest
date_str = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
# The name of the test report
report_name = date_str + " Mengxiaotian's exclusive test report .html"
pytest.main([f"--html={
report}"])
We all have smoke tests , Also know the smoke test case ,pytest
Support case filtering , You can mark the use cases you want , This is a smoke test case :
import pytest
# The format is :@pytest.mark. Custom tagnames
@pytest.mark.smoke
def test_True()
assert True
@pytest.mark.smoke
def test_False()
assert False
We can attach individual tags to a use case or multiple use cases , But it doesn't work , We need to register the tag first , Create a new one pytest.ini
And configure :
[pytest]
markers =
smoke
After registration, we need to run , Enter at the command line pytest - m "smoke"
, In this way, you can run the test case just marked , It is worth mentioning that , If this tag is on a function , It means that the function belongs to the filter case of the tag , If the tag is on a class , Then all the functions under the whole class belong to the filter case , As the example shows , That is, all smoke test cases
""" Use case screening process : 1、 Need to be in pytest.ini Register the name of the tag in 2、 Add... To the test case function or test case class @pytest.mark. Tagnames 3、 Run the specified label pytest -m " Tagnames " """
If you run multiple tags, you can continue to make new tags on the function or class again , for example login Mark , That means I just want to execute the smoke test case of the login module , Then register again and run , Run using pytest -m "smoke and login"
, If the smoke test case and the login module case meet one , Then you can use it or that will do , Choose one of the two , Meet and run
pytest
Data driven implementation can use unittest
To implement , You can also use your own ddt:
Be careful :pytest
Parameterization and unittest
Parameterization of can only have one , Cannot be used together
""" pytest Use unittest Data driven implementation """
import unittest
imoort pytest
from unittesetreport import ddt, list_data
@pytest.mark.smoke
@unittestreport.ddt
class TestAddwithUnittest(unittest.TestCase):
@unittestreport.list_data(["hello", "world", "mengxiaotian"])
def test_add_three(self, case_info):
aseert " Meng Xiaotian " in " The best cute smile "
def test_add_four(self):
assert " Meng Xiaotian " in " The best cute smile "
""" Use your own pytest Realization """
@pytest.mark.smoke
@pytest.mark.login
@pytest.mark.parametrize("case_info", ["hello", "world"])
def test_add(case_info):
assert True
pytest
The fixture will work with unittest
There are some differences , See the code for details. :
def setup_function():
""" precondition , Before each test case """
print("hello, world!")
def teardown_function():
""" Postcondition , After each test case """
def test_hello():
assert 520 == 1314
def test_world():
assert " ' " in " Meng Xiaotian "
import pytest
# Declare that this is a test fixture
@pytest.fixture()
def connet_to_db():
print(" precondition : Connecting to database ...")
yield # stay yield The front is the front
# Cleaning action
print(" Post cleaning , Disconnect the database ...")
@pytest.mark.usefixtures("connect_to_db")
def test_mengxiaotian_love():
assert 1314 == 1314
Universal Baidu search allure Enter into GitHub Download or click the hyperlink directly :allure download
find Download Wording , And click releases
adopt pip install allure-pytest
Installation
To generate a report, enter... On the command line :pytest --alluredir= Catalog
View reports using :allure serve Catalog
allure It can be translated into Chinese , How to view report data is not discussed here , Interested students can learn about
It will be more complicated if it is presented in code , The author directly uses notes to explain , If the previous project is unittest
The project can be converted into pytest
:
""" unittest turn pytest: 1、 Data driven ddt Switch to pytest The marking form of 2、unittest Of testcase Inheritance needs to be removed 3、self.asserEqual Need to repack 4、setUpclass Change to pytest setup_class ( Refer to the code above ) """
All right. ~ The above is all the content shared in this article , Have you learned ? I hope I can help you !