Python Unit Test Pytest

Source: Internet
Author: User
Tags virtual environment continuous integration tools

1, Pytest Introduction

Pytest is a unit test framework for Python, similar to the UnitTest test framework that Python comes with, but is more concise and more efficient than the unittest framework.

    • Some tests can be skipped during the execution of the test, or marked as failed for some cases that are expected to fail
    • Ability to support simple unit tests and complex functional tests
    • A case that supports repeated execution failure
    • Support for running test case written by nose, unittest
    • has many third-party plug-ins and can customize the extension
    • Easy integration with continuous integration tools
    • Support Parameterization

2, Installation Pytest

Install Pytest

3. Example

(1) Single test case

To perform the test, we only need to run Py.test in the same directory as the test file test_sample. Pytest in the current directory and its subdirectories looking for a py file that starts with test or a py file ending with test (that is, a test file), after locating the test file, go to the test file and look for the test function at the beginning of the Test_ and execute it.

Create a new file in the current directory test_champ.py

def func (x):     return x + 1def  test_answer ():    assert func (3) ==5

Entering Py.test [-Q] on the command line, plus the-Q (quiet) output saves pytest version information, and you can see why the success and failure of the execution

(2) Multi-test case

When you need to write more than one test sample, we can put it into a test class, such as:

 class   TestClass:  def   Test_one (self):  assert   " h    in   "  This   " def   Test_two (self): x  = "  hello   " assert  hasattr (X, " check  " ) 

We can execute the above test by executing the test file method: Py.test-q test_class.py

4, Pytest test sample writing rules

Using the above 2 examples, we found that writing the Pytest test sample is very simple, just follow the rules below:
    • Test file begins with Test_ (ends with _test)
    • The test class starts with test and cannot have the __init__ method
    • Test function starts with Test_
    • Assert that you use basic assert

5. How to perform the Pytest test sample

There are many ways to execute a test sample, and the first instance above is to execute py.test directly, and the second instance is to pass the test file to Py.test. In fact, Py.test has several ways to perform tests:
Py.test#Run all tests below current dirPy.test test_mod.py#Run tests in modulePy.test Somepath#Run all tests below SomepathPy.test-k stringexpr#Only Run tests with names that match the                      #The "string expression", e.g. "MyClass and not Method"                      #Would select Testmyclass.test_something                      #But not testmyclass.test_method_simplePy.test Test_mod.py::test_func#Only Run tests that match the "node ID",                   #e.g "Test_mod.py::test_func" would select                               #Only Test_func in test_mod.py

6. Test Report

Pytest can easily generate test reports that can generate HTML test reports or generate XML-formatted test reports for integration with continuous integration tools.

Generate a TXT format report:

Generate reports in XML format:

Py.test--junitxml=path/log.xml  

Send the test report to the Pastebin server and execute the following command to generate the report URL

Send only failed reports

Generating HTML format reports

This third-party plug-in pytest-html needs to install Pytest:
Install pytest-

7. How to get help information

Py.test--version # shows where pytest is imported  fromfunction  arguments  file Options  

Similar to the setup and teardown in Python's unitest test framework, PYTEST provides fixture functions for necessary preparation and cleanup before and after the test is executed. However, the fixture function makes great improvements to setup and teardown.

    • The fixture function can be used in test functions, in test classes, in test files, and throughout the test project.
    • Fixture supports modularity, fixture can be nested with each other
    • Fixture Support Parameterization
    • Fixture supports unittest type of setup and teardown
Setup completes the pre-test initialization work and teardown the garbage back after the test is complete. If the test program uses JDBC to connect to the database, then the Setupbeforeclass () method can write some code that initializes the database connection, and the Teardownafterclass () method can write some code that closes the database connection.

8. Best Practices

In fact, for testing, especially in a continuous integration environment, all of our tests are best in a virtual environment. In this way, tests in different virtual environments do not interfere with each other. Because of our actual work, in the same jekins, there are many different kinds of project book tests, so each test project runs in its own virtual environment. Install Pytest in a virtual environment: 1. Create the current directory as a virtual environment
Virtualenv.        inch The current directory  Source bin

2. Install pytest in a virtual environment:

Install Pytest  

9. Use of assertions

① Normal Assertion

# Sub-signature class, ignoring the process of intermediate printing, directly indicating the cause of the error # Assert value = = 0, "value was odd, should is even  " # equal, unequal, less than, greater than assert func (2) ==3

② Exception Assertion

Using the Pytest.raise method (import pytest required)

An assertion of 1 divided by 0 will result in an exception of type Zerodivisionerror.

Import pytest   def test_zero_division (): With      pytest.raises (zerodivisionerror):          

Sometimes, we may need to use some of the information in the test to produce the exception, such as the type of the exception, the value of the exception, and so on. Let's revise the test above

Import pytest   def test_recursion_depth (): With      pytest.raises (zerodivisionerror) as Excinfo:      1/0        Assert'runtimeerror'  

The test failed because the test assertion produced an exception type of RuntimeError, and the exception type that was actually produced was Zerodivisionerror. In the test results, you can see the value of the Assert subexpression Excinfo.type.

Python Unit Test Pytest

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.