예제 #1
0
def test_create_diagnostic_id():
    test_config = Config(sdk_key="SDK_KEY", http=HTTPConfig())
    diag_id = create_diagnostic_id(test_config)
    assert len(diag_id) == 2
    uid = diag_id['diagnosticId']
    # Will throw if invalid UUID4
    uuid.UUID('urn:uuid:' + uid)
    assert diag_id['sdkKeySuffix'] == 'DK_KEY'
예제 #2
0
    def __init__(self,
                 url,
                 last_id=None,
                 retry=3000,
                 connect_timeout=10,
                 read_timeout=300,
                 chunk_size=10000,
                 verify_ssl=False,
                 http=None,
                 http_proxy=None,
                 http_factory=None,
                 **kwargs):
        self.url = url
        self.last_id = last_id
        self.retry = retry
        self._chunk_size = chunk_size

        if http_factory:
            self._timeout = http_factory.timeout
            base_headers = http_factory.base_headers
        else:
            # for backward compatibility in case anyone else is using this class
            self._timeout = urllib3.Timeout(connect=connect_timeout,
                                            read=read_timeout)
            base_headers = {}

        # Optional support for passing in an HTTP client
        if http:
            self.http = http
        else:
            hf = http_factory
            if hf is None:  # build from individual parameters which we're only retaining for backward compatibility
                hc = HTTPConfig(connect_timeout=connect_timeout,
                                read_timeout=read_timeout,
                                disable_ssl_verification=not verify_ssl,
                                http_proxy=http_proxy)
                hf = HTTPFactory({}, hc)
            self.http = hf.create_pool_manager(1, url)

        # Any extra kwargs will be fed into the request call later.
        self.requests_kwargs = kwargs

        # The SSE spec requires making requests with Cache-Control: nocache
        if 'headers' not in self.requests_kwargs:
            self.requests_kwargs['headers'] = {}

        self.requests_kwargs['headers'].update(base_headers)

        self.requests_kwargs['headers']['Cache-Control'] = 'no-cache'

        # The 'Accept' header is not required, but explicit > implicit
        self.requests_kwargs['headers']['Accept'] = 'text/event-stream'

        # Keep data here as it streams in
        self.buf = u''

        self._connect()
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()
예제 #4
0
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,
                        http=HTTPConfig(disable_ssl_verification=True))
        with LDClient(config=config) as client:
            assert client.is_initialized()
예제 #5
0
def do_proxy_tests(action, action_method, monkeypatch):
    # We'll test each permutation of use_env_vars, secure, and use_auth, except that if secure is
    # true then we'll only test with use_auth=false because we don't have a way to test proxy
    # authorization over HTTPS (even though we believe it works).
    for (use_env_vars, secure, use_auth) in [(False, False, False),
                                             (False, False, True),
                                             (False, True, False),
                                             (True, False, False),
                                             (True, False, True),
                                             (True, True, False)]:
        test_desc = "%s, %s, %s" % (
            "using env vars" if use_env_vars else "using Config", "secure"
            if secure else "insecure", "with auth" if use_auth else "no auth")
        with start_server() as server:
            proxy_uri = server.uri.replace(
                'http://', 'http://*****:*****@') if use_auth else server.uri
            target_uri = 'https://not-real' if secure else 'http://not-real'
            if use_env_vars:
                monkeypatch.setenv('https_proxy' if secure else 'http_proxy',
                                   proxy_uri)
            config = Config(sdk_key='sdk_key',
                            base_uri=target_uri,
                            events_uri=target_uri,
                            stream_uri=target_uri,
                            http=HTTPConfig(http_proxy=proxy_uri),
                            diagnostic_opt_out=True)
            try:
                action(server, config, secure)
            except:
                print("test action failed (%s)" % test_desc)
                raise
            # For an insecure proxy request, our stub server behaves enough like the real thing to satisfy the
            # HTTP client, so we should be able to see the request go through. Note that the URI path will
            # actually be an absolute URI for a proxy request.
            try:
                req = server.require_request()
            except:
                print("server did not receive a request (%s)" % test_desc)
                raise
            expected_method = 'CONNECT' if secure else action_method
            assert req.method == expected_method, "method should be %s, was %s (%s)" % (
                expected_method, req.method, test_desc)
            if use_auth:
                expected_auth = 'Basic dXNlcjpwYXNz'
                actual_auth = req.headers.get('Proxy-Authorization')
                assert actual_auth == expected_auth, "auth header should be %s, was %s (%s)" % (
                    expected_auth, actual_auth, test_desc)
            print("do_proxy_tests succeeded for: %s" % test_desc)
예제 #6
0
def test_create_diagnostic_config_custom():
    test_store = CachingStoreWrapper(_TestStoreForDiagnostics(),
                                     CacheConfig.default())
    test_config = Config("SDK_KEY",
                         base_uri='https://test.com',
                         events_uri='https://test.com',
                         events_max_pending=10,
                         flush_interval=1,
                         stream_uri='https://test.com',
                         stream=False,
                         poll_interval=60,
                         use_ldd=True,
                         feature_store=test_store,
                         all_attributes_private=True,
                         user_keys_capacity=10,
                         user_keys_flush_interval=60,
                         inline_users_in_events=True,
                         http=HTTPConfig(http_proxy='proxy',
                                         read_timeout=1,
                                         connect_timeout=1),
                         diagnostic_recording_interval=60)
    diag_config = _create_diagnostic_config_object(test_config)

    assert len(diag_config) == 17
    assert diag_config['customBaseURI'] is True
    assert diag_config['customEventsURI'] is True
    assert diag_config['customStreamURI'] is True
    assert diag_config['eventsCapacity'] == 10
    assert diag_config['connectTimeoutMillis'] == 1000
    assert diag_config['socketTimeoutMillis'] == 1000
    assert diag_config['eventsFlushIntervalMillis'] == 1000
    assert diag_config['usingProxy'] is True
    assert diag_config['streamingDisabled'] is True
    assert diag_config['usingRelayDaemon'] is True
    assert diag_config['allAttributesPrivate'] is True
    assert diag_config['pollingIntervalMillis'] == 60000
    assert diag_config['userKeysCapacity'] == 10
    assert diag_config['userKeysFlushIntervalMillis'] == 60000
    assert diag_config['inlineUsersInEvents'] is True
    assert diag_config['diagnosticRecordingIntervalMillis'] == 60000
    assert diag_config['dataStoreType'] == 'MyFavoriteStore'
예제 #7
0
    ldclient.set_config(
        Config(settings.FEATURE_FLAGS_API_KEY or 'whatever', offline=True))
    client = ldclient.get()
else:
    # Production usage
    if hasattr(settings, 'REDIS_LOCATION'):
        logger.debug(
            f'Set LaunchDarkly config with Redis feature store at {settings.REDIS_LOCATION}'
        )
        store = Redis.new_feature_store(url=settings.REDIS_LOCATION,
                                        prefix='feature-flags',
                                        caching=CacheConfig(expiration=30))
        ldclient.set_config(
            Config(settings.FEATURE_FLAGS_API_KEY,
                   feature_store=store,
                   http=HTTPConfig(connect_timeout=5)))
    else:
        logger.debug('Set LaunchDarkly config without Redis...')
        ldclient.set_config(
            Config(settings.FEATURE_FLAGS_API_KEY,
                   http=HTTPConfig(connect_timeout=5)))
    client = ldclient.get()


def _get_user_repr(user):
    """Turn user object into dict with required properties"""
    from users.serializers import UserSerializer
    if user.is_anonymous:
        return {'key': str(user)}
    user_data = UserSerializer(user).data
    user_data['key'] = user_data['email']