Python 3.x Python Unittest在运行测试时没有隔离修补程序

Python 3.x Python Unittest在运行测试时没有隔离修补程序,python-3.x,unit-testing,python-unittest,Python 3.x,Unit Testing,Python Unittest,我有两个测试,每个测试对代码中使用的方法的返回值进行不同的修补。当我单独运行测试时,它们通过了。如果我同时运行它们,我可以看到unittest在第二次测试中使用了错误的补丁 我尝试过为补丁使用decorator语法,我甚至尝试过将测试更改为pytest,我还尝试过使用nose运行测试。我遇到了同样的问题,第二个测试的结果是“foo”而不是“bar” 有没有办法按顺序运行测试?我错过了什么?我们是否可以假设我无法更改正在测试的类,例如使用依赖项注入而不是修补。让我们假设我必须使用补丁 import

我有两个测试,每个测试对代码中使用的方法的返回值进行不同的修补。当我单独运行测试时,它们通过了。如果我同时运行它们,我可以看到unittest在第二次测试中使用了错误的补丁

我尝试过为补丁使用decorator语法,我甚至尝试过将测试更改为pytest,我还尝试过使用nose运行测试。我遇到了同样的问题,第二个测试的结果是“foo”而不是“bar”

有没有办法按顺序运行测试?我错过了什么?我们是否可以假设我无法更改正在测试的类,例如使用依赖项注入而不是修补。让我们假设我必须使用补丁

import unittest
from unittest.mock import patch
from unittest.mock import MagicMock
class TestMember(unittest.TestCase):
    def setUp(self):
        pass

    def test_1(self):
        test_json = {
            "something-123": []
        }

        mock = MagicMock()
        mock.return_value = test_json
        with patch('imported_module.get_json', mock):
            from some_module import some_method
            result = some_method()
            self.assertEqual(result, "foo")

    def test_2(self):
        test_json = {
            "something-else-123": []
        }

        mock = MagicMock()
        mock.return_value = test_json
        with patch('imported_module.get_json', mock):
            from some_module import some_method
            result = some_method()
            self.assertEqual(result, "bar")

if __name__ == '__main__':
    unittest.main()
我正在测试的课程:

from imported_module import get_json

def some_method():
    json_obj = get_json()
    if "something-123" in json_obj.keys():
        return "foo"
    else:
        return "bar"
为完整起见,以下是导入的_模块代码:

def get_json():
    return {}

您需要在使用json的地方(
some\u module
),而不是在定义json的地方(
imported\u module
)进行修补。这是因为
patch()

如果您更新了
补丁()
,则测试将按预期通过:

with patch('some_module.get_json', mock):
有关在何处进行修补的详细信息