有什么好的方法可以做到这一点吗?
@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/