我有以下要测试的文件
manage.py
import socket
def __get_pod():
try:
pod = socket.gethostname().split("-")[-1].split(".")[0]
except:
pod = "Unknown"
return pod下面是我的测试脚本测试/ test _manage.py e.py
import sys
import pytest
sys.path.append('../')
from manage import __get_pod
#
# create a fixture for a softlayer IP stack
@pytest.fixture
def patch_socket(monkeypatch):
class my_gethostname:
@classmethod
def gethostname(cls):
return 'web01-east.domain.com'
monkeypatch.setattr(socket, 'socket', my_gethostname)
def test__get_pod_single_dash():
assert __get_pod() == 'east'所以,当我尝试测试它时,当我想要它使用夹具时,它承载了我的笔记本主机名。是否可以在另一个文件中使用夹具?
$ py.test -v
======================================================================= test session starts ========================================================================
platform darwin -- Python 2.7.8 -- py-1.4.26 -- pytest-2.6.4 -- /usr/local/opt/python/bin/python2.7
collected 1 items
test_manage.py::test__get_pod_single_dash FAILED
============================================================================= FAILURES =============================================================================
____________________________________________________________________ test__get_pod_single_dash _____________________________________________________________________
def test__get_pod_single_dash():
> assert __get_pod() == 'east'
E assert '2' == 'east'
E - 2
E + east发布于 2015-01-11 16:13:26
首先,您需要修改测试函数,以便它接受一个名为patch_socket的参数。
def test__get_pod_single_dash(patch_socket):
assert __get_pod() == 'east'这意味着py.test将调用您的夹具,并将结果传递给您的函数。这里最重要的是确实有人打电话给我。
第二件事是,您的monkeypatch调用将一个名为socket.socket的变量设置为my_gethostname,这不会影响您的函数。将patch_socket简化为:
import socket
@pytest.fixture
def patch_socket(monkeypatch):
def gethostname():
return 'web01-east.domain.com'
monkeypatch.setattr(socket, 'gethostname', gethostname)然后让测试通过。
https://stackoverflow.com/questions/27888562
复制相似问题