python-3.x - pytest - 默认 fixture 参数值

标签 python-3.x pytest

我在 pytest 中编写了一个 fixture ,它没有参数化,但被很多测试使用。后来我需要参数化这个 fixture 。

为了不用mark.parametrize我做了以下所有旧测试:

def ldap_con(request):
    try:
        server_name = request.param
    except AttributeError:
        server_name = "ldaps://my_default_server"
    c = Connection(server_name, use_ssl=True)
    yield c
    c.unbind()

现在我可以同时拥有:
def test_old(ldap_con):
    run_test_to_default_connection(ldap_con)


@pytest.mark.parametrize('ldap_con', ['mynewserver'], indirect=True)
def test_new(ldap_con):
    run_test_to_new_connection(ldap_con)

该解决方案有几个缺点:
  • 我发现了一个任意的属性错误(可能还有另一个)
  • 它不考虑命名参数
  • 读者不清楚是否存在默认值

  • 是否有标准方法来定义 fixture 参数的默认值?

    最佳答案

    间接参数化很麻烦。为了避免这种情况,我通常编写fixture 以便它返回一个函数。我最终会这样写:

    def ldap_con():
        def _ldap_con(server_name="ldaps://my_default_server"):
            c = Connection(server_name, use_ssl=True)
            yield c
            c.unbind()
        return _ldap_con
    
    def test_old(ldap_con):
        run_test_to_default_connection(ldap_con())
    
    
    @pytest.mark.parametrize('server', ['mynewserver'])
    def test_new(server):
        run_test_to_new_connection(ldap_con(server))
    

    关于python-3.x - pytest - 默认 fixture 参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54109759/

    相关文章:

    python - 将for循环内部和外部的print stmt连接成python中的一个句子

    python-3.x - headless chrome 网络驱动程序太慢,无法下载文件

    python-3.x - 将属性添加到 junit xml pytest

    python - Pytest 未运行任何测试

    Python pytest mock 失败,函数调用断言为 "assert None"

    python - 无法在pytest中使用pytest-mock同时验证构造和实例方法调用

    python - 放大后无法获取任何元素的屏幕截图

    python - 将 2 个字节从字节数组转换为一个整数

    python - Pygame 显示空白的白色窗口

    python - 在 python 中使用假设和 py.test 测试复合策略,我必须一次测试它们吗?