运行 Django 测试而不收集静态

Jam*_*gar 7 python django pytest

我正在尝试运行一个使用 inlinecss 的 django 测试套件。inlinecss 在模板中引用静态文件,如下所示:

{% load inlinecss %}
{% inlinecss "css/emails/base.css" %}
Run Code Online (Sandbox Code Playgroud)

在调试模式下运行时,这可以正常工作,在生产环境中运行(已运行collectstatic)时,这也可以正常工作。

但是,当运行测试时(之前没有运行collectstatic)我得到以下信息:

FileNotFoundError: [Errno 2] No such file or directory: '/app/project-name/staticfiles/css/emails/base.css'
Run Code Online (Sandbox Code Playgroud)

STATIC_ROOT = os.path.normpath(join(os.path.dirname(BASE_DIR), "staticfiles"))这是有道理的,因为 django 正在 STATIC_ROOT ( )中查找文件

我想知道是否有一种方法可以让 Django 无需运行即可访问此文件collectstatic?如果我可以添加一些设置,test.py以便它可以收集静态到 tmp 目录或根本不需要收集静态(就像在调试模式下运行时),那将是理想的,但我没有成功尝试此操作。我正在使用 pytest 来运行测试。

小智 1

我在测试期间使用以下构造将静态文件收集到临时文件夹。我确信这个解决方案对于大量测试来说可能不是最佳的,但它应该适用于单个测试用例。

import tempfile
import shutil
from contextlib import contextmanager
from django.core.management import call_command
from django.test import TestCase, override_settings

@contextmanager
def static_files_context():
    static_root = tempfile.mkdtemp(prefix="test_static")
    with override_settings(STATIC_ROOT=static_root):
        try:
            call_command("collectstatic", "--noinput")
            yield
        finally:
            shutil.rmtree(static_root)

class YourTestCase(TestCase):

    @override_settings(STATIC_ROOT=None)
    def test_your_test_name(self):
        with static_files_context():
            # Your test code
Run Code Online (Sandbox Code Playgroud)