Home > front end >  How to use external files for Django tests
How to use external files for Django tests

Time:07-12

I have to test model validation for checking SVG files. Therefore I want to access to my test files but I've stucked with a error SuspiciousFileOperation. I tried get files from app directory, store the files in static folder and use django.contrib.staticfiles.finders.find function to get them but the problem appears again and again.

Unit-test:

from os import path
from contextlib import contextmanager

from django.forms import ValidationError
from django.test import TestCase
from django.core.files import File
from django.contrib.staticfiles import finders

from .models import Link


class LinkSVGTestCase(TestCase):
    DIR_PATH = "/tests/LinkSVG/"

    def test_svg_file(self) -> None:
        file_path = finders.find(path.join(self.DIR_PATH, "triangle.svg"))
        with open(file_path) as file:
            Link.objects.create(
                name="Triangle",
                url="https://example.com/",
                icon=File(file, name=file.name)
            )

Models:

from django.core.exceptions import ValidationError
from django.db import models


def validate_svg_file(file) -> None:
    """Validating SVG files for FileField in django models"""
    # Unwritten code


class Link(models.Model):
    """Django model for social & media links"""

    name = models.CharField(
        verbose_name="Name",
        unique=True, 
        max_length=32
    )
    url = models.URLField(
        verbose_name="URL"
    )
    icon = models.FileField(
        verbose_name="Icon",
        upload_to="images/links/",
        help_text="Only SVG files",
        validators=[validate_svg_file]
    )

    def __str__(self) -> str:
        return self.name

CodePudding user response:

The problem was in using absolute path of files that Django doesn't allow and thinks actions like that suspicious. A solution of this problem using relative path that set STATIC_URL in settings.py. In my case I changed DIR_PATH to static/tests/LinkSVG and further just get access to my files without using any extra functions.

The result:

class LinkSVGTestCase(TestCase):
    DIR_PATH = "static/tests/LinkSVG/"


    def test_svg_file(self) -> None:
        with open(path.join(self.DIR_PATH, "triangle.svg"), "rb") as file:
            link = Link.objects.create(
                name="Triangle",
                url="https://example.com/",
                icon=File(file, name=file.name)
            )
            link.full_clean()
  • Related