पाठ 24 / 27
API और अनुबंध का Testing
Unit, integration, contract और breaking-change tests को मिलाएँ।
भरोसे की परतें
API को कई स्तरों पर परखें। Unit tests व्यावसायिक तर्क ढकते हैं। Integration tests परीक्षण database के विरुद्ध असली HTTP endpoints बुलाते हैं और status codes, headers और bodies जाँचते हैं, error मामलों और auth/ownership नियमों समेत। Contract tests जाँचते हैं कि responses OpenAPI schema से मेल खाते हैं (और consumer-driven contracts, जैसे Pact, से कि API अब भी वह पूरा करता है जिसकी असली उपभोक्ता अपेक्षा रखते हैं)। CI में breaking-change जाँच नई spec की जारी spec से तुलना करती है (oasdiff जैसे tools यह करते हैं) और असंगत बदलावों पर pull request विफल करती है, जब तक नया version इरादतन न हो। Pagination की सीमाओं (ख़ाली, आख़िरी पन्ना), idempotent retries, rate-limit responses और webhook signature verification के tests जोड़ें। हर deploy के बाद production पर smoke test चलाएँ।
pytest में API tests (उदाहरण)
ये कोर्स में पहले दिखाए व्यवहार test client के विरुद्ध जाँचते हैं। client आपके framework का test client fixture है।
def test_idempotent_payment(client):
h = {"Idempotency-Key": "k-1"}
first = client.post("/v1/payments", json={"amount": 500}, headers=h)
again = client.post("/v1/payments", json={"amount": 500}, headers=h)
assert first.status_code == 201 and again.status_code == 200
assert first.json() == again.json()
assert again.headers["Idempotent-Replayed"] == "true"
def test_other_users_order_is_404(client, token_a, order_of_b):
r = client.get(f"/v2/orders/{order_of_b}", headers={"Authorization": f"Bearer {token_a}"})
assert r.status_code == 404
def test_last_page_has_null_cursor(client):
assert client.get("/v1/items?limit=100").json()["next_cursor"] is NoneTests में versions pin करें
हर समर्थित version के लिए एक test suite रखें। Version विदा करें तो उसके tests कोड के साथ हटाएँ, उससे पहले नहीं।
त्वरित जाँच: CI की breaking-change जाँच क्या करती है?
- पुराने versions हटाती है
- Production पर deploy करती है
- नई spec की जारी spec से तुलना करती है और असंगत बदलाव चिह्नित करती है
- Spec encrypt करती है
Answer
नई spec की जारी spec से तुलना करती है और असंगत बदलाव चिह्नित करती है — स्वचालित diff अनजाने तोड़ने वाले बदलावों को users तक पहुँचने से रोकता है।