Pengujian API manual lambat, rawan salah ulang. Tim deploy fitur baru, API rusak, baru sadar saat user komplain. Solusi: otomatiskan. Python + pytest tangani dari smoke test sampai regression test. Artikel ini panduan praktis, siap pakai di CI.
📌 Baca Juga (Scripting & Automation): Membangun Sistem Monitoring Log Otomatis dengan Python dan Notifikasi Real-time
Mengapa Pytest untuk Pengujian API?
Pytest ringan, ekosistem besar, assertion bawaan jelas. Kombinasi python requests pytest jadi standar de facto. Requests tangani HTTP, pytest urus organisasi test, laporan, dan integrasi CI. Tidak perlu framework berat.
Persiapan Lingkungan
Install tiga dependensi:
pip install pytest requests jsonschema
Struktur proyek sederhana:
tests/
conftest.py
test_smoke.py
test_regression.py
pytest.ini
Fixture Dasar di conftest.py
Fixture bagikan sesi HTTP ke semua test. Hindari buat request berulang di tiap fungsi.
import pytest
import requests
@pytest.fixture(scope="session")
def client():
session = requests.Session()
session.base_url = "https://api.example.com"
yield session
Smoke Test API — Deteksi Dini Kerusakan
Smoke test cek satu hal: API hidup atau tidak. Cepat, minim asersi. Jalankan setelah deploy, sebelum test berat.
# tests/test_smoke.py
import requests
def test_health_check():
resp = requests.get("https://api.example.com/health", timeout=5)
assert resp.status_code == 200
def test_api_root_accessible():
resp = requests.get("https://api.example.com/", timeout=5)
assert resp.status_code < 500
Jalankan:
pytest tests/test_smoke.py -v
Gagal di sini = masalah infrastruktur, bukan logika bisnis. Tim tahu cepat.
Regression Test API — Lindungi Kontrak
Regression test pastikan perubahan kode tidak ubah perilaku API. Cek status code, struktur JSON, nilai penting. Ini inti pytest API testing.
Contoh Test Regresi
# tests/test_regression.py
def test_get_user_success(client):
resp = client.get("/users/1", timeout=5)
assert resp.status_code == 200
data = resp.json()
assert data["id"] == 1
assert "name" in data
assert "email" in data
def test_get_user_not_found(client):
resp = client.get("/users/99999", timeout=5)
assert resp.status_code == 404
def test_create_user(client):
payload = {"name": "Budi", "email": "budi@example.com"}
resp = client.post("/users", json=payload, timeout=5)
assert resp.status_code == 201
assert resp.json()["name"] == payload["name"]
Validasi JSON Schema
Asersi manual tidak cukup. Satu field hilang = KeyError membingungkan. JSON Schema validation beri pesan jelas: field apa hilang, tipe apa salah.
from jsonschema import validate
user_schema = {
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": {"type": "integer"},
"name": {"type": "string"},
"email": {"type": "string", "format": "email"}
}
}
def test_user_matches_schema(client):
resp = client.get("/users/1", timeout=5)
validate(resp.json(), user_schema)
Schema jadi kontrak tertulis. Backend ubah struktur, test gagal, diskusi muncul sebelum merge.
Siap CI — GitHub Actions
Test lokal tidak cukup. Otomatisasi pengujian API dengan pytest bernilai penuh saat jalan di CI. Workflow sederhana:
# .github/workflows/api-test.yml
name: API Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install pytest requests jsonschema
- run: pytest tests/ -v --tb=short
Pull request rusak = build merah. Developer perbaiki sebelum review. Otomatis, tanpa intervensi manusia.
Pisahkan Smoke dan Regression Test di CI
Smoke test cepat, jalan duluan. Regression test lengkap, jalan paralel atau setelahnya. Pakai marker pytest:
# pytest.ini
[pytest]
markers =
smoke: smoke test cepat, cek API hidup
regression: regression test penuh, cek kontrak
# tests/test_smoke.py
import pytest
@pytest.mark.smoke
def test_health_check():
...
Perintah run terpisah:
pytest -m smoke
pytest -m regression
Di CI, smoke test jalan di staging setelah deploy. Regression test jalan di setiap pull request.
Praktik Terbaik
- Base URL dari environment variable — jangan hardcode. CI pakai URL staging, lokal pakai localhost.
- Timeout di setiap request — API menggantung = test menggantung. Set
timeout=5. - Retry untuk flaky network — gunakan
requests.adapters.HTTPAdapterdenganRetry. - Fixture scope session — sekali login, reuse token. Hemat waktu.
- Laporan artefak — install
pytest-html, simpan laporan untuk audit CI. - Data test terisolasi — buat data khusus test, hapus setelah selesai. Jangan pakai data produksi.
💡 Baca Juga & Rekomendasi Jaringan AI Network:
- Gunakan racikan prompt profesional di SolusiAI.my.id (Rekomendasi Tools & Otomatisasi AI).
- Pelajari tutorial skrip dan otomatisasi teknis di PromptHack.my.id (Kumpulan AI Prompt & Content Growth).
Kesimpulan
Otomatisasi pengujian API dengan pytest bukan opsional lagi. Smoke test API tangkap kegagalan deploy dalam hitungan detik. Regression test API lindungi kontrak dari perubahan tak sengaja. JSON Schema validation perkuat asersi dengan pesan jelas. CI jalankan semuanya otomatis di setiap push.
Mulai kecil: satu smoke test, satu regression test. Perluas bertahap. Tim hemat waktu, API lebih stabil, user tidak jadi korban bug. Kode tersedia, tinggal jalankan.
Posting Komentar