Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Python testing Framework pytest

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the Python testing framework pytest how to use the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will get something after reading this Python testing framework pytest article, let's take a look at it.

A brief introduction to Pytest

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 that Pytest is a very mature full-function python testing framework, which mainly has the following characteristics:

Simple, flexible and easy to use

Support for parameterization

Supports simple unit testing and complex functional testing, and can also be used for automated testing

There are many third-party plug-ins, and you can customize the extension

Skip and xfail processing of test cases

It can be well integrated with Jenkins.

Support to run test cases written by Nose and UnitTest

II. Pytest installation

1. Install directly using the pip command:

Pip install-U pytest #-U automatically upgrades the latest version if installed

two。 Verify the installation results:

Pytest-- version # shows the current installation version C:\ Users\ edison > pytest-- versionpytest 6.2.5

3. In the pytest testing framework, the following constraints are followed:

The test file name should conform to the test_.py or _ test.py format (for example, test_min.py)

Test classes should start with Test and cannot have an init method

In a single test class, you can include one or more functions that begin with test_

III. Pytest test execution

Pytest is relatively easy to test. Let's take a look at an example:

Import pytest # Import pytest package def test_001 (): # function begins with test_ print ("test_01") def test_002 (): print ("test_02") if _ _ name__ = ='_ _ main__': pytest.main (["- v", "test_1214.py"]) # call pytest's main function to perform the test

Here we define two test functions, print the results directly, and execute the test below:

= 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.execachedir: .pytest _ cacherootdir: d:\ Codecollecting. Collected 2 itemstest_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 were executed, the corresponding test module, the number of passes, and the execution time.

4. Test class main function pytest.main (["- v", "test_1214.py"])

Execute pytest.main () through python code:

Execute pytest.main () directly [automatically find files in the current directory that begin with test_ or py files ending with _ test]

Set the execution parameter pytest.main (['- html=./report.html','test_login.py']) of pytest [execute the test_login.py file and generate a report in html format].

Execution parameters and plug-in parameters can be passed in main () parentheses, which are divided by [], and multiple parameters in [] are divided by 'comma,':

Run all use cases pytest.main (['directory name']) under the directory and subpackage

Run all use cases pytest.main (['test_reg.py']) of the specified module

Run the specified module to specify the class to specify the use case pytest.main (['test_reg.py::TestClass::test_method']) colon division

-m=xxx: run a tagged use case

-reruns=xxx: failed to rerun

-Q: quiet mode, no environmental information output

-v: rich information mode, output more detailed use case execution information

-s: displays the print/logging output in the program

-resultlog=./log.txt generates log

-junitxml=./log.xml generates xml report

5. Assertion method

Pytest assertions mainly use Python native assertion methods, which mainly include the following:

= content and type must be equal at the same time

The actual results of in include the expected results

Is asserts that two values are equal before and after.

Import pytest # Import pytest package def add (XMagi y): # define the function return x + ydef test_add (): assert add (1jue 2) = = 3 # asserting success str1 = "Python,Java,Ruby" def test_in (): assert "PHP" in str1 # asserting failure if _ _ name__ = ='_ main__': pytest.main (["- v") "test_pytest.py"]) # call the main function to 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.execachedir: .pytest _ cacherootdir: d:\ Codecollecting. Collected 2 itemstest_pytest.py::test_add PASSED [50] test_pytest.py::test_in FAILED [100%] = = FAILURES = = _ _ test_in _ _ _ def test_in (): > assert "PHP" in str1E 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 result of the run clearly indicates that the cause of the error is "AssertionError" because PHP is not in str1.

VI. Detailed explanation of commonly used commands

1. Run the specified case:

If _ _ name__ ='_ _ main__': pytest.main (["- v", "- s", "test_1214.py"])

two。 Run all use cases for the current folder, including subfolders:

If _ _ name__ ='_ _ main__': pytest.main (["- v", "- s", ". /"])

3. Run the specified folder (all use cases under the code directory):

If _ _ name__ ='_ _ main__': pytest.main (["- v", "- s", "code/"])

4. Specify the use case in the run module (test_add use case in the run module):

If _ _ name__ ='_ _ main__': pytest.main (["- v", "- s", "test_pytest.py::test_add"])

5. Maximum number of execution failures

Use the expression "- maxfail=num" to implement (note: there can be no spaces in the middle of the expression), indicating that the total number of use case failures is equal to num to stop running.

6. The error message is displayed on one line.

If there are many use case execution failures in a real project, it will be troublesome to view the error message. Using the "- tb=line" command, you can solve this problem very well.

7. Call the API

Write an interface to query user information locally, call it through pytest, 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"]) this is the end of the article on "how to use the Python testing Framework pytest". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to use the Python testing framework pytest". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report