Files
smartsoltech_site/smartsoltech/settings_test.py
Andrey K. Choi c0d890b4de
Some checks failed
continuous-integration/drone/push Build is failing
🔧 CRITICAL: Force CSRF_TRUSTED_ORIGINS at end of settings
- Added final override of CSRF_TRUSTED_ORIGINS at end of file
- Django 4.0+ compliance with proper scheme formatting
- Added debug print to verify final values
- Should resolve persistent 4_0.E001 error in CI

Previous attempts failed because settings were being overridden
after our initial definition. This ensures final precedence.
2025-11-25 07:55:24 +09:00

127 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
import os
import sys
import dj_database_url
from .settings import *
print("🧪 Test settings loaded")
# ВАЖНО: Переопределяем CSRF_TRUSTED_ORIGINS сразу после импорта
# так как settings.py устанавливает пустое значение
CSRF_TRUSTED_ORIGINS = [
'http://localhost',
'http://127.0.0.1',
'http://postgres',
'https://smartsoltech.kr'
]
print("🔒 CSRF_TRUSTED_ORIGINS переопределен:", CSRF_TRUSTED_ORIGINS)
# База данных для тестирования
DATABASES = {
'default': dj_database_url.config(
default=os.environ.get(
'DATABASE_URL',
'postgresql://postgres:postgres@postgres:5432/smartsoltech_test'
)
)
}
print("📊 Database:", DATABASES['default']['NAME'], "at", DATABASES['default']['HOST'])
# Секретный ключ для тестирования
SECRET_KEY = os.environ.get(
'SECRET_KEY',
'test-secret-key-for-ci-very-long-and-secure-key-12345'
)
print("🔐 Secret key length:", len(SECRET_KEY))
# Отладка отключена в тестах
DEBUG = os.environ.get('DEBUG', 'False').lower() in ['true', '1', 'yes']
# Разрешенные хосты для CI
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1,postgres,*').split(',')
print("🌐 Allowed hosts:", ALLOWED_HOSTS)
print("🔒 CSRF trusted origins:", CSRF_TRUSTED_ORIGINS)
# Упрощенный хеширователь паролей для быстрых тестов
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.MD5PasswordHasher',
]
# Отключаем миграции для ускорения тестов
class DisableMigrations:
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
# В CI не применяем миграции для ускорения
if os.environ.get('CI'):
MIGRATION_MODULES = DisableMigrations()
# Логирование для отладки в CI
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
},
'web': {
'handlers': ['console'],
'level': 'DEBUG',
},
},
}
# Кеширование отключено для тестов
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
# Email для тестов (console backend)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Медиа файлы для тестов
MEDIA_ROOT = '/tmp/media_test/'
# Статические файлы для тестов
STATIC_ROOT = '/tmp/static_test/'
# Telegram Bot настройки для тестирования
TELEGRAM_BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN', 'test-token')
# Отключаем инициализацию Telegram бота в тестах
TELEGRAM_BOT_ENABLED = False
# Отключаем CSRF для API тестов
if 'test' in sys.argv:
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
# Отключаем сигналы для ускорения тестов
if 'test' in sys.argv:
from django.core.signals import setting_changed
setting_changed.disconnect()
# КРИТИЧЕСКИ ВАЖНО: Финальное переопределение CSRF_TRUSTED_ORIGINS
# Django 4.0+ требует схемы (http://, https://)
CSRF_TRUSTED_ORIGINS = [
'http://localhost',
'http://127.0.0.1',
'http://postgres',
'https://smartsoltech.kr'
]
print("🔒 ФИНАЛЬНАЯ проверка CSRF_TRUSTED_ORIGINS:", CSRF_TRUSTED_ORIGINS)