在测试中模拟特定方法不起作用

Mocking specific method in tests not working

我正在使用 Python 3.5.2。我试图在不同的测试用例下模拟相同的方法,但似乎 sys.argv 没有被模拟。

我也尝试过使用 @patch 装饰器,但没有用。

main.py:

from os import path
from sys import argv

globals = {}

def get_target_dir():
    if len(argv) < 2 or not path.exists(argv[1]):
        print("You must specify valid full path of instances directory as command line argument.")
        exit(1)
    globals['TARGET_DIR'] = argv[1] + ('/' if argv[1][-1] != '/' else '')

tests.py:

import unittest
from unittest.mock import patch
from main import get_target_dir, globals

class TestMain(unittest.TestCase):
    def test_correct_target_dir(self):
        argv = [None, '/test']
        with patch('sys.argv', argv), patch('os.path.exists', lambda _: True):
            get_target_dir()
            assert globals['TARGET_DIR'] == argv[1] + '/'

    def test_invalid_target_dir(self):
        argv = [None, '/']
        with patch('sys.argv', argv), patch('os.path.exists', lambda _: False):
            try:
                get_target_dir()
            except SystemExit:
                assert True
            else:
                assert False

当我 运行 测试时,由于上述问题,它们无法按预期工作。

我意识到我不知道 gotchas,所以我错误地将 sys.argv 方法包含在 main.py 中 - 在将导入 from sys import argv 替换为 import sys(并在代码中进一步将 sys. 放在 argv 之前)一切都开始工作了。