Detailed explanation of API testing using Pytest in Python automation practice

9cbc19c2690b4d83b49f5f78cb26ebdd.jpg


 

overview

 

Every time the API is manually tested, the same data needs to be entered repeatedly, and multiple test cases need to be run, which is very tedious and boring. So, is there a way you can test your API more efficiently? Pytest automated testing! Today, the editor will introduce you how to use Pytest for API automated testing.


 

What is API testing?

API testing is a software testing method used to test application programming interfaces (APIs) to ensure their functionality, reliability, performance, and security. Unlike other types of software testing, API testing focuses primarily on the functionality and performance of the API rather than the functionality and performance of the entire application. API testing can help developers and testers test APIs quickly and accurately, thereby improving development efficiency and software quality.

Pytest framework

Pytest is a popular Python testing framework for writing and running tests. Pytest has a simple and easy-to-use syntax that makes it easy to write various types of tests, including unit tests, integration tests, and API tests. Pytest also provides many useful features such as auto-discovery of tests, test repetition, test filtering and test reporting.

API testing with Pytest

Below, I will show you how to use the Pytest framework for API testing. I'll take the example of testing a simple API that takes two numbers and returns their sum. We will write a test case to test the API.

First, we need to install the Pytest framework. Enter the following command in the terminal to install Pytest:

pip install pytest

We need to write a test case. In this test case, we will use Python's requests library to send requests to the API and use assertions to verify that the API's response is correct. Here is the source code of the test case:

import requests

def test_addition():
    url = "http://localhost:5000/add"
    data = {"num1": 2, "num2": 3}
    response = requests.post(url, data=data)
    assert response.status_code == 200
    assert response.json() == {"result": 5}

In the above code, we first define a test function called test_addition. The function sends a POST request to the API using the requests library and takes two numbers as input data. We then use two assertions to verify that the API's response is correct. The first assertion verifies that the status code of the response is 200, while the second assertion verifies that the JSON data of the response is {"result": 5}.

Now, we can use Pytest to run this test case. Run the test by entering the following command in a terminal:

pytest test_api.py

If everything is fine, Pytest will output the test results and tell you whether the test passed or not. If a test fails, Pytest will display the failed test case and an error message.

advanced usage

1. Parametric testing

When testing, we often need to test different input data. If we use traditional testing methods, we need to write multiple test cases. But using pytest's parameterized test function, we can automatically generate multiple test cases through some parameters. This can greatly reduce our code volume and improve test efficiency.

Below is an example where we use parameterized tests to test multiple sets of inputs and outputs for a calculator function.

import pytest

@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (2, 3, 5),
    (3, 4, 7),
])
def test_add(a, b, expected):
    assert a + b == expected

In this example, we use the pytest.mark.parametrize decorator to specify parameters for a parameterized test. In a parameterized list, each set of parameters is a tuple, which contains the parameters of the function and the expected output value. pytest will automatically combine these parameters into multiple test cases and execute them sequentially.

2. Use of Fixtures

When testing, we often need to create some test data or test environment, then we can use the Fixture function of pytest. Fixture is a function that can provide test data or test environment, and we can use it through decorators in test cases.

The following is an example, we use Fixture to create a test environment, and then test.

import pytest

@pytest.fixture
def setup_environment():
    # 创建测试环境
    env = {'name': 'test'}
    yield env
    # 清理测试环境
    del env

def test_env(setup_environment):
    assert setup_environment['name'] == 'test'

In this example, we use the @pytest.fixture decorator to define the setup_environment function as a Fixture. In this function we can create the test environment and return it in the yield statement. In the test case, we can use the Fixture through the parameter name, and pytest will automatically pass the return value of the Fixture to the test case.

3. Custom plugins

pytest has many built-in plug-ins that can help us complete some common testing tasks. But in actual use, we often need more functions. At this time, we can use pytest's plug-in mechanism to customize the plug-in to meet our needs.

The following is an example, we use pytest's plug-in mechanism to customize a plug-in to output some information before the test case is executed.

import pytest

@pytest.hookimpl(tryfirst=True)
def pytest_runtest_logstart(nodeid):
    print(f"Running test {nodeid}...")

def test_example():
    assert 1 + 1 == 2

In this example, we use the @pytest.hookimpl decorator to define the pytest_runtest_logstart function as a plugin. In this function, we output the ID of the test case. Before the test case is executed, pytest will automatically call this plugin and output information.

 

Technical summary

This article introduces the concept of API testing and details how to use the Pytest framework for API testing. Hope this article can help you better understand API testing and how to use Python automated testing to improve testing efficiency and software quality. At the same time, I hope you can learn how to write and run API test cases through this example and a brief introduction to the Pytest framework.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/Rocky006/article/details/132131132