【问题标题】:How delete image files after unit test finished?单元测试完成后如何删除图像文件?
【发布时间】:2018-02-26 15:26:03
【问题描述】:

在单元测试中,我在开始时创建了 3 个对象(文章)。测试完成后,我注意到media_root 文件夹中有 3 张图片。

问题:如何删除测试完成后创建的图像?

P.S.我尝试使用下一个代码,但它删除了media_root 文件夹。

def tearDown(self):
        rmtree(settings.MEDIA_ROOT, ignore_errors=True)

注意:方法 test_article_form_validtest_article_crud 中的问题。

tests.py:

class ArticleTestCase(TestCase):
    def setUp(self):  
        self.image = open(os.path.join(BASE_DIR, 'static/images/tests/image.jpg'), "r")

    def test_article_form_valid(self):
        data = {
            'head': 'TEXT',
        }
        files_data = {
            'image': SimpleUploadedFile(
                name=self.image.name,
                content=self.image.read(),
                content_type='image/jpeg'
            )
        }
        form = ArticleForm(data=data, files=files_data)
        self.assertTrue(form.is_valid())  <-- ERROR

    def test_article_crud(self):
        response = self.client.get(reverse("article:article_create"))
        self.assertEquals(response.status_code, 200)
        response = self.client.post(
            reverse("article:article_create"),
            data={
                'head': 'TEST',
                'image': self.image
            },
            follow=True,
            format='multipart'
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Article.objects.all().count(), 1) <-- ERROR

    def test_article_view(self):
        first_article = Article.objects.create(
            pk=150,
            head='First',
            image=SimpleUploadedFile(
                name=self.image.name,
                content=self.image.read(),
                content_type='image/jpeg'
            )
        )

        second_article = Article.objects.create(
            pk=160,
            head='Second',
            image=SimpleUploadedFile(
                name=self.image.name,
                content=self.image.read(),
                content_type='image/jpeg'
            )
        )

        third_article = Article.objects.create(
            pk=170,
            head='Third',
            image=SimpleUploadedFile(
                name=self.image.name,
                content=self.image.read(),
                content_type='image/jpeg'
            )
        )
        [***]

错误

FAIL: test_article_crud (article.tests.ArticleTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/nurzhan/CA/article/tests.py", line 55, in test_article_crud
    self.assertEqual(Article.objects.all().count(), 1)
AssertionError: 0 != 1

======================================================================
FAIL: test_article_form_valid (article.tests.ArticleTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/nurzhan/CA/article/tests.py", line 117, in test_article_form_valid
    self.assertTrue(form.is_valid())
AssertionError: False is not true

【问题讨论】:

    标签: python django python-2.7 unit-testing django-1.11


    【解决方案1】:

    我找到了这个article,它对我有用

    import shutil, tempfile
    from django.test import TestCase, override_settings
    
    MEDIA_ROOT = tempfile.mkdtemp()
    
    @override_settings(MEDIA_ROOT=MEDIA_ROOT)
    class MeuPetTest(TestCase):
        @classmethod
        def tearDownClass(cls): 
            shutil.rmtree(MEDIA_ROOT, ignore_errors=True)
            super().tearDownClass()
    

    【讨论】:

    • 它不能正常工作,它会在新的 MEDIA_ROOT 中创建文件,是的,但也在项目的 MEDIA_ROOT 中,至少对我来说是这样。
    【解决方案2】:

    在python中使用tempfile模块,在TestCasesetUp()方法中作为settings.MEDIA_ROOT使用,

    from django.conf import settings
    import tempfile
    
    def setUp(self):
        settings.MEDIA_ROOT = tempfile.mkdtemp()
    

    那么,测试中创建的文件会在测试完成后自动删除。

    更新

    那么,测试中创建的文件不会在测试完成后自动删除,所以测试完成后不要忘记删除临时目录。

    【讨论】:

    • 但我认为 OP 想要保留该目录,只需从其中删除文件即可。
    • @SiHa 绝对正确!我只需要删除在我的测试中创建的图像文件。不要触摸文件夹。您还有其他想法吗?
    • 测试的重点是在不影响实际数据库和测试的情况下模拟某个功能,不是吗?如果您使用tempfile 模块,您不必创建实际的图像对象,而是为它们创建一个模拟并进行测试,然后在测试后,对象将自动删除。甚至没有关于删除文件的问题,没有创建文件,在运行时创建和销毁它们。
    • @zaidfazil 您的代码在我的其他测试中引发错误。我用错误消息和一些代码更新了我的帖子。你能再检查一次吗?你知道为什么我在你的代码之后会出现这样的错误吗?
    • “测试完成后会自动删除测试中创建的文件”这不是真的。文档指出The user of mkdtemp() is responsible for deleting the temporary directory and its contents when done with it.
    【解决方案3】:

    对我来说最好的解决方案是编写一个删除图像的函数并将其添加到测试类的 tearDown 方法中。

    def delete_test_image():
        images_path = os.path.join(PROJECT_PATH, 'media/images')
        files = [i for i in os.listdir(images_path) 
                 if os.path.isfile(os.path.join(images_path, i))
                 and i.startswith('test_image_')]
    
        for file in files:
            os.remove(os.path.join(images_path, file))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多