python - 将整数与MagicMock进行比较在python的unittest中不起作用

标签 python mocking python-unittest magicmock

我有一个类,它使用类变量来选择要执行的逻辑。

#in file1:

class SomeHelper():
    def __init__(self):
        self.my_var = 0

#in file2: 
import file1
class MyClass():
    ...
    ...
    def calculate():
        inst = file1.SomeHelper()
        if x > inst.my_var:
           etc etc

我正在编写一个单元测试并在另一个文件中模拟 SomeHelper():

from file 2 import MyClass
# tried both
@patch('file2.file1') OR @patch('file2.file1.SomeHelper')
def test_calculate(self, mock_helper):
    mock_helper.my_var = 0
    to_test = MyClass.calculate()

我收到以下错误:

TypeError: '>' not supported between instances of 'MagicMock' and 'int'.

我以为我在修补模块后定义了 my_var

最佳答案

这是Python 3.7.5的单元测试解决方案:

file1.py:

class SomeHelper():
    def __init__(self):
        self.my_var = 0

file2.py:

import file1


class MyClass():
    @classmethod
    def calculate(cls):
        x = 1
        inst = file1.SomeHelper()
        if x > inst.my_var:
            return True
        return False

test_file2.py:

import unittest
from unittest.mock import patch
from file2 import MyClass


class TestMyClass(unittest.TestCase):
    @patch('file2.file1')
    def test_calculate(self, mock_file1):
        inst = mock_file1.SomeHelper.return_value
        inst.my_var = 0.5
        to_test = MyClass.calculate()
        self.assertTrue(to_test)
        mock_file1.SomeHelper.assert_called_once()

    @patch('file2.file1')
    def test_calculate_2(self, mock_file1):
        inst = mock_file1.SomeHelper.return_value
        inst.my_var = 2
        to_test = MyClass.calculate()
        self.assertFalse(to_test)
        mock_file1.SomeHelper.assert_called_once()


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

带有覆盖率报告的单元测试结果:

..
----------------------------------------------------------------------
Ran 2 tests in 0.002s

OK
Name                                       Stmts   Miss  Cover   Missing
------------------------------------------------------------------------
src/stackoverflow/50242955/file1.py            3      1    67%   3
src/stackoverflow/50242955/file2.py            8      0   100%
src/stackoverflow/50242955/test_file2.py      16      0   100%
------------------------------------------------------------------------
TOTAL                                         27      1    96%

源代码:https://github.com/mrdulin/python-codelab/tree/master/src/stackoverflow/50242955

关于python - 将整数与MagicMock进行比较在python的unittest中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50242955/

相关文章:

SUDS 的 C# 版本?

java - lateinit 属性模拟对象尚未初始化

ruby - RSpec - 如何模拟存储过程

python-3.x - Python 模拟 : missing 1 required positional argument

Python 3 - CSV 阅读器到达文件末尾后,CSV 编写器循环不会关闭

python - 在pyqt中选择单选按钮时更改lineEdit的文本

python - App Engine Python - 如何确保用户使用唯一的用户名注册

python - 在单元测试中模拟 API 调用

Python:在 VS Code 中发现单元测试失败

Python:如何从unittest模块访问测试结果变量