1

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

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

我的代码示例:

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

is_enabled()方法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)

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

谢谢!

4

2 回答 2

0

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

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

于 2019-06-05T11:12:17.607 回答
0

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

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

于 2019-08-12T02:42:07.213 回答