python - 来自另一个文件的 pytest fixture

标签 python unit-testing pytest

我有以下文件要测试

管理.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'

因此,当我尝试测试它托管我的笔记本电脑主机名时,当我希望它使用 fixture 时......是否可以在另一个文件中使用 fixture ?

$ 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 将调用您的 fixture ,并将结果传递给您的函数。这里重要的是它确实被调用了。

第二件事是您的 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)

然后允许测试通过。

关于python - 来自另一个文件的 pytest fixture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27888562/

相关文章:

java - Mockito - 返回通用类型(多个)

python - 使用 py.test xdist 控制测试的分布

python - 如何在 Selenium 中避免 StaleElementReferenceException - Python

Python:如何使用 rdflib 将 Dbpedia 中的信息添加到我的图表中?

python - 使用 scikit Pipeline 测试模型但仅预处理一次数据

reactjs - Jest/ enzyme 单元测试 : How to pass store to shallow component that uses redux 4 and react-redux 6 connect function

java - java后期开发的自动化测试工具

python - 神秘的 "cannot import name"异常

python - 如何使用命令行在pytest中传递多个参数?

python - 模拟导入失败