Build a Pytest API Automation Test Project from 0 to 1

1. Create a project directory

mkdir Pytest-API-Testing-Demo

2.Project initialization

// Go to the project folder
cd Pytest-API-Testing-Demo
// Create the project python project virtual environment
python -m venv .env
// Enable the project python project virtual environment
source .env/bin/activate

3.Install project dependencies

// Install the requests package
pip install requests
// Install the pytest package
pip install pytest
// Save the project dependencies to the requirements.txt file.
pip freeze > requirements.txt

4. Create new test files and test cases

// Create a new tests folder
mkdir tests
// Create a new test case file
cd tests

5. Writing Test Cases

The test API can be referred to the file in the project.

import requests

class TestPytestDemo:

    def test_get_demo(self):
        base_url = ""
        # SEND REQUEST
        response = requests.get(f"{base_url}/posts/1")
        # ASSERT
        assert response.status_code == 200
        assert response.json()['userId'] == 1
        assert response.json()['id'] == 1

    def test_post_demo(self):
        base_url = ""
        requests_data = {
            "title": "foo",
            "body": "bar",
            "userId": 1
        # SEND REQUEST
        response ="{base_url}/posts", requests_data)
        # ASSERT
        assert response.status_code == 201
        assert response.json()['userId'] == '1'
        assert response.json()['id'] == 101

6.Run test cases


7.View test report


8.Integration pytest-html-reporter test report

8.1 Install pytest-html-reporter dependency

pip install pytest-html-reporter 

8.2 Configuring Test Report Parameters

  • Create a new pytest.ini file in the project root directory.
  • Add the following
addopts = -vs -rf --html-report=./report --title='PYTEST REPORT' --self-contained-html

8.3 Run test cases


8.4 Viewing the test report

The report is located in the report directory in the project root directory, use your browser to open the pytest_html_report.html file to view it.