-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_base_helpers.py
More file actions
219 lines (179 loc) · 8.42 KB
/
Copy pathtest_base_helpers.py
File metadata and controls
219 lines (179 loc) · 8.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"""Tests for `_join_tickers` validation and null-envelope paginator coercion."""
from __future__ import annotations
import httpx
import pytest
import respx
from pydantic import BaseModel
from kalshi._base_client import AsyncTransport, SyncTransport
from kalshi.auth import KalshiAuth
from kalshi.config import KalshiConfig
from kalshi.errors import KalshiError
from kalshi.resources._base import AsyncResource, SyncResource, _join_tickers
class _Item(BaseModel):
id: str
class TestJoinTickersValidation:
def test_empty_element_in_list_raises(self) -> None:
with pytest.raises(ValueError, match=r"tickers\[1\] is empty"):
_join_tickers(["A", "", "B"])
def test_empty_element_in_tuple_raises(self) -> None:
with pytest.raises(ValueError, match=r"tickers\[0\] is empty"):
_join_tickers(("", "B"))
def test_embedded_comma_in_list_raises(self) -> None:
with pytest.raises(ValueError, match=r"contains a comma"):
_join_tickers(["FOO", "BAR,EVIL"])
def test_embedded_comma_in_tuple_raises(self) -> None:
with pytest.raises(ValueError, match=r"contains a comma"):
_join_tickers(("A,B", "C"))
def test_prejoined_string_passthrough_preserved(self) -> None:
assert _join_tickers("A,,B") == "A,,B"
assert _join_tickers("A,B,C") == "A,B,C"
def test_happy_path_still_works(self) -> None:
assert _join_tickers(["A", "B", "C"]) == "A,B,C"
assert _join_tickers(("A", "B")) == "A,B"
assert _join_tickers("A,B,C") == "A,B,C"
assert _join_tickers(None) is None
assert _join_tickers([]) is None
assert _join_tickers(()) is None
assert _join_tickers("") is None
def test_non_string_bool_element_raises_unhelpful_type_error(self) -> None:
# Pins crash path: bool fails `"," in elem` check; update if validation is added.
with pytest.raises(TypeError, match=r"argument of type 'bool' is not iterable"):
_join_tickers([True, "A"]) # type: ignore[list-item]
def test_non_string_int_element_raises_unhelpful_type_error(self) -> None:
"""Mirror of the bool case: int element crashes the same way."""
with pytest.raises(TypeError, match=r"argument of type 'int' is not iterable"):
_join_tickers((1, "A")) # type: ignore[arg-type]
class TestSyncListNullItemsCoercion:
@respx.mock
def test_null_items_key_returns_empty_page(
self, test_auth: KalshiAuth, test_config: KalshiConfig
) -> None:
respx.get("https://test.kalshi.com/trade-api/v2/things").mock(
return_value=httpx.Response(200, json={"items": None, "cursor": ""})
)
resource = SyncResource(SyncTransport(test_auth, test_config))
page = resource._list("/things", _Item, "items")
assert page.items == []
assert page.has_next is False
@respx.mock
def test_null_items_key_stops_list_all(
self, test_auth: KalshiAuth, test_config: KalshiConfig
) -> None:
respx.get("https://test.kalshi.com/trade-api/v2/things").mock(
return_value=httpx.Response(200, json={"items": None, "cursor": ""})
)
resource = SyncResource(SyncTransport(test_auth, test_config))
collected = list(resource._list_all("/things", _Item, "items"))
assert collected == []
@respx.mock
def test_missing_items_key_still_returns_empty(
self, test_auth: KalshiAuth, test_config: KalshiConfig
) -> None:
respx.get("https://test.kalshi.com/trade-api/v2/things").mock(
return_value=httpx.Response(200, json={"cursor": ""})
)
resource = SyncResource(SyncTransport(test_auth, test_config))
page = resource._list("/things", _Item, "items")
assert page.items == []
class TestAsyncListNullItemsCoercion:
@respx.mock
@pytest.mark.asyncio
async def test_null_items_key_returns_empty_page(
self, test_auth: KalshiAuth, test_config: KalshiConfig
) -> None:
respx.get("https://test.kalshi.com/trade-api/v2/things").mock(
return_value=httpx.Response(200, json={"items": None, "cursor": ""})
)
resource = AsyncResource(AsyncTransport(test_auth, test_config))
page = await resource._list("/things", _Item, "items")
assert page.items == []
assert page.has_next is False
@respx.mock
@pytest.mark.asyncio
async def test_null_items_key_stops_list_all(
self, test_auth: KalshiAuth, test_config: KalshiConfig
) -> None:
respx.get("https://test.kalshi.com/trade-api/v2/things").mock(
return_value=httpx.Response(200, json={"items": None, "cursor": ""})
)
resource = AsyncResource(AsyncTransport(test_auth, test_config))
collected: list[_Item] = []
async for item in resource._list_all("/things", _Item, "items"):
collected.append(item)
assert collected == []
@respx.mock
@pytest.mark.asyncio
async def test_missing_items_key_still_returns_empty(
self, test_auth: KalshiAuth, test_config: KalshiConfig
) -> None:
respx.get("https://test.kalshi.com/trade-api/v2/things").mock(
return_value=httpx.Response(200, json={"cursor": ""})
)
resource = AsyncResource(AsyncTransport(test_auth, test_config))
page = await resource._list("/things", _Item, "items")
assert page.items == []
class TestSyncListAllCursorLoopDetection:
@respx.mock
def test_repeated_cursor_raises(
self, test_auth: KalshiAuth, test_config: KalshiConfig
) -> None:
"""Server that returns the same cursor twice must bail fast, not retry 1000x."""
route = respx.get("https://test.kalshi.com/trade-api/v2/things").mock(
return_value=httpx.Response(
200, json={"items": [{"id": "x"}], "cursor": "loop"}
)
)
resource = SyncResource(SyncTransport(test_auth, test_config))
with pytest.raises(KalshiError, match=r"[Cc]ursor loop.*'loop'"):
list(resource._list_all("/things", _Item, "items"))
# First call (no cursor) fetches cursor="loop". Second call (cursor=loop) returns
# cursor="loop" again → loop detected before a third request. Total: 2 requests,
# not 1000.
assert route.call_count == 2
@respx.mock
def test_multi_page_loop_raises(
self, test_auth: KalshiAuth, test_config: KalshiConfig
) -> None:
"""A → B → A revisit also trips detection."""
responses = [
httpx.Response(200, json={"items": [{"id": "1"}], "cursor": "A"}),
httpx.Response(200, json={"items": [{"id": "2"}], "cursor": "B"}),
httpx.Response(200, json={"items": [{"id": "3"}], "cursor": "A"}),
]
respx.get("https://test.kalshi.com/trade-api/v2/things").mock(
side_effect=responses
)
resource = SyncResource(SyncTransport(test_auth, test_config))
with pytest.raises(KalshiError, match=r"[Cc]ursor loop.*'A'"):
list(resource._list_all("/things", _Item, "items"))
@respx.mock
def test_normal_pagination_does_not_trip(
self, test_auth: KalshiAuth, test_config: KalshiConfig
) -> None:
"""Regression guard: healthy two-page pagination must not raise."""
responses = [
httpx.Response(200, json={"items": [{"id": "1"}], "cursor": "A"}),
httpx.Response(200, json={"items": [{"id": "2"}], "cursor": ""}),
]
respx.get("https://test.kalshi.com/trade-api/v2/things").mock(
side_effect=responses
)
resource = SyncResource(SyncTransport(test_auth, test_config))
collected = list(resource._list_all("/things", _Item, "items"))
assert [item.id for item in collected] == ["1", "2"]
class TestAsyncListAllCursorLoopDetection:
@respx.mock
@pytest.mark.asyncio
async def test_repeated_cursor_raises(
self, test_auth: KalshiAuth, test_config: KalshiConfig
) -> None:
route = respx.get("https://test.kalshi.com/trade-api/v2/things").mock(
return_value=httpx.Response(
200, json={"items": [{"id": "x"}], "cursor": "loop"}
)
)
resource = AsyncResource(AsyncTransport(test_auth, test_config))
with pytest.raises(KalshiError, match=r"[Cc]ursor loop.*'loop'"):
async for _ in resource._list_all("/things", _Item, "items"):
pass
assert route.call_count == 2