2

I have a new code line which has to be surrounded with a feature toggle. Since it is a service (Flask application) which initiates all its connections and relevant integration with external sources on the start-up - I have no instance of LaunchDarkly running when executing unit-tests.

Is there a simple way to mock and predefine a feature toggle for unit-tests/integration-tests in Python? I am using pytest for writing the unit-tests.

Example of my code:

if FeatureToggle.is_enabled("my-feature-toggle-name"):
     *my code logic*

the is_enabled() method impl:

@staticmethod
def is_enabled(flag_name: str, user_key: str=None, custom_params: dict=None) -> bool:
    if user_key is None:
        user_key = 'defaut_user_key'

    return FeatureToggle.ld_client.variation(flag_name, {"key": user_key, "custom": custom_params}, False)

When running the application FeatureToggle.ld_client is initiated with a proper api-key to launch darkly and then allows me to use their variation() method.
I understand that I can change my is_enabled() method to return predefined value when there is not instance of ld_client but I am looking for more elegant way to do it.

Thanks!

andreygold
  • 192
  • 2
  • 13

2 Answers2

0

So after investigating and advising my colleagues this can be done by using unittest.mock library.

I will update the answer when I will have full working solution

andreygold
  • 192
  • 2
  • 13
0

I would also add that in addition to using a mocking library, you can also instantiate the client to read from a file[1] instead of connecting to the LaunchDarkly API. This way you can have a pre-determined set of test values that you can use for testing purposes.

[1] https://launchdarkly-python-sdk.readthedocs.io/en/latest/api-integrations.html?highlight=test#ldclient.integrations.Files

levlaz
  • 101
  • 2