From f8d04a2a5accbc2982a49e9f4bbf2815f6ce233d Mon Sep 17 00:00:00 2001 From: Matthew Keeler Date: Thu, 5 Nov 2026 14:02:39 -0500 Subject: [PATCH] test: Run the client-level tests on the FDv2 data system The evaluation, events, hooks, listeners, fork, singleton, migration and async client tests no longer inject data through the FDv1 data system. They use FDv2 daemon mode over the test's store, or TestDataV2 as a synchronizer. Tests that check FDv1 behavior on purpose stay until FDv1 is removed. Also add client-level FDv2 tests over a real HTTP server: streaming, polling and the default strategy, retry after a recoverable error, a 401 at start, TLS settings, HTTP proxies, offline and daemon modes, and evaluation with the FDv2 file data source and TestDataV2. Two tests are marked xfail: a network error during polling removes the polling synchronizer. --- ldclient/testing/test_async_client.py | 130 ++---- .../test_async_ldclient_end_to_end_fdv2.py | 122 ++++++ ldclient/testing/test_ldclient.py | 76 ++-- .../testing/test_ldclient_end_to_end_fdv2.py | 388 ++++++++++++++++++ ldclient/testing/test_ldclient_evaluation.py | 15 +- ldclient/testing/test_ldclient_events.py | 4 +- ldclient/testing/test_ldclient_fork.py | 13 +- ldclient/testing/test_ldclient_hooks.py | 38 +- ldclient/testing/test_ldclient_listeners.py | 27 +- ldclient/testing/test_ldclient_singleton.py | 37 +- 10 files changed, 681 insertions(+), 169 deletions(-) create mode 100644 ldclient/testing/test_async_ldclient_end_to_end_fdv2.py create mode 100644 ldclient/testing/test_ldclient_end_to_end_fdv2.py diff --git a/ldclient/testing/test_async_client.py b/ldclient/testing/test_async_client.py index 5d3f17aa..f02ae83c 100644 --- a/ldclient/testing/test_async_client.py +++ b/ldclient/testing/test_async_client.py @@ -9,12 +9,13 @@ import pytest from ldclient.async_client import AsyncLDClient -from ldclient.async_config import AsyncConfig +from ldclient.async_config import AsyncConfig, AsyncDataSystemConfig from ldclient.context import Context +from ldclient.integrations.test_datav2 import TestDataV2 +from ldclient.interfaces import DataStoreMode from ldclient.testing.mock_async_components import ( MockAsyncEventProcessor, - MockAsyncFeatureStore, - MockAsyncUpdateProcessor + MockAsyncFeatureStore ) from ldclient.versioned_data_kind import FEATURES @@ -24,6 +25,26 @@ def _offline_config(**kwargs): return AsyncConfig("test-sdk-key", offline=True, **kwargs) +def _test_data_config(td=None, **kwargs): + """Return an AsyncConfig whose FDv2 data system syncs from TestDataV2.""" + if td is None: + td = TestDataV2.data_source() + return AsyncConfig( + "test-sdk-key", + datasystem_config=AsyncDataSystemConfig(synchronizers=[td.async_builder]), + **kwargs, + ) + + +def _daemon_config(store, **kwargs): + """Return an AsyncConfig whose FDv2 data system reads only from the given store.""" + return AsyncConfig( + "test-sdk-key", + datasystem_config=AsyncDataSystemConfig(data_store=store, data_store_mode=DataStoreMode.READ_ONLY), + **kwargs, + ) + + def _make_flag(key: str, value, version: int = 1) -> dict: """Build a minimal feature flag dict usable with AsyncInMemoryFeatureStore.""" return { @@ -54,27 +75,17 @@ async def test_default_variation_returns_default_when_not_started(): @pytest.mark.asyncio async def test_variation_returns_flag_value_when_initialized(): - """After start(), variation() returns the stored flag value. + """After start(), variation() returns the flag value from the data source. - We use update_processor_class=MockAsyncUpdateProcessor so that the client - considers itself initialized (store.initialized becomes True once the - NullUpdateProcessor fires ready) without any network connection. + TestDataV2 supplies the flag without any network connection, so the + client initializes as soon as the synchronizer delivers its basis. """ - store = MockAsyncFeatureStore() - flag = _make_flag('my-flag', 'hello') - await store.force_set(FEATURES, flag) - # Pre-initialize the store so is_initialized() returns True - store._initialized = True + td = TestDataV2.data_source() + td.update(td.flag('my-flag').value_for_all('hello')) - # Use MockAsyncUpdateProcessor which sets ready immediately - config = AsyncConfig( - "test-sdk-key", - feature_store=store, - update_processor_class=MockAsyncUpdateProcessor, - send_events=False, - ) - client = AsyncLDClient(config) + client = AsyncLDClient(_test_data_config(td, send_events=False)) await client.start(start_wait=1.0) + assert await client.is_initialized() context = Context.create('user-1') result = await client.variation('my-flag', context, 'default') @@ -117,12 +128,7 @@ async def test_context_manager(): @pytest.mark.asyncio async def test_flush_delegates_to_event_processor(): """flush() calls flush() on the underlying event processor.""" - config = AsyncConfig( - "test-sdk-key", - update_processor_class=MockAsyncUpdateProcessor, - send_events=False, - ) - client = AsyncLDClient(config) + client = AsyncLDClient(_test_data_config(send_events=False)) await client.start() # Replace the event processor with a mock that tracks flush calls @@ -243,18 +249,10 @@ async def test_flag_tracker_available_before_start(): @pytest.mark.asyncio async def test_variation_detail_returns_reason(): """variation_detail() returns an EvaluationDetail with a non-None reason.""" - store = MockAsyncFeatureStore() - flag = _make_flag('detail-flag', 'hello') - await store.force_set(FEATURES, flag) - store._initialized = True + td = TestDataV2.data_source() + td.update(td.flag('detail-flag').value_for_all('hello')) - config = AsyncConfig( - "test-sdk-key", - feature_store=store, - update_processor_class=MockAsyncUpdateProcessor, - send_events=False, - ) - async with AsyncLDClient(config) as client: + async with AsyncLDClient(_test_data_config(td, send_events=False)) as client: context = Context.create('user-1') detail = await client.variation_detail('detail-flag', context, 'fallback') @@ -266,14 +264,8 @@ async def test_variation_detail_returns_reason(): @pytest.mark.asyncio async def test_track_sends_event(): """track() sends a custom event to the event processor.""" - store = MockAsyncFeatureStore() - store._initialized = True - mock_ep = MockAsyncEventProcessor() - config = AsyncConfig( - "test-sdk-key", - feature_store=store, - update_processor_class=MockAsyncUpdateProcessor, + config = _test_data_config( event_processor_class=lambda _cfg: mock_ep, send_events=True, ) @@ -292,16 +284,7 @@ async def test_track_sends_event(): @pytest.mark.asyncio async def test_data_source_status_provider_accessible(): """data_source_status_provider is not None after start().""" - store = MockAsyncFeatureStore() - store._initialized = True - - config = AsyncConfig( - "test-sdk-key", - feature_store=store, - update_processor_class=MockAsyncUpdateProcessor, - send_events=False, - ) - async with AsyncLDClient(config) as client: + async with AsyncLDClient(_test_data_config(send_events=False)) as client: assert client.data_source_status_provider is not None @@ -311,12 +294,7 @@ async def test_is_offline_reflects_config(): async with AsyncLDClient(_offline_config()) as client: assert client.is_offline() is True - config = AsyncConfig( - "test-sdk-key", - update_processor_class=MockAsyncUpdateProcessor, - send_events=False, - ) - async with AsyncLDClient(config) as client: + async with AsyncLDClient(_test_data_config(send_events=False)) as client: assert client.is_offline() is False @@ -438,13 +416,7 @@ async def test_all_flags_state_returns_flag_values(): 'flag-b': _make_flag('flag-b', 'value-b'), }}) - config = AsyncConfig( - "test-sdk-key", - feature_store=store, - update_processor_class=MockAsyncUpdateProcessor, - send_events=False, - ) - async with AsyncLDClient(config) as client: + async with AsyncLDClient(_daemon_config(store, send_events=False)) as client: context = Context.create('user-1') state = await client.all_flags_state(context) @@ -469,13 +441,7 @@ async def test_all_flags_state_degrades_gracefully_when_evaluator_raises(): 'flag-bad-last': _make_flag('flag-bad-last', 'y'), }}) - config = AsyncConfig( - "test-sdk-key", - feature_store=store, - update_processor_class=MockAsyncUpdateProcessor, - send_events=False, - ) - async with AsyncLDClient(config) as client: + async with AsyncLDClient(_daemon_config(store, send_events=False)) as client: async def fake_evaluate(flag, context, event_factory): if flag['key'].startswith('flag-bad'): raise RuntimeError("boom") @@ -503,25 +469,15 @@ async def fake_evaluate(flag, context, event_factory): assert 'prerequisites' not in flags_state['flag-bad-first'] -class UninitializedAsyncUpdateProcessor(MockAsyncUpdateProcessor): - def initialized(self) -> bool: - return False - - @pytest.mark.asyncio async def test_cached_data_warnings_are_logged_once_per_client(caplog): caplog.set_level(logging.WARNING, logger='ldclient.util') store = MockAsyncFeatureStore() await store.force_set(FEATURES, _make_flag('my-flag', 'hello')) - store._initialized = True - config = AsyncConfig( - "test-sdk-key", - feature_store=store, - update_processor_class=UninitializedAsyncUpdateProcessor, - send_events=False, - ) - client = AsyncLDClient(config) + # Daemon mode reports cached data, so every evaluation reads last known values. + client = AsyncLDClient(_daemon_config(store, send_events=False)) await client.start(start_wait=1.0) + assert await client.is_initialized() context = Context.create('user-1') assert await client.variation('my-flag', context, 'default') == 'hello' diff --git a/ldclient/testing/test_async_ldclient_end_to_end_fdv2.py b/ldclient/testing/test_async_ldclient_end_to_end_fdv2.py new file mode 100644 index 00000000..3fa5a6af --- /dev/null +++ b/ldclient/testing/test_async_ldclient_end_to_end_fdv2.py @@ -0,0 +1,122 @@ +""" +End-to-end tests of the async client on the FDv2 data system, run against a +mock HTTP server. +""" + +import time + +import pytest + +from ldclient.async_client import AsyncLDClient +from ldclient.async_config import AsyncConfig, AsyncDataSystemConfig +from ldclient.client import Context +from ldclient.impl.datasourcev2.async_polling import ( + AsyncPollingDataSourceBuilder +) +from ldclient.impl.datasourcev2.async_streaming import ( + AsyncStreamingDataSourceBuilder +) +from ldclient.testing.http_util import ( + BasicResponse, + CauseNetworkError, + SequentialHandler, + start_server +) +from ldclient.testing.test_ldclient_end_to_end_fdv2 import ( + always_true_flag, + poll_response, + sdk_key, + stream_response +) + +user = Context.from_dict({'key': 'userkey', 'kind': 'user'}) + + +def make_config(uri, synchronizer): + return AsyncConfig( + sdk_key, + base_uri=uri, + stream_uri=uri, + send_events=False, + datasystem_config=AsyncDataSystemConfig(synchronizers=[synchronizer]), + ) + + +@pytest.mark.asyncio +async def test_async_client_starts_in_streaming_mode(): + with start_server() as server: + with stream_response([always_true_flag]) as stream: + server.for_path('/sdk/stream', stream) + + async with AsyncLDClient(make_config(server.uri, AsyncStreamingDataSourceBuilder())) as client: + assert await client.is_initialized() + assert await client.variation(always_true_flag['key'], user, False) is True + + r = server.await_request() + assert r.path == '/sdk/stream' + assert r.headers['Authorization'] == sdk_key + + +@pytest.mark.asyncio +async def test_async_client_starts_in_polling_mode(): + with start_server() as server: + server.for_path('/sdk/poll', poll_response([always_true_flag])) + + async with AsyncLDClient(make_config(server.uri, AsyncPollingDataSourceBuilder())) as client: + assert await client.is_initialized() + assert await client.variation(always_true_flag['key'], user, False) is True + + r = server.await_request() + assert r.path == '/sdk/poll' + assert r.headers['Authorization'] == sdk_key + + +@pytest.mark.asyncio +async def test_async_client_fails_fast_in_streaming_mode_with_401_error(): + with start_server() as server: + server.for_path('/sdk/stream', BasicResponse(401)) + + start_wait = 10 + client = AsyncLDClient(make_config(server.uri, AsyncStreamingDataSourceBuilder())) + try: + started = time.monotonic() + await client.start(start_wait=start_wait) + # A 401 turns the data source off, which releases start() early. + assert time.monotonic() - started < start_wait / 2 + assert not await client.is_initialized() + assert await client.variation(always_true_flag['key'], user, False) is False + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_async_client_fails_fast_in_polling_mode_with_401_error(): + with start_server() as server: + server.for_path('/sdk/poll', BasicResponse(401)) + + start_wait = 10 + client = AsyncLDClient(make_config(server.uri, AsyncPollingDataSourceBuilder())) + try: + started = time.monotonic() + await client.start(start_wait=start_wait) + assert time.monotonic() - started < start_wait / 2 + assert not await client.is_initialized() + assert await client.variation(always_true_flag['key'], user, False) is False + finally: + await client.close() + + +@pytest.mark.xfail( + reason='AsyncPollingDataSource.sync lets a requester exception escape, so a network error removes the synchronizer', + strict=True, +) +@pytest.mark.asyncio +async def test_async_client_retries_poll_after_network_error(): + with start_server() as server: + server.for_path('/sdk/poll', SequentialHandler( + CauseNetworkError(), CauseNetworkError(), CauseNetworkError(), poll_response([always_true_flag]))) + builder = AsyncPollingDataSourceBuilder().poll_interval(0.05) + + async with AsyncLDClient(make_config(server.uri, builder)) as client: + assert await client.is_initialized() + assert await client.variation(always_true_flag['key'], user, False) is True diff --git a/ldclient/testing/test_ldclient.py b/ldclient/testing/test_ldclient.py index 6ce5442a..bec5fa85 100644 --- a/ldclient/testing/test_ldclient.py +++ b/ldclient/testing/test_ldclient.py @@ -1,16 +1,26 @@ import pytest +from ldclient import datasystem from ldclient.client import Config, Context, LDClient +from ldclient.datasystem import DataStoreMode from ldclient.feature_store import InMemoryFeatureStore from ldclient.impl.datasource.polling import PollingUpdateProcessor from ldclient.impl.datasource.streaming import StreamingUpdateProcessor from ldclient.impl.stubs import NullUpdateProcessor -from ldclient.interfaces import UpdateProcessor +from ldclient.impl.util import _Success +from ldclient.interfaces import ( + Basis, + BasisResult, + ChangeSetBuilder, + IntentCode, + ObjectKind, + Selector, + SelectorStore +) from ldclient.testing.builders import * from ldclient.testing.stub_util import ( CapturingFeatureStore, - MockEventProcessor, - MockUpdateProcessor + MockEventProcessor ) from ldclient.versioned_data_kind import FEATURES, SEGMENTS @@ -31,8 +41,7 @@ def make_client(store=InMemoryFeatureStore()): events_uri=unreachable_uri, stream_uri=unreachable_uri, event_processor_class=MockEventProcessor, - update_processor_class=MockUpdateProcessor, - feature_store=store, + datasystem_config=datasystem.daemon(store).build(), ) ) @@ -42,7 +51,7 @@ def make_offline_client(): def make_ldd_client(): - return LDClient(config=Config(sdk_key="secret", use_ldd=True, base_uri=unreachable_uri, events_uri=unreachable_uri, stream_uri=unreachable_uri)) + return LDClient(config=Config(sdk_key="secret", datasystem_config=datasystem.daemon(InMemoryFeatureStore()).build(), base_uri=unreachable_uri, events_uri=unreachable_uri, stream_uri=unreachable_uri)) def get_first_event(c): @@ -63,7 +72,8 @@ def test_client_has_null_update_processor_in_offline_mode(): def test_client_has_null_update_processor_in_ldd_mode(): - with make_ldd_client() as client: + config = Config(sdk_key="secret", use_ldd=True, base_uri=unreachable_uri, events_uri=unreachable_uri, stream_uri=unreachable_uri) + with LDClient(config=config) as client: assert isinstance(client._data_system._update_processor, NullUpdateProcessor) @@ -98,8 +108,7 @@ def test_defaults_and_online(): base_uri="http://localhost:3000", defaults={"foo": expected}, event_processor_class=MockEventProcessor, - update_processor_class=MockUpdateProcessor, - feature_store=InMemoryFeatureStore(), + datasystem_config=datasystem.daemon(InMemoryFeatureStore()).build(), ) ) actual = my_client.variation('foo', user, default="originalDefault") @@ -107,7 +116,7 @@ def test_defaults_and_online(): def test_defaults_and_online_no_default(): - my_client = LDClient(config=Config("SDK_KEY", base_uri="http://localhost:3000", defaults={"foo": "bar"}, event_processor_class=MockEventProcessor, update_processor_class=MockUpdateProcessor)) + my_client = LDClient(config=Config("SDK_KEY", base_uri="http://localhost:3000", defaults={"foo": "bar"}, event_processor_class=MockEventProcessor, datasystem_config=datasystem.daemon(InMemoryFeatureStore()).build())) assert "jim" == my_client.variation('baz', user, default="jim") @@ -125,34 +134,49 @@ def test_secure_mode_hash(): assert client.secure_mode_hash(equivalent_user_to_hash) == expected_hash +# Items carry the fields the in-memory store needs to decode them. dependency_ordering_test_data = { FEATURES: { - "a": {"key": "a", "prerequisites": [{"key": "b"}, {"key": "c"}]}, - "b": {"key": "b", "prerequisites": [{"key": "c"}, {"key": "e"}]}, - "c": {"key": "c"}, - "d": {"key": "d"}, - "e": {"key": "e"}, - "f": {"key": "f"}, + "a": {"key": "a", "version": 1, "prerequisites": [{"key": "b", "variation": 0}, {"key": "c", "variation": 0}]}, + "b": {"key": "b", "version": 1, "prerequisites": [{"key": "c", "variation": 0}, {"key": "e", "variation": 0}]}, + "c": {"key": "c", "version": 1}, + "d": {"key": "d", "version": 1}, + "e": {"key": "e", "version": 1}, + "f": {"key": "f", "version": 1}, }, - SEGMENTS: {"o": {"key": "o"}}, + SEGMENTS: {"o": {"key": "o", "version": 1}}, } -class DependencyOrderingDataUpdateProcessor(UpdateProcessor): - def __init__(self, config, store, ready): - store.init(dependency_ordering_test_data) - ready.set() +class DependencyOrderingDataInitializer: + # Returns the unordered test data set as a persistable full transfer. + @property + def name(self) -> str: + return "DependencyOrderingDataInitializer" + + def fetch(self, ss: SelectorStore) -> BasisResult: + builder = ChangeSetBuilder() + builder.start(IntentCode.TRANSFER_FULL) + for kind, object_kind in ((FEATURES, ObjectKind.FLAG), (SEGMENTS, ObjectKind.SEGMENT)): + for key, item in dependency_ordering_test_data[kind].items(): + builder.add_put(object_kind, key, item['version'], item) + change_set = builder.finish(Selector.new_selector("state", 1)) + return _Success(Basis(change_set=change_set, persist=True, environment_id=None)) - def start(self): - pass - def initialized(self): - return True +class DependencyOrderingDataInitializerBuilder: + def build(self, config): + return DependencyOrderingDataInitializer() def test_store_data_set_ordering(): store = CapturingFeatureStore() - config = Config(sdk_key='SDK_KEY', send_events=False, feature_store=store, update_processor_class=DependencyOrderingDataUpdateProcessor) + # The data system sorts the data set when it writes to a READ_WRITE store. + datasystem_config = datasystem.custom() \ + .initializers([DependencyOrderingDataInitializerBuilder()]) \ + .data_store(store, DataStoreMode.READ_WRITE) \ + .build() + config = Config(sdk_key='SDK_KEY', send_events=False, datasystem_config=datasystem_config) LDClient(config=config) data = store.received_data diff --git a/ldclient/testing/test_ldclient_end_to_end_fdv2.py b/ldclient/testing/test_ldclient_end_to_end_fdv2.py new file mode 100644 index 00000000..0bc24f76 --- /dev/null +++ b/ldclient/testing/test_ldclient_end_to_end_fdv2.py @@ -0,0 +1,388 @@ +""" +End-to-end tests of the sync client on the FDv2 data system, run against a +mock HTTP server. +""" + +import json +import os +import tempfile +import time + +import pytest + +from ldclient import datasystem +from ldclient.client import Context, LDClient +from ldclient.config import Config, HTTPConfig +from ldclient.feature_store import InMemoryFeatureStore +from ldclient.integrations.test_datav2 import TestDataV2 +from ldclient.testing.http_util import ( + BasicResponse, + CauseNetworkError, + ChunkedResponse, + JsonResponse, + SequentialHandler, + start_secure_server, + start_server +) +from ldclient.versioned_data_kind import FEATURES, SEGMENTS + +sdk_key = 'sdk-key' +user = Context.from_dict({'key': 'userkey', 'kind': 'user'}) +always_true_flag = {'key': 'flagkey', 'version': 1, 'on': False, 'offVariation': 1, 'variations': [False, True]} +selfsigned_cert = './ldclient/testing/selfsigned.pem' + +# An unreachable host. The proxy tests rely on the proxy, not this host, to answer. +not_real_uri = 'http://not-real' + + +def fdv2_events(flags): + """Return the FDv2 events for a full transfer of the given flags.""" + events = [{ + 'event': 'server-intent', + 'data': {'payloads': [{'id': 'p1', 'target': 1, 'intentCode': 'xfer-full', 'reason': 'payload-missing'}]}, + }] + for flag in flags: + events.append({ + 'event': 'put-object', + 'data': {'kind': 'flag', 'key': flag['key'], 'version': flag['version'], 'object': flag}, + }) + events.append({ + 'event': 'payload-transferred', + 'data': {'state': '(p:p1:1)', 'id': 'p1', 'version': 1}, + }) + return events + + +def poll_response(flags): + """Return a poll response that carries a full transfer of the given flags.""" + return JsonResponse({'events': fdv2_events(flags)}) + + +def stream_response(flags): + """Return an open SSE stream that sends a full transfer of the given flags.""" + stream = ChunkedResponse({'Content-Type': 'text/event-stream'}) + for e in fdv2_events(flags): + stream.push('event: %s\ndata: %s\n\n' % (e['event'], json.dumps(e['data']))) + return stream + + +def make_config(uri, builder, **kwargs): + return Config( + sdk_key, + base_uri=uri, + stream_uri=uri, + send_events=False, + datasystem_config=builder.build(), + **kwargs, + ) + + +def test_client_starts_in_streaming_mode(): + with start_server() as server: + with stream_response([always_true_flag]) as stream: + server.for_path('/sdk/stream', stream) + + with LDClient(config=make_config(server.uri, datasystem.streaming())) as client: + assert client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is True + + r = server.await_request() + assert r.path == '/sdk/stream' + assert r.headers['Authorization'] == sdk_key + + +def test_client_starts_in_polling_mode(): + with start_server() as server: + server.for_path('/sdk/poll', poll_response([always_true_flag])) + + with LDClient(config=make_config(server.uri, datasystem.polling())) as client: + assert client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is True + + r = server.await_request() + assert r.path == '/sdk/poll' + assert r.headers['Authorization'] == sdk_key + + +def test_default_mode_polls_then_streams(): + with start_server() as server: + with stream_response([always_true_flag]) as stream: + server.for_path('/sdk/poll', poll_response([always_true_flag])) + server.for_path('/sdk/stream', stream) + + with LDClient(config=make_config(server.uri, datasystem.default())) as client: + assert client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is True + + first = server.await_request() + assert first.path == '/sdk/poll' + assert first.headers['Authorization'] == sdk_key + + # The stream carries the basis from the poll as a query parameter. + second = server.await_request() + assert second.path.startswith('/sdk/stream') + assert second.headers['Authorization'] == sdk_key + + +def test_client_retries_stream_after_recoverable_error(): + with start_server() as server: + with stream_response([always_true_flag]) as stream: + server.for_path('/sdk/stream', SequentialHandler(BasicResponse(503), stream)) + config = make_config(server.uri, datasystem.streaming(), initial_reconnect_delay=0.001) + + with LDClient(config=config) as client: + assert client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is True + + assert server.await_request().path == '/sdk/stream' + assert server.await_request().path == '/sdk/stream' + + +@pytest.mark.xfail( + reason='PollingDataSource.sync lets a requester exception escape, so a network error removes the synchronizer', + strict=True, +) +def test_client_retries_poll_after_network_error(): + with start_server() as server: + # The requester retries once per poll, so two errors fail the whole first poll. + server.for_path('/sdk/poll', SequentialHandler( + CauseNetworkError(), CauseNetworkError(), CauseNetworkError(), poll_response([always_true_flag]))) + builder = datasystem.custom().synchronizers(datasystem.polling_ds_builder().poll_interval(0.05)) + + with LDClient(config=make_config(server.uri, builder)) as client: + assert client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is True + + +def test_client_fails_fast_in_streaming_mode_with_401_error(): + with start_server() as server: + server.for_path('/sdk/stream', BasicResponse(401)) + + start_wait = 10 + started = time.monotonic() + with LDClient(config=make_config(server.uri, datasystem.streaming()), start_wait=start_wait) as client: + # A 401 turns the data source off, which releases the constructor early. + assert time.monotonic() - started < start_wait / 2 + assert not client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is False + + +def test_client_fails_fast_in_polling_mode_with_401_error(): + with start_server() as server: + server.for_path('/sdk/poll', BasicResponse(401)) + + start_wait = 10 + started = time.monotonic() + with LDClient(config=make_config(server.uri, datasystem.polling()), start_wait=start_wait) as client: + assert time.monotonic() - started < start_wait / 2 + assert not client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is False + + +def test_cannot_connect_with_selfsigned_cert_by_default(): + with start_secure_server() as server: + server.for_path('/sdk/poll', poll_response([])) + + with LDClient(config=make_config(server.uri, datasystem.polling()), start_wait=1) as client: + assert not client.is_initialized() + + +def test_can_connect_with_selfsigned_cert_if_disable_ssl_verification_is_true(): + with start_secure_server() as server: + server.for_path('/sdk/poll', poll_response([])) + config = make_config(server.uri, datasystem.polling(), http=HTTPConfig(disable_ssl_verification=True)) + + with LDClient(config=config) as client: + assert client.is_initialized() + + +def test_can_connect_with_selfsigned_cert_by_setting_ca_certs(): + with start_secure_server() as server: + server.for_path('/sdk/poll', poll_response([])) + config = make_config(server.uri, datasystem.polling(), http=HTTPConfig(ca_certs=selfsigned_cert)) + + with LDClient(config=config) as client: + assert client.is_initialized() + + +def test_can_stream_with_selfsigned_cert_if_disable_ssl_verification_is_true(): + with start_secure_server() as server: + with stream_response([always_true_flag]) as stream: + server.for_path('/sdk/stream', stream) + config = make_config(server.uri, datasystem.streaming(), http=HTTPConfig(disable_ssl_verification=True)) + + with LDClient(config=config) as client: + assert client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is True + + +def test_polling_goes_through_http_proxy(): + with start_server() as proxy: + # A proxied request names the absolute target URI as its path. + proxy.for_path(not_real_uri + '/sdk/poll', poll_response([always_true_flag])) + config = make_config(not_real_uri, datasystem.polling(), http=HTTPConfig(http_proxy=proxy.uri)) + + with LDClient(config=config) as client: + assert client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is True + + r = proxy.await_request() + assert r.method == 'GET' + assert r.path == not_real_uri + '/sdk/poll' + + +def test_streaming_goes_through_http_proxy(): + with start_server() as proxy: + with stream_response([always_true_flag]) as stream: + proxy.for_path(not_real_uri + '/sdk/stream', stream) + config = make_config(not_real_uri, datasystem.streaming(), http=HTTPConfig(http_proxy=proxy.uri)) + + with LDClient(config=config) as client: + assert client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is True + + r = proxy.await_request() + assert r.method == 'GET' + assert r.path == not_real_uri + '/sdk/stream' + + +def test_proxy_receives_proxy_authorization_header(): + with start_server() as proxy: + proxy.for_path(not_real_uri + '/sdk/poll', poll_response([])) + proxy_uri = proxy.uri.replace('http://', 'http://user:pass@') + config = make_config(not_real_uri, datasystem.polling(), http=HTTPConfig(http_proxy=proxy_uri)) + + with LDClient(config=config) as client: + assert client.is_initialized() + + r = proxy.await_request() + assert r.headers.get('Proxy-Authorization') == 'Basic dXNlcjpwYXNz' + + +def test_https_request_tunnels_through_http_proxy(): + with start_server() as proxy: + # The mock proxy cannot complete a tunnel, so the test only checks the CONNECT. + config = make_config('https://not-real', datasystem.polling(), http=HTTPConfig(http_proxy=proxy.uri)) + + with LDClient(config=config, start_wait=0): + assert proxy.await_request().method == 'CONNECT' + + +def test_offline_mode_makes_no_requests_and_returns_defaults(): + with start_server() as server: + server.for_path('/sdk/poll', poll_response([always_true_flag])) + server.for_path('/sdk/stream', BasicResponse(401)) + config = make_config(server.uri, datasystem.default(), offline=True) + + with LDClient(config=config) as client: + assert client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is False + + assert server.requests.empty() + + +def test_daemon_mode_evaluates_from_store_and_makes_no_requests(): + store = InMemoryFeatureStore() + store.init({FEATURES: {always_true_flag['key']: always_true_flag}, SEGMENTS: {}}) + + with start_server() as server: + server.for_path('/sdk/poll', poll_response([])) + server.for_path('/sdk/stream', BasicResponse(401)) + + with LDClient(config=make_config(server.uri, datasystem.daemon(store))) as client: + assert client.is_initialized() + assert client.variation(always_true_flag['key'], user, False) is True + + assert server.requests.empty() + + +file_flags_json = ''' + { + "flags": { + "flag1": { + "key": "flag1", + "on": true, + "fallthrough": { + "variation": 2 + }, + "variations": [ "fall", "off", "on" ] + } + }, + "flagValues": { + "flag2": "value2" + } + } +''' + + +def make_temp_file(content): + f, path = tempfile.mkstemp() + os.write(f, content.encode('utf-8')) + os.close(f) + return path + + +def file_client(path): + builder = datasystem.custom().synchronizers(datasystem.file_ds_builder([path])) + return LDClient(config=Config(sdk_key, send_events=False, datasystem_config=builder.build())) + + +def test_evaluates_full_flag_from_file_data_source(): + path = make_temp_file(file_flags_json) + try: + with file_client(path) as client: + assert client.is_initialized() + assert client.variation('flag1', user, '') == 'on' + finally: + os.remove(path) + + +def test_evaluates_simplified_flag_from_file_data_source(): + path = make_temp_file(file_flags_json) + try: + with file_client(path) as client: + assert client.variation('flag2', user, '') == 'value2' + finally: + os.remove(path) + + +def make_test_data_client(td): + builder = datasystem.custom().synchronizers(td.builder) + return LDClient(config=Config(sdk_key, send_events=False, datasystem_config=builder.build())) + + +def rule_flag(td): + return td.flag(key='test-flag').fallthrough_variation(False).if_match('firstName', 'Mike').and_not_match('country', 'gb').then_return(True) + + +def test_evaluates_flag_from_test_data_v2(): + td = TestDataV2.data_source() + td.update(rule_flag(td)) + + with make_test_data_client(td) as client: + # The first context matches the rule. + user1 = Context.from_dict({'kind': 'user', 'key': 'user1', 'firstName': 'Mike', 'country': 'us'}) + eval1 = client.variation_detail('test-flag', user1, default='default') + assert eval1.value is True + assert eval1.variation_index == 0 + assert eval1.reason['kind'] == 'RULE_MATCH' + + # The second context fails the firstName clause and falls through. + user2 = Context.from_dict({'kind': 'user', 'key': 'user2', 'firstName': 'Joe', 'country': 'us'}) + eval2 = client.variation_detail('test-flag', user2, default='default') + assert eval2.value is False + assert eval2.variation_index == 1 + assert eval2.reason['kind'] == 'FALLTHROUGH' + + +def test_evaluates_all_flags_from_test_data_v2(): + td = TestDataV2.data_source() + td.update(rule_flag(td)) + + with make_test_data_client(td) as client: + user1 = Context.from_dict({'kind': 'user', 'key': 'user1', 'firstName': 'Mike', 'country': 'us'}) + flags_state = client.all_flags_state(user1, with_reasons=True) + + assert flags_state.valid + assert flags_state.get_flag_value('test-flag') is True + assert (flags_state.get_flag_reason('test-flag') or {}).get('kind') == 'RULE_MATCH' diff --git a/ldclient/testing/test_ldclient_evaluation.py b/ldclient/testing/test_ldclient_evaluation.py index 0fdb2378..059cc613 100644 --- a/ldclient/testing/test_ldclient_evaluation.py +++ b/ldclient/testing/test_ldclient_evaluation.py @@ -1,6 +1,7 @@ import logging import time +from ldclient import datasystem from ldclient.client import Config, Context, LDClient from ldclient.config import BigSegmentsConfig from ldclient.evaluation import BigSegmentsStatus, EvaluationDetail @@ -10,7 +11,7 @@ from ldclient.interfaces import FeatureStore from ldclient.testing.builders import * from ldclient.testing.mock_components import MockBigSegmentStore -from ldclient.testing.stub_util import MockEventProcessor, MockUpdateProcessor +from ldclient.testing.stub_util import MockEventProcessor from ldclient.testing.test_ldclient import make_client, unreachable_uri, user from ldclient.versioned_data_kind import FEATURES, SEGMENTS @@ -167,7 +168,7 @@ def test_flag_using_big_segment(): segstore = MockBigSegmentStore() segstore.setup_metadata_always_up_to_date() segstore.setup_membership(_hash_for_user_key(user['key']), {_make_big_segment_ref(segment): True}) - config = Config(sdk_key='SDK_KEY', feature_store=store, big_segments=BigSegmentsConfig(store=segstore), event_processor_class=MockEventProcessor, update_processor_class=MockUpdateProcessor) + config = Config(sdk_key='SDK_KEY', datasystem_config=datasystem.daemon(store).build(), big_segments=BigSegmentsConfig(store=segstore), event_processor_class=MockEventProcessor) with LDClient(config) as client: detail = client.variation_detail(flag['key'], user, False) assert detail.value is True @@ -446,12 +447,9 @@ def fake_evaluate(flag, context, event_factory): assert 'prerequisites' not in metadata['bad-last'] -class UninitializedUpdateProcessor(MockUpdateProcessor): - def initialized(self): - return False - - def make_client_with_cached_data(store): + # Daemon mode never receives data from a data source, so the client serves + # cached values from the store. return LDClient( config=Config( sdk_key='SDK_KEY', @@ -459,8 +457,7 @@ def make_client_with_cached_data(store): events_uri=unreachable_uri, stream_uri=unreachable_uri, event_processor_class=MockEventProcessor, - update_processor_class=UninitializedUpdateProcessor, - feature_store=store, + datasystem_config=datasystem.daemon(store).build(), ) ) diff --git a/ldclient/testing/test_ldclient_events.py b/ldclient/testing/test_ldclient_events.py index 3bc25917..c78d7f72 100644 --- a/ldclient/testing/test_ldclient_events.py +++ b/ldclient/testing/test_ldclient_events.py @@ -1,3 +1,4 @@ +from ldclient import datasystem from ldclient.client import Config, Context, LDClient from ldclient.evaluation import EvaluationDetail from ldclient.feature_store import InMemoryFeatureStore @@ -11,7 +12,6 @@ from ldclient.migrations import Operation, OpTracker, Origin, Stage from ldclient.migrations.tracker import MigrationOpEvent from ldclient.testing.builders import * -from ldclient.testing.stub_util import MockUpdateProcessor from ldclient.testing.test_ldclient import ( context, make_client, @@ -41,7 +41,7 @@ def test_client_has_null_event_processor_if_offline(): def test_client_has_null_event_processor_if_send_events_off(): - config = Config(sdk_key="secret", base_uri=unreachable_uri, update_processor_class=MockUpdateProcessor, send_events=False) + config = Config(sdk_key="secret", base_uri=unreachable_uri, datasystem_config=datasystem.daemon(InMemoryFeatureStore()).build(), send_events=False) with LDClient(config=config) as client: assert isinstance(client._event_processor, NullEventProcessor) diff --git a/ldclient/testing/test_ldclient_fork.py b/ldclient/testing/test_ldclient_fork.py index 0608f393..3f52860a 100644 --- a/ldclient/testing/test_ldclient_fork.py +++ b/ldclient/testing/test_ldclient_fork.py @@ -13,7 +13,9 @@ import pytest +from ldclient import datasystem from ldclient.client import Config, Context, LDClient +from ldclient.integrations.test_datav2 import TestDataV2 from ldclient.migrations import Stage from ldclient.testing.stub_util import MockEventProcessor, MockUpdateProcessor @@ -31,7 +33,7 @@ def make_config(**kwargs) -> Config: events_uri=unreachable_uri, stream_uri=unreachable_uri, event_processor_class=MockEventProcessor, - update_processor_class=MockUpdateProcessor, + datasystem_config=datasystem.custom().synchronizers(TestDataV2.data_source().builder).build(), ) params.update(kwargs) return Config(**params) @@ -41,6 +43,11 @@ def make_client(**kwargs) -> LDClient: return LDClient(config=make_config(**kwargs), start_wait=0) +def make_ldd_client(**kwargs) -> LDClient: + # The fork check keys on use_ldd, which only the FDv1 data system honors. + return make_client(use_ldd=True, datasystem_config=None, update_processor_class=MockUpdateProcessor, **kwargs) + + def fork_warnings(caplog) -> list: return [r for r in caplog.records if r.levelno == logging.WARNING and WARNING_TEXT in r.getMessage()] @@ -179,7 +186,7 @@ def test_no_warning_in_offline_mode(caplog, monkeypatch): def test_no_warning_in_ldd_mode_with_events_disabled(caplog, monkeypatch): - with make_client(use_ldd=True, send_events=False) as client: + with make_ldd_client(send_events=False) as client: pretend_forked(monkeypatch) client.variation("flag", context, False) client.identify(context) @@ -188,7 +195,7 @@ def test_no_warning_in_ldd_mode_with_events_disabled(caplog, monkeypatch): def test_warns_in_ldd_mode_with_events_enabled(caplog, monkeypatch): - with make_client(use_ldd=True, send_events=True) as client: + with make_ldd_client(send_events=True) as client: pretend_forked(monkeypatch) client.variation("flag", context, False) assert len(fork_warnings(caplog)) == 1 diff --git a/ldclient/testing/test_ldclient_hooks.py b/ldclient/testing/test_ldclient_hooks.py index dcf085db..56c0759e 100644 --- a/ldclient/testing/test_ldclient_hooks.py +++ b/ldclient/testing/test_ldclient_hooks.py @@ -1,9 +1,9 @@ from typing import Callable -from ldclient import Config, Context, LDClient +from ldclient import Config, Context, LDClient, datasystem from ldclient.evaluation import EvaluationDetail from ldclient.hook import EvaluationSeriesContext, Hook, Metadata -from ldclient.integrations.test_data import TestData +from ldclient.integrations.test_datav2 import TestDataV2 from ldclient.migrations import Stage @@ -30,6 +30,10 @@ def after_evaluation(self, series_context: EvaluationSeriesContext, data: dict, return self.__after_evaluation(series_context, data, detail) +def datasystem_config(td: TestDataV2): + return datasystem.custom().synchronizers(td.builder).build() + + user = Context.from_dict({'key': 'userkey', 'kind': 'user'}) @@ -41,7 +45,7 @@ def test_verify_hook_execution_order(): clientHook1 = MockHook(before_evaluation=record('clientHook1::before', calls), after_evaluation=record('clientHook1::after', calls)) clientHook2 = MockHook(before_evaluation=record('clientHook2::before', calls), after_evaluation=record('clientHook2::after', calls)) - config = Config('SDK_KEY', update_processor_class=TestData.data_source(), send_events=False, hooks=[configHook1, configHook2]) + config = Config('SDK_KEY', datasystem_config=datasystem_config(TestDataV2.data_source()), send_events=False, hooks=[configHook1, configHook2]) client = LDClient(config=config) client.add_hook(clientHook1) client.add_hook(clientHook2) @@ -55,7 +59,7 @@ def test_ignores_invalid_hooks(): calls = [] hook = MockHook(before_evaluation=record('before', calls), after_evaluation=record('after', calls)) - config = Config('SDK_KEY', update_processor_class=TestData.data_source(), send_events=False, hooks=[True, hook, 42]) + config = Config('SDK_KEY', datasystem_config=datasystem_config(TestDataV2.data_source()), send_events=False, hooks=[True, hook, 42]) client = LDClient(config=config) client.add_hook("Hook, Hook, give us the Hook!") client.add_hook(hook) @@ -70,10 +74,10 @@ def test_after_evaluation_receives_evaluation_detail(): details = [] hook = MockHook(before_evaluation=record('before', []), after_evaluation=lambda series_context, data, detail: details.append(detail)) - td = TestData.data_source() + td = TestDataV2.data_source() td.update(td.flag('flag-key').variation_for_all(True)) - config = Config('SDK_KEY', update_processor_class=td, send_events=False, hooks=[hook]) + config = Config('SDK_KEY', datasystem_config=datasystem_config(td), send_events=False, hooks=[hook]) client = LDClient(config=config) client.variation('flag-key', user, False) @@ -86,7 +90,7 @@ def test_passing_data_from_before_to_after(): calls = [] hook = MockHook(before_evaluation=lambda series_context, data: "from before", after_evaluation=lambda series_context, data, detail: calls.append(data)) - config = Config('SDK_KEY', update_processor_class=TestData.data_source(), send_events=False, hooks=[hook]) + config = Config('SDK_KEY', datasystem_config=datasystem_config(TestDataV2.data_source()), send_events=False, hooks=[hook]) client = LDClient(config=config) client.variation('flag-key', user, False) @@ -101,7 +105,7 @@ def raise_exception(series_context, data): calls = [] hook = MockHook(before_evaluation=raise_exception, after_evaluation=lambda series_context, data, detail: calls.append(data)) - config = Config('SDK_KEY', update_processor_class=TestData.data_source(), send_events=False, hooks=[hook]) + config = Config('SDK_KEY', datasystem_config=datasystem_config(TestDataV2.data_source()), send_events=False, hooks=[hook]) client = LDClient(config=config) client.variation('flag-key', user, False) @@ -118,7 +122,7 @@ def raise_exception(series_context, data): hook2 = MockHook(before_evaluation=raise_exception, after_evaluation=lambda series_context, data, detail: calls.append(data)) hook3 = MockHook(before_evaluation=lambda series_context, data: "third hook", after_evaluation=lambda series_context, data, detail: calls.append(data)) - config = Config('SDK_KEY', update_processor_class=TestData.data_source(), send_events=False, hooks=[hook1, hook2, hook3]) + config = Config('SDK_KEY', datasystem_config=datasystem_config(TestDataV2.data_source()), send_events=False, hooks=[hook1, hook2, hook3]) client = LDClient(config=config) client.variation('flag-key', user, False) @@ -134,10 +138,10 @@ def test_migration_evaluation_detail_contains_stage_value(): details = [] hook = MockHook(before_evaluation=record('before', []), after_evaluation=lambda series_context, data, detail: details.append(detail)) - td = TestData.data_source() + td = TestDataV2.data_source() td.update(td.flag('flag-key').variations("off").variation_for_all(0)) - config = Config('SDK_KEY', update_processor_class=td, send_events=False, hooks=[hook]) + config = Config('SDK_KEY', datasystem_config=datasystem_config(td), send_events=False, hooks=[hook]) client = LDClient(config=config) client.migration_variation('flag-key', user, Stage.LIVE) @@ -150,10 +154,10 @@ def test_migration_evaluation_detail_gets_default_if_flag_isnt_migration_flag(): details = [] hook = MockHook(before_evaluation=record('before', []), after_evaluation=lambda series_context, data, detail: details.append(detail)) - td = TestData.data_source() + td = TestDataV2.data_source() td.update(td.flag('flag-key').variations("nonstage").variation_for_all(0)) - config = Config('SDK_KEY', update_processor_class=td, send_events=False, hooks=[hook]) + config = Config('SDK_KEY', datasystem_config=datasystem_config(td), send_events=False, hooks=[hook]) client = LDClient(config=config) client.migration_variation('flag-key', user, Stage.LIVE) @@ -166,10 +170,10 @@ def test_migration_evaluation_detail_default_converts_to_off_if_invalid(): details = [] hook = MockHook(before_evaluation=record('before', []), after_evaluation=lambda series_context, data, detail: details.append(detail)) - td = TestData.data_source() + td = TestDataV2.data_source() td.update(td.flag('flag-key').variations("nonstage").variation_for_all(0)) - config = Config('SDK_KEY', update_processor_class=td, send_events=False, hooks=[hook]) + config = Config('SDK_KEY', datasystem_config=datasystem_config(td), send_events=False, hooks=[hook]) client = LDClient(config=config) client.migration_variation('flag-key', user, "invalid") @@ -182,10 +186,10 @@ def test_series_context_environment_id_is_none_without_environment_id(): contexts = [] hook = MockHook(before_evaluation=lambda series_context, data: contexts.append(series_context), after_evaluation=record('after', [])) - td = TestData.data_source() + td = TestDataV2.data_source() td.update(td.flag('flag-key').variation_for_all(True)) - config = Config('SDK_KEY', update_processor_class=td, send_events=False, hooks=[hook]) + config = Config('SDK_KEY', datasystem_config=datasystem_config(td), send_events=False, hooks=[hook]) client = LDClient(config=config) client.variation('flag-key', user, False) diff --git a/ldclient/testing/test_ldclient_listeners.py b/ldclient/testing/test_ldclient_listeners.py index 2ad697db..c4d0ad4d 100644 --- a/ldclient/testing/test_ldclient_listeners.py +++ b/ldclient/testing/test_ldclient_listeners.py @@ -1,20 +1,23 @@ +import json from queue import Queue +from ldclient import datasystem from ldclient.client import Config, LDClient from ldclient.config import BigSegmentsConfig from ldclient.interfaces import DataSourceState from ldclient.testing.http_util import start_server from ldclient.testing.mock_components import MockBigSegmentStore -from ldclient.testing.stub_util import ( - MockEventProcessor, - MockUpdateProcessor, - make_put_event, - stream_content -) +from ldclient.testing.stub_util import MockEventProcessor, stream_content + + +def make_fdv2_full_transfer_events() -> str: + intent = {'payloads': [{'id': 'p1', 'target': 1, 'intentCode': 'xfer-full', 'reason': 'payload-missing'}]} + transferred = {'state': '(p:p1:1)', 'version': 1} + return 'event: server-intent\ndata: %s\n\nevent: payload-transferred\ndata: %s\n\n' % (json.dumps(intent), json.dumps(transferred)) def test_big_segment_store_status_unavailable(): - config = Config(sdk_key='SDK_KEY', event_processor_class=MockEventProcessor, update_processor_class=MockUpdateProcessor) + config = Config(sdk_key='SDK_KEY', event_processor_class=MockEventProcessor, datasystem_config=datasystem.custom().build()) client = LDClient(config) assert client.big_segment_store_status_provider.status.available is False @@ -22,7 +25,7 @@ def test_big_segment_store_status_unavailable(): def test_big_segment_store_status_updates(): segstore = MockBigSegmentStore() segstore.setup_metadata_always_up_to_date() - config = Config(sdk_key='SDK_KEY', big_segments=BigSegmentsConfig(store=segstore, status_poll_interval=0.01), event_processor_class=MockEventProcessor, update_processor_class=MockUpdateProcessor) + config = Config(sdk_key='SDK_KEY', big_segments=BigSegmentsConfig(store=segstore, status_poll_interval=0.01), event_processor_class=MockEventProcessor, datasystem_config=datasystem.custom().build()) statuses = Queue() with LDClient(config) as client: @@ -47,16 +50,16 @@ def test_big_segment_store_status_updates(): def test_data_source_status_default(): - config = Config(sdk_key='SDK_KEY', event_processor_class=MockEventProcessor, update_processor_class=MockUpdateProcessor) + config = Config(sdk_key='SDK_KEY', event_processor_class=MockEventProcessor, datasystem_config=datasystem.custom().build()) client = LDClient(config) assert client.data_source_status_provider.status.state == DataSourceState.INITIALIZING def test_data_source_status_updates(): with start_server() as stream_server: - with stream_content(make_put_event()) as stream_handler: - stream_server.for_path('/all', stream_handler) - config = Config(sdk_key='sdk-key', stream_uri=stream_server.uri, send_events=False) + with stream_content(make_fdv2_full_transfer_events()) as stream_handler: + stream_server.for_path('/sdk/stream', stream_handler) + config = Config(sdk_key='sdk-key', stream_uri=stream_server.uri, send_events=False, datasystem_config=datasystem.streaming().build()) with LDClient(config=config) as client: assert client.data_source_status_provider.status.state == DataSourceState.VALID diff --git a/ldclient/testing/test_ldclient_singleton.py b/ldclient/testing/test_ldclient_singleton.py index f5b474f7..df8f6ed9 100644 --- a/ldclient/testing/test_ldclient_singleton.py +++ b/ldclient/testing/test_ldclient_singleton.py @@ -1,10 +1,10 @@ import json import ldclient -from ldclient import _reset_client +from ldclient import _reset_client, datasystem from ldclient.config import Config from ldclient.testing.http_util import BasicResponse, start_server -from ldclient.testing.stub_util import make_put_event, stream_content +from ldclient.testing.stub_util import stream_content from ldclient.testing.sync_util import wait_until sdk_key = 'sdk-key' @@ -13,14 +13,24 @@ # network behavior because what we're really testing is the singleton mechanism. +def make_fdv2_full_transfer_events() -> str: + intent = {'payloads': [{'id': 'p1', 'target': 1, 'intentCode': 'xfer-full', 'reason': 'payload-missing'}]} + transferred = {'state': '(p:p1:1)', 'version': 1} + return 'event: server-intent\ndata: %s\n\nevent: payload-transferred\ndata: %s\n\n' % (json.dumps(intent), json.dumps(transferred)) + + +def make_streaming_config(key: str, stream_uri: str) -> Config: + return Config(key, stream_uri=stream_uri, send_events=False, datasystem_config=datasystem.streaming().build()) + + def test_set_sdk_key_before_init(): _reset_client() with start_server() as stream_server: - with stream_content(make_put_event()) as stream_handler: + with stream_content(make_fdv2_full_transfer_events()) as stream_handler: try: - stream_server.for_path('/all', stream_handler) + stream_server.for_path('/sdk/stream', stream_handler) - ldclient.set_config(Config(sdk_key, stream_uri=stream_server.uri, send_events=False)) + ldclient.set_config(make_streaming_config(sdk_key, stream_server.uri)) wait_until(ldclient.get().is_initialized, timeout=10) r = stream_server.await_request() @@ -33,20 +43,21 @@ def test_set_sdk_key_after_init(): _reset_client() other_key = 'other-key' with start_server() as stream_server: - with stream_content(make_put_event()) as stream_handler: + with stream_content(make_fdv2_full_transfer_events()) as stream_handler: try: - stream_server.for_path('/all', BasicResponse(401)) + stream_server.for_path('/sdk/stream', BasicResponse(401)) - config = Config(other_key, stream_uri=stream_server.uri, send_events=False) + config = make_streaming_config(other_key, stream_server.uri) ldclient.set_config(config) assert ldclient.get().is_initialized() is False r = stream_server.await_request() assert r.headers['Authorization'] == other_key - stream_server.for_path('/all', stream_handler) + stream_server.for_path('/sdk/stream', stream_handler) - ldclient.set_config(config.copy_with_new_sdk_key(sdk_key)) + # copy_with_new_sdk_key drops datasystem_config, so the test builds a new config. + ldclient.set_config(make_streaming_config(sdk_key, stream_server.uri)) wait_until(ldclient.get().is_initialized, timeout=30) r = stream_server.await_request() @@ -58,14 +69,14 @@ def test_set_sdk_key_after_init(): def test_set_config(): _reset_client() with start_server() as stream_server: - with stream_content(make_put_event()) as stream_handler: + with stream_content(make_fdv2_full_transfer_events()) as stream_handler: try: - stream_server.for_path('/all', stream_handler) + stream_server.for_path('/sdk/stream', stream_handler) ldclient.set_config(Config(sdk_key, offline=True)) assert ldclient.get().is_offline() is True - ldclient.set_config(Config(sdk_key, stream_uri=stream_server.uri, send_events=False)) + ldclient.set_config(make_streaming_config(sdk_key, stream_server.uri)) assert ldclient.get().is_offline() is False wait_until(ldclient.get().is_initialized, timeout=10)