簡體   English   中英

monkeypatch需要在conftest中導入的函數

[英]monkeypatch a function that needs to be imported in conftest

我正在嘗試使用pytest.monkeypatch修補我在另一個文件中定義的功能。 然后,我需要從依賴此第一個monkeypatch另一個函數中修補一個函數。 這是一個簡單的例子

# class_def.py
class C:
    def __init__(self):
        # Normally, there is something that makes self.p
        # that will use a file that will exist on production
        raise FileNotFoundError

def factory():
    print('in factory')
    return C()

----
# function_def.py
from .class_def import factory

foo = factory()

def bar():
    return 0

----
# conftest.py
from unittest.mock import MagicMock

import pytest

import playground.class_def

@pytest.fixture(autouse=True)
def patch_c(monkeypatch):
    fake_c = MagicMock()
    def factory():
        print('in monkey factory')
        return fake_c
    monkeypatch.setattr('playground.class_def.factory', factory)

from .function_def import bar

# Then I would patch bar

並運行pytest . 將失敗,出現FileNotFoundError 我相信這是因為我在function_def.py的頂層調用foo = factory() 我希望不會發生這種情況,因為我在進行此導入之前正在為factory補丁,但這似乎沒有發生。 有沒有辦法確保此monkeypatch.setattrconftest.py中的conftest.py from .function_def import bar之前conftest.py

另外,文件結構看起來像

playground
|--- __init__.py
|--- conftest.py
|--- class_def.py
|--- function_def

您可以直接訪問要更改的屬性。 您根本不需要Monkeypatch。

這是我的樹:

$ tree .
.
├── a.py
├── b.py
├── __init__.py
└── test_a.py

0 directories, 4 files

a.py

class A:
    def __init__(self):
        raise Exception

def factory():
    return A()

b.py

import a

print(a.factory())

test_a.py

import a


def test_a():
    def fake_factory():
        return 'A'
    a.factory = fake_factory
    import b

它的工作原理是:

$ pytest
=============================================================================================== test session starts ===============================================================================================
platform linux -- Python 3.6.5, pytest-3.5.1, py-1.5.3, pluggy-0.6.0
rootdir: /home/ahorgnies/test/monkeypatch, inifile:
plugins: remotedata-0.2.1, openfiles-0.3.0, doctestplus-0.1.3, arraydiff-0.2
collected 1 item                                                                                                                                                                                                  

test_a.py .                                                                                                                                                                                                 [100%]

============================================================================================ 1 passed in 0.01 seconds =============================================================================================

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM