2013-06-10 1 views
2

Я пытаюсь получить свой тестовый набор для создания другого файла журнала, чем тот, который я использую в разработке, но по какой-то причине декоратор override_settings, похоже, не работает. Когда я запускаю тест, записывается тот же «проект/проект/debug_logfile». Куда я возился?Django: Как вы переопределяете переменную журнала в процессе тестирования?

# settings.py 
... 
LOGFILE = ROOT + '/debug_logfile' 

LOGGING = { 
    'version': 1, 
    'disable_existing_loggers': True, 
    'formatters': { 
     'verbose': { 
      'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' 
     }, 
     'simple': { 
      'format': '%(levelname)s %(message)s' 
     }, 
     'standard': { 
      'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 
      'datefmt' : "%d/%b/%Y %H:%M:%S" 
     }, 
    }, 
    'filters': { 
     'require_debug_false': { 
      '()': 'django.utils.log.RequireDebugFalse' 
     } 
    }, 
    'handlers': { 
     'null': { 
      'level': 'DEBUG', 
      'class': 'django.utils.log.NullHandler', 
     }, 
     'console': { 
      'level': 'DEBUG', 
      'class': 'logging.StreamHandler', 
      'formatter': 'simple' 
     }, 
     'mail_admins': { 
      'level': 'ERROR', 
      'class': 'django.utils.log.AdminEmailHandler', 
      'filters': ['require_debug_false'] 
     }, 
     'logfile': { 
      'level':'DEBUG', 
      'class':'logging.handlers.RotatingFileHandler', 
      'filename': LOGFILE, 
      'maxBytes': 50000, 
      'backupCount': 2, 
      'formatter': 'standard', 
     }, 
    }, 
    'loggers': { 
     'django': { 
      'handlers': ['null'], 
      'propagate': True, 
      'level': 'INFO', 
     }, 
     'django.request': { 
      'handlers': ['mail_admins'], 
      'level': 'ERROR', 
      'propagate': False, 
     }, 
     'clients': { 
      'handlers': ['console', 'logfile'], 
      'level': 'DEBUG', 
     }, 
     # display the db queries 
     #'django.db.backends': { 
     # 'handlers': ['console'], 
     # 'level': 'DEBUG', 
     #} 
    } 
} 

# clients.management.commands.remindmanagers.py 

class Command(BaseCommand): 
    help = 'Creates task reminders and send emails to account and senior \ 
      managers when their client\'s contracts are about to expire' 

    def handle(self, *args, **kwargs): 
     three_months = datetime.date.today() + datetime.timedelta(days=90) 
     # get all contracts that will be completed in the next 3 months 
     contracts = Contract.objects.filter(finish__lte=three_months 
            ).exclude(notices_left=0) 

     if not contracts.exists(): 
      log.info('Tried running but there are no contracts about to expire.') 
      return 0 
     ... 

# tests.test_clients 

... 
from django.core.management import call_command 

@override_settings(LOGFILE=settings.ROOT + "/test_logfile") 
class ClientCommandTest(BaseTestCase): 
    def _file_exists(file_path): 
     return os.path.exists(file_path) 

    def test_remindmanagers_no_contracts(self): 
     args = [] 
     kwargs = {} 
     #self.assertFalse() 
     # since there are no contracts yet, this should create an entry in ROOT + /logfile 
     call_command('remindmanagers', *args, **kwargs)          # this should log in project/project/test_logfile not debug_logfile 

ответ

0

Ваш LOGGING ДИКТ литерал содержит переменную LOGFILE, которая получает оцененную сразу при обработке Dict буквальным. Переопределяя LOGFILE, вы не меняете запись в LOGGING dict, потому что строка LOGFILE просто заменена; сама строка не мутирована, поэтому в итоге вы получите LOGFILE, просто указывая на другую строку.

Я думаю, что вы должны быть в состоянии отменить только обработчик файла журнала с новым именем, как так:

@override_settings(LOGGING={ 
    'handlers': { 
    'logfile': { 
     'filename': settings.ROOT + "/test_logfile" 
    } 
    } 
}) 
class ClientCommandTest(BaseTestCase): 
    ... 
Смежные вопросы