I have some special cases that I need to test for in django. I am trying to extend the the existing django tests by writing my own test cases. Here is how I am currently doing it.
from django.tests import TestCase
# define my own method as a function
def assertOptionsEqual(self, first, second):
# logic here
pass
# Attach the method to the TestCase class. This feels inelegant!
TestCase.assertOptionsEqual = assertOptionsEqual
# tests go here
class KnownGoodInputs(TestCase):
def test_good_options(self):
self.assertOptionsEqual(...)
While this works, defining a method as a function with self as the first parameter and then attaching it to TestCase feels inelegant. Is there a better way of augmenting the TestCase class with my own methods? I can do this …
class MyTestCase(TestCase):
def assertOptionsEqual(self, first, second):
...
and use MyTestCase for all tests, but was wondering if there was a better alternative. Thanks!
I think you’ve covered both options. You can either subclass or monkeypatch. Typically, monkeypatching, actually changing the 3rd party class at runtime is frowned upon but depending on what change you need to make it may be the only way to work around a bug or make sure that every time that class is used it has your new method.
Since the only tests that use your method will be your tests monkeypatching is unnecessary and it’s quite reasonable to subclass
TestCase. Typically you’d use monkeypatching when you needed to augment a method of a existing class. For example, if you wanted calls toTestCase.assertEqualin your existing test cases to be augmented with logic to compare toOptionobjects you could monkeypatchTestCase.assertEqualto include your custom logic plus its normal logic by doing something like:However, it seems that at least in this example that both subclasses and monkeypatches are unnecessary.
Assuming that the issue is that calling
self.assertEqual(firstOptions, secondOptions)fails even though theOptioninstances are equal you don’t need to write a newassertOptionsEqualmethod. You probably just need yourOptionobjects to define__eq__properly.So assuming that you’ve got:
What are the classes of
firstandsecondabove?For all Python builtin types
assertEqualshould work. For a customOptionclass just do something like this:class Option(object):
def init(self):
use_foo = False
use_bar = True
Then assuming that
firstandsecondare instances ofOptionyou can write your test just as: