Python py.test针对不同的结果进行多个测试
有什么好办法可以做到这一点吗Python py.test针对不同的结果进行多个测试,python,unit-testing,pytest,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(s
@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,那么u get_pod函数返回unknown
有没有一种方法可以告诉py.test我想要通过一个参数列表,其中列出了测试应该是什么样子的
[
('web01-east.domain.com', 'web')
('redis01-master-east.domain.com', 'redis-master')
('web01.domain.com', 'Unknown')
]
与monkey patching socket.gethostname不同,让_get_pod接受一个参数。这将使代码更易于测试: 下面是一个例子: 如果你想用mockey补丁或,你不能改变\uuuuuu获得\uu 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
falsetru的答案的另一种选择,更像是您开始喜欢的,是使用来自fixture的返回值。鉴于uuu get_upod看起来像是从falsetru的假人中修改过来的:
def __get_pod():
hostname = socket.gethostname().split('.', 1)[0]
if '-' not in hostname:
return 'Unknown'
hostname = re.sub(r'\d+', '', hostname)
return hostname.rsplit('-', 1)[0]
您可以通过以下方式进行测试:
@pytest.fixture(params=[
('web01-east.domain.com', 'web'),
('redis01-master-east.domain.com', 'redis-master'),
('web01.domain.com', 'Unknown')
])
def patch_socket(request, monkeypatch):
def gethostname():
return request.param[0]
monkeypatch.setattr(socket, 'gethostname', gethostname)
return request.param[1]
def test__get_pod(patch_socket):
assert __get_pod() == patch_socket
这需要对原始代码进行较少的更改
@pytest.fixture(params=[
('web01-east.domain.com', 'web'),
('redis01-master-east.domain.com', 'redis-master'),
('web01.domain.com', 'Unknown')
])
def patch_socket(request, monkeypatch):
def gethostname():
return request.param[0]
monkeypatch.setattr(socket, 'gethostname', gethostname)
return request.param[1]
def test__get_pod(patch_socket):
assert __get_pod() == patch_socket