栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python:使用文件进行模拟或伪造目录创建以进行单元测试

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python:使用文件进行模拟或伪造目录创建以进行单元测试

首先,您忘记将模拟对象传递给测试函数。在测试中使用模拟的正确方法应该是这样的。

@mock.patch('my_module.os')def test_my_function(self, mock_path):

无论如何,您不应嘲笑

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 unittestimport mockfrom app import check_filesclass 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

@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应该是一个好主意。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659885.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号