Ejemplo n.º 1
0
def test_defaults_and_online_no_default():
    client = LDClient("API_KEY", Config("http://localhost:3000", defaults={"foo": "bar"},
                                        feature_requester_class=MockFeatureRequester,
                                        consumer_class=MockConsumer))
    assert "jim" == client.toggle('baz', user, default="jim")
    assert wait_for_event(client, lambda e: e['kind'] == 'feature' and e[
                          'key'] == u'baz' and e['user'] == user)
Ejemplo n.º 2
0
def test_defaults_and_online_no_default():
    client = LDClient(config=Config(base_uri="http://localhost:3000",
                                    defaults={"foo": "bar"},
                                    event_consumer_class=MockConsumer,
                                    feature_requester_class=MockFeatureRequester))
    assert "jim" == client.variation('baz', user, default="jim")
    assert wait_for_event(client, lambda e: e['kind'] == 'feature' and e['key'] == u'baz' and e['user'] == user)
Ejemplo n.º 3
0
def main():
    #if len(sys.argv) is not 4:
    #    raise Exception("Must call with endpoint, username, and password" +\
    #                    " i.e.: python example.py http://<server>:9087 <user> <pass>")
    #endpoint = sys.argv[1]
    #username = sys.argv[2]
    #password = sys.argv[3]
    parser = argparse.ArgumentParser(description='Parse input parameters')
    parser.add_argument('-i', '--id', type=int)
    parser.add_argument('-e', '--endpoint', type=str)
    parser.add_argument('-u', '--username', type=str)
    parser.add_argument('-p', '--password', type=str)
    parser.add_argument('-d', '--database', type=str)
    args = parser.parse_args()
    args = vars(args)
    live_report_id = args['id']
    endpoint = args['endpoint']
    username = args['username']
    password = args['password']
    database = args['database']

    apiSuffix = "/api"
    apiEndpoint = endpoint + apiSuffix
    api = Api(apiEndpoint, username, password)
    api.delete_live_report(live_report_id)
Ejemplo n.º 4
0
def test_defaults_and_online_no_default():
    my_client = LDClient(config=Config(base_uri="http://localhost:3000",
                                       defaults={"foo": "bar"},
                                       event_processor_class=MockEventProcessor,
                                       update_processor_class=MockUpdateProcessor))
    assert "jim" == my_client.variation('baz', user, default="jim")
    e = get_first_event(my_client)
    assert e['kind'] == 'feature' and e['key'] == u'baz' and e['user'] == user
Ejemplo n.º 5
0
def test_sse_init(stream):
    stream.queue.put(Event(event="put", data=feature("foo", "jim")))
    client = LDClient(
        "apikey",
        Config(feature_requester_class=partial(create_redis_ldd_requester,
                                               expiration=0),
               events=False))
    wait_until(lambda: client.toggle("foo", user('xyz'), "blah") == "jim",
               timeout=10)
Ejemplo n.º 6
0
def test_defaults_and_online_no_default():
    my_client = LDClient(
        config=Config(base_uri="http://localhost:3000",
                      defaults={"foo": "bar"},
                      event_processor_class=MockEventProcessor,
                      update_processor_class=MockUpdateProcessor))
    assert "jim" == my_client.variation('baz', user, default="jim")
    e = get_first_event(my_client)
    assert e['kind'] == 'feature' and e['key'] == u'baz' and e['user'] == user
Ejemplo n.º 7
0
def test_defaults_and_online():
    expected = "bar"
    my_client = LDClient(config=Config(base_uri="http://localhost:3000",
                                       defaults={"foo": expected},
                                       event_consumer_class=MockConsumer,
                                       feature_requester_class=MockFeatureRequester,
                                       feature_store=InMemoryFeatureStore()))
    actual = my_client.variation('foo', user, default="originalDefault")
    assert actual == expected
    assert wait_for_event(my_client, lambda e: e['kind'] == 'feature' and e['key'] == u'foo' and e['user'] == user)
Ejemplo n.º 8
0
def test_sse_init(stream):
    stream.queue.put(Event(event="put", data=feature("foo", "jim")))
    client = LDClient(
        "apikey",
        TwistedConfig(stream=True,
                      stream_processor_class=create_redis_ldd_processor,
                      feature_requester_class=NoOpFeatureRequester,
                      events=False))
    yield wait_until(
        is_equal(lambda: client.toggle("foo", user('xyz'), "blah"), "jim"))
Ejemplo n.º 9
0
def test_defaults_and_online():
    expected = "bar"
    my_client = LDClient(config=Config(base_uri="http://localhost:3000",
                                       defaults={"foo": expected},
                                       event_processor_class=MockEventProcessor,
                                       update_processor_class=MockUpdateProcessor,
                                       feature_store=InMemoryFeatureStore()))
    actual = my_client.variation('foo', user, default="originalDefault")
    assert actual == expected
    e = get_first_event(my_client)
    assert e['kind'] == 'feature' and e['key'] == u'foo' and e['user'] == user
def test_evaluates_simplified_flag_with_client_as_expected():
    path = make_temp_file(all_properties_json)
    try:
        factory = Files.new_data_source(paths = path)
        client = LDClient(config=Config(update_processor_class = factory, send_events = False))
        value = client.variation('flag2', { 'key': 'user' }, '')
        assert value == 'value2'
    finally:
        os.remove(path)
        if client is not None:
            client.close()
def test_evaluates_simplified_flag_with_client_as_expected():
    path = make_temp_file(all_properties_json)
    try:
        factory = Files.new_data_source(paths=path)
        client = LDClient(
            config=Config(update_processor_class=factory, send_events=False))
        value = client.variation('flag2', {'key': 'user'}, '')
        assert value == 'value2'
    finally:
        os.remove(path)
        if client is not None:
            client.close()
Ejemplo n.º 12
0
def test_defaults_and_online():
    expected = "bar"
    my_client = LDClient(
        config=Config(base_uri="http://localhost:3000",
                      defaults={"foo": expected},
                      event_processor_class=MockEventProcessor,
                      update_processor_class=MockUpdateProcessor,
                      feature_store=InMemoryFeatureStore()))
    actual = my_client.variation('foo', user, default="originalDefault")
    assert actual == expected
    e = get_first_event(my_client)
    assert e['kind'] == 'feature' and e['key'] == u'foo' and e['user'] == user
Ejemplo n.º 13
0
def test_exception_in_retrieval():
    class ExceptionFeatureRequester(FeatureRequester):

        def __init__(self, *_):
            pass

        def get(self, key, callback):
            raise Exception("blah")

    client = LDClient("API_KEY", Config("http://localhost:3000", defaults={"foo": "bar"},
                                        feature_requester_class=ExceptionFeatureRequester,
                                        consumer_class=MockConsumer))
    assert "bar" == client.toggle('foo', user, default="jim")
    assert wait_for_event(client, lambda e: e['kind'] == 'feature' and e['key'] == u'foo' and e['user'] == user)
Ejemplo n.º 14
0
def test_exception_in_retrieval():
    class ExceptionFeatureRequester(FeatureRequester):
        def __init__(self, *_):
            pass

        def get_all(self):
            raise Exception("blah")

    client = LDClient(config=Config(base_uri="http://localhost:3000",
                                    defaults={"foo": "bar"},
                                    feature_store=InMemoryFeatureStore(),
                                    feature_requester_class=ExceptionFeatureRequester,
                                    event_consumer_class=MockConsumer))
    assert "bar" == client.variation('foo', user, default="jim")
    assert wait_for_event(client, lambda e: e['kind'] == 'feature' and e['key'] == u'foo' and e['user'] == user)
Ejemplo n.º 15
0
def test_defaults():
    config = Config("SDK_KEY",
                    base_uri="http://localhost:3000",
                    defaults={"foo": "bar"},
                    offline=True)
    with LDClient(config=config) as client:
        assert "bar" == client.variation('foo', user, default=None)
Ejemplo n.º 16
0
def test_client_has_streaming_processor_by_default():
    config = Config(sdk_key="secret",
                    base_uri=unreachable_uri,
                    stream_uri=unreachable_uri,
                    send_events=False)
    with LDClient(config=config, start_wait=0) as client:
        assert isinstance(client._update_processor, StreamingUpdateProcessor)
Ejemplo n.º 17
0
def test_store_data_set_ordering():
    store = CapturingFeatureStore()
    config = Config(
        sdk_key='SDK_KEY',
        send_events=False,
        feature_store=store,
        update_processor_class=DependencyOrderingDataUpdateProcessor)
    LDClient(config=config)

    data = store.received_data
    assert data is not None
    assert len(data) == 2
    keys = list(data.keys())
    values = list(data.values())

    assert keys[0] == SEGMENTS
    assert len(values[0]) == len(dependency_ordering_test_data[SEGMENTS])

    assert keys[1] == FEATURES
    flags_map = values[1]
    flags_list = list(flags_map.values())
    assert len(flags_list) == len(dependency_ordering_test_data[FEATURES])
    for item_index, item in enumerate(flags_list):
        for prereq in item.get("prerequisites", []):
            prereq_item = flags_map[prereq["key"]]
            prereq_index = flags_list.index(prereq_item)
            if prereq_index > item_index:
                all_keys = (f["key"] for f in flags_list)
                raise Exception(
                    "%s depends on %s, but %s was listed first; keys in order are [%s]"
                    % (item["key"], prereq["key"], item["key"],
                       ", ".join(all_keys)))
Ejemplo n.º 18
0
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)
    with LDClient(config=config) as client:
        assert isinstance(client._event_processor, NullEventProcessor)
Ejemplo n.º 19
0
def auth_check(endpoint, username, password):
    auth_return = {'authorized': True, 'error': None}
    try:
        sessionClient = LDClient(host=endpoint, username=username, password=password)
    except Exception as e:
        auth_return['authorized'] = False
        auth_return['error'] = e.message    
    return auth_return
Ejemplo n.º 20
0
def make_client(store = InMemoryFeatureStore()):
    return LDClient(config=Config(sdk_key = 'SDK_KEY',
                                  base_uri=unreachable_uri,
                                  events_uri=unreachable_uri,
                                  stream_uri=unreachable_uri,
                                  event_processor_class=MockEventProcessor,
                                  update_processor_class=MockUpdateProcessor,
                                  feature_store=store))
Ejemplo n.º 21
0
def test_client_has_polling_processor_if_streaming_is_disabled():
    config = Config(sdk_key="secret",
                    stream=False,
                    base_uri=unreachable_uri,
                    stream_uri=unreachable_uri,
                    send_events=False)
    with LDClient(config=config, start_wait=0) as client:
        assert isinstance(client._update_processor, PollingUpdateProcessor)
def test_cannot_connect_with_selfsigned_cert_by_default():
    with start_secure_server() as server:
        server.for_path('/sdk/latest-all', poll_content())
        config = Config(sdk_key='sdk_key',
                        base_uri=server.uri,
                        stream=False,
                        send_events=False)
        with LDClient(config=config, start_wait=1.5) as client:
            assert not client.is_initialized()
def test_can_connect_with_selfsigned_cert_if_ssl_verify_is_false():
    with start_secure_server() as server:
        server.for_path('/sdk/latest-all', poll_content())
        config = Config(sdk_key='sdk_key',
                        base_uri=server.uri,
                        stream=False,
                        send_events=False,
                        verify_ssl=False)
        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/latest-all', poll_content())
        config = Config(sdk_key='sdk_key',
                        base_uri=server.uri,
                        stream=False,
                        send_events=False,
                        http=HTTPConfig(ca_certs='./testing/selfsigned.pem'))
        with LDClient(config=config) as client:
            assert client.is_initialized()
def test_client_fails_to_start_in_streaming_mode_with_401_error():
    with start_server() as stream_server:
        stream_server.for_path('/all', BasicResponse(401))
        config = Config(sdk_key=sdk_key,
                        stream_uri=stream_server.uri,
                        send_events=False)

        with LDClient(config=config) as client:
            assert not client.is_initialized()
            assert client.variation(always_true_flag['key'], user,
                                    False) == False
def test_can_connect_with_selfsigned_cert_if_disable_ssl_verification_is_true(
):
    with start_secure_server() as server:
        server.for_path('/sdk/latest-all', poll_content())
        config = Config(sdk_key='sdk_key',
                        base_uri=server.uri,
                        stream=False,
                        send_events=False,
                        http=HTTPConfig(disable_ssl_verification=True))
        with LDClient(config=config) as client:
            assert client.is_initialized()
Ejemplo n.º 27
0
def main():
    parser = get_parser()
    args = parser.parse_args()
    endpoint = "{0}/api".format(args.ld_server)
    if args.method != "auth_check":
        client = LDClient(host=endpoint, username=args.username, password=args.password)
        method = eval(args.method)
        result = method(client, *args.args)
    else:
        result = auth_check(endpoint, *args.args)

    print json.dumps(result)
def test_does_not_allow_unsafe_yaml():
    if not have_yaml:
        pytest.skip(
            "skipping file source test with YAML because pyyaml isn't available"
        )

    # This extended syntax defined by pyyaml allows arbitrary code execution. We should be using
    # yaml.safe_load() which does not support such things.
    unsafe_yaml = '''
!!python/object/apply:testing.test_file_data_source.arbitrary_method_called_from_yaml ["hi"]
'''
    path = make_temp_file(unsafe_yaml)
    try:
        factory = Files.new_data_source(paths=path)
        client = LDClient(
            config=Config(update_processor_class=factory, send_events=False))
    finally:
        os.remove(path)
        if client is not None:
            client.close()
    assert unsafe_yaml_caused_method_to_be_called == False
def test_client_starts_in_streaming_mode():
    with start_server() as stream_server:
        with stream_content(make_put_event([always_true_flag
                                            ])) 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 LDClient(config=config) as client:
                assert client.is_initialized()
                assert client.variation(always_true_flag['key'], user,
                                        False) == True

                r = stream_server.await_request()
                assert r.headers['Authorization'] == sdk_key
def test_client_starts_in_polling_mode():
    with start_server() as poll_server:
        poll_server.for_path('/sdk/latest-all',
                             poll_content([always_true_flag]))
        config = Config(sdk_key=sdk_key,
                        base_uri=poll_server.uri,
                        stream=False,
                        send_events=False)

        with LDClient(config=config) as client:
            assert client.is_initialized()
            assert client.variation(always_true_flag['key'], user,
                                    False) == True

            r = poll_server.await_request()
            assert r.headers['Authorization'] == sdk_key
def test_client_sends_diagnostics():
    with start_server() as poll_server:
        with start_server() as events_server:
            poll_server.for_path('/sdk/latest-all',
                                 poll_content([always_true_flag]))
            events_server.for_path('/diagnostic', BasicResponse(202))

            config = Config(sdk_key=sdk_key,
                            base_uri=poll_server.uri,
                            events_uri=events_server.uri,
                            stream=False)
            with LDClient(config=config) as client:
                assert client.is_initialized()

                r = events_server.await_request()
                assert r.headers['Authorization'] == sdk_key
                data = json.loads(r.body)
                assert data['kind'] == 'diagnostic-init'
def test_client_retries_connection_in_streaming_mode_with_non_fatal_error():
    with start_server() as stream_server:
        with stream_content(make_put_event([always_true_flag
                                            ])) as stream_handler:
            error_then_success = SequentialHandler(BasicResponse(503),
                                                   stream_handler)
            stream_server.for_path('/all', error_then_success)
            config = Config(sdk_key=sdk_key,
                            stream_uri=stream_server.uri,
                            initial_reconnect_delay=0.001,
                            send_events=False)

            with LDClient(config=config) as client:
                assert client.is_initialized()
                assert client.variation(always_true_flag['key'], user,
                                        False) == True

                r = stream_server.await_request()
                assert r.headers['Authorization'] == sdk_key
def test_client_sends_event_without_diagnostics():
    with start_server() as poll_server:
        with start_server() as events_server:
            poll_server.for_path('/sdk/latest-all',
                                 poll_content([always_true_flag]))
            events_server.for_path('/bulk', BasicResponse(202))

            config = Config(sdk_key=sdk_key,
                            base_uri=poll_server.uri,
                            events_uri=events_server.uri,
                            stream=False,
                            diagnostic_opt_out=True)
            with LDClient(config=config) as client:
                assert client.is_initialized()
                client.identify(user)
                client.flush()

                r = events_server.await_request()
                assert r.headers['Authorization'] == sdk_key
                data = json.loads(r.body)
                assert len(data) == 1
                assert data[0]['kind'] == 'identify'
Ejemplo n.º 34
0
def test_sse_init(stream):
    stream.queue.put(Event(event="put", data=feature("foo", "jim")))
    client = LDClient("apikey", Config(feature_requester_class=partial(create_redis_ldd_requester, expiration=0),
                                       events=False))
    wait_until(lambda: client.toggle(
        "foo", user('xyz'), "blah") == "jim", timeout=10)
Ejemplo n.º 35
0
 def __init__(self, api_key, config=None):
     if config is None:
         config = TwistedConfig()
     LDClient.__init__(self, api_key, config)
Ejemplo n.º 36
0
def test_defaults():
    client = LDClient("API_KEY", Config("http://localhost:3000", defaults={"foo": "bar"}))
    client.set_offline()
    assert "bar" == client.toggle('foo', user, default=None)
Ejemplo n.º 37
0
def test_toggle(server):
    server.add_feature("foo", feature("foo", "jim")['foo'])
    client = LDClient("apikey", Config(base_uri=server.url))
    wait_until(lambda: client.toggle("foo", user('xyz'), "blah") == "jim")
Ejemplo n.º 38
0
def test_sse_init(server, stream):
    stream.queue.put(Event(event="put", data=feature("foo", "jim")))
    client = LDClient("apikey", Config(stream=True, base_uri=server.url, stream_uri=stream.url))
    wait_until(lambda: client.toggle("foo", user('xyz'), "blah") == "jim")
Ejemplo n.º 39
0
def test_defaults():
    client = LDClient(config=Config(base_uri="http://localhost:3000",
                                    defaults={"foo": "bar"},
                                    offline=True))
    assert "bar" == client.variation('foo', user, default=None)
Ejemplo n.º 40
0
def test_sse_init(stream):
    stream.queue.put(Event(event="put", data=feature("foo", "jim")))
    client = LDClient("apikey", TwistedConfig(stream=True, stream_processor_class=create_redis_ldd_processor,
                                              feature_requester_class=NoOpFeatureRequester,
                                              events=False))
    yield wait_until(is_equal(lambda: client.toggle("foo", user('xyz'), "blah"), "jim"))