【问题标题】:Mocking specific method in tests not working在测试中模拟特定方法不起作用
【发布时间】:2019-11-05 11:27:11
【问题描述】:

我正在使用 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

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

【问题讨论】:

    标签: python python-unittest


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      相关资源
      最近更新 更多