python 为什么使用SimpleUploadedFile对图像字段进行单元测试会创建多个图像?

6ljaweal  于 2023-04-10  发布在  Python
关注(0)|答案(1)|浏览(87)

这是tests.py

class ArticleModelTestCase(TestCase):
    def setUp(self):
        self.article = Article.objects.create(
            title = 'Title test.',
            content = 'Content test.',
            date_posted = timezone.localtime(),
            image = SimpleUploadedFile(
                name = 'test_image.jpg',
                content = b'',
                content_type = 'image/jpeg'
            )
        )

    def test_title(self):
        self.assertEqual(self.article.title, 'Title test.')

    def test_content(self):
        self.assertEqual(self.article.content, 'Content test.')

    def test_image_field(self):
        self.assertEqual(self.article.image.name, 'test_image.jpg')

我得到了这个错误

> Creating test database for alias 'default'... System check identified
> no issues (0 silenced). .F.
> ====================================================================== FAIL: test_image_field (articles.tests.ArticleModelTestCase)
> ---------------------------------------------------------------------- Traceback (most recent call last):   File
> "/home/xxx/projects/xxxx/backend/articles/tests.py",
> line 27, in test_image_field
>     self.assertEqual(self.article.image.name, 'test_image.jpg') AssertionError: 'article_images/test_image_7U9qlax.jpg' !=
> 'test_image.jpg'
> - article_images/test_image_7U9qlax.jpg
> + test_image.jpg
> 
> 
> ---------------------------------------------------------------------- Ran 3 tests in 0.004s
> 
> FAILED (failures=1) Destroying test database for alias 'default'...

发生的事情是,SimpleUploadedFile不仅创建了一个'test_image.jpg',而且还创建了3个文件:

  1. test_image.jpg
  2. test_image_CWK5SDf.jpg
  3. test_image_7U9qlax
    每次我运行测试时,它总是会创建3个图像文件,其中随机单词和数字作为'test_image'后的后缀。
    它应该做的是创建一个名为'test_image'的图像文件。
    为什么会发生这种情况,如何解决?
pgky5nke

pgky5nke1#

显然,因为有3个测试,def setUp被调用了3次,这就是为什么SimpleUploadedFile一直创建3个图像的原因。
这是我的新代码,现在它的工作

class ArticleModelTestCase(TestCase):
    def setUp(self):
        self.article = Article.objects.create(
            title='Title test.',
            content='Content test.',
            date_posted=timezone.localtime(),
            image=None
        )

    def tearDown(self):
        if self.article.image:
            os.remove(self.article.image.path)

    def test_title(self):
        self.assertEqual(self.article.title, 'Title test.')

    def test_content(self):
        self.assertEqual(self.article.content, 'Content test.')

    def test_image_field(self):
        test_image = SimpleUploadedFile(
            name='test_image.jpg',
            content=b'',
            content_type='image/jpeg'
        )
        self.article.image = test_image
        self.article.save()
        self.assertEqual(self.article.image.name, 'article_images/test_image.jpg')

相关问题