通过模拟测试open
with a FileNotFoundError
raises AttributeError: __exit__
。为什么会发生这种情况以及我可以采取什么措施来解决它?
以下代码打开一个简单的文本文件。如果文件丢失,它会生成一个默认值。它已经通过定期运行进行了检查,并且看起来运行良好。
so_main.py
import os
import so_config
def load_savelocation():
path = os.path.join(so_config.ROOT, so_config.SAVELOCATION_FN)
savelocation_path = os.path.normpath(path)
try:
with open(savelocation_path) as f:
so_config.SAVELOCATION_PATH = f.readline()
except FileNotFoundError:
so_config.SAVELOCATION_PATH = so_config.ROOT
so_config.py
import os
ROOT, _ = os.path.split(__file__)
SAVELOCATION_PATH = None
SAVELOCATION_FN = 'savelocation.ini'
单元测试则是另一回事。我曾经嘲笑过open
命令输入so.main
. test_so_main.py
有两个测试:一个用于正常打开存在的文件,第二个用于测试FileNotFoundError
处理。
常规文件打开第一次测试test_read_path_from_disk_file_into_config_py
工作正常。
第二次测试失败是因为FileNotFoundError
raises AttributeError: __exit__
。
我可以设置self.mock_open.return_value
to FileNotFoundError
或者我可以将其设置为'garbage'
。这没有什么区别。
测试so_main.py
import unittest
import unittest.mock as mock
import so_config
import so_main
class TestReadSaveLocation(unittest.TestCase):
def setUp(self):
self.savelocation_path = so_config.SAVELOCATION_PATH
self.root = so_config.ROOT
so_config.ROOT = 'program root'
p = mock.patch('so_main.open')
self.mock_open = p.start()
self.addCleanup(p.stop)
def tearDown(self):
so_config.SAVELOCATION_PATH = self.savelocation_path
so_config.ROOT = self.root
def test_read_path_from_disk_file_into_config_py(self):
self.mock_open().__enter__().readline.return_value = 'data files location'
so_main.load_savelocation()
self.assertEqual('data files location', so_config.SAVELOCATION_PATH)
def test_missing_file_defaults_savelocation_to_program_root(self):
self.mock_open.return_value = FileNotFoundError
so_main.load_savelocation()
self.assertEqual('program root', so_config.SAVELOCATION_PATH)
我正在 Windows 7 计算机上通过 PyCharm 2016.2.1 运行 Python 3.5.2。