From ef56a3ebcbcc6311b04bc2d6f11fcdbdd9062ebf Mon Sep 17 00:00:00 2001 From: Karl Hobley Date: Tue, 19 Jul 2016 13:24:32 +0100 Subject: [PATCH] Fixed search tests (#2850) A test was mutating the search_fields attribute of the SearchTest model causing subsequent tests that depended on the previous value to fail. --- .../wagtailsearch/tests/test_indexed_class.py | 32 +++++++++++++------ 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/wagtail/wagtailsearch/tests/test_indexed_class.py b/wagtail/wagtailsearch/tests/test_indexed_class.py index 5e518add7..8b409f7d7 100644 --- a/wagtail/wagtailsearch/tests/test_indexed_class.py +++ b/wagtail/wagtailsearch/tests/test_indexed_class.py @@ -1,5 +1,7 @@ from __future__ import absolute_import, unicode_literals +from contextlib import contextmanager + from django.core import checks from django.test import TestCase @@ -7,6 +9,18 @@ from wagtail.tests.search import models from wagtail.wagtailsearch import index +@contextmanager +def patch_search_fields(model, new_search_fields): + """ + A context manager to allow testing of different search_fields configurations + without permanently changing the models' search_fields. + """ + old_search_fields = model.search_fields + model.search_fields = new_search_fields + yield + model.search_fields = old_search_fields + + class TestContentTypeNames(TestCase): def test_base_content_type_name(self): name = models.SearchTestChild.indexed_get_toplevel_content_type() @@ -71,12 +85,12 @@ class TestSearchFields(TestCase): self.assertEqual(len(cls.get_filterable_search_fields()), 1) def test_checking_search_fields(self): - models.SearchTest.search_fields += [index.SearchField('foo')] - expected_errors = [ - checks.Warning( - "SearchTest.search_fields contains field 'foo' but it doesn't exist", - obj=models.SearchTest - ) - ] - errors = models.SearchTest.check() - self.assertEqual(errors, expected_errors) + with patch_search_fields(models.SearchTest, models.SearchTest.search_fields + [index.SearchField('foo')]): + expected_errors = [ + checks.Warning( + "SearchTest.search_fields contains field 'foo' but it doesn't exist", + obj=models.SearchTest + ) + ] + errors = models.SearchTest.check() + self.assertEqual(errors, expected_errors)