I've started using a custom context processor to pass an object to every response. The only problem with this is that my tests now fail because they can't find this object in the database. I tried creating a test with Request Factory, as my understanding was that this isolates tests from Django bloat like middleware, etc. I'm guessing that context processors are still run though. Is there any way to get past this? Am I going to have to pass this object to every test? If there's any way to avoid it, I'd much rather do so.

有帮助吗?

解决方案

After further investigation, I think the best solution is to override the context_processors tuple during each test. This has been possible since 1.4. It seems better than sending the required object to each test. I'd like to investigate whether I can write a custom decorator for it, but don't know enough about them yet. Reference: https://docs.djangoproject.com/en/dev/topics/testing/overview/#overriding-settings

edit: Another implementation of this solution outlined here: How to Unit test with different settings in Django? probably better as it can be done for an entire tests.py

edit2: having discovered that decorators are actually python constructs (assumed they were custom django functionality! massive newbie to python, by the way. learnt django before i learnt any python), i think a custom decorator is the way i'll go with this.

edit3: I think actually a simpler solution would to be have a test.py file in my settings module, and to override my base settings context_processor module with that of the test settings in the tests. E.g.:

from settings import localsettings
from settings import testsetttings

localtestsettings.context_processors = testsettings.context_processors

tests(unittest):.....

Any other suggestions are more than welcome.

edit4: Okay. I feel stupid now. Obviously the solution I have ended up using is to create a tests settings file, and to pass that to the test command.

其他提示

Use this on tests.py worked fine with me

from django.test import TestCase, Client, override_settings

@override_settings (
  TEMPLATES = [
  {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    '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',
        ],
    },
  },
  ]
)

class HomeViewTestCase(TestCase):
    ...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top