我正在尝试为以下功能创建单元测试:
def my_function(path): #Search files at the given path for file in os.listdir(path): if file.endswith(".json"): #Search for file i'm looking for if file == "file_im_looking_for.json": #Open file os.chdir(path) json_file=json.load(open(file)) print json_file["name"]
但是,我无法成功创建包含文件的伪目录,以使该功能正常运行而不是通过错误进行处理。
下面是到目前为止我所拥有的,但是对我而言不起作用,并且我不确定如何将“ file_im_looking_for”作为文件包含在假目录中。
tmpfilepath = os.path.join(tempfile.gettempdir(), "tmp-testfile") @mock.patch('my_module.os') def test_my_function(self): # make the file 'exist' mock_path.endswith.return_value = True file_im_looking_for=[{ "name": "test_json_file", "type": "General" }] my_module.my_function("tmpfilepath")
对于我要去哪里的任何建议或解决此问题的其他想法,我们将不胜感激!
首先,您忘记将模拟对象传递给测试函数。在测试中使用模拟的正确方法应该是这样的。
@mock.patch('my_module.os') def test_my_function(self, mock_path):
无论如何,您不应嘲笑endswith,而应嘲笑listdir。下面的代码段是一个示例,可能会对您有所帮助。
endswith
listdir
app.py
def check_files(path): files = [] for _file in os.listdir(path): if _file.endswith('.json'): files.append(_file) return files
test_app.py
import unittest import mock from app import check_files class TestCheckFile(unittest.TestCase): @mock.patch('app.os.listdir') def test_check_file_should_succeed(self, mock_listdir): mock_listdir.return_value = ['a.json', 'b.json', 'c.json', 'd.txt'] files = check_files('.') self.assertEqual(3, len(files)) @mock.patch('app.os.listdir') def test_check_file_should_fail(self, mock_listdir): mock_listdir.return_value = ['a.json', 'b.json', 'c.json', 'd.txt'] files = check_files('.') self.assertNotEqual(2, len(files)) if __name__ == '__main__': unittest.main()
编辑:在评论中回答您的问题,您需要从您的应用中模拟json.loads和open。
json.loads
open
@mock.patch('converter.open') @mock.patch('converter.json.loads') @mock.patch('converter.os.listdir') def test_check_file_load_json_should_succeed(self, mock_listdir, mock_json_loads, mock_open): mock_listdir.return_value = ['a.json', 'file_im_looking_for.json', 'd.txt'] mock_json_loads.return_value = [{"name": "test_json_file", "type": "General"}] files = check_files('.') self.assertEqual(1, len(files))
但要记住!如果您过于广泛或难以维护,那么重构API应该是一个好主意。