2016-08-12 1 views
2

openFileNotFoundErrorと偽装してテストすると、AttributeError: __exit__が発生します。なぜこれが起こっているのですか、それを修正するために何ができますか?なぜ「オープン」してFileNotFoundErrorを返すのですか?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には2つのテストがあります.1つは通常のファイルを開くためのもので、もう1つはFileNotFoundErrorの処理をテストするものです。

通常のファイルオープンtest_read_path_from_disk_file_into_config_pyの最初のテストは正常に動作します。

AttributeError: __exit__になるため、2番目のテストは失敗します。 self.mock_open.return_valueFileNotFoundErrorに設定するか、'garbage'に設定することができます。それは何の違いもありません。

test_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を実行していますよ。

答えて

2

あなたはに戻り、に戻り、の代わりにを返します。

side_effectdocs)を使用してみてください:

self.mock_open.side_effect = FileNotFoundError 
関連する問題