# 别再手动测API了!用Python+pytest一周搞定自动化测试

> 作者:易先生 | API自动化测试工程师

---

如果你每次发版前都要手动测一遍接口,这篇文章就是为你写的。

## 痛点

- 接口改了,忘了通知测试,上线就炸
- 回归测试要一整天,没人愿意干
- 测试用例散落在Postman里,没法复用
- 老板问"自动化覆盖率多少",答不上来

## 解决方案:pytest + requests + Allure

### 第一步:环境准备

\`\`\`bash
pip install pytest requests allure-pytest
\`\`\`

### 第二步:项目结构

\`\`\`
api-tests/
├── conftest.py          # 公共配置
├── config.yaml          # 环境变量
├── test_cases/
│   └── test_user.py     # 测试用例
├── data/
│   └── user_data.json   # 测试数据
└── allure-results/      # 测试报告
\`\`\`

### 第三步:写第一个测试

\`\`\`python
import pytest
import requests

class TestUserAPI:
    BASE_URL = "https://api.example.com"
    
    def test_create_user(self):
        payload = {"name": "test", "email": "test@example.com"}
        resp = requests.post(f"{self.BASE_URL}/users", json=payload)
        
        assert resp.status_code == 201
        data = resp.json()
        assert data["name"] == "test"
        assert "id" in data
    
    def test_get_user_not_found(self):
        resp = requests.get(f"{self.BASE_URL}/users/99999")
        assert resp.status_code == 404
\`\`\`

### 第四步:数据驱动

\`\`\`python
import pytest
import json

class TestLoginAPI:
    
    @pytest.mark.parametrize("username,password,expected", [
        ("admin", "123456", 200),
        ("admin", "wrong", 401),
        ("", "123456", 400),
    ])
    def test_login(self, username, password, expected):
        resp = requests.post(
            "https://api.example.com/login",
            json={"username": username, "password": password}
        )
        assert resp.status_code == expected
\`\`\`

### 第五步:生成报告

\`\`\`bash
pytest --alluredir=allure-results
allure serve allure-results
\`\`\`

## 进阶:CI/CD集成

在GitHub Actions里加一步:

\`\`\`yaml
- name: Run API Tests
  run: |
    pip install pytest requests allure-pytest
    pytest --alluredir=allure-results
- name: Publish Allure Report
  uses: simple-elf/allure-report-action@master
  with:
    allure_results: allure-results
\`\`\`

## 总结

API自动化测试不是什么高深技术,**核心是先把框架搭起来,跑通第一个用例,后面就是复制粘贴的工作量。**

如果你连第一个用例都不想写,或者团队没人会搭框架——

**找我。** 2-3周,帮你搞定。

---

*关注我,下期讲:API自动化测试的数据驱动实战*

更多推荐