[Python] Pytest fails with "ValueError: Missing staticfiles manifest entry for...

Discussão em 'Python' iniciado por Stack, Dezembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    FAILED tests/test_views.py::test_index_view - ValueError: Missing staticfiles manifest entry for 'assets/img/favicon.ico'

    In my Django Template based project I have the error above when running pytests on views. Generally I understand what this is and how to deal with this when deploying BUT do not wish to worry about the static files manifest with these tests. The most obvios solution I found is to disable it by setting STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' in settings/test.py; this being the default, I shouldn't be worrying about the manifest entries any more, but it persists. I wrote a testcase to confirm that pytest infact uses this setting and that test case passes.

    In summary, why do I have a manifest entry error from tests running with the default STATICFILES_STORAGE setting and how do I specifically fix this? have tried a few other options but the general principle seems to be around changing the settings for STATICFILES_STORAGE. What am I missing/getting wrong?

    The simple view function:

    def index(request):
    return render (request, "main/index.html")



    The test cases i.e. tests/test_views.py:

    import pytest
    from django.urls import reverse
    from django.test import Client
    from django.conf import settings

    from main.models import SubscriptionPlan

    def test_static_storage():
    print(settings.STATICFILES_STORAGE)
    assert settings.STATICFILES_STORAGE == 'django.contrib.staticfiles.storage.StaticFilesStorage'

    def test_index_view():
    """
    Test that the index view renders the correct template.
    """
    client = Client()

    response = client.get(reverse('index'))
    assert response.status_code == 200
    assert 'main/index.html' in [template.name for template in response.templates]


    pytest.ini

    [pytest]
    DJANGO_SETTINGS_MODULE = project.settings.test


    settings/test.py

    from .base import *

    # Override static file storage for tests
    STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'



    settings/base.py

    import os, secrets
    from pathlib import Path
    import environ
    import dj_database_url

    # import sys

    env = environ.Env()

    # Take environment variables from .env file
    environ.Env.read_env()

    # Build paths inside the project like this: BASE_DIR / 'subdir'.
    BASE_DIR = Path(__file__).resolve().parent.parent.parent # add ".parent" after creating new folder for settings

    PROJECT_DIR = Path(__file__).resolve().parent.parent

    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = SECRET_KEY = os.environ.get(
    "DJANGO_SECRET_KEY",
    default=secrets.token_urlsafe(nbytes=64),
    )

    # Heroku configs
    # The `DYNO` env var is set on Heroku CI, but it's not a real Heroku app, so we have to
    # also explicitly exclude CI:
    # https://devcenter.heroku.com/articles/heroku-ci#immutable-environment-variables
    IS_HEROKU_APP = "DYNO" in os.environ and not "CI" in os.environ

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    ALLOWED_HOSTS = ['*']


    # Application definition

    INSTALLED_APPS = [
    "whitenoise.runserver_nostatic", # added whitenoise
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',

    #project apps
    'main',

    #3rd party apps
    'djmoney',
    'stripe',
    'background_task',
    ]

    MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    "whitenoise.middleware.WhiteNoiseMiddleware", # whitenoise after security middleware
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    APPEND_SLASH = True

    ROOT_URLCONF = 'project.urls'

    TEMPLATES = [
    {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
    os.path.realpath (PROJECT_DIR) + '/templates/',
    ],
    'APP_DIRS': True,
    'OPTIONS': {
    'context_processors': [
    'django.template.context_processors.debug',
    'django.template.context_processors.request',
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',

    'project.settings.debug_context_processor', # add debug to template context
    ],
    },
    },
    ]

    WSGI_APPLICATION = 'project.wsgi.application'


    # Database
    # https://docs.djangoproject.com/en/5.1/ref/settings/#databases

    # default config
    DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': BASE_DIR / 'db.sqlite3',
    }
    }

    if IS_HEROKU_APP: # heroku config
    DATABASES['default'] = dj_database_url.parse( os.environ.get("DATABASE_URL"),
    conn_max_age=600)
    else:
    ENV_NAME = os.environ.get("ENV_NAME", None)
    if ENV_NAME in ["staging", "production"]: # other(not heroku) config
    DATABASES['default'] = dj_database_url.parse( os.environ.get("DATABASE_URL"),
    conn_max_age=600)


    # Password validation
    # https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

    AUTH_PASSWORD_VALIDATORS = [
    {
    'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
    ]


    # Internationalization
    # https://docs.djangoproject.com/en/5.1/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_TZ = True


    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/5.1/howto/static-files/

    STATIC_URL = 'static/'

    STORAGES = {
    # Enable WhiteNoise's GZip and Brotli compression of static assets:
    # https://whitenoise.readthedocs.io/en/latest/django.html#add-compression-and-caching-support
    "staticfiles": {
    "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
    },
    }

    STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    ]

    STATICFILES_DIRS = [
    os.path.join(PROJECT_DIR, 'static'), # other project based static files
    ]

    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

    # Default primary key field type
    # https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

    DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

    # Don't store the original (un-hashed filename) version of static files, to reduce slug size:
    # https://whitenoise.readthedocs.io/en/latest/django.html#WHITENOISE_KEEP_ONLY_HASHED_FILES
    WHITENOISE_KEEP_ONLY_HASHED_FILES = True

    STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY")
    STRIPE_PUBLISHABLE_KEY = os.environ.get("STRIPE_PUBLISHABLE_KEY")

    # paystack api keys
    PAYSTACK_SECRET_KEY = os.environ.get("PAYSTACK_SECRET_KEY")
    PAYSTACK_PUBLIC_KEY = os.environ.get("PAYSTACK_PUBLIC_KEY")

    # Honor the 'X-Forwarded-Proto' header for request.is_secure()
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

    # email config
    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

    SUBSCRIPTION_NOTIFICATION_EMAIL = env('SUBSCRIPTION_NOTIFICATION_EMAIL')


    # Django-background-tasks config
    BACKGROUND_TASK_RUN_ASYNC = True
    MAX_RUN_TIME = 300


    # djmoney
    CURRENCY_DECIMAL_PLACES = 2

    # auth settings
    #set default login redirect url
    LOGIN_URL = '/portal/login/'
    LOGIN_REDIRECT_URL = '/portal/'
    LOGOUT_REDIRECT_URL = '/portal/login/'


    It is the test_index_view that is currently failing with the error above and by extension, all of the other testcases that will follow. I have just realized that I have not used much of pytest with anything that involves templates so thanks in advance!

    Continue reading...

Compartilhe esta Página