【问题标题】:How to clean up downloaded files in Django view testing?如何在 Django 视图测试中清理下载的文件?
【发布时间】:2021-01-18 16:45:12
【问题描述】:

我有一个 Django 视图,它返回一个要下载的文件 (response['Content-Disposition'] = 'attachment; filename=' + filename) 以响应 POST,因为文件的内容取决于表单提交的数据。在为此视图设置测试时,我很难找到一种干净的方式来下载文件并确保它在之后被清理,因为 TestCase 行为并不是免费的。目前我有以下:

with tempfile.TemporaryDirectory(dir='.') as temp_dir:
    os.chdir(temp_dir)
    response = self.client.post(...)
    # Do asserts of the downloaded file/response object here
    os.chdir('..')

这样做的好处是创建了一个临时目录,将文件下载到该目录,并在测试完成时删除整个目录。此外,如果任何断言失败,临时目录(和内容)将保留,但这特别脆弱,并且可能由于目录更改而破坏其他测试。

有没有更好的方法/模式来完成这个?

【问题讨论】:

    标签: python django testing automated-tests


    【解决方案1】:

    您正在使用 TestCase,我认为您用于此测试的文件名具有固定名称。 TestCase 提供了两种方法(setUp 和 tearDown)来帮助您在每次测试之前和之后执行操作。

    setUp > test_first_test > tearDown

    setUp > test_second_test > tearDown

    等等

    class Mytests(TestCase):
    
        def test_first_test(self): 
            your definition here
    
        def test_second_test(self): 
            your definition here
    
        def tearDown(self):
            os.system('rm -rf ./mytestfile.extension') # command for linux
    

    【讨论】:

    • 正确,我的文件名在测试的上下文中是固定的,这个解决方案肯定会起作用。不过感觉有点不对劲,因为该文件是在我项目中的其他文件旁边的目录中创建/删除的,并且使用 tempfile.TemporaryDirectory 至少为此提供了一点点隔离。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多