杰瑞科技汇

Python HttpRunner 怎么快速上手 API 自动化测试?

Of course! HttpRunner is a powerful and popular Python-based framework for API testing and automation. It's designed to be simple, intuitive, and highly productive, allowing you to write tests in a human-readable format and then run them.

Python HttpRunner 怎么快速上手 API 自动化测试?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering what HttpRunner is, its key features, how to install it, and a step-by-step tutorial to get you started.


What is HttpRunner?

HttpRunner is an open-source HTTP testing framework that can help you to:

  • Automate API Testing: Test RESTful APIs, GraphQL, WebSocket, and other web services.
  • Automate Web UI Testing: It can simulate user interactions on web pages (like clicking buttons, filling forms) by leveraging tools like playwright.
  • Performance Testing: Run tests with a high number of concurrent users to check your application's performance.
  • Service Integration Testing: Test the entire workflow of a microservice architecture by calling multiple services in sequence.

Its core philosophy is "Write Once, Run Anywhere". You write your test cases in a structured format (like YAML/JSON or Python), and HttpRunner can execute them.


Key Features

  • Human-Readable Test Cases: Write tests in YAML or JSON format, which is easy to read and understand, even for non-programmers.
  • Python as a Foundation: Test cases can also be written directly in Python, allowing for maximum flexibility and the use of the entire Python ecosystem.
  • Powerful Test Runner: The httprunner command-line tool can run single test files, entire test directories, or test suites with a single command.
  • Built-in Assertions: It comes with a rich set of built-in assertion methods to verify response status codes, headers, cookies, and response body content (JSON, HTML, XML).
  • Parameterization & Data-Driven Testing: Easily run the same test case with different sets of data using CSV, JSON, or Python lists.
  • Hooks: Use setup and teardown hooks to perform actions before and after test cases or test suites (e.g., creating test data, cleaning up databases).
  • Variables & Extractors: Extract values from a response (like a token or user_id) and use them as variables in subsequent requests.
  • Reports & Logs: Generate detailed HTML reports with charts, logs, and failure reasons. It also supports exporting results in JUnit XML format for CI/CD integration.
  • CI/CD Ready: Integrates seamlessly with continuous integration systems like Jenkins, GitLab CI, GitHub Actions, etc.

Installation

You can install HttpRunner using pip. It's recommended to install it in a virtual environment.

Python HttpRunner 怎么快速上手 API 自动化测试?-图2
(图片来源网络,侵删)
# Create a virtual environment (optional but recommended)
python -m venv httprunner_env
source httprunner_env/bin/activate  # On Windows: httprunner_env\Scripts\activate
# Install HttpRunner
pip install httprunner

Quick Start Tutorial: Your First API Test

Let's test a public API: JSONPlaceholder, a free fake REST API for testing.

Our goal is to:

  1. Create a new "todo" item.
  2. Verify that the response status code is 201.
  3. Verify that the response contains the correct data.
  4. Fetch the newly created "todo" item by its ID.
  5. Verify its title.

Step 1: Create a Test File

Create a file named test_create_todo.py and add the following Python code. HttpRunner uses classes and methods to define tests.

# test_create_todo.py
from httprunner import HttpRunner, Config, Step, HttpxRequest
class TestCaseCreateTodo(HttpRunner):
    config = (
        Config("Test create a new todo item")
        .base_url("https://jsonplaceholder.typicode.com")
        .export(*["todo_id"])  # Export the 'id' from the response to use in other tests
    )
    teststeps = [
        Step(
            "Create a new todo item",
            HttpxRequest(
                "POST /todos",
                json={
                    "title": "delectus aut autem",
                    "completed": False,
                    "userId": 1,
                },
            )
            .validate()
            .assert_equal("status_code", 201)
            .assert_equal("body.title", "delectus aut autem")
            .assert_equal("body.completed", False)
            .assert_equal("body.userId", 1),
        ),
        Step(
            "Get the created todo item",
            HttpxRequest(
                "GET /todos/${todo_id}", # Use the exported variable here
            )
            .validate()
            .assert_equal("status_code", 200)
            .assert_equal("body.title", "delectus aut autem"),
        ),
    ]
if __name__ == "__main__":
    TestCaseCreateTodo().test_start()

Explanation of the code:

Python HttpRunner 怎么快速上手 API 自动化测试?-图3
(图片来源网络,侵删)
  • Config: Defines the global configuration for the test case. Here, we set the base URL and export a variable named todo_id from the response of the first step.
  • Step: Represents a single step in your test, which is usually an HTTP request.
  • HttpxRequest: Defines the HTTP request. We specify the method (POST), path (/todos), and the JSON payload.
  • .validate(): This starts the validation chain for the response.
  • .assert_equal(...): This is the assertion. It checks if the value of a specific key in the response matches the expected value. The path body.title looks for the title key inside the JSON response body.
  • /todos/${todo_id}: This is a powerful feature. ${todo_id} is a variable that will be replaced by the value exported from the first step.

Step 2: Run the Test

Open your terminal in the same directory as test_create_todo.py and run:

python test_create_todo.py

Step 3: Check the Output and Report

You will see output in your terminal indicating that the tests passed or failed.

...
PASSED Test create a new todo item -> test_create_todo.py:10
PASSED Get the created todo item -> test_create_todo.py:30
...

HttpRunner also generates a detailed HTML report. By default, it's saved in the reports/ directory. Open reports/index.html in your browser to see a beautiful report with request details, response data, and assertions.


YAML Format (More Human-Readable)

HttpRunner also allows you to write tests in YAML, which is often preferred for teams that include non-developers. The same test case can be written as test_create_todo.yml:

# test_create_todo.yml
config:
  name: "Test create a new todo item (YAML)"
  base_url: "https://jsonplaceholder.typicode.com"
  export: ["todo_id"]
teststeps:
  - name: "Create a new todo item"
    request:
      method: POST
      url: /todos
      json:
        title: "delectus aut autem"
        completed: false
        userId: 1
    validate:
      - eq: ["status_code", 201]
      - eq: ["body.title", "delectus aut autem"]
      - eq: ["body.completed", false]
      - eq: ["body.userId", 1]
  - name: "Get the created todo item"
    request:
      method: GET
      url: /todos/${todo_id}
    validate:
      - eq: ["status_code", 200]
      - eq: ["body.title", "delectus aut autem"]

You can run this YAML file directly with the httprunner command:

httprunner test_create_todo.yml

When to Use HttpRunner?

Use HttpRunner when:

  • You need to automate API testing for a web service.
  • Your team includes both developers and QA engineers, and you want a format that is easy for everyone to understand (YAML).
  • You are building a microservice architecture and need to test the integration between services.
  • You want to include UI testing alongside your API tests in the same framework.
  • You need to generate professional-looking test reports for stakeholders.

Consider other tools if:

  • You are testing a complex desktop or mobile application (Selenium, Appium, Playwright might be more suitable for pure UI testing).
  • Your primary goal is load testing at a massive scale (tools like k6, Locust, or JMeter might be more performant for this specific purpose).
  • You are heavily invested in the Java ecosystem and prefer tools like RestAssured or Postman (though HttpRunner can be used from anywhere).

Summary

HttpRunner is a versatile and modern testing framework that bridges the gap between simple API tools and complex test automation suites. Its ability to use both Python and YAML, combined with powerful features like variable extraction and detailed reporting, makes it an excellent choice for teams looking to level up their API and web testing automation.

分享:
扫描分享到社交APP
上一篇
下一篇