Skip to content

Commit

Permalink
prepare 7.6.0 release (#192)
Browse files Browse the repository at this point in the history
* comment

* add end-to-end unit tests for proxy config

* indents

* add 3.8 build

* image name

* fail on SyntaxWarning

* typo

* command syntax

* pin expiringdict dependency for Python 3.3 compatibility

* add Windows CircleCI job

* periods are no longer valid in CircleCI job names

* syntax fix

* install Python in Windows

* set path

* move command

* turn off debug logging

* Py3 in Windows

* config param

* rm redundant step

* choco switch

* refactor Linux jobs using CircleCI 2.1 features

* set log level before anything else

* rm Azure config

* use yaml.safe_load() to avoid code execution vulnerability in file data source

* Initial work on wrapper_name, wrapper_version, diagnostic config
options and start of diagnostic config event creation.

* Python 2 compat changes.

* More event generation code and starting to integrate tracking diagnostic values.

* Add minimum diagnostic recording interval. Fix diagnostic.py to be
importable. Add more diagnostic event fields.

* don't let user fall outside of last bucket in rollout

* fixing conditional logic

* Add docstrings for diagnostic configuration options.

* fix off-by-1 error

* avoid redundant dict lookups

* add unit tests for basic bucketing logic and edge case

* Stream init tracking. Feeding of accumulator object through SDK. Various fixes.

* Track events in last batch.

* Fix sdk version field, some stylistic improvements.

* Last of diagnostic configuration object fields.

* Fill out rest of platform fields.

* Cleanup and failed stream initialization tracking.

* Add diagnostic config option test.

* Add tests for diagnostics.py

* Testing rest of diagnostic fields.

* Test that streaming update processor records successful and unsuccessful
connection attempts in the diagnostic accumulator when available.

* Improvements to testability of event processor.

* Rest of event processor tests.

* Remove janky reflection.

* Test change to filesource optional test requirements.

* [ch61092] Add event payload ID on event requests.

* normalize data store type and OS name in diagnostic events

* gitignore

* copyedit to diagnostic event config property comment

* fix spurious error after sending diagnostic event

* make verify_ssl=False turn off certificate verification too (#129)

* add more TLS config options and collect HTTP/HTTPS config options in a class (#130)

* make stream retry/backoff/jitter behavior consistent with other SDKs + improve testing (#131)

* streams shouldn't use the same read timeout as the rest of the SDK (#132)

* implement our own retry logic & logging for event posts, don't use urllib3.Retry (#133)

* remove support for indirect/patch and indirect/put

* remove unused logic for individual flag/segment poll for indirect/patch

* Ehaisley/84082/remove python2 (#136)

* remove all references to six and remove queue fallback imports

* remove NullHandler logger backwards compat

* update circleci config to remove python 2.7 tests

* remove ordereddict backwards compat

* update setup.py to no longer list python 2.7 as compatible

* no longer inherit from object for python 2 backwards compat

* update readme and manifest to reflect python 2.7 removal

* remove unicode type compatibility

* remove 2.7 support from circleci

* Allow authenticating with proxy

This commit allows for authenticating with a proxy configured with the
`http_proxy` environment variable. Authentication requires passing a
header, and is not parsed by urllib3 from the proxy_url.

* reimplement proxy tests for DRY and add test of proxy auth params

* doc comment on auth params in proxy URL

* add type hints to some of the public facing api.
update some docs

* Revert "add type hints to some of the public facing api."

This reverts commit c35fa61.

* Ehaisley/ch86857/type hints (#138)

* add typehints to the public API
* validate typehints in the public api and tests with mypy

* remove all current deprecations (#139)

* remove all currently deprecated classes, methods, arguments, and tests
* also update semver usage to remove calls to deprecated functions and classes

* remove global set_sdk_key, make SDK key required in Config (#140)

* Removed the guides link

* Pinning mypy and running it against different python versions (#141)

* fix time zone mishandling that could make event debugging not work (#142)

* fix 6.x build (#143)

* fix time zone mishandling that could make event debugging not work (6.x) (#144)

* prepare 6.13.3 release (#154)

* Releasing version 6.13.3

* [ch99756] Add alias events (#145)

* add support for experiment rollouts

* fix unit test

* address PR comments

* use Releaser v2 config

* Use newer docker images (#147)

* Updates docs URLs

* Add support for 3.10 (#150)

* started work on FlagBuilder in as part of test data source implementation

* finished FlagBuilder implementation and added FlagRuleBuilder implementation

* added initial TestData interface and updated tests to not rely on test data internals

* started data source implementation

* changed FlagBuilder to public class; changed FlagBuilder attributes to be initialized in __init__ and eliminated use of try ... except: pass for handling empty attributes

* (big segments 1) add public config/interface types

* added implementation of test data source

* docstring

* formatting

* ensure property doesn't return None

* (big segments 2) implement evaluation, refactor eval logic & modules

* linting

* (big segments 3) implement big segment status tracking, wire up components

* typing fixes

* typing fixes

* implement SSE contract tests

* fix CI

* fix CI again

* fix CI

* disable SSE tests in Python 3.5

* make test service port configurable

* better SSE implementation that fixes linefeed and multi-byte char issues

* fix constructor parameters in test service

* comment

* test improvements

* rm obsolete default config logic

* (big segments 4) implement big segment stores in Redis+DynamoDB, refactor db tests (#158)

* converted ldclient.integrations module from file to directory; started moving public classes out of ldclient.impl.integrations.test_data* and instead into ldclient.integrations.test_data*; started adding TestData documentation

* removed setup/teardown functions leftover from test scaffold

* added TestData, FlagBuilder, and FlagRuleBuilder documentation; minor adjustments to implementation details

* removed warning supression from TestData tests

* fix big segments user hash algorithm to use SHA256

* update mypy version

* updates to tests and related bug fixes

* always cache Big Segment query result even if it's None

* fix test assertion

* lint

* fix big segment ref format

* fix big segments cache TTL being set to wrong value

* fixed structure of fallthrough variation in result of FlagBuilder.build()

* moved __test__ attribute into TestData class definition to prevent mypy from complaining about a missing class attribute

* minor doc comment fix

* Apply suggestions related to Sphinx docstring formatting from code review

Co-authored-by: Eli Bishop <[email protected]>

* fixed errors in the implementation of FlagBuilder's fallthrough_variation and off_variation when passing boolean variation values; updated tests to assert the expected behavior

* added missing value_for_all_users() method to FlagBuilder class

* Fix operator parsing errors (#169)

* identify should not emit event if user key is empty (#164)

* secondary should be treated as built-in attribute (#168)

* URIs should have trailing slashes trimmed (#165)

* all_flags_state should always include flag version (#166)

* output event should not include a null prereqOf key (#167)

* Account for traffic allocation on all flags (#171)

* Add SDK contract tests (#170)

* misc fixes to test data docs + add type hints

* more type hints

* remove some methods from the public test_data API

* can't use "x|y" shortcut in typehints in older Pythons; use Union

* fix misc type mistakes because I forgot to run the linter

* update CONTRIBUTING.md and provide make targets

* fixed a bug with flag rule clause builder internals; added unit test to verify rule evaluation

* added ready argument to _TestDataSource class and indicated ready upon start to avoid delays in TestData initialization

* Update contract tests to latest flask version (#176)

Our contract tests depend on flask v1, which in turn depends on Jinja 2.
Both of these are terribly dated and no longer supported.

Jinja depends on markupsafe. markupsafe recently updated its code to no longer provide
soft_unicode which in turn broke Jinja.

Updating to the latest flask keeps all transitive dependencies better
aligned and addresses this mismatch.

* Adds link to Relay Proxy docs

* Handle explicit None values in test payload (#179)

The test harness may send explicit None values which should be treated
the same as if the value was omitted entirely.

* Fix "unhandled response" error in test harness (#180)

When we return a `('', 204)` response from the flask handler, [Werkzeug
intentionally removes the 'Content-Type' header][1], which causes the
response to be created as a chunked response.

The test harness is likely seeing a 204 response and isn't trying to
read anything more from the stream. But since we are re-using
connections, the next time it reads from the stream, it sees the
`0\r\n\r\n` chunk and outputs an error:

> 2022/04/20 14:23:39 Unsolicited response received on idle HTTP channel starting with "0\r\n\r\n"; err=<nil>

Changing this response to 202 causes Werkzeug to return an empty
response and silences the error.

[1]: https://github.com/pallets/werkzeug/blob/560dd5f320bff318175f209595d42f5a80045417/src/werkzeug/wrappers/response.py#L540

* Exclude booleans when getting bucketable value (#181)

When calculating a bucket, we get the bucketable value from the
specified bucket by attribute. If this value is a string or an int, we
can use it. Otherwise, we return None.

Python considers a bool an instance of an int, which isn't what we want.
So we need to add an explicit exclusion for this.

* master -> main (#182)

* Loosen restriction on expiringdict (#183)

Originally this was pinned to a max version to deal with the
incompatibility of Python 3.3 and the `typing` package. See [this
PR][1].

Now that we now only support >=3.5, we can safely relax this restriction
again.

[1]: launchdarkly/python-server-sdk-private#120

* Fix mypy type checking (#184)

A [customer requested][original-pr] that we start including a py.typed file in our
repository. This would enable mypy to take advantage of our typehints.
Unfortunately, this didn't completely solve the customers issue.

A [second pr][second-pr] was opened to address the missing step of including the
py.typed file in the `Manifest.in` file. However, this change alone is not
sufficient.

According to the [documentation][include_package_data], you must also
include the `include_package_data=True` directive so that files
specified in the `Manifest.in` file are included in distribution.

[original-pr]: #166
[second-pr]: #172
[include_package_data]: https://setuptools.pypa.io/en/latest/userguide/datafiles.html#include-package-data

* Add support for extra Redis connection parameters (#185)

* Include wheel artifact when publishing package (#186)

* skip tests that use a self-signed TLS cert in Python 3.7

* remove warn-level logging done for every Big Segments query (#190)

* remove warn-level logging done for every Big Segments query

* skip tests that use a self-signed TLS cert in Python 3.7

* update release metadata

* Add application info support (#214)

* Upgrade pip to fix failing CI build (#216)

The CI build was failing because pip had an outdated list of available wheels for installation. Since it couldn't find a match, it was trying to build a package from source, which requires the rust compiler, which in turn isn't present on some of the docker images.

By updating pip we get the updated list of available wheels, thereby allowing us to bypass source building and the need for the rust compiler entirely.

---------

Co-authored-by: Eli Bishop <[email protected]>
Co-authored-by: LaunchDarklyCI <[email protected]>
Co-authored-by: Ben Woskow <[email protected]>
Co-authored-by: Gavin Whelan <[email protected]>
Co-authored-by: Elliot <[email protected]>
Co-authored-by: Gabor Angeli <[email protected]>
Co-authored-by: Elliot <[email protected]>
Co-authored-by: Ben Woskow <[email protected]>
Co-authored-by: LaunchDarklyCI <[email protected]>
Co-authored-by: hroederld <[email protected]>
Co-authored-by: Robert J. Neal <[email protected]>
Co-authored-by: Robert J. Neal <[email protected]>
Co-authored-by: Ember Stevens <[email protected]>
Co-authored-by: ember-stevens <[email protected]>
Co-authored-by: Matthew M. Keeler <[email protected]>
Co-authored-by: charukiewicz <[email protected]>
Co-authored-by: LaunchDarklyReleaseBot <[email protected]>
Co-authored-by: Christian Charukiewicz <[email protected]>
Co-authored-by: Matthew M. Keeler <[email protected]>
  • Loading branch information
20 people authored Jan 31, 2023
1 parent 92f86e9 commit c06f80f
Show file tree
Hide file tree
Showing 13 changed files with 150 additions and 10 deletions.
1 change: 1 addition & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ jobs:
- run:
name: install requirements
command: |
pip install --upgrade pip
pip install -r test-requirements.txt;
pip install -r test-filesource-optional-requirements.txt;
pip install -r consul-requirements.txt;
Expand Down
3 changes: 2 additions & 1 deletion .ldrelease/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ publications:

branches:
- name: main
description: 7.x
description: 8.x
- name: 7.x
- name: 6.x

jobs:
Expand Down
7 changes: 7 additions & 0 deletions contract-tests/client_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ def __init__(self, tag, config):
self.log = logging.getLogger(tag)
opts = {"sdk_key": config["credential"]}

tags = config.get('tags', {})
if tags:
opts['application'] = {
'id': tags.get('applicationId', ''),
'version': tags.get('applicationVersion', ''),
}

if config.get("streaming") is not None:
streaming = config["streaming"]
if streaming.get("baseUri") is not None:
Expand Down
1 change: 1 addition & 0 deletions contract-tests/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ def status():
'all-flags-with-reasons',
'all-flags-client-side-only',
'all-flags-details-only-for-tracked-flags',
'tags',
]
}
return (json.dumps(body), 200, {'Content-type': 'application/json'})
Expand Down
20 changes: 18 additions & 2 deletions ldclient/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from typing import Optional, Callable, List, Any, Set

from ldclient.feature_store import InMemoryFeatureStore
from ldclient.util import log
from ldclient.util import log, validate_application_info
from ldclient.interfaces import BigSegmentStore, EventProcessor, FeatureStore, UpdateProcessor, FeatureRequester

GET_LATEST_FEATURES_PATH = '/sdk/latest-flags'
Expand Down Expand Up @@ -173,7 +173,8 @@ def __init__(self,
wrapper_name: Optional[str]=None,
wrapper_version: Optional[str]=None,
http: HTTPConfig=HTTPConfig(),
big_segments: Optional[BigSegmentsConfig]=None):
big_segments: Optional[BigSegmentsConfig]=None,
application: Optional[dict]=None):
"""
:param sdk_key: The SDK key for your LaunchDarkly account. This is always required.
:param base_uri: The base URL for the LaunchDarkly server. Most users should use the default
Expand Down Expand Up @@ -239,6 +240,7 @@ def __init__(self,
servers.
:param http: Optional properties for customizing the client's HTTP/HTTPS behavior. See
:class:`HTTPConfig`.
:param application: Optional properties for setting application metadata. See :py:attr:`~application`
"""
self.__sdk_key = sdk_key

Expand Down Expand Up @@ -271,6 +273,7 @@ def __init__(self,
self.__wrapper_version = wrapper_version
self.__http = http
self.__big_segments = BigSegmentsConfig() if not big_segments else big_segments
self.__application = validate_application_info(application or {}, log)

def copy_with_new_sdk_key(self, new_sdk_key: str) -> 'Config':
"""Returns a new ``Config`` instance that is the same as this one, except for having a different SDK key.
Expand Down Expand Up @@ -441,3 +444,16 @@ def big_segments(self) -> BigSegmentsConfig:
def _validate(self):
if self.offline is False and self.sdk_key is None or self.sdk_key == '':
log.warning("Missing or blank sdk_key.")

@property
def application(self) -> dict:
"""
An object that allows configuration of application metadata.
Application metadata may be used in LaunchDarkly analytics or other
product features, but does not affect feature flag evaluations.
If you want to set non-default values for any of these fields, provide
the appropriately configured dict to the {Config} object.
"""
return self.__application
1 change: 0 additions & 1 deletion ldclient/impl/big_segments.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ def get_user_membership(self, user_key: str) -> Tuple[Optional[dict], str]:
membership = self.__cache.get(user_key)
if membership is None:
user_hash = _hash_for_user_key(user_key)
log.warn("*** querying Big Segments for user hash: %s" % user_hash)
try:
membership = self.__store.get_membership(user_hash)
if membership is None:
Expand Down
20 changes: 20 additions & 0 deletions ldclient/impl/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,34 @@
from os import environ
import urllib3

def _application_header_value(application: dict) -> str:
parts = []
id = application.get('id', '')
version = application.get('version', '')

if id:
parts.append("application-id/%s" % id)

if version:
parts.append("application-version/%s" % version)

return " ".join(parts)


def _base_headers(config):
headers = {'Authorization': config.sdk_key or '',
'User-Agent': 'PythonClient/' + VERSION}

app_value = _application_header_value(config.application)
if app_value:
headers['X-LaunchDarkly-Tags'] = app_value

if isinstance(config.wrapper_name, str) and config.wrapper_name != "":
wrapper_version = ""
if isinstance(config.wrapper_version, str) and config.wrapper_version != "":
wrapper_version = "/" + config.wrapper_version
headers.update({'X-LaunchDarkly-Wrapper': config.wrapper_name + wrapper_version})

return headers

def _http_factory(config):
Expand Down
22 changes: 22 additions & 0 deletions ldclient/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
# currently excluded from documentation - see docs/README.md

import logging
import re
from os import environ
import sys
import urllib3

from typing import Any
from ldclient.impl.http import HTTPFactory, _base_headers

log = logging.getLogger(sys.modules[__name__].__name__)
Expand All @@ -25,6 +27,26 @@

_retryable_statuses = [400, 408, 429]

def validate_application_info(application: dict, logger: logging.Logger) -> dict:
return {
"id": validate_application_value(application.get("id", ""), "id", logger),
"version": validate_application_value(application.get("version", ""), "version", logger),
}

def validate_application_value(value: Any, name: str, logger: logging.Logger) -> str:
if not isinstance(value, str):
return ""

if len(value) > 64:
logger.warning('Value of application[%s] was longer than 64 characters and was discarded' % name)
return ""

if re.search(r"[^a-zA-Z0-9._-]", value):
logger.warning('Value of application[%s] contained invalid characters and was discarded' % name)
return ""

return value

def _headers(config):
base_headers = _base_headers(config)
base_headers.update({'Content-Type': "application/json"})
Expand Down
27 changes: 27 additions & 0 deletions testing/test_config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from ldclient.config import Config
import pytest


def test_copy_config():
Expand Down Expand Up @@ -40,3 +41,29 @@ def test_trims_trailing_slashes_on_uris():
assert config.base_uri == "https://launchdarkly.com"
assert config.events_uri == "https://docs.launchdarkly.com/bulk"
assert config.stream_base_uri == "https://blog.launchdarkly.com"

def application_can_be_set_and_read():
application = {"id": "my-id", "version": "abcdef"}
config = Config(sdk_key = "SDK_KEY", application = application)
assert config.application == {"id": "my-id", "version": "abcdef"}

def application_can_handle_non_string_values():
application = {"id": 1, "version": 2}
config = Config(sdk_key = "SDK_KEY", application = application)
assert config.application == {"id": "1", "version": "2"}

def application_will_ignore_invalid_keys():
application = {"invalid": 1, "key": 2}
config = Config(sdk_key = "SDK_KEY", application = application)
assert config.application == {"id": "", "version": ""}

@pytest.fixture(params = [
" ",
"@",
":",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-a"
])
def application_will_drop_invalid_values(value):
application = {"id": value, "version": value}
config = Config(sdk_key = "SDK_KEY", application = application)
assert config.application == {"id": "", "version": ""}
16 changes: 16 additions & 0 deletions testing/test_event_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,22 @@ def test_wrapper_header_sent_without_version():

assert mock_http.request_headers.get('X-LaunchDarkly-Wrapper') == "Flask"

def test_application_header_not_sent_when_not_set():
with DefaultTestProcessor() as ep:
ep.send_event({ 'kind': 'identify', 'user': user })
ep.flush()
ep._wait_until_inactive()

assert mock_http.request_headers.get('X-LaunchDarkly-Tags') is None

def test_application_header_sent_when_set():
with DefaultTestProcessor(wrapper_name = "Flask", application = {"id": "my-id", "version": "my-version"}) as ep:
ep.send_event({ 'kind': 'identify', 'user': user })
ep.flush()
ep._wait_until_inactive()

assert mock_http.request_headers.get('X-LaunchDarkly-Tags') == "application-id/my-id application-version/my-version"

def test_event_schema_set_on_event_send():
with DefaultTestProcessor() as ep:
ep.send_event({ 'kind': 'identify', 'user': user })
Expand Down
14 changes: 14 additions & 0 deletions testing/test_feature_requester.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def test_get_all_data_sends_headers():
assert req.headers['Authorization'] == 'sdk-key'
assert req.headers['User-Agent'] == 'PythonClient/' + VERSION
assert req.headers.get('X-LaunchDarkly-Wrapper') is None
assert req.headers.get('X-LaunchDarkly-Tags') is None

def test_get_all_data_sends_wrapper_header():
with start_server() as server:
Expand Down Expand Up @@ -62,6 +63,19 @@ def test_get_all_data_sends_wrapper_header_without_version():
req = server.require_request()
assert req.headers.get('X-LaunchDarkly-Wrapper') == 'Flask'

def test_get_all_data_sends_tags_header():
with start_server() as server:
config = Config(sdk_key = 'sdk-key', base_uri = server.uri,
application = {"id": "my-id", "version": "my-version"})
fr = FeatureRequesterImpl(config)

resp_data = { 'flags': {}, 'segments': {} }
server.for_path('/sdk/latest-all', JsonResponse(resp_data))

fr.get_all_data()
req = server.require_request()
assert req.headers.get('X-LaunchDarkly-Tags') == 'application-id/my-id application-version/my-version'

def test_get_all_data_can_use_cached_data():
with start_server() as server:
config = Config(sdk_key = 'sdk-key', base_uri = server.uri)
Expand Down
12 changes: 6 additions & 6 deletions testing/test_ldclient_end_to_end.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,12 @@ def test_client_sends_diagnostics():
data = json.loads(r.body)
assert data['kind'] == 'diagnostic-init'

# The TLS tests are skipped in Python 3.3 because the embedded HTTPS server does not work correctly, causing
# The TLS tests are skipped in Python 3.7 because the embedded HTTPS server does not work correctly, causing
# a TLS handshake failure on the client side. It's unclear whether this is a problem with the self-signed
# certificate we are using or with some other server settings, but it does not appear to be a client-side
# problem.
# problem since we know that the SDK is able to connect to secure LD endpoints.

@pytest.mark.skipif(sys.version_info.major == 3 and sys.version_info.minor == 3, reason = "test is skipped in Python 3.3")
@pytest.mark.skipif(sys.version_info.major == 3 and sys.version_info.minor == 7, reason = "test is skipped in Python 3.7")
def test_cannot_connect_with_selfsigned_cert_by_default():
with start_secure_server() as server:
server.for_path('/sdk/latest-all', poll_content())
Expand All @@ -120,7 +120,7 @@ def test_cannot_connect_with_selfsigned_cert_by_default():
with LDClient(config = config, start_wait = 1.5) as client:
assert not client.is_initialized()

@pytest.mark.skipif(sys.version_info.major == 3 and sys.version_info.minor == 3, reason = "test is skipped in Python 3.3")
@pytest.mark.skipif(sys.version_info.major == 3 and sys.version_info.minor == 7, reason = "test is skipped in Python 3.7")
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())
Expand All @@ -134,7 +134,7 @@ def test_can_connect_with_selfsigned_cert_if_ssl_verify_is_false():
with LDClient(config = config) as client:
assert client.is_initialized()

@pytest.mark.skipif(sys.version_info.major == 3 and sys.version_info.minor == 3, reason = "test is skipped in Python 3.3")
@pytest.mark.skipif(sys.version_info.major == 3 and sys.version_info.minor == 7, reason = "test is skipped in Python 3.7")
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())
Expand All @@ -148,7 +148,7 @@ def test_can_connect_with_selfsigned_cert_if_disable_ssl_verification_is_true():
with LDClient(config = config) as client:
assert client.is_initialized()

@pytest.mark.skipif(sys.version_info.major == 3 and sys.version_info.minor == 3, reason = "test is skipped in Python 3.3")
@pytest.mark.skipif(sys.version_info.major == 3 and sys.version_info.minor == 7, reason = "test is skipped in Python 3.7")
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())
Expand Down
16 changes: 16 additions & 0 deletions testing/test_streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ def test_request_properties():
assert req.headers.get('Authorization') == 'sdk-key'
assert req.headers.get('User-Agent') == 'PythonClient/' + VERSION
assert req.headers.get('X-LaunchDarkly-Wrapper') is None
assert req.headers.get('X-LaunchDarkly-Tags') is None

def test_sends_wrapper_header():
store = InMemoryFeatureStore()
Expand Down Expand Up @@ -69,6 +70,21 @@ def test_sends_wrapper_header_without_version():
req = server.await_request()
assert req.headers.get('X-LaunchDarkly-Wrapper') == 'Flask'

def test_sends_tag_header():
store = InMemoryFeatureStore()
ready = Event()

with start_server() as server:
with stream_content(make_put_event()) as stream:
config = Config(sdk_key = 'sdk-key', stream_uri = server.uri,
application = {"id": "my-id", "version": "my-version"})
server.for_path('/all', stream)

with StreamingUpdateProcessor(config, store, ready, None) as sp:
sp.start()
req = server.await_request()
assert req.headers.get('X-LaunchDarkly-Tags') == 'application-id/my-id application-version/my-version'

def test_receives_put_event():
store = InMemoryFeatureStore()
ready = Event()
Expand Down

0 comments on commit c06f80f

Please sign in to comment.