|
| 1 | +import pytest |
| 2 | + |
| 3 | +from aikido_zen.context import current_context, get_current_context |
| 4 | +from aikido_zen.context.apply_or_bypass import apply_context_or_bypass |
| 5 | +from aikido_zen.storage import bypassed_context_store |
| 6 | +from aikido_zen.test_utils.context_utils import generate_context |
| 7 | +from aikido_zen.thread.thread_cache import get_cache |
| 8 | + |
| 9 | + |
| 10 | +@pytest.fixture(autouse=True) |
| 11 | +def _reset_state(): |
| 12 | + yield |
| 13 | + current_context.set(None) |
| 14 | + bypassed_context_store.clear() |
| 15 | + cache = get_cache() |
| 16 | + if cache: |
| 17 | + cache.reset() |
| 18 | + |
| 19 | + |
| 20 | +def _set_bypass_list(ips): |
| 21 | + cache = get_cache() |
| 22 | + cache.config.bypassed_ips = _IPMatcherStub(ips) |
| 23 | + |
| 24 | + |
| 25 | +class _IPMatcherStub: |
| 26 | + def __init__(self, ips): |
| 27 | + self._ips = set(ips) |
| 28 | + |
| 29 | + def has(self, ip): |
| 30 | + return ip in self._ips |
| 31 | + |
| 32 | + |
| 33 | +def test_non_bypassed_ip_sets_context_and_clears_flag(): |
| 34 | + _set_bypass_list({"9.9.9.9"}) |
| 35 | + bypassed_context_store.set_bypassed(True) # stale value from previous request |
| 36 | + |
| 37 | + ctx = generate_context(ip="1.2.3.4") |
| 38 | + apply_context_or_bypass(ctx) |
| 39 | + |
| 40 | + assert get_current_context() is ctx |
| 41 | + assert bypassed_context_store.is_bypassed() is False |
| 42 | + |
| 43 | + |
| 44 | +def test_bypassed_ip_clears_context_and_sets_flag(): |
| 45 | + _set_bypass_list({"1.2.3.4"}) |
| 46 | + |
| 47 | + ctx = generate_context(ip="1.2.3.4") |
| 48 | + apply_context_or_bypass(ctx) |
| 49 | + |
| 50 | + assert get_current_context() is None |
| 51 | + assert bypassed_context_store.is_bypassed() is True |
| 52 | + |
| 53 | + |
| 54 | +def test_no_remote_address_falls_through_to_set_context(): |
| 55 | + _set_bypass_list({"1.2.3.4"}) |
| 56 | + |
| 57 | + ctx = generate_context() |
| 58 | + ctx.remote_address = None |
| 59 | + apply_context_or_bypass(ctx) |
| 60 | + |
| 61 | + assert get_current_context() is ctx |
| 62 | + assert bypassed_context_store.is_bypassed() is False |
| 63 | + |
| 64 | + |
| 65 | +def test_bypass_then_non_bypass_resets_flag(): |
| 66 | + _set_bypass_list({"1.2.3.4"}) |
| 67 | + |
| 68 | + ctx_bypassed = generate_context(ip="1.2.3.4") |
| 69 | + apply_context_or_bypass(ctx_bypassed) |
| 70 | + assert bypassed_context_store.is_bypassed() is True |
| 71 | + |
| 72 | + ctx_normal = generate_context(ip="9.9.9.9") |
| 73 | + apply_context_or_bypass(ctx_normal) |
| 74 | + assert get_current_context() is ctx_normal |
| 75 | + assert bypassed_context_store.is_bypassed() is False |
0 commit comments