<commit_before>Django admin testing
####################

:date: 2016-11-13 23:16
:tags: django, python, testing
:category: Django
:slug: django-admin-testing
:authors: <NAME>
:summary: How to test custom admin actions

Hello<commit_msg>Get post about testing django admin<commit_after>Django admin testing
====================

:date: 2016-11-13 23:16
:tags: django, python, testing
:category: Django
:slug: django-admin-testing
:authors: <NAME>
:summary: How to test custom admin actions

There is a some case where you have to write custom admin methods. For example it can be a custom admin object action or
custom field in list of objects. For example:

.. code-block::python

    def rules_count(self, obj):
        """Calculate count of ``rules``"""
        return obj.rules.count()


To test this you can write something like this:

.. code-block::python

    class TaskAdminTest(TestCase):
    """Test case for ``OneTimeTaskAdmin`` and ``PeriodicTaskAdmin`` classes"""

    def setUp(self):
        self.admin = OneTimeTaskAdmin(OneTimeTask, AdminSite())
        self.task = OneTimeTaskFactory(rules=[RuleFactory()],
                                       profiles=[ProfileFactory()])

    def test_rules_count(self):
        """Test ``rules_count`` admin method"""
        self.assertEqual(self.admin.rules_count(self.task),
                         self.task.rules.count())


{'fraction_non_alphanumeric': 0.13636363636363635, 'fraction_numerical': 0.017316017316017316, 'mean_word_length': 3.517915309446254, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6322451', 'n_tokens_mistral': 406, 'n_tokens_neox': 376, 'n_words': 128}