test_ChangelistInlineAdminMixin.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. from unittest import mock
  3. from django.contrib import admin
  4. from django.http import HttpRequest
  5. from django.test import TestCase
  6. from django_changelist_inline import (
  7. ChangelistInline,
  8. ChangelistInlineAdminMixin,
  9. ChangelistInlineModelAdmin,
  10. )
  11. from testing.factories import ThingFactory, UserFactory
  12. from testing.models import RelatedThing, Thing
  13. class RelatedThingChangelistInline(ChangelistInline):
  14. model = RelatedThing
  15. class ChangelistModelAdmin(ChangelistInlineModelAdmin):
  16. pass
  17. class ThingAdmin(ChangelistInlineAdminMixin, admin.ModelAdmin):
  18. inlines = [RelatedThingChangelistInline]
  19. class ChangelistInlineAdminMixinTestCase(TestCase):
  20. def setUp(self):
  21. self.fake_user = UserFactory()
  22. self.fake_request = mock.Mock(spec=HttpRequest)
  23. self.fake_request.user = self.fake_user
  24. self.thing = ThingFactory()
  25. def test_get_inline_instances_no_obj(self):
  26. # Given
  27. thing_admin = ThingAdmin(Thing, admin.site)
  28. with mock.patch.object(self.fake_user, 'has_perm') as mock_has_perm:
  29. with mock.patch.object(RelatedThingChangelistInline, 'bind') as mock_bind:
  30. mock_has_perm.return_value = True
  31. # When
  32. result = thing_admin.get_inline_instances(
  33. self.fake_request, obj=None,
  34. )
  35. # Then
  36. self.assertEqual(len(result), 0)
  37. self.assertFalse(mock_bind.called)
  38. def test_get_inline_instances(self):
  39. # Given
  40. thing_admin = ThingAdmin(Thing, admin.site)
  41. with mock.patch.object(self.fake_user, 'has_perm') as mock_has_perm:
  42. with mock.patch.object(RelatedThingChangelistInline, 'bind') as mock_bind:
  43. mock_has_perm.return_value = True
  44. # When
  45. result = thing_admin.get_inline_instances(
  46. self.fake_request, obj=self.thing,
  47. )
  48. # Then
  49. self.assertEqual(len(result), 1)
  50. self.assertIsInstance(result[0], RelatedThingChangelistInline)
  51. mock_bind.assert_called_with(self.fake_request, self.thing)