class TestPreferences:
"""
Dynamically adds test methods for testing related preferences for objects. For example:
@TestPreferences([('status', TaskStatusFactory), ('importance', TaskImportanceFactory)])
class TaskApiTestCase(..., APITestCase):
...
TaskApiTestCase will be dynamically extended with test methods for ensuring that it's not possible to use status
or importance from another organization.
"""
def __init__(self, preferences):
self.preferences = preferences
def __call__(self, cls):
if self.preferences is not None:
for field_name, pref_factory in self.preferences:
template_methods = inspect.getmembers(TestPreferences, inspect.ismethod)
for name, tempalte_method in template_methods:
if name.startswith('template_'):
test_method_name_template, test_method = tempalte_method(field_name, pref_factory)
test_method_name = test_method_name_template % {'field_name': field_name}
setattr(cls, test_method_name, test_method)
return cls
@staticmethod
def template_create_global(field_name, pref_factory):
def method(self):
self.client.force_authenticate(self.user)
user_org = OrganizationMembership.objects.get_primary(self.user).organization
sub_matter = SubMatterFactory(matter__organization=user_org)
preference = pref_factory(organization=None)
res = self._post_request(sub_matter=sub_matter.pk, **{field_name: preference.pk})
self.assertEqual(res.status_code, status.HTTP_201_CREATED, res.data)
self.assertEqual(res.data[field_name], preference.pk)
return "test_can_use_global_%(field_name)s", method