I got a problem on Pycharm.

When I run my tests I can't display django.db.backends logs on stdout/stderr.

When I use runserver it works like a charm.

Do you have any simple solution to display all logs with level=DEBUG on stdout on my tests?

More info:

  • my DEBUG is set to True in my settings
  • I use SOUTH_TESTS_MIGRATE = False and SKIP_SOUTH_TESTS = True

Thank you

有帮助吗?

解决方案

First, django forces settings.DEBUG to False during UnitTest (Writing and running tests in Django). So you should activate temporary this settings using override_settings decorator:

From django documentation:

from django.test import TestCase
from django.test.utils import override_settings

class LoginTestCase(TestCase):

    @override_settings(LOGIN_URL='/other/login/')
    def test_login(self):
        response = self.client.get('/sekrit/')
        self.assertRedirects(response, '/other/login/?next=/sekrit/')

But reading the django source code, you can also set the use_debug_cursor attribute of the connection object. If set to True, the CursorDebugWrapper will be used and queries logs will appear.

Extract from django source (django/db/backends/__init__.py):

class BaseDatabaseWrapper(object):
    # [...]
    def cursor(self):
        self.validate_thread_sharing()
        if (self.use_debug_cursor or
            (self.use_debug_cursor is None and settings.DEBUG)):
            cursor = self.make_debug_cursor(self._cursor())
        else:
            cursor = util.CursorWrapper(self._cursor(), self)
        return cursor

    def make_debug_cursor(self, cursor):
        return util.CursorDebugWrapper(cursor, self)

其他提示

I dare say it's got nothing to do with pycharm. It's standard python you're battling with. First glance it seems you're just asking how to configure the logging to be noisier.

https://docs.djangoproject.com/en/1.5/topics/logging/#configuring-logging

Admittedly i'm not making any real effort here, but perhaps something like this in your settings file will give you ideas...

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'simple':   {'format': '%(asctime)s %(levelname)s %(message)s'},
    },
    'handlers': {
        'console':     {'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple'},
    },
    'loggers': {
        'django.db.backends': {'level': 'DEBUG', 'handlers': ['console'], 'propagate': False},
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top