Перемешивание функции в функции - PullRequest
1 голос
/ 05 июля 2019

Я пытаюсь смоделировать пару вызовов функций в функции, чтобы я мог проверить их поведение.

Я пробовал несколько разных подходов, показанных в коде, но функция should_be_mocked никогда не подвергается насмешкам,Я использую python3, PyCharm, среда тестирования установлена ​​в pytest

test.py

from unittest import mock, TestCase
from unittest.mock import patch

from path import should_be_mocked
from other_path import flow


def test_flow(monkeypatch):
    def ret_val():
        return should_be_mocked("hi")

    monkeypatch.setattr('path', "should_be_mocked", ret_val())

    assert flow() == "hi"


def test_flow2(monkeypatch):
    monkeypatch.setattr('path.should_be_mocked', lambda x: "hi")
    assert flow() == "hi"


@patch('path.should_be_mocked')
def test_flow3(mocker):
    mocker.return_value = "hello returned"
    flow()
    mocker.test.assert_called_with("hello")


class TestStuff(TestCase):
    @patch('path.should_be_mocked')
    def test_flow4(self, mocker):
        mocker.return_value = "hello returned"
        flow()
        mocker.test.assert_called_with("hello")

path

def should_be_mocked(hello):
    return hello

other_path

def flow():
    # business logic here
    return should_be_mocked("hello")

Все тесты не пройдены и возвращают значение из реальной функции.Где я ошибся?

Добавлена ​​информация.

Попытка изменить путь к other_path приводит к

E       AttributeError: 'other_path' has no attribute 'should_be_mocked'

1 Ответ

1 голос
/ 08 июля 2019

Я отвечаю на свой вопрос здесь.Благодаря @hoefling я узнал, что путь был ошибочным.Но я не смог запустить первый тестовый сценарий.Остальные работали после их доработки следующим образом.

def test_flow2(monkeypatch):
    monkeypatch.setattr('other_path', lambda x: "hi")
    assert flow() == "hi"


@patch('other_path.should_be_mocked')
def test_flow3(mocker):
    flow()
    mocker.assert_called_with("hello")


class TestStuff(TestCase):
    @patch('other_path.should_be_mocked')
    def test_flow4(self, mocker):
        flow()
        mocker.assert_called_with("hello")

Первый не работал, второй работал после изменения пути.3-му и 4-му необходимо удалить .test из оператора assert

...