【问题标题】:django cookiecutter media/ location for testing用于测试的 django cookiecutter 媒体/位置
【发布时间】:2021-12-04 02:32:33
【问题描述】:

问题:我在模型中有一个 ImageField。 TestCase 无法找到默认图像文件来对其执行图像调整大小(@receiver(pre_save, sender=UserProfile) 装饰器)

class UserProfile(Model):
    user = ForeignKey(AUTH_USER_MODEL ...)
    ...
    photo = ImageField(
        verbose_name=_("Photo"),
        upload_to="media",
        null=True,
        blank=True,
        help_text=_("a photo will spark recognition from others."),
        default="default.png")

概述:我正在本地运行从 pycharm 到 docker 容器的测试。该项目基于 django cookiecutter 项目。

我在presave钩子中搜索了目标文件,在这2个目录中找到了该文件['/app/media/default.png', '/opt/project/media/default.png']

我在 '/app//media/default.png' 上收到 FileNotFound 错误

如何让媒体文件在这些目录中查找?

@receiver(pre_save, sender=UserProfile)
def user_profile_face_photo_reduction(sender, instance, *args, **kwargs):
    """
    This creates the thumbnail photo for a concept
    """

    test_image_size(instance) # this is the function that gives problems.  it's below.
    im = generic_resize_image(size=face_dimensions, image=instance.photo)
    save_images_as_filename(
        filename=Path(instance.photo.path).with_suffix(".png"),
        image=im,
        instance=instance,
    ) 


def test_image_size(instance=None, size_limit=None):
    """
    size_limit is a namedtuple with a height and width that is too large to save.
    instance needs to have a photo attribute to work
    """
    if instance and instance.photo:
        print([x.absolute() for x in sorted(Path("/").rglob("default.png"))]) # this is where I got the actual location info
        assert instance.photo.size <= 10_000_000, ValueError("Image size is too big") # THE PROBLEM LINE IS THIS ONE.
        if (
            instance.photo.width > size_limit.width
            or instance.photo.height > size_limit.height
        ):
            raise ValueError(_("the picture dimensions are too big"))

【问题讨论】:

    标签: django docker cookiecutter-django


    【解决方案1】:
    1. 您是否将主机的媒体卷挂载到 dockerfile 中?您可能需要向我们展示 dockerfile,以便我们更好地了解您的配置。

    2. 如果直接在主机上使用文件夹运行测试不是硬性要求,您可以在 Django 项目根文件夹中创建另一个文件夹(即“testmedia”)。在您的 tests.py 文件中,您可以覆盖您的测试的媒体根设置以使用“testmedia”文件夹。将您的测试图像文件放在文件夹中。以下是覆盖媒体根设置的示例:

      TEST_DIR = os.path.join(settings.BASE_DIR, 'testmedia/') #Defines test media root
      
      @override_settings(MEDIA_ROOT=(TEST_DIR))
      def test_create_blogpost(self):
       print("\nTesting blog post creation...")
      
       testUser = User.objects.create_user(username='testUser', password='12345') #Creates test user
       self.client.login(username='testuser', password='12345') #Logs in testUser
      
       PNGtestpic = SimpleUploadedFile(name="pngtest.png", content=open(settings.MEDIA_ROOT + "pngtest.png", 'rb').read(), content_type='image/png') #Uploads test picture to media root
       Blogpost.objects.create(title="How to run tests", cover_image= PNGtestpic, author=testUser)
      

    【讨论】:

      【解决方案2】:

      我开始在 app_root 文件夹 (/Users///) 中创建一个“媒体”目录。那是一个愚蠢的举动。 (/Users////media) 文件夹中已经有一个我没有看到的媒体文件夹。我尝试使用诸如 docker 安装技巧和更改我的代码之类的技巧来强制它,这是浪费时间。

      我赞成 @heyylateef 对 override_settings 的回答,因为这是一个简洁的装饰器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多