测试档案创建和发送文件

时间:2019-12-30 14:30:36

标签: python python-3.x unit-testing flask

在Flask应用程序中,存在一条路由/getArchive/。调用路由时,将执行在目录中搜索文件,创建zip存档并发送存档文件的操作。

@app.route('/getArchive/')
def get_archive():
    with ZipFile('archive.zip', 'w') as zipObj:
        for dirpath, dirnames, filenames in os.walk("archive"):
            for filename in filenames:
                filePath = os.path.join(dirpath, filename)
                zipObj.write(filePath)
    return send_from_directory(directory="",
                               filename='archive.zip',
                               as_attachment=True,
                               cache_timeout=0.0)

我想为此路线创建单元测试:检查zipObj.writesend_from_directory是否用正确的参数调用。

def test_get_archive(self):
    with app.test_client() as c:
        with patch('os.walk') as mock_walk:
            mock_walk.return_value = [
                ('archive', [], ['1.txt', '2.doc', '3.mp4']),
            ]
            mock_ZipFile = Mock()
            with patch("zipfile.ZipFile", mock_ZipFile, create=True):
                mock_zip_write = Mock()
                with patch("zipfile.ZipFile.write", mock_zip_write, create=True):
                    mock_send_from_directory = Mock()
                    with patch("flask.send_from_directory", mock_send_from_directory, create=True):
                        rv = c.get('/getArchive/')
                        self.assertTrue(mock_zip_write.call_args_list[0][0][0] == "archive\1.txt")
                        self.assertTrue(mock_zip_write.call_args_list[1][0][0] == "archive\2.doc")
                        self.assertTrue(mock_zip_write.call_args_list[2][0][0] == "archive\3.mp4")

                        self.assertTrue(mock_send_from_directory.call_args_list[0][0][0] == "")
                        self.assertTrue(mock_send_from_directory.call_args_list[0][0][1] == 'archive.zip')
                        self.assertTrue(mock_send_from_directory.call_args_list[0][0][2])
                        self.assertTrue(mock_send_from_directory.call_args_list[0][0][3] == 0.0)

以上提供的测试无效。原因之一是FileNotFoundError。它找不到archive\\1.txt(我相信不是双反斜杠的原因)。您可以在test_get_archive中进行更改以使其正常工作还是提供可以测试get_archive的工作代码?也欢迎对测试的想法提出建议。

0 个答案:

没有答案