| 1 | from new import classobj |
| 2 | from unittest import TestCase |
| 3 | |
| 4 | from django.conf import settings |
| 5 | from django.db import models |
| 6 | |
| 7 | class AbsoluteUrlOverrideTests(TestCase): |
| 8 | """ |
| 9 | Tests for inserting or overriding model class get_absolute_url methods with |
| 10 | ABSOLUTE_URL_OVERRIDES -setting. |
| 11 | """ |
| 12 | def setUp(self): |
| 13 | super(AbsoluteUrlOverrideTests, self).setUp() |
| 14 | self.old_overrides = settings.ABSOLUTE_URL_OVERRIDES |
| 15 | settings.ABSOLUTE_URL_OVERRIDES = {} |
| 16 | |
| 17 | def tearDown(self): |
| 18 | super(AbsoluteUrlOverrideTests, self).tearDown() |
| 19 | settings.ABSOLUTE_URL_OVERRIDES = self.old_overrides |
| 20 | |
| 21 | def test_insert_method(self): |
| 22 | klass_one = self._create_model_class('TestModelOne') |
| 23 | self.assertFalse(hasattr(klass_one, 'get_absolute_url')) |
| 24 | |
| 25 | settings.ABSOLUTE_URL_OVERRIDES['url_overrides.testmodeltwo'] = lambda o: '/%s/' % o.name |
| 26 | |
| 27 | klass_two = self._create_model_class('TestModelTwo') |
| 28 | self.assertTrue(hasattr(klass_two, 'get_absolute_url')) |
| 29 | name = 'Rose' |
| 30 | self.assertEquals('/%s/' % name, klass_two(name=name).get_absolute_url()) |
| 31 | |
| 32 | def test_override_method(self): |
| 33 | class_method = lambda o: 'class_method' |
| 34 | klass_one = self._create_model_class('TestModelUno', class_method) |
| 35 | name = 'Rose' |
| 36 | self.assertTrue(hasattr(klass_one, 'get_absolute_url')) |
| 37 | self.assertEqual('class_method', klass_one(name=name).get_absolute_url()) |
| 38 | |
| 39 | settings.ABSOLUTE_URL_OVERRIDES['url_overrides.testmodeldos'] = lambda o: '/%s/' % o.name |
| 40 | |
| 41 | klass_two = self._create_model_class('TestModelDos', class_method) |
| 42 | self.assertEquals('/%s/' % name, klass_two(name=name).get_absolute_url()) |
| 43 | |
| 44 | |
| 45 | def _create_model_class(self, class_name, get_absolute_url_method=None): |
| 46 | members = {'name': models.CharField(max_length=50)} |
| 47 | if get_absolute_url_method: |
| 48 | members['get_absolute_url'] = get_absolute_url_method |
| 49 | |
| 50 | return classobj(class_name, (models.Model,), members) |
| 51 | No newline at end of file |