【问题标题】:How to mock feature toggle without connection to Launch Darkly?如何在不连接到 Launch Darkly 的情况下模拟功能切换?
【发布时间】:2019-10-18 16:13:51
【问题描述】:

我有一个新的代码行,它必须被一个功能切换包围。由于它是一项服务(Flask 应用程序),它在启动时启动其所有连接以及与外部源的相关集成 - 在执行单元测试时我没有运行 LaunchDarkly 的实例。

有没有一种简单的方法来模拟和预定义 Python 中单元测试/集成测试的功能切换?我正在使用 pytest 编写单元测试。

我的代码示例:

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

is_enabled() 方法实现:

@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)

当运行应用程序 FeatureToggle.ld_client 时,使用适当的 api 密钥启动以暗启动,然后允许我使用他们的 variation() 方法。
我知道当没有ld_client 的实例时,我可以更改我的is_enabled() 方法以返回预定义的值,但我正在寻找更优雅的方法。

谢谢!

【问题讨论】:

    标签: python unit-testing launchdarkly


    【解决方案1】:

    因此,在调查并建议我的同事之后,这可以通过使用 unittest.mock 库来完成。

    当我有完整的工作解决方案时,我会更新答案

    【讨论】:

    • 那么,你找到了吗?
    【解决方案2】:

    我还要补充一点,除了使用模拟库之外,您还可以实例化客户端以从文件 [1] 中读取,而不是连接到 LaunchDarkly API。通过这种方式,您可以获得一组可用于测试目的的预先确定的测试值。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-18
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      相关资源
      最近更新 更多