2017-02-20 40 views
0

我有一个函数,首先检查一个txt文件是否存在,如果它没有创建一个。如果txt文件已经存在,它会读取信息。我正在尝试编写单元测试来检查函数的逻辑是否正确。我想修补文件的存在,文件的创建和文件的读取。 的功能进行测试看起来是这样的:如何在unitest框架中模拟创建文本文件python2.7?

import json 
import os.path 

def read_create_file(): 

    filename = 'directory/filename.txt' 
    info_from_file = [] 

    if os.path.exists(filename): 

     with open(filename, 'r') as f: 
      content = f.readlines() 
      for i in range(len(content)): 
       info_from_file.append(json.loads(content[i])) 
     return info_from_file 

    else: 
     with open(filename, 'w') as f: 
      pass 

     return [] 

的单元测试是这样的:

import unittest 
import mock 
from mock import patch 


class TestReadCreateFile(unittest.TestCase): 

    def setUp(self): 
     pass 

    def function(self): 
     return read_create_file() 

    @patch("os.path.exists", return_value=False) 
    @mock.patch('directory/filename.txt.open', new=mock.mock_open()) 
    def test_file_does_not_exist(self, mock_existence, mock_open_patch): 
     result = self.function() 
     self.assertEqual(result, (True, [])) 

错误:导入错误:不支持按文件名导入。

或像这样:

import unittest 
import mock 
from mock import patch 

@patch("os.path.exists", return_value=False) 
def test_file_not_exist_yet(self, mock_existence): 
    m = mock.mock_open() 
    with patch('__main__.open', m, create=True): 
     handle = open('directory/filename.txt', 'w') 
    result = self.function() 

    self.assertEqual(result, (True, {})) 

错误: IO错误:[错误2]没有这样的文件或目录: '目录/ FILENAME.TXT'

作为一个新手,我似乎无法让我的头绕解决方案,任何帮助,不胜感激。

谢谢

回答

0

你嘲笑os.path.exists错误。当你从被测文件中修补你的补丁时。

@patch("path_to_method_under_test.path.exists", return_value=False) 
def test_file_not_exist_yet(self, mock_existence):