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



我使用的是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之前(,一切都开始工作了。

最新更新