pythonunit-testinglaunchdarkly

How to mock feature toggle without connection to Launch Darkly?


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!


Solution

  • 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