python - py.test 多次测试不同结果

标签 python unit-testing pytest

有什么好的方法可以做到这一点吗?

@pytest.fixture(params=[
    "web01-east.domain.com",
    "web01-master-east.domain.com",
    "web01.domain.com",
])
def patch_socket(request, monkeypatch):
    def gethostname():
        return request.param

    monkeypatch.setattr(socket, 'gethostname', gethostname)


def test__get_pod(patch_socket):
    assert __get_pod() == 'east'

现在这可以工作,但我想让最后一个测试失败,但没关系,因为如果主机名中没有 -east __get_pod() 函数返回未知。

有没有办法告诉 py.test 我想传递测试应该等于的参数列表

[
 ('web01-east.domain.com', 'web')
 ('redis01-master-east.domain.com', 'redis-master')
 ('web01.domain.com', 'Unknown')
]

最佳答案

不要对 socket.gethostname 进行猴子修补,而是让 __get_pod 接受参数。这将使代码更易于测试:

这是一个带有 pytest.mark.parametrize 的示例:

import re

import pytest


def __get_pod(hostname):  # dummy impl.
    hostname = hostname.split('.', 1)[0]
    if '-' not in hostname:
        return 'Unknown'
    hostname = re.sub(r'\d+', '', hostname)
    return hostname.rsplit('-', 1)[0]


@pytest.mark.parametrize(['hostname', 'expected'], [
    ["web01-east.domain.com", 'web'],
    ["redis01-master-east.domain.com", 'redis-master'],
    ["web01.domain.com", 'Unknown'],
])
def test__get_pod(hostname, expected):
    assert __get_pod(hostname) == expected

如果您想通过模拟修补来完成此操作(或者,您无法更改 __get_pod 签名)

import re
import socket

import pytest


def __get_pod():
    hostname = socket.gethostname()
    hostname = hostname.split('.', 1)[0]
    if '-' not in hostname:
        return 'Unknown'
    hostname = re.sub(r'\d+', '', hostname)
    return hostname.rsplit('-', 1)[0]


@pytest.mark.parametrize(['hostname', 'expected'], [
    ["web01-east.domain.com", 'web'],
    ["redis01-master-east.domain.com", 'redis-master'],
    ["web01.domain.com", 'Unknown'],
])
def test__get_pod(monkeypatch, hostname, expected):
    monkeypatch.setattr(socket, 'gethostname', lambda: hostname)
    assert __get_pod() == expected

关于python - py.test 多次测试不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27907040/

相关文章:

java - 如何在 Python 测试框架中实现 TestNG 监听器?

python - 检查提供给另一个可调用参数的参数

python - 是否可以跟踪未分配的值?

python Pandas 。如何使用滚动窗口进行减法

python - 比较 tf.string 和 python 字符串

ruby-on-rails - 由于命名空间冲突而无法测试 RSpec?

javascript - MatDialog 服务单元测试 Angular 6 错误

c# - 如何创建仅在手动指定时运行的单元测试?

python - 通过 Django REST Framework list_route 使用单个 URL 进行 GET 和 POST

javascript - Websocket 是否发送和接收完整消息?