【问题标题】:Python - unittest, mock, patch, inputPython - 单元测试、模拟、补丁、输入
【发布时间】:2019-04-09 21:04:02
【问题描述】:

所以我的代码有问题。 文件 1:

class Abc(object):
...
def function1(self):
 #do something
def function2(self):
 x = input()
 return x+1

现在我正在尝试测试函数 2,所以我为它编写了一个测试,但我不知道我做错了什么:

from unittest.mock import patch
import unittest
from file1 import *

class TestBackend(unittest.TestCase):

    def test_mode_first(self):
        self.assertEqual(Abc().funcion1(), 30)

    @patch('funcion2.input', create=True)
    def test_mode_second(self, mocked_input):
        mocked_input.side_effect = ["QWE"]
        result = Abc().funcion2()
        self.assertEqual(result, 10)

if __name__ == '__main__':
    unittest.main()

我得到 ModuleNotFoundError: No module named 'function2' 那我在这里做错了什么?

感谢您的帮助:)

【问题讨论】:

标签: python unit-testing mocking return patch


【解决方案1】:

你得到ModuleNotFoundError 因为funcion2 不是一个模块。 patch doc 很清楚这一点:

target 应该是格式为“package.module.ClassName”的字符串。这 导入目标并将指定的对象替换为新的 对象,因此目标必须可以从您所在的环境中导入 调用 patch() 从。装饰时导入目标 函数被执行,而不是在装饰时。

当使用文件所在目录中的python3 -m unittest discover 执行时,这对我有用。

顺便说一句,您的示例中有几个拼写错误,例如Abc().funcion2(),注意funcion2 中缺少的t。

另外,尽量不要使用from … import *:https://docs.quantifiedcode.com/python-anti-patterns/maintainability/from_module_import_all_used.html#using-wildcard-imports-from-import

# file1.py
class Abc(object):
    def function1(self):
        return 30

    def function2(self):
        x = input()
        return x + "1"


# test_file1.py
import unittest
from unittest.mock import patch
from file1 import Abc


class TestBackend(unittest.TestCase):
    def test_mode_first(self):
        self.assertEqual(Abc().function1(), 30)

    @patch('builtins.input')
    def test_mode_second(self, mocked_input):
        mocked_input.return_value = "QWE"

        result = Abc().function2()
        self.assertEqual(result, "QWE1")

【讨论】:

    猜你喜欢
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2020-12-09
    相关资源
    最近更新 更多