微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python-来自另一个文件的py.test固定装置

我有以下文件要测试

manage.py

import socket
def __get_pod():
    try:
        pod = socket.gethostname().split("-")[-1].split(".")[0]
    except:
        pod = "UnkNown"

    return pod

这是我的测试脚本
测试/ test_manage.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

解决方法:

您需要做的第一件事就是修改测试函数,使其采用名为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)

然后允许测试通过.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐