Debian Codegraph @

tests/test_base.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import collections
4 import contextlib
5 import json
6 from typing import Any, Callable, Optional
7
8 import pytest
9
10 import consul.check
11
12 Request = collections.namedtuple("Request", ["method", "path", "params", "headers", "data"])
13
14
15 class HTTPClient:
16 def __init__(
17 self, host: Optional[str] = None, port: Optional[int] = None, scheme=None, verify: bool = True, cert=None
18 ) -> None:
19 self.host = host
20 self.port = int(port) if port else None
21 self.scheme = scheme
22 self.verify = verify
23 self.cert = cert
24
25 def get(self, callback, path, params=None, headers=None): # pylint: disable=unused-argument
26 return Request("get", path, params, headers, None)
27
28 def put(self, callback, path, params=None, headers=None, data: str = ""): # pylint: disable=unused-argument
29 return Request("put", path, params, headers, data)
30
31 def delete(self, callback, path, params=None, headers=None): # pylint: disable=unused-argument
32 return Request("delete", path, params, headers, None)
33
34
35 class Consul(consul.base.Consul):
36 def http_connect(self, host: str, port: int, scheme, verify: bool = True, cert=None):
37 return HTTPClient(host=host, port=port, scheme=scheme, verify=verify, cert=None)
38
39
40 def _should_support(c: Consul) -> tuple[Callable[..., Any], ...]:
41 return (
42 # kv
43 lambda **kw: c.kv.get("foo", **kw),
44 # catalog
45 c.catalog.nodes,
46 c.catalog.services,
47 lambda **kw: c.catalog.node("foo", **kw),
48 lambda **kw: c.catalog.service("foo", **kw),
49 # session
50 c.session.list,
51 lambda **kw: c.session.info("foo", **kw),
52 lambda **kw: c.session.node("foo", **kw),
53 )
54
55
56 def _should_support_node_meta(c: Consul) -> tuple[Callable[..., Any], ...]:
57 return (
58 # catalog
59 c.catalog.nodes,
60 c.catalog.services,
61 lambda **kw: c.catalog.service("foo", **kw),
62 lambda **kw: c.catalog.register("foo", "bar", **kw),
63 # health
64 lambda **kw: c.health.service("foo", **kw),
65 lambda **kw: c.health.checks("foo", **kw),
66 lambda **kw: c.health.state("unknown", **kw),
67 )
68
69
70 def _should_support_meta(c: Consul) -> tuple[Callable[..., Any], ...]:
71 return (
72 # agent
73 lambda **kw: c.agent.service.register("foo", **kw),
74 lambda **kw: c.agent.service.register("foo", "bar", **kw),
75 )
76
77
78 class TestBaseInit:
79 """
80 Tests that connection arguments are handled
81 """
82
83 @pytest.mark.parametrize(
84 ("env", "host", "port", "want"),
85 [
86 (
87 None,
88 None,
89 None,
90 {
91 "host": "127.0.0.1",
92 "port": 8500,
93 },
94 ),
95 (
96 "127.0.0.1:443",
97 None,
98 None,
99 {
100 "host": "127.0.0.1",
101 "port": 443,
102 },
103 ),
104 (
105 None,
106 "consul.domain.tld",
107 None,
108 {
109 "host": "consul.domain.tld",
110 "port": 8500,
111 },
112 ),
113 (
114 "consul.domain.tld:443",
115 "127.0.0.1",
116 None,
117 {
118 "host": "127.0.0.1",
119 "port": 8500,
120 },
121 ),
122 (
123 "consul.domain.tld:443",
124 "127.0.0.1",
125 8080,
126 {
127 "host": "127.0.0.1",
128 "port": 8080,
129 },
130 ),
131 (
132 "bad",
133 "127.0.0.1",
134 8080,
135 {
136 "host": "127.0.0.1",
137 "port": 8080,
138 },
139 ),
140 ],
141 )
142 def test_base_init_addr(self, monkeypatch, env, host, port, want) -> None:
143 if env:
144 monkeypatch.setenv("CONSUL_HTTP_ADDR", env)
145 else:
146 with contextlib.suppress(KeyError):
147 monkeypatch.delenv("CONSUL_HTTP_ADDR")
148
149 c = Consul(host=host, port=port)
150 assert c.http.host == want["host"]
151 assert c.http.port == want["port"]
152
153 @pytest.mark.parametrize(
154 ("env", "scheme", "want"),
155 [
156 ("true", None, "https"),
157 ("false", None, "http"),
158 (None, "https", "https"),
159 (None, "http", "http"),
160 ("http", "https", "https"),
161 ],
162 )
163 def test_base_init_scheme(self, monkeypatch, env, scheme, want) -> None:
164 if env:
165 monkeypatch.setenv("CONSUL_HTTP_SSL", env)
166 else:
167 with contextlib.suppress(KeyError):
168 monkeypatch.delenv("CONSUL_HTTP_SSL")
169
170 c = Consul(scheme=scheme)
171 assert c.http.scheme == want
172
173 @pytest.mark.parametrize(
174 ("env", "verify", "want"),
175 [
176 ("true", None, True),
177 (None, True, True),
178 ("false", True, True),
179 ],
180 )
181 def test_base_init_verify(self, monkeypatch, env, verify, want) -> None:
182 if env:
183 monkeypatch.setenv("CONSUL_HTTP_SSL_VERIFY", env)
184 else:
185 with contextlib.suppress(KeyError):
186 monkeypatch.delenv("CONSUL_HTTP_SSL_VERIFY")
187
188 c = Consul(verify=verify)
189 assert c.http.verify == want
190
191
192 class TestIndex:
193 """
194 Tests read requests that should support blocking on an index
195 """
196
197 def test_index(self) -> None:
198 c = Consul()
199 for r in _should_support(c):
200 assert r().params == []
201 assert r(index="5").params == [("index", "5")]
202
203
204 class TestConsistency:
205 """
206 Tests read requests that should support consistency modes
207 """
208
209 def test_explict(self) -> None:
210 c = Consul()
211 for r in _should_support(c):
212 assert r().params == []
213 assert r(consistency="default").params == []
214 assert r(consistency="consistent").params == [("consistent", "1")]
215 assert r(consistency="stale").params == [("stale", "1")]
216
217 def test_implicit(self) -> None:
218 c = Consul(consistency="consistent")
219 for r in _should_support(c):
220 assert r().params == [("consistent", "1")]
221 assert r(consistency="default").params == []
222 assert r(consistency="consistent").params == [("consistent", "1")]
223 assert r(consistency="stale").params == [("stale", "1")]
224
225
226 class TestNodemeta:
227 """
228 Tests read requests that should support node_meta
229 """
230
231 def test_node_meta(self) -> None:
232 c = Consul()
233 for r in _should_support_node_meta(c):
234 assert r().params == []
235 assert sorted(r(node_meta={"env": "prod", "net": 1}).params) == sorted([
236 ("node-meta", "net:1"),
237 ("node-meta", "env:prod"),
238 ])
239
240
241 class TestMeta:
242 """
243 Tests read requests that should support meta
244 """
245
246 def test_meta(self) -> None:
247 c = Consul()
248 for r in _should_support_meta(c):
249 d = json.loads(r(meta={"env": "prod", "net": 1}).data)
250 assert sorted(d["meta"]) == sorted({"env": "prod", "net": 1})
251
252
253 class TestChecks:
254 """
255 Check constructor helpers return valid check configurations.
256 """
257
258 @pytest.mark.parametrize(
259 ("url", "interval", "timeout", "deregister", "header", "want"),
260 [
261 (
262 "http://example.com",
263 "10s",
264 None,
265 None,
266 None,
267 {
268 "http": "http://example.com",
269 "interval": "10s",
270 },
271 ),
272 (
273 "http://example.com",
274 "10s",
275 "1s",
276 None,
277 None,
278 {
279 "http": "http://example.com",
280 "interval": "10s",
281 "timeout": "1s",
282 },
283 ),
284 (
285 "http://example.com",
286 "10s",
287 None,
288 "1m",
289 None,
290 {
291 "http": "http://example.com",
292 "interval": "10s",
293 "DeregisterCriticalServiceAfter": "1m",
294 },
295 ),
296 (
297 "http://example.com",
298 "10s",
299 "1s",
300 "1m",
301 None,
302 {
303 "http": "http://example.com",
304 "interval": "10s",
305 "timeout": "1s",
306 "DeregisterCriticalServiceAfter": "1m",
307 },
308 ),
309 (
310 "http://example.com",
311 "10s",
312 "1s",
313 "1m",
314 {"X-Test-Header": ["TestHeaderValue"]},
315 {
316 "http": "http://example.com",
317 "interval": "10s",
318 "timeout": "1s",
319 "DeregisterCriticalServiceAfter": "1m",
320 "header": {"X-Test-Header": ["TestHeaderValue"]},
321 },
322 ),
323 ],
324 )
325 def test_http_check(self, url, interval, timeout, deregister, header, want) -> None:
326 ch = consul.check.Check.http(url, interval, timeout=timeout, deregister=deregister, header=header)
327 assert ch == want
328
329 @pytest.mark.parametrize(
330 ("host", "port", "interval", "timeout", "deregister", "want"),
331 [
332 (
333 "localhost",
334 1234,
335 "10s",
336 None,
337 None,
338 {
339 "tcp": "localhost:1234",
340 "interval": "10s",
341 },
342 ),
343 (
344 "localhost",
345 1234,
346 "10s",
347 "1s",
348 None,
349 {
350 "tcp": "localhost:1234",
351 "interval": "10s",
352 "timeout": "1s",
353 },
354 ),
355 (
356 "localhost",
357 1234,
358 "10s",
359 None,
360 "1m",
361 {
362 "tcp": "localhost:1234",
363 "interval": "10s",
364 "DeregisterCriticalServiceAfter": "1m",
365 },
366 ),
367 (
368 "localhost",
369 1234,
370 "10s",
371 "1s",
372 "1m",
373 {
374 "tcp": "localhost:1234",
375 "interval": "10s",
376 "timeout": "1s",
377 "DeregisterCriticalServiceAfter": "1m",
378 },
379 ),
380 ],
381 )
382 def test_tcp_check(self, host: str, port: int, interval, timeout, deregister, want) -> None:
383 ch = consul.check.Check.tcp(host, port, interval, timeout=timeout, deregister=deregister)
384 assert ch == want
385
386 @pytest.mark.parametrize(
387 ("container_id", "shell", "script", "interval", "deregister", "want"),
388 [
389 (
390 "wandering_bose",
391 "/bin/sh",
392 "/bin/true",
393 "10s",
394 None,
395 {
396 "docker_container_id": "wandering_bose",
397 "shell": "/bin/sh",
398 "script": "/bin/true",
399 "interval": "10s",
400 },
401 ),
402 (
403 "wandering_bose",
404 "/bin/sh",
405 "/bin/true",
406 "10s",
407 "1m",
408 {
409 "docker_container_id": "wandering_bose",
410 "shell": "/bin/sh",
411 "script": "/bin/true",
412 "interval": "10s",
413 "DeregisterCriticalServiceAfter": "1m",
414 },
415 ),
416 ],
417 )
418 def test_docker_check(self, container_id, shell, script, interval, deregister, want) -> None:
419 ch = consul.check.Check.docker(container_id, shell, script, interval, deregister=deregister)
420 assert ch == want
421
422 def test_ttl_check(self) -> None:
423 ch = consul.check.Check.ttl("1m")
424 assert ch == {"ttl": "1m"}