【问题标题】:Django test model with FilerImageField带有 FilerImageField 的 Django 测试模型
【发布时间】:2023-04-03 08:47:02
【问题描述】:

所有 Django 新手,我想为 IndexViewDetailView 编写测试,类似于 Django tutorial

我的模型包含 FilerImageField 作为必填字段 (blank=False)。

为了测试与该模型相关的视图,我想以编程方式创建模型实例。

我知道this 问题解决了如何在代码中创建FilerImageField。我在应用所谓的解决方案时遇到的问题是正确处理图像所有者的部分。

def create_exhibitor(name, image_path, active):
    filename = 'file'
    user = User.objects.get(username='myuser')
    with open(image_path) as f:
        file_obj = File(f, name=filename)
        image = Image.objects.create(
            owner=user,
            original_filename=filename,
            file=file_obj
        )

        return Exhibitor(name=name, image=image, active=active)

运行它们的测试产生:

Traceback (most recent call last):
...
DoesNotExist: User matching query does not exist.

对我来说,测试数据库中似乎没有用户。

所以我的问题确实是双重的:

我需要用户在那里创建一个包含FilerImageField 的模型实例吗?

如果是这样,我如何创建一个用于测试目的?

【问题讨论】:

    标签: django python-2.7 django-testing django-1.6 django-filer


    【解决方案1】:

    我终于这样做了:

    from django.test import TestCase
    from django.contrib.auth.models import User
    from django.core.files.uploadedfile import SimpleUploadedFile
    from .models import Exhibitor
    
    class TestCase():
        su_username = 'user'
        su_password = 'pass'
    
        def setUp(self):
            self.superuser = self.create_superuser()
    
        def create_superuser(self):
            return User.objects.create_superuser(self.su_username, 'email@example.com', self.su_password)
    
        def create_exhibitor(self):
           name = 'eins'
           active = True
           image_file = SimpleUploadedFile(
            'monkey.jpg', b'monkey', content_type="image/jpeg"
           )
           return Exhibitor(name=name, image=image_file, active=active)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-04
      • 2018-06-09
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多