krz/hutch-stats
Server-side utility for calculating contributions for sourcehut users.
clone: git clone https://gitbay.org/krz/hutch-stats.git
main: tests/test_srht_client.py · raw
1import httpx
2import pytest
3
4from srht_contrib.services.srht_client import SourceHutClientError, SourceHutGraphQLClient
5
6
7def test_graphql_client_retries_http_5xx_and_succeeds() -> None:
8 attempts = {"count": 0}
9
10 def handler(request: httpx.Request) -> httpx.Response:
11 attempts["count"] += 1
12 if attempts["count"] == 1:
13 return httpx.Response(502, json={"error": "bad gateway"})
14 return httpx.Response(200, json={"data": {"ok": True}})
15
16 client = SourceHutGraphQLClient(
17 "https://todo.sr.ht/query",
18 "token",
19 transport=httpx.MockTransport(handler),
20 )
21
22 data = client.execute("query Ping { ping }")
23
24 assert data == {"ok": True}
25 assert attempts["count"] == 2
26 client.close()
27
28
29def test_graphql_client_raises_for_graphql_errors() -> None:
30 client = SourceHutGraphQLClient(
31 "https://todo.sr.ht/query",
32 "token",
33 transport=httpx.MockTransport(lambda request: httpx.Response(200, json={"errors": [{"message": "nope"}]})),
34 )
35
36 with pytest.raises(SourceHutClientError):
37 client.execute("query Ping { ping }")
38
39 client.close()
40
41
42def test_graphql_client_raises_for_network_errors() -> None:
43 def handler(request: httpx.Request) -> httpx.Response:
44 raise httpx.ConnectError("offline", request=request)
45
46 client = SourceHutGraphQLClient(
47 "https://todo.sr.ht/query",
48 "token",
49 max_retries=0,
50 transport=httpx.MockTransport(handler),
51 )
52
53 with pytest.raises(SourceHutClientError):
54 client.execute("query Ping { ping }")
55
56 client.close()
57
58
59def test_graphql_client_applies_request_delay_and_retry_backoff(monkeypatch: pytest.MonkeyPatch) -> None:
60 attempts = {"count": 0}
61 sleeps: list[float] = []
62
63 def handler(request: httpx.Request) -> httpx.Response:
64 attempts["count"] += 1
65 if attempts["count"] < 3:
66 return httpx.Response(502, json={"error": "bad gateway"})
67 return httpx.Response(200, json={"data": {"ok": True}})
68
69 monkeypatch.setattr("srht_contrib.services.srht_client.time.sleep", sleeps.append)
70 client = SourceHutGraphQLClient(
71 "https://todo.sr.ht/query",
72 "token",
73 max_retries=2,
74 request_delay=0.5,
75 transport=httpx.MockTransport(handler),
76 )
77
78 data = client.execute("query Ping { ping }")
79
80 assert data == {"ok": True}
81 assert sleeps == [0.5, 1, 2]
82 client.close()