Changing settings for tests in django (for a specific search engine for haystack)

I have a project that uses the SOLR search engine through django-haystack. The search engine is located on another live server and is undesirable to touch it during the test run (in fact, this is impossible, since access to this host is protected by a firewall).

I am using the standard django testrunner. Fortunately, this gives me those object settings that I can change to my liking, but it turns out that this is not the end of the story.

A lot of things in django-haystack are created during import-time, so by the time the test settings are changed in my test run, it's too late, and despite the fact that I change SEARCH_BACKEND to the dummy, the tests still call SOLR. The problem is not specific to HAYSTACK - the same problem occurs with mongoengine. Any class-level statements (e.g. CharField (default = Blah.objects.find (...))) are executed during instance creation before django can change the settings.

Of course, the root of the problem is that Django's settings are a terrible globally mutable mess, and Django does not provide a centralized place for the creation code. Considering there are any suggestions as to which test solution would be the easiest? At the moment, I'm thinking of a shell script that will change the DJANGO_SETTINGS environment variable to test_settings and continue the test. /manage.py. It would be better if I could still do something through. /manage.py though.

Any better ideas? People with similar problems?

+4
source share
1 answer

I accepted the answer here and modified it a bit. This works fine for me:

from contextlib import contextmanager @contextmanager def connection(**kwargs): from haystack import connections for key, new_value in kwargs.items(): setattr(connections, key, new_value) connections['default'].options['URL'] = connections.connections_info['default']['URL'] yield 

Then my test looks like this:

 def test_job_detail_by_title_slug_job_id(self): with connection(connections_info=solr_settings.HAYSTACK_CONNECTIONS): resp = self.client.get('/0/rts-crb-unix-production-engineer/27216666/job/') self.assertEqual(resp.status_code, 404) resp = self.client.get('/indianapolis/indiana/usa/jobs/') self.assertEqual(resp.status_code, 200) 
0
source

Source: https://habr.com/ru/post/1382638/


All Articles