Beispiel #1
0
    def test_user_roles_updated(self):
        iuser = InstanceUser(user=self.user2,
                             instance=self.instance,
                             role=self.instance.default_role)
        iuser.save_with_user(self.commander)

        new_role = Role(name='Ambassador',
                        instance=self.instance,
                        rep_thresh=0)
        new_role.save()

        body = {'users': {iuser.pk: {'role': new_role.pk, 'admin': False}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander), self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.role, new_role)
        self.assertEqual(iuser.admin, False)

        body = {'users': {iuser.pk: {'role': new_role.pk, 'admin': True}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander), self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.role, new_role)
        self.assertEqual(iuser.admin, True)
class FieldPermMgmtTest(OTMTestCase):
    def setUp(self):
        self.instance = make_instance()
        self.commander = make_commander_user(self.instance)

        self.new_role = Role(name='Ambassador', instance=self.instance,
                             rep_thresh=0)
        self.new_role.save()

        self.factory = RequestFactory()

    def assertInvalidFPRaises(self, **kwargs):
        fp = FieldPermission(**kwargs)
        fp.role = self.instance.default_role
        fp.instance = self.instance
        self.assertRaises(ValidationError, fp.save)

    def test_invalid_model_does_not_exist_unit(self):
        self.assertInvalidFPRaises(model_name='Gethen', field_name='readonly')

    def test_invalid_model_does_not_authorizable_unit(self):
        self.assertInvalidFPRaises(model_name='FieldPermission',
                                   field_name='role')

    def test_invalid_field_name_unit(self):
        self.assertInvalidFPRaises(model_name='Tree', field_name='model_name')
    def setUp(self):
        self.instance = make_instance()
        self.instance.save()
        self.role = Role(name='role', instance=self.instance, rep_thresh=0)
        self.role.save()

        self.observer = make_observer_user(self.instance)

        self.udf_role = Role(name='udf', instance=self.instance, rep_thresh=0)
        self.udf_role.save()

        self.template_dir = tempfile.mkdtemp()
        self.template_file_path = os.path.join(self.template_dir,
                                               "field_template.html")

        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type='Plot',
            datatype=json.dumps({'type': 'choice',
                                 'choices': ["a", "b", "c"]}),
            iscollection=False,
            name='Test choice')

        udf_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='udf:Test choice',
            permission_level=FieldPermission.READ_ONLY,
            role=self.role, instance=self.instance)
        udf_perm.save()
        udf_write_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='udf:Test choice',
            permission_level=FieldPermission.WRITE_DIRECTLY,
            role=self.udf_role, instance=self.instance)
        udf_write_perm.save()
    def setUp(self):
        self.instance = make_instance()

        self.user = make_user(username='******', password='******')

        self.role = Role(name='role', instance=self.instance, rep_thresh=0)
        self.role.save()

        self.user_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=self.role, instance=self.instance)

        iuser = InstanceUser(instance=self.instance, user=self.user,
                             role=self.role)
        iuser.save_with_user(self.user)

        inst_role = Role(name='inst def role',
                         instance=self.instance,
                         rep_thresh=0)
        inst_role.save()

        self.inst_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=inst_role, instance=self.instance)

        self.instance.default_role = inst_role
        self.instance.save()

        self.plot = Plot(instance=self.instance)
Beispiel #5
0
class FieldPermMgmtTest(OTMTestCase):
    def setUp(self):
        self.instance = make_instance()
        self.commander = make_commander_user(self.instance)

        self.new_role = Role(name='Ambassador', instance=self.instance,
                             rep_thresh=0)
        self.new_role.save()

        self.factory = RequestFactory()

    def assertInvalidFPRaises(self, **kwargs):
        fp = FieldPermission(**kwargs)
        fp.role = self.instance.default_role
        fp.instance = self.instance
        self.assertRaises(ValidationError, fp.save)

    def test_invalid_model_does_not_exist_unit(self):
        self.assertInvalidFPRaises(model_name='Gethen', field_name='readonly')

    def test_invalid_model_does_not_authorizable_unit(self):
        self.assertInvalidFPRaises(model_name='FieldPermission',
                                   field_name='role')

    def test_invalid_field_name_unit(self):
        self.assertInvalidFPRaises(model_name='Tree', field_name='model_name')
    def setUp(self):
        self.instance = make_instance()
        self.instance.config['advanced_search_fields'] = {}
        self.instance.save()
        self.role = Role(name='role', instance=self.instance, rep_thresh=0)
        self.role.save()

        self.observer = make_observer_user(self.instance)

        self.udf_role = Role(name='udf', instance=self.instance, rep_thresh=0)
        self.udf_role.save()

        self.template_dir = tempfile.mkdtemp()
        self.template_file_path = os.path.join(self.template_dir,
                                               "field_template.html")

        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type='Plot',
            datatype=json.dumps({'type': 'choice',
                                 'choices': ["a", "b", "c"]}),
            iscollection=False,
            name='Test choice')

        udf_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='udf:Test choice',
            permission_level=FieldPermission.READ_ONLY,
            role=self.role, instance=self.instance)
        udf_perm.save()
        udf_write_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='udf:Test choice',
            permission_level=FieldPermission.WRITE_DIRECTLY,
            role=self.udf_role, instance=self.instance)
        udf_write_perm.save()
Beispiel #7
0
    def test_invites_updated(self):
        email = "*****@*****.**"
        invite = InstanceInvitation(email=email,
                                    instance=self.instance,
                                    created_by=self.user4,
                                    role=self.instance.default_role)
        invite.save()

        new_role = Role(name='Ambassador', instance=self.instance,
                        rep_thresh=0)
        new_role.save()

        body = {'invites':
                {invite.pk:
                 {'role': new_role.pk}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander),
            self.instance)

        # requery invite
        invite = InstanceInvitation.objects.get(pk=invite.pk)
        self.assertEqual(invite.role, new_role)
    def setUp(self):
        self.instance = make_instance()
        self.commander = make_commander_user(self.instance)

        self.new_role = Role(name='Ambassador', instance=self.instance,
                             rep_thresh=0)
        self.new_role.save()

        self.factory = RequestFactory()
Beispiel #9
0
    def setUp(self):
        self.instance = make_instance(name='Test Instance')

        self.species = Species(instance=self.instance,
                               common_name='Test Common Name',
                               genus='Test Genus',
                               cultivar='Test Cultivar',
                               species='Test Species')
        self.species.save_base()

        self.user = make_user(username='******', password='******')

        self.plot = Plot(geom=Point(1, 1),
                         instance=self.instance,
                         address_street="123 Main Street")

        self.plot.save_base()

        self.tree = Tree(plot=self.plot, instance=self.instance)

        self.tree.save_base()

        self.boundary = make_simple_boundary("Test Boundary")

        self.role = Role(instance=self.instance,
                         name='Test Role',
                         rep_thresh=2)
        self.role.save()

        self.field_permission = FieldPermission(
            model_name="Tree",
            field_name="readonly",
            permission_level=FieldPermission.READ_ONLY,
            role=self.role,
            instance=self.instance)
        self.field_permission.save_base()

        self.audit = Audit(action=Audit.Type.Update,
                           model="Tree",
                           field="readonly",
                           model_id=1,
                           user=self.user,
                           previous_value=True,
                           current_value=False)
        self.audit.save_base()

        self.reputation_metric = ReputationMetric(instance=self.instance,
                                                  model_name="Tree",
                                                  action="Test Action")
        self.reputation_metric.save_base()
Beispiel #10
0
 def _user_can_do(self, user, action):
     role = user.get_role(self.get_instance())
     Clz = self.map_feature.__class__
     if callable(getattr(self.map_feature, 'cast_to_subtype', None)):
         Clz = self.map_feature.cast_to_subtype().__class__
     codename = Role.permission_codename(Clz, action, photo=True)
     return role.has_permission(codename, Model=MapFeaturePhoto)
Beispiel #11
0
    def setUp(self):
        self.instance = make_instance()
        self.commander = make_commander_user(self.instance)

        self.new_role = Role(name='Ambassador', instance=self.instance,
                             rep_thresh=0)
        self.new_role.save()

        self.factory = RequestFactory()
    def setUp(self):
        self.instance = make_instance()

        self.user = make_user(username='******', password='******')

        self.role = Role(name='role', instance=self.instance, rep_thresh=0)
        self.role.save()

        self.user_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=self.role, instance=self.instance)

        iuser = InstanceUser(instance=self.instance, user=self.user,
                             role=self.role)
        iuser.save_with_user(self.user)

        inst_role = Role(name='inst def role',
                         instance=self.instance,
                         rep_thresh=0)
        inst_role.save()

        self.inst_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=inst_role, instance=self.instance)

        self.instance.default_role = inst_role
        self.instance.save()

        self.plot = Plot(instance=self.instance)
Beispiel #13
0
    def setUp(self):
        self.p1 = Point(0, 0)
        self.p2 = Point(5, 5)

        self.instance1 = make_instance(point=self.p1)
        self.instance1.default_role.instance_permissions.add(
            *Role.model_permissions((Plot, Tree)))

        self.user = make_user_with_default_role(self.instance1, 'auser')
        self.instance1.default_role.instance_permissions.add(
            *Role.model_permissions((Plot, Tree)))

        self.instance2 = make_instance(name='i2')
        self.instance2.save()

        iuser = InstanceUser(instance=self.instance2,
                             user=self.user,
                             role=self.instance1.default_role)
        iuser.save_with_user(self.user)

        self.plot1 = Plot(geom=self.p1, instance=self.instance1)

        self.plot1.save_with_user(self.user)

        self.plot2 = Plot(geom=self.p2, instance=self.instance2)

        self.plot2.save_with_user(self.user)

        tree_combos = [
            (self.plot1, self.instance1, True),
            (self.plot1, self.instance1, False),
            (self.plot2, self.instance2, True),
            (self.plot2, self.instance2, False),
        ]

        for plot, instance, readonly in tree_combos:
            t = Tree(plot=plot, instance=instance, readonly=readonly)

            t.save_with_user(self.user)
Beispiel #14
0
    def setUp(self):
        self.p1 = Point(0, 0)
        self.p2 = Point(5, 5)

        self.instance1 = make_instance(point=self.p1)
        self.instance1.default_role.instance_permissions.add(
            *Role.model_permissions((Plot, Tree)))

        self.user = make_user_with_default_role(self.instance1, 'auser')
        self.instance1.default_role.instance_permissions.add(
            *Role.model_permissions((Plot, Tree)))

        self.instance2 = make_instance(name='i2')
        self.instance2.save()

        iuser = InstanceUser(instance=self.instance2, user=self.user,
                             role=self.instance1.default_role)
        iuser.save_with_user(self.user)

        self.plot1 = Plot(geom=self.p1, instance=self.instance1)

        self.plot1.save_with_user(self.user)

        self.plot2 = Plot(geom=self.p2, instance=self.instance2)

        self.plot2.save_with_user(self.user)

        tree_combos = [
            (self.plot1, self.instance1, True),
            (self.plot1, self.instance1, False),
            (self.plot2, self.instance2, True),
            (self.plot2, self.instance2, False),
        ]

        for plot, instance, readonly in tree_combos:
            t = Tree(plot=plot, instance=instance, readonly=readonly)

            t.save_with_user(self.user)
    def setUp(self):
        self.instance = make_instance()
        self.instance.save()
        self.role = Role(name="role", instance=self.instance, rep_thresh=0)
        self.role.save()

        self.observer = make_observer_user(self.instance)

        self.udf_role = Role(name="udf", instance=self.instance, rep_thresh=0)
        self.udf_role.save()

        self.template_dir = tempfile.mkdtemp()
        self.template_file_path = os.path.join(self.template_dir, "field_template.html")

        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type="Plot",
            datatype=json.dumps({"type": "choice", "choices": ["a", "b", "c"]}),
            iscollection=False,
            name="Test choice",
        )

        udf_perm, __ = FieldPermission.objects.get_or_create(
            model_name="Plot",
            field_name="udf:Test choice",
            permission_level=FieldPermission.READ_ONLY,
            role=self.role,
            instance=self.instance,
        )
        udf_perm.save()
        udf_write_perm, __ = FieldPermission.objects.get_or_create(
            model_name="Plot",
            field_name="udf:Test choice",
            permission_level=FieldPermission.WRITE_DIRECTLY,
            role=self.udf_role,
            instance=self.instance,
        )
        udf_write_perm.save()
Beispiel #16
0
    def test_invites_updated(self):
        email = "*****@*****.**"
        invite = InstanceInvitation(email=email,
                                    instance=self.instance,
                                    created_by=self.user4,
                                    role=self.instance.default_role)
        invite.save()

        new_role = Role(name='Ambassador',
                        instance=self.instance,
                        rep_thresh=0)
        new_role.save()

        body = {'invites': {invite.pk: {'role': new_role.pk}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander), self.instance)

        # requery invite
        invite = InstanceInvitation.objects.get(pk=invite.pk)
        self.assertEqual(invite.role, new_role)
Beispiel #17
0
    def test_user_roles_updated(self):
        iuser = InstanceUser(user=self.user2, instance=self.instance,
                             role=self.instance.default_role)
        iuser.save_with_user(self.commander)

        new_role = Role(name='Ambassador', instance=self.instance,
                        rep_thresh=0)
        new_role.save()

        body = {'users':
                {iuser.pk:
                 {'role': new_role.pk, 'admin': False}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander),
            self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.role, new_role)
        self.assertEqual(iuser.admin, False)

        body = {'users':
                {iuser.pk: {'role': new_role.pk, 'admin': True}}}

        update_user_roles(
            make_request(method='POST',
                         body=json.dumps(body),
                         user=self.commander),
            self.instance)

        #requery iuser
        iuser = InstanceUser.objects.get(pk=iuser.pk)
        self.assertEqual(iuser.role, new_role)
        self.assertEqual(iuser.admin, True)
Beispiel #18
0
    def setUp(self):
        self.instance = make_instance(name="Test Instance")

        self.species = Species(
            instance=self.instance,
            common_name="Test Common Name",
            genus="Test Genus",
            cultivar="Test Cultivar",
            species="Test Species",
        )
        self.species.save_base()

        self.user = make_user(username="******", password="******")

        self.plot = Plot(geom=Point(0, 0), instance=self.instance, address_street="123 Main Street")

        self.plot.save_base()

        self.tree = Tree(plot=self.plot, instance=self.instance)

        self.tree.save_base()

        self.boundary = make_simple_boundary("Test Boundary")

        self.role = Role(instance=self.instance, name="Test Role", rep_thresh=2)
        self.role.save()

        self.field_permission = FieldPermission(
            model_name="Tree",
            field_name="readonly",
            permission_level=FieldPermission.READ_ONLY,
            role=self.role,
            instance=self.instance,
        )
        self.field_permission.save_base()

        self.audit = Audit(
            action=Audit.Type.Update,
            model="Tree",
            field="readonly",
            model_id=1,
            user=self.user,
            previous_value=True,
            current_value=False,
        )
        self.audit.save_base()

        self.reputation_metric = ReputationMetric(instance=self.instance, model_name="Tree", action="Test Action")
        self.reputation_metric.save_base()
Beispiel #19
0
class ModelPermMgmtTest(OTMTestCase):
    def setUp(self):
        self.instance = make_instance()

        self.commander = make_commander_user(self.instance)

        self.new_role = Role(name='Ambassador', instance=self.instance,
                             rep_thresh=0)
        self.new_role.save()

        self.factory = RequestFactory()

        self.RolePermissionModel = Role.instance_permissions.through

    def request_updates(self, perm_specs):
        updates = {self.new_role.pk: {'fields': {}, 'models': perm_specs}}
        request = make_request(method='PUT', body=json.dumps(updates))
        roles_update(request, self.instance)

    def assert_assignment(self, permission, role, is_assigned=True):
        assignment = self.RolePermissionModel.objects.filter(
            role=role, permission=permission)
        self.assertEqual(assignment.exists(), is_assigned)

    def test_instance_assignment(self):
        permission = make_permission('do_all_the_things', Instance)
        self.request_updates({'Instance.do_all_the_things': True})

        self.assert_assignment(permission, self.new_role)

    def test_model_assignment(self):
        self.instance.add_map_feature_types(['Bioswale'])
        permissions = [
            'Plot.add_plot',
            'Plot.delete_plot',
            'Tree.add_tree',
            'Tree.delete_tree',
            'TreePhoto.add_treephoto',
            'TreePhoto.delete_treephoto',
            'Bioswale.add_bioswale',
            'Bioswale.delete_bioswale',
            'MapFeaturePhoto.add_bioswalephoto',
            'MapFeaturePhoto.delete_bioswalephoto']

        self.request_updates(
            dict(zip(permissions, [True] * len(permissions))))

        for existing in permissions:
            __, codename = dotted_split(existing, 2, maxsplit=1)
            permission = Permission.objects.get(codename=codename)
            self.assert_assignment(permission, self.new_role)

    def test_unassignment(self):
        instance_permission = make_permission('do_all_the_things', Instance)
        add_plot_permission = Permission.objects.get(codename='add_plot')
        self.assertIsNotNone(instance_permission)
        self.assertIsNotNone(add_plot_permission)

        self.RolePermissionModel.objects.bulk_create([
            self.RolePermissionModel(
                role=self.new_role, permission=instance_permission),
            self.RolePermissionModel(
                role=self.new_role, permission=add_plot_permission)])

        self.assertEqual(
            self.RolePermissionModel.objects.filter(
                role=self.new_role).count(), 2)

        self.request_updates({
            'Instance.do_all_the_things': False,
            'Plot.add_plot': False})

        self.assertEqual(
            self.RolePermissionModel.objects.filter(
                role=self.new_role).count(), 0)
Beispiel #20
0
class FieldPermMgmtTest(OTMTestCase):
    def setUp(self):
        self.instance = make_instance()
        self.commander = make_commander_user(self.instance)

        self.new_role = Role(name='Ambassador', instance=self.instance,
                             rep_thresh=0)
        self.new_role.save()

        self.factory = RequestFactory()

    def make_updates(self, role_id, field_json):
        return {
            role_id: {
                'fields': field_json,
                'models': {}
            }
        }

    def test_updates(self):

        # TODO: For now, don't use '2', which is pending
        updates = self.make_updates(
            self.new_role.pk, {'Tree.diameter': 3})

        json_updates = json.dumps(updates)
        request = make_request(method='PUT', body=json_updates)
        roles_update(request, self.instance)

        #requery new_role
        self.new_role = Role.objects.get(pk=self.new_role.pk)

        self.assertEqual(1,
                         FieldPermission.objects.filter(
                             model_name='Tree',
                             field_name='diameter',
                             instance=self.instance,
                             role=self.new_role,
                             permission_level=3).count())

    def test_no_updates(self):
        updates = {}

        json_updates = json.dumps(updates)
        request = make_request(method='PUT', body=json_updates)
        roles_update(request, self.instance)

    def assertUpdatesRaisesValidation(self, updates):
        json_updates = json.dumps(updates)
        request = make_request(method='PUT', body=json_updates)
        self.assertRaises(ValidationError, roles_update,
                          request, self.instance)

    def test_invalid_model_does_not_exist_integration(self):
        updates = self.make_updates(
            self.new_role.pk, {'Gethen.model_name': 2})
        self.assertUpdatesRaisesValidation(updates)

    def test_invalid_model_not_authorizable_integration(self):
        updates = self.make_updates(
            self.new_role.pk, {'FieldPermission.model_name': 2})
        self.assertUpdatesRaisesValidation(updates)

    def test_invalid_field_name_integration(self):
        updates = self.make_updates(
            self.new_role.pk, {'Tree.model_name': 2})
        self.assertUpdatesRaisesValidation(updates)

    def test_invalid_role_id_integration(self):
        updates = self.make_updates(
            100, {'Tree.readonly': 2})
        self.assertUpdatesRaisesValidation(updates)
Beispiel #21
0
class ModelUnicodeTests(OTMTestCase):
    def setUp(self):
        self.instance = make_instance(name='Test Instance')

        self.species = Species(instance=self.instance,
                               common_name='Test Common Name',
                               genus='Test Genus',
                               cultivar='Test Cultivar',
                               species='Test Species')
        self.species.save_base()

        self.user = make_user(username='******', password='******')

        self.plot = Plot(geom=Point(1, 1),
                         instance=self.instance,
                         address_street="123 Main Street")

        self.plot.save_base()

        self.tree = Tree(plot=self.plot, instance=self.instance)

        self.tree.save_base()

        self.boundary = make_simple_boundary("Test Boundary")

        self.role = Role(instance=self.instance,
                         name='Test Role',
                         rep_thresh=2)
        self.role.save()

        self.field_permission = FieldPermission(
            model_name="Tree",
            field_name="readonly",
            permission_level=FieldPermission.READ_ONLY,
            role=self.role,
            instance=self.instance)
        self.field_permission.save_base()

        self.audit = Audit(action=Audit.Type.Update,
                           model="Tree",
                           field="readonly",
                           model_id=1,
                           user=self.user,
                           previous_value=True,
                           current_value=False)
        self.audit.save_base()

        self.reputation_metric = ReputationMetric(instance=self.instance,
                                                  model_name="Tree",
                                                  action="Test Action")
        self.reputation_metric.save_base()

    def test_instance_model(self):
        self.assertEqual(unicode(self.instance), "Test Instance")

    def test_species_model(self):
        self.assertEqual(
            unicode(self.species),
            "Test Common Name [Test Genus Test Species 'Test Cultivar']")

    def test_user_model(self):
        self.assertEqual(unicode(self.user), 'commander')

    def test_plot_model(self):
        self.assertEqual(unicode(self.plot), 'Plot (1.0, 1.0) 123 Main Street')

    def test_tree_model(self):
        self.assertEqual(unicode(self.tree), '')

    def test_boundary_model(self):
        self.assertEqual(unicode(self.boundary), 'Test Boundary')

    def test_role_model(self):
        self.assertEqual(unicode(self.role), 'Test Role (%s)' % self.role.pk)

    def test_field_permission_model(self):
        self.assertEqual(
            unicode(self.field_permission),
            'Tree.readonly - Test Role (%s) - Read Only' % self.role.pk)

    def test_audit_model(self):
        self.assertEqual(
            unicode(self.audit),
            'pk=%s - action=Update - Tree.readonly:(1) - True => False' %
            self.audit.pk)

    def test_reputation_metric_model(self):
        self.assertEqual(unicode(self.reputation_metric),
                         'Test Instance - Tree - Test Action')
class InlineFieldTagTests(OTMTestCase):

    def setUp(self):
        self.instance = make_instance()
        self.instance.config['advanced_search_fields'] = {}
        self.instance.save()
        self.role = Role(name='role', instance=self.instance, rep_thresh=0)
        self.role.save()

        self.observer = make_observer_user(self.instance)

        self.udf_role = Role(name='udf', instance=self.instance, rep_thresh=0)
        self.udf_role.save()

        self.template_dir = tempfile.mkdtemp()
        self.template_file_path = os.path.join(self.template_dir,
                                               "field_template.html")

        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type='Plot',
            datatype=json.dumps({'type': 'choice',
                                 'choices': ["a", "b", "c"]}),
            iscollection=False,
            name='Test choice')

        udf_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='udf:Test choice',
            permission_level=FieldPermission.READ_ONLY,
            role=self.role, instance=self.instance)
        udf_perm.save()
        udf_write_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='udf:Test choice',
            permission_level=FieldPermission.WRITE_DIRECTLY,
            role=self.udf_role, instance=self.instance)
        udf_write_perm.save()

    def tearDown(self):
        rmtree(self.template_dir)

    def _form_template_with_request_user_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = """{% load form_extras %}""" +\
            """{% field "Test Field" from """ + field_name +\
            """ for request.user withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _form_template_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = """{% load form_extras %}""" +\
            """{% field "Test Field" from """ + field_name +\
            """ withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _form_template_labelless_with_request_user_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = """{% load form_extras %}""" +\
            """{% field from """ + field_name +\
            """ for request.user withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _form_template_labelless_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = """{% load form_extras %}""" +\
            """{% field from """ + field_name +\
            """ withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _form_template_create(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = """{% load form_extras %}""" +\
            """{% create from """ + field_name +\
            """ in request.instance""" +\
            """ withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _form_template_search(self):
        template_text = """{% load form_extras %}""" +\
            """{% search from search_json""" +\
            """ for request.user in request.instance """ +\
            """ withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _write_field_template(self, text):
        with open(self.template_file_path, 'w') as f:
                f.write(text)

    def assert_plot_length_context_value(self, user, name, value,
                                         template_fn=None):
        if template_fn is None:
            template_fn = (self._form_template_with_request_user_for
                           if user else self._form_template_for)
        plot = Plot(length=12.3, instance=self.instance)
        plot.convert_to_display_units()

        template = template_fn('plot.length')
        self._write_field_template("{{" + name + "}}")
        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(Context({
                'request': {'user': user, 'instance': self.instance},
                'plot': plot})).strip()
            self.assertEqual(content, value)

    def assert_search_context_value(self, user, name, value, search_json):
        template = self._form_template_search()
        self._write_field_template("{{" + name + "}}")
        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(Context({
                'request': {'user': user, 'instance': self.instance},
                'search_json': search_json})).strip()
            self.assertEqual(content, value)

    def assert_plot_udf_context_value(self, user, name, value):
        self.assert_plot_udf_template(user, "{{" + name + "}}", value)

    def assert_plot_udf_template(self, user, template_text, value):
        plot = Plot(length=12.3, instance=self.instance)
        plot.udfs['Test choice'] = 'b'
        template = self._form_template_with_request_user_for(
            'plot.udf:Test choice')
        self._write_field_template(template_text)
        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(Context({
                'request': {'user': user},
                'plot': plot})).strip()
            self.assertEqual(content, value)

    def test_sets_is_visible_to_true_if_user_is_not_specified(self):
        # A user without permissions would normaly not be able to
        # view the field, but using the tag without "for user" allows
        # anyone to get the rendered markup
        self.assert_plot_length_context_value(None, 'field.is_visible',
                                              'True')

    def test_sets_is_editable_to_true_if_user_is_not_specified(self):
        # A user without permissions would normaly not be able to
        # edit the field, but using the tag without "for user" allows
        # anyone to get the rendered markup
        self.assert_plot_length_context_value(None, 'field.is_editable',
                                              'True')

    def test_labelless_sets_is_visible_to_true_if_user_is_not_specified(self):
        # A user without permissions would normaly not be able to
        # view the field, but using the tag without "for user" allows
        # anyone to get the rendered markup
        self.assert_plot_length_context_value(
            None, 'field.is_visible', 'True',
            self._form_template_labelless_for)

    def test_sets_is_visible_to_false_for_user_without_perms(self):
        user = make_user(username='******')
        self.assert_plot_length_context_value(user, 'field.is_visible',
                                              'False')

    def test_sets_is_visible_to_true_for_user_with_perms(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.is_visible', 'True')

    def test_sets_is_editable_to_false_for_user_without_perms(self):
        user = make_user(username='******')
        self.assert_plot_length_context_value(user, 'field.is_editable',
                                              'False')

    def test_sets_is_editable_to_true_for_user_with_perms(self):
        user = make_commander_user(self.instance)
        self.assert_plot_length_context_value(user, 'field.is_editable',
                                              'True')

    def test_udf_sets_is_visible_to_false_for_user_without_perms(self):
        user = make_user(username='******')
        self.assert_plot_udf_context_value(user, 'field.is_visible', 'False')

    def test_udf_sets_is_visible_to_true_for_user_with_perms(self):
        user = make_user(self.instance, username='******',
                         make_role=lambda _: self.udf_role)
        self.assert_plot_udf_context_value(user, 'field.is_visible', 'True')

    def test_udf_sets_is_editable_to_false_for_user_without_perms(self):
        user = make_user(username='******')
        self.assert_plot_udf_context_value(user, 'field.is_editable', 'False')

    def test_udf_sets_is_editable_to_true_for_user_with_perms(self):
        user = make_user(self.instance, username='******',
                         make_role=lambda _: self.udf_role)
        self.assert_plot_udf_context_value(user, 'field.is_editable', 'True')

    def test_sets_label(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.label', 'Test Field')

    def test_sets_identifier(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.identifier', 'plot.length')

    def test_sets_value(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.value', '12.3')

    def test_sets_units(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.units', 'in')

    def test_sets_digits(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.digits', '1')

    def test_sets_display_value(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.display_value', '12.3 in')

    PLOT_LENGTH_DISPLAY_DEFAULTS = {'plot':
                                    {'length': {'units': 'in', 'digits': 1}}}

    @override_settings(DISPLAY_DEFAULTS=PLOT_LENGTH_DISPLAY_DEFAULTS)
    def test_uses_custom_units_and_digits(self):
        set_attr_on_json_field(
            self.instance, 'config.value_display.plot.length.units', 'm')
        set_attr_on_json_field(
            self.instance, 'config.value_display.plot.length.digits', '3')
        self.assert_plot_length_context_value(
            self.observer, 'field.display_value', '0.312 m')

    def test_sets_data_type(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.data_type', 'float')

    def test_sets_value_for_udf_field(self):
        self.assert_plot_udf_context_value(self.observer, 'field.value', 'b')

    def test_sets_display_value_for_udf_field(self):
        self.assert_plot_udf_context_value(
            self.observer, 'field.display_value', 'b')

    def test_sets_data_type_for_udf_field(self):
        self.assert_plot_udf_context_value(
            self.observer, 'field.data_type', 'choice')

    def test_sets_choices_for_udf_field(self):
        template_string = """
            {% for c in field.choices %}{{c.value}}-{% endfor %}"""
        self.assert_plot_udf_template(
            self.observer, template_string, '-a-b-c-')

    def test_sets_choices_to_empty_if_not_set(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.choices', '[]')

    def test_labelless_sets_label_to_default(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.label',
            Plot._meta.get_field('length').help_text,
            self._form_template_labelless_with_request_user_for)

    def test_labelless_sets_identifier(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.identifier', 'plot.length',
            self._form_template_labelless_with_request_user_for)

    def test_create_uses_new_model(self):
        template = self._form_template_create('Plot.length')
        self._write_field_template("{{ field.value }}")

        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(Context({
                'request': {'user': self.observer, 'instance': self.instance}
            })).strip()
            self.assertEqual(content, unicode(Plot().length))

    def test_search_uses_new_model(self):
        self.assert_search_context_value(
            self.observer, 'field.value', unicode(Plot().length),
            {'identifier': 'Plot.length'})

    def test_search_adds_field_config(self):
        search = {'identifier': 'Plot.length',
                  'label': 'testing',
                  'search_type': 'range',
                  'default': [0, 100]}
        self.assert_search_context_value(
            self.observer, 'field.identifier', 'plot.length', search)

        self.assert_search_context_value(
            self.observer, 'field.label', 'testing', search)

        self.assert_search_context_value(
            self.observer, 'field.search_type', 'range', search)

        self.assert_search_context_value(
            self.observer, 'field.default', '[0, 100]', search)

    def test_search_gets_default_label_when_none_given(self):
        self.assert_search_context_value(
            self.observer, 'field.label',
            unicode(Plot._meta.get_field('length').help_text),
            {'identifier': 'Plot.length', 'label': None})

    def test_search_fields_get_added_only_for_valid_json_matches(self):
        with self.assertRaises(TemplateSyntaxError):
            with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
                self._write_field_template("{{ field.identifier }}")
                self._form_template_search().render(Context({
                    'request': {'user': self.observer,
                                'instance': self.instance},
                    'search_json': {'identifiers': 'Plot.width'}}
                )).strip()
class UserCanReadTagTest(OTMTestCase):

    def setUp(self):
        self.instance = make_instance()

        self.user = make_user(username='******', password='******')

        self.role = Role(name='role', instance=self.instance, rep_thresh=0)
        self.role.save()

        self.user_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=self.role, instance=self.instance)

        iuser = InstanceUser(instance=self.instance, user=self.user,
                             role=self.role)
        iuser.save_with_user(self.user)

        inst_role = Role(name='inst def role',
                         instance=self.instance,
                         rep_thresh=0)
        inst_role.save()

        self.inst_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=inst_role, instance=self.instance)

        self.instance.default_role = inst_role
        self.instance.save()

        self.plot = Plot(instance=self.instance)

    basic_template = Template(
        """
        {% load auth_extras %}
        {% usercanread plot "width" as w %}
        plot width {{ w }}
        {% endusercanread %}
        """)

    def _render_basic_template_with_vars(self, user, plot):
        return UserCanReadTagTest.basic_template.render(
            Context({
                'request': {'user': user},
                'plot': plot})).strip()

    def test_works_with_empty_user_no_perm(self):
        self.assertEqual(
            self._render_basic_template_with_vars(None, self.plot), '')

    def test_works_with_empty_user_with_perm(self):
        perms = [FieldPermission.READ_ONLY,
                 FieldPermission.WRITE_WITH_AUDIT,
                 FieldPermission.WRITE_DIRECTLY]

        self.plot.width = 9

        for plevel in perms:
            self.inst_perm.permission_level = plevel
            self.inst_perm.save()

            self.assertEqual(
                self._render_basic_template_with_vars(None, self.plot),
                'plot width 9')

    def test_works_with_user_with_role_no_perm(self):
        self.assertEqual(
            self._render_basic_template_with_vars(self.user, self.plot), '')

    def test_works_with_user_with_role_with_perm(self):
        perms = [FieldPermission.READ_ONLY,
                 FieldPermission.WRITE_WITH_AUDIT,
                 FieldPermission.WRITE_DIRECTLY]

        self.plot.width = 9

        for plevel in perms:
            self.user_perm.permission_level = plevel
            self.user_perm.save()

            self.assertEqual(
                self._render_basic_template_with_vars(self.user, self.plot),
                'plot width 9')

    def test_works_with_udf(self):
        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type='Plot',
            datatype=json.dumps({'type': 'choice',
                                 'choices': ['a', 'b', 'c']}),
            iscollection=False,
            name='Test choice')

        udf_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='udf:Test choice',
            permission_level=FieldPermission.NONE,
            role=self.role, instance=self.instance)
        udf_perm.save()

        plot = self.plot
        plot.udfs['Test choice'] = 'b'

        def render():
            return Template(
                """
                {% load auth_extras %}
                {% usercanread plot the_key as w %}
                plot udf {{ w }}
                {% endusercanread %}
                """)\
                .render(Context({
                    'request': {'user': self.user},
                    'plot': plot,
                    'the_key': 'udf:Test choice'})).strip()

        self.assertEqual(render(), '')

        udf_perm.permission_level = FieldPermission.READ_ONLY
        udf_perm.save()

        self.assertEqual(render(), 'plot udf b')
class UserCanReadTagTest(OTMTestCase):

    def setUp(self):
        self.instance = make_instance()

        self.user = make_user(username='******', password='******')

        self.role = Role(name='role', instance=self.instance, rep_thresh=0)
        self.role.save()

        self.user_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=self.role, instance=self.instance)

        iuser = InstanceUser(instance=self.instance, user=self.user,
                             role=self.role)
        iuser.save_with_user(self.user)

        inst_role = Role(name='inst def role',
                         instance=self.instance,
                         rep_thresh=0)
        inst_role.save()

        self.inst_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='width',
            permission_level=FieldPermission.NONE,
            role=inst_role, instance=self.instance)

        self.instance.default_role = inst_role
        self.instance.save()

        self.plot = Plot(instance=self.instance)

    basic_template = Template(
        """
        {% load auth_extras %}
        {% usercanread plot "width" as w %}
        plot width {{ w }}
        {% endusercanread %}
        """)

    def _render_basic_template_with_vars(self, user, plot):
        return UserCanReadTagTest.basic_template.render(
            Context({
                'request': {'user': user},
                'plot': plot})).strip()

    def test_works_with_empty_user_no_perm(self):
        self.assertEqual(
            self._render_basic_template_with_vars(None, self.plot), '')

    def test_works_with_empty_user_with_perm(self):
        perms = [FieldPermission.READ_ONLY,
                 FieldPermission.WRITE_WITH_AUDIT,
                 FieldPermission.WRITE_DIRECTLY]

        self.plot.width = 9

        for plevel in perms:
            self.inst_perm.permission_level = plevel
            self.inst_perm.save()

            self.assertEqual(
                self._render_basic_template_with_vars(None, self.plot),
                'plot width 9')

    def test_works_with_user_with_role_no_perm(self):
        self.assertEqual(
            self._render_basic_template_with_vars(self.user, self.plot), '')

    def test_works_with_user_with_role_with_perm(self):
        perms = [FieldPermission.READ_ONLY,
                 FieldPermission.WRITE_WITH_AUDIT,
                 FieldPermission.WRITE_DIRECTLY]

        self.plot.width = 9

        for plevel in perms:
            self.user_perm.permission_level = plevel
            self.user_perm.save()

            self.assertEqual(
                self._render_basic_template_with_vars(self.user, self.plot),
                'plot width 9')

    def test_works_with_udf(self):
        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type='Plot',
            datatype=json.dumps({'type': 'choice',
                                 'choices': ['a', 'b', 'c']}),
            iscollection=False,
            name='Test choice')

        udf_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='udf:Test choice',
            permission_level=FieldPermission.NONE,
            role=self.role, instance=self.instance)
        udf_perm.save()

        plot = self.plot
        plot.udfs['Test choice'] = 'b'

        def render():
            return Template(
                """
                {% load auth_extras %}
                {% usercanread plot the_key as w %}
                plot udf {{ w }}
                {% endusercanread %}
                """)\
                .render(Context({
                    'request': {'user': self.user},
                    'plot': plot,
                    'the_key': 'udf:Test choice'})).strip()

        self.assertEqual(render(), '')

        udf_perm.permission_level = FieldPermission.READ_ONLY
        udf_perm.save()

        self.assertEqual(render(), 'plot udf b')
Beispiel #25
0
class InlineFieldTagTests(TestCase):
    def setUp(self):
        self.instance = make_instance()
        self.instance.config["advanced_search_fields"] = {}
        self.instance.save()
        self.role = Role(name="role", instance=self.instance, rep_thresh=0)
        self.role.save()

        self.observer = make_observer_user(self.instance)

        self.udf_role = Role(name="udf", instance=self.instance, rep_thresh=0)
        self.udf_role.save()

        self.template_dir = tempfile.mkdtemp()
        self.template_file_path = os.path.join(self.template_dir, "field_template.html")

        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type="Plot",
            datatype=json.dumps({"type": "choice", "choices": ["a", "b", "c"]}),
            iscollection=False,
            name="Test choice",
        )

        udf_perm, _ = FieldPermission.objects.get_or_create(
            model_name="Plot",
            field_name="udf:Test choice",
            permission_level=FieldPermission.READ_ONLY,
            role=self.role,
            instance=self.instance,
        )
        udf_perm.save()
        udf_write_perm, _ = FieldPermission.objects.get_or_create(
            model_name="Plot",
            field_name="udf:Test choice",
            permission_level=FieldPermission.WRITE_DIRECTLY,
            role=self.udf_role,
            instance=self.instance,
        )
        udf_write_perm.save()

    def tearDown(self):
        rmtree(self.template_dir)

    def _form_template_with_request_user_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = (
            """{% load form_extras %}"""
            + """{% field "Test Field" from """
            + field_name
            + """ for request.user withtemplate "field_template.html" %}"""
        )
        return Template(template_text)

    def _form_template_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = (
            """{% load form_extras %}"""
            + """{% field "Test Field" from """
            + field_name
            + """ withtemplate "field_template.html" %}"""
        )
        return Template(template_text)

    def _form_template_labelless_with_request_user_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = (
            """{% load form_extras %}"""
            + """{% field from """
            + field_name
            + """ for request.user withtemplate "field_template.html" %}"""
        )
        return Template(template_text)

    def _form_template_labelless_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = (
            """{% load form_extras %}"""
            + """{% field from """
            + field_name
            + """ withtemplate "field_template.html" %}"""
        )
        return Template(template_text)

    def _form_template_create(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = (
            """{% load form_extras %}"""
            + """{% create from """
            + field_name
            + """ in request.instance"""
            + """ withtemplate "field_template.html" %}"""
        )
        return Template(template_text)

    def _form_template_search(self):
        template_text = (
            """{% load form_extras %}"""
            + """{% search from search_json"""
            + """ for request.user in request.instance """
            + """ withtemplate "field_template.html" %}"""
        )
        return Template(template_text)

    def _write_field_template(self, text):
        with open(self.template_file_path, "w") as f:
            f.write(text)

    def assert_plot_length_context_value(self, user, name, value, template_fn=None):
        if template_fn is None:
            template_fn = self._form_template_with_request_user_for if user else self._form_template_for
        plot = Plot(length=12.3, instance=self.instance)
        plot.convert_to_display_units()

        template = template_fn("plot.length")
        self._write_field_template("{{" + name + "}}")
        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(
                Context({"request": {"user": user, "instance": self.instance}, "plot": plot})
            ).strip()
            self.assertEqual(content, value)

    def assert_search_context_value(self, user, name, value, search_json):
        template = self._form_template_search()
        self._write_field_template("{{" + name + "}}")
        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(
                Context({"request": {"user": user, "instance": self.instance}, "search_json": search_json})
            ).strip()
            self.assertEqual(content, value)

    def assert_plot_udf_context_value(self, user, name, value):
        self.assert_plot_udf_template(user, "{{" + name + "}}", value)

    def assert_plot_udf_template(self, user, template_text, value):
        plot = Plot(length=12.3, instance=self.instance)
        plot.udfs["Test choice"] = "b"
        template = self._form_template_with_request_user_for("plot.udf:Test choice")
        self._write_field_template(template_text)
        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(Context({"request": {"user": user}, "plot": plot})).strip()
            self.assertEqual(content, value)

    def test_sets_is_visible_to_true_if_user_is_not_specified(self):
        # A user without permissions would normaly not be able to
        # view the field, but using the tag without "for user" allows
        # anyone to get the rendered markup
        self.assert_plot_length_context_value(None, "field.is_visible", "True")

    def test_sets_is_editable_to_true_if_user_is_not_specified(self):
        # A user without permissions would normaly not be able to
        # edit the field, but using the tag without "for user" allows
        # anyone to get the rendered markup
        self.assert_plot_length_context_value(None, "field.is_editable", "True")

    def test_labelless_sets_is_visible_to_true_if_user_is_not_specified(self):
        # A user without permissions would normaly not be able to
        # view the field, but using the tag without "for user" allows
        # anyone to get the rendered markup
        self.assert_plot_length_context_value(None, "field.is_visible", "True", self._form_template_labelless_for)

    def test_sets_is_visible_to_false_for_user_without_perms(self):
        user = make_user(username="******")
        self.assert_plot_length_context_value(user, "field.is_visible", "False")

    def test_sets_is_visible_to_true_for_user_with_perms(self):
        self.assert_plot_length_context_value(self.observer, "field.is_visible", "True")

    def test_sets_is_editable_to_false_for_user_without_perms(self):
        user = make_user(username="******")
        self.assert_plot_length_context_value(user, "field.is_editable", "False")

    def test_sets_is_editable_to_true_for_user_with_perms(self):
        user = make_commander_user(self.instance)
        self.assert_plot_length_context_value(user, "field.is_editable", "True")

    def test_udf_sets_is_visible_to_false_for_user_without_perms(self):
        user = make_user(username="******")
        self.assert_plot_udf_context_value(user, "field.is_visible", "False")

    def test_udf_sets_is_visible_to_true_for_user_with_perms(self):
        user = make_user(self.instance, username="******", make_role=lambda _: self.udf_role)
        self.assert_plot_udf_context_value(user, "field.is_visible", "True")

    def test_udf_sets_is_editable_to_false_for_user_without_perms(self):
        user = make_user(username="******")
        self.assert_plot_udf_context_value(user, "field.is_editable", "False")

    def test_udf_sets_is_editable_to_true_for_user_with_perms(self):
        user = make_user(self.instance, username="******", make_role=lambda _: self.udf_role)
        self.assert_plot_udf_context_value(user, "field.is_editable", "True")

    def test_sets_label(self):
        self.assert_plot_length_context_value(self.observer, "field.label", "Test Field")

    def test_sets_identifier(self):
        self.assert_plot_length_context_value(self.observer, "field.identifier", "plot.length")

    def test_sets_value(self):
        self.assert_plot_length_context_value(self.observer, "field.value", "12.3")

    def test_sets_units(self):
        self.assert_plot_length_context_value(self.observer, "field.units", "in")

    def test_sets_digits(self):
        self.assert_plot_length_context_value(self.observer, "field.digits", "1")

    def test_sets_display_value(self):
        self.assert_plot_length_context_value(self.observer, "field.display_value", "12.3 in")

    PLOT_LENGTH_DISPLAY_DEFAULTS = {"plot": {"length": {"units": "in", "digits": 1}}}

    @override_settings(DISPLAY_DEFAULTS=PLOT_LENGTH_DISPLAY_DEFAULTS)
    def test_uses_custom_units_and_digits(self):
        set_attr_on_json_field(self.instance, "config.value_display.plot.length.units", "m")
        set_attr_on_json_field(self.instance, "config.value_display.plot.length.digits", "3")
        self.assert_plot_length_context_value(self.observer, "field.display_value", "0.312 m")

    def test_sets_data_type(self):
        self.assert_plot_length_context_value(self.observer, "field.data_type", "float")

    def test_sets_value_for_udf_field(self):
        self.assert_plot_udf_context_value(self.observer, "field.value", "b")

    def test_sets_display_value_for_udf_field(self):
        self.assert_plot_udf_context_value(self.observer, "field.display_value", "b")

    def test_sets_data_type_for_udf_field(self):
        self.assert_plot_udf_context_value(self.observer, "field.data_type", "choice")

    def test_sets_choices_for_udf_field(self):
        template_string = """
            {% for c in field.choices %}{{c.value}}-{% endfor %}"""
        self.assert_plot_udf_template(self.observer, template_string, "-a-b-c-")

    def test_sets_choices_to_empty_if_not_set(self):
        self.assert_plot_length_context_value(self.observer, "field.choices", "[]")

    def test_labelless_sets_label_to_default(self):
        self.assert_plot_length_context_value(
            self.observer,
            "field.label",
            Plot._meta.get_field("length").help_text,
            self._form_template_labelless_with_request_user_for,
        )

    def test_labelless_sets_identifier(self):
        self.assert_plot_length_context_value(
            self.observer, "field.identifier", "plot.length", self._form_template_labelless_with_request_user_for
        )

    def test_create_uses_new_model(self):
        template = self._form_template_create("Plot.length")
        self._write_field_template("{{ field.value }}")

        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(Context({"request": {"user": self.observer, "instance": self.instance}})).strip()
            self.assertEqual(content, unicode(Plot().length))

    def test_search_uses_new_model(self):
        self.assert_search_context_value(
            self.observer, "field.value", unicode(Plot().length), {"identifier": "Plot.length"}
        )

    def test_search_adds_field_config(self):
        search = {"identifier": "Plot.length", "label": "testing", "search_type": "range", "default": [0, 100]}
        self.assert_search_context_value(self.observer, "field.identifier", "plot.length", search)

        self.assert_search_context_value(self.observer, "field.label", "testing", search)

        self.assert_search_context_value(self.observer, "field.search_type", "range", search)

        self.assert_search_context_value(self.observer, "field.default", "[0, 100]", search)

    def test_search_gets_default_label_when_none_given(self):
        self.assert_search_context_value(
            self.observer,
            "field.label",
            unicode(Plot._meta.get_field("length").help_text),
            {"identifier": "Plot.length", "label": None},
        )

    def test_search_fields_get_added_only_for_valid_json_matches(self):
        with self.assertRaises(TemplateSyntaxError):
            with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
                self._write_field_template("{{ field.identifier }}")
                self._form_template_search().render(
                    Context(
                        {
                            "request": {"user": self.observer, "instance": self.instance},
                            "search_json": {"identifiers": "Plot.width"},
                        }
                    )
                ).strip()
class InlineFieldTagTests(OTMTestCase):

    def setUp(self):
        self.instance = make_instance()
        self.instance.save()
        self.role = Role(name='role', instance=self.instance, rep_thresh=0)
        self.role.save()

        self.observer = make_observer_user(self.instance)

        self.udf_role = Role(name='udf', instance=self.instance, rep_thresh=0)
        self.udf_role.save()

        self.template_dir = tempfile.mkdtemp()
        self.template_file_path = os.path.join(self.template_dir,
                                               "field_template.html")

        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type='Plot',
            datatype=json.dumps({'type': 'choice',
                                 'choices': ["a", "b", "c"]}),
            iscollection=False,
            name='Test choice')

        udf_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='udf:Test choice',
            permission_level=FieldPermission.READ_ONLY,
            role=self.role, instance=self.instance)
        udf_perm.save()
        udf_write_perm, __ = FieldPermission.objects.get_or_create(
            model_name='Plot', field_name='udf:Test choice',
            permission_level=FieldPermission.WRITE_DIRECTLY,
            role=self.udf_role, instance=self.instance)
        udf_write_perm.save()

    def tearDown(self):
        rmtree(self.template_dir)

    def _form_template_with_request_user_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = """{% load form_extras %}""" +\
            """{% field "Test Field" from """ + field_name +\
            """ for request.user withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _form_template_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = """{% load form_extras %}""" +\
            """{% field "Test Field" from """ + field_name +\
            """ withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _form_template_labelless_with_request_user_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = """{% load form_extras %}""" +\
            """{% field from """ + field_name +\
            """ for request.user withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _form_template_labelless_for(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = """{% load form_extras %}""" +\
            """{% field from """ + field_name +\
            """ withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _form_template_create(self, identifier):
        field_name = '"' + identifier + '"'
        template_text = """{% load form_extras %}""" +\
            """{% create from """ + field_name +\
            """ in request.instance""" +\
            """ withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _form_template_search(self):
        template_text = """{% load form_extras %}""" +\
            """{% search from search_json""" +\
            """ for request.user in request.instance """ +\
            """ withtemplate "field_template.html" %}"""
        return Template(template_text)

    def _write_field_template(self, text):
        with open(self.template_file_path, 'w') as f:
                f.write(text)

    def assert_plot_length_context_value(self, user, name, value,
                                         template_fn=None):
        if template_fn is None:
            template_fn = (self._form_template_with_request_user_for
                           if user else self._form_template_for)
        plot = Plot(length=12.3, instance=self.instance)
        plot.convert_to_display_units()

        template = template_fn('plot.length')
        self._write_field_template("{{" + name + "}}")
        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(Context({
                'request': {'user': user, 'instance': self.instance},
                'plot': plot})).strip()
            self.assertEqual(content, value)

    def assert_search_context_value(self, user, name, value, search_json):
        template = self._form_template_search()
        self._write_field_template("{{" + name + "}}")
        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(Context({
                'request': {'user': user, 'instance': self.instance},
                'search_json': search_json})).strip()
            self.assertEqual(content, value)

    def assert_plot_udf_context_value(self, user, name, value):
        self.assert_plot_udf_template(user, "{{" + name + "}}", value)

    def assert_plot_udf_template(self, user, template_text, value):
        plot = Plot(length=12.3, instance=self.instance)
        plot.udfs['Test choice'] = 'b'
        template = self._form_template_with_request_user_for(
            'plot.udf:Test choice')
        self._write_field_template(template_text)
        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(Context({
                'request': {'user': user},
                'plot': plot})).strip()
            self.assertEqual(content, value)

    def test_sets_is_visible_to_true_if_user_is_not_specified(self):
        # A user without permissions would normaly not be able to
        # view the field, but using the tag without "for user" allows
        # anyone to get the rendered markup
        self.assert_plot_length_context_value(None, 'field.is_visible',
                                              'True')

    def test_sets_is_editable_to_true_if_user_is_not_specified(self):
        # A user without permissions would normaly not be able to
        # edit the field, but using the tag without "for user" allows
        # anyone to get the rendered markup
        self.assert_plot_length_context_value(None, 'field.is_editable',
                                              'True')

    def test_labelless_sets_is_visible_to_true_if_user_is_not_specified(self):
        # A user without permissions would normaly not be able to
        # view the field, but using the tag without "for user" allows
        # anyone to get the rendered markup
        self.assert_plot_length_context_value(
            None, 'field.is_visible', 'True',
            self._form_template_labelless_for)

    def test_sets_is_visible_to_false_for_user_without_perms(self):
        user = make_user(username='******')
        self.assert_plot_length_context_value(user, 'field.is_visible',
                                              'False')

    def test_sets_is_visible_to_true_for_user_with_perms(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.is_visible', 'True')

    def test_sets_is_editable_to_false_for_user_without_perms(self):
        user = make_user(username='******')
        self.assert_plot_length_context_value(user, 'field.is_editable',
                                              'False')

    def test_sets_is_editable_to_true_for_user_with_perms(self):
        user = make_commander_user(self.instance)
        self.assert_plot_length_context_value(user, 'field.is_editable',
                                              'True')

    def test_udf_sets_is_visible_to_false_for_user_without_perms(self):
        user = make_user(username='******')
        self.assert_plot_udf_context_value(user, 'field.is_visible', 'False')

    def test_udf_sets_is_visible_to_true_for_user_with_perms(self):
        user = make_user(self.instance, username='******',
                         make_role=lambda _: self.udf_role)
        self.assert_plot_udf_context_value(user, 'field.is_visible', 'True')

    def test_udf_sets_is_editable_to_false_for_user_without_perms(self):
        user = make_user(username='******')
        self.assert_plot_udf_context_value(user, 'field.is_editable', 'False')

    def test_udf_sets_is_editable_to_true_for_user_with_perms(self):
        user = make_user(self.instance, username='******',
                         make_role=lambda _: self.udf_role)
        self.assert_plot_udf_context_value(user, 'field.is_editable', 'True')

    def test_sets_label(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.label', 'Test Field')

    def test_sets_identifier(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.identifier', 'plot.length')

    def test_sets_value(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.value', '12.3')

    def test_sets_units(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.units', 'in')

    def test_sets_digits(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.digits', '1')

    def test_sets_display_value(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.display_value', '12.3 in')

    PLOT_LENGTH_DISPLAY_DEFAULTS = {'plot':
                                    {'length': {'units': 'in', 'digits': 1}}}

    @override_settings(DISPLAY_DEFAULTS=PLOT_LENGTH_DISPLAY_DEFAULTS)
    def test_uses_custom_units_and_digits(self):
        set_attr_on_json_field(
            self.instance, 'config.value_display.plot.length.units', 'm')
        set_attr_on_json_field(
            self.instance, 'config.value_display.plot.length.digits', '3')
        self.assert_plot_length_context_value(
            self.observer, 'field.display_value', '0.312 m')

    def test_sets_data_type(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.data_type', 'float')

    def test_sets_value_for_udf_field(self):
        self.assert_plot_udf_context_value(self.observer, 'field.value', 'b')

    def test_sets_display_value_for_udf_field(self):
        self.assert_plot_udf_context_value(
            self.observer, 'field.display_value', 'b')

    def test_sets_data_type_for_udf_field(self):
        self.assert_plot_udf_context_value(
            self.observer, 'field.data_type', 'choice')

    def test_sets_choices_for_udf_field(self):
        template_string = """
            {% for c in field.choices %}{{c.value}}-{% endfor %}"""
        self.assert_plot_udf_template(
            self.observer, template_string, '-a-b-c-')

    def test_sets_choices_to_empty_if_not_set(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.choices', '[]')

    def test_labelless_sets_label_to_default(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.label',
            Plot._meta.get_field('length').verbose_name,
            self._form_template_labelless_with_request_user_for)

    def test_labelless_sets_identifier(self):
        self.assert_plot_length_context_value(
            self.observer, 'field.identifier', 'plot.length',
            self._form_template_labelless_with_request_user_for)

    def test_create_uses_new_model(self):
        template = self._form_template_create('Plot.length')
        self._write_field_template("{{ field.value }}")

        with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
            content = template.render(Context({
                'request': {'user': self.observer, 'instance': self.instance}
            })).strip()
            self.assertEqual(content, unicode(Plot().length))

    def test_search_uses_new_model(self):
        self.assert_search_context_value(
            self.observer, 'field.value', unicode(Plot().length),
            {'identifier': 'Plot.length'})

    def test_search_adds_field_config(self):
        search = {'identifier': 'Plot.length',
                  'label': 'testing',
                  'search_type': 'range',
                  'default': [0, 100]}
        self.assert_search_context_value(
            self.observer, 'field.identifier', 'plot.length', search)

        self.assert_search_context_value(
            self.observer, 'field.label', 'testing', search)

        self.assert_search_context_value(
            self.observer, 'field.search_type', 'range', search)

        self.assert_search_context_value(
            self.observer, 'field.default', '[0, 100]', search)

    def test_search_gets_default_label_when_none_given(self):
        self.assert_search_context_value(
            self.observer, 'field.label',
            unicode(Plot._meta.get_field('length').verbose_name),
            {'identifier': 'Plot.length', 'label': None})

    def test_search_fields_get_added_only_for_valid_json_matches(self):
        with self.assertRaises(TemplateSyntaxError):
            with self.settings(TEMPLATE_DIRS=(self.template_dir,)):
                self._write_field_template("{{ field.identifier }}")
                self._form_template_search().render(Context({
                    'request': {'user': self.observer,
                                'instance': self.instance},
                    'search_json': {'identifiers': 'Plot.width'}}
                )).strip()
Beispiel #27
0
class ModelPermMgmtTest(OTMTestCase):
    def setUp(self):
        self.instance = make_instance()

        self.commander = make_commander_user(self.instance)

        self.new_role = Role(name='Ambassador',
                             instance=self.instance,
                             rep_thresh=0)
        self.new_role.save()

        self.factory = RequestFactory()

        self.RolePermissionModel = Role.instance_permissions.through

    def request_updates(self, perm_specs):
        updates = {self.new_role.pk: {'fields': {}, 'models': perm_specs}}
        request = make_request(method='PUT', body=json.dumps(updates))
        roles_update(request, self.instance)

    def assert_assignment(self, permission, role, is_assigned=True):
        assignment = self.RolePermissionModel.objects.filter(
            role=role, permission=permission)
        self.assertEqual(assignment.exists(), is_assigned)

    def test_instance_assignment(self):
        permission = make_permission('do_all_the_things', Instance)
        self.request_updates({'Instance.do_all_the_things': True})

        self.assert_assignment(permission, self.new_role)

    def test_model_assignment(self):
        self.instance.add_map_feature_types(['Bioswale'])
        permissions = [
            'Plot.add_plot', 'Plot.delete_plot', 'Tree.add_tree',
            'Tree.delete_tree', 'TreePhoto.add_treephoto',
            'TreePhoto.delete_treephoto', 'Bioswale.add_bioswale',
            'Bioswale.delete_bioswale', 'MapFeaturePhoto.add_bioswalephoto',
            'MapFeaturePhoto.delete_bioswalephoto'
        ]

        self.request_updates(dict(zip(permissions, [True] * len(permissions))))

        for existing in permissions:
            __, codename = dotted_split(existing, 2, maxsplit=1)
            permission = Permission.objects.get(codename=codename)
            self.assert_assignment(permission, self.new_role)

    def test_unassignment(self):
        instance_permission = make_permission('do_all_the_things', Instance)
        add_plot_permission = Permission.objects.get(codename='add_plot')
        self.assertIsNotNone(instance_permission)
        self.assertIsNotNone(add_plot_permission)

        self.RolePermissionModel.objects.bulk_create([
            self.RolePermissionModel(role=self.new_role,
                                     permission=instance_permission),
            self.RolePermissionModel(role=self.new_role,
                                     permission=add_plot_permission)
        ])

        self.assertEqual(
            self.RolePermissionModel.objects.filter(
                role=self.new_role).count(), 2)

        self.request_updates({
            'Instance.do_all_the_things': False,
            'Plot.add_plot': False
        })

        self.assertEqual(
            self.RolePermissionModel.objects.filter(
                role=self.new_role).count(), 0)
Beispiel #28
0
class UserCanReadTagTest(TestCase):
    def setUp(self):
        self.instance = make_instance()

        self.user = make_user(username="******", password="******")

        self.role = Role(name="role", instance=self.instance, rep_thresh=0)
        self.role.save()

        self.user_perm, _ = FieldPermission.objects.get_or_create(
            model_name="Plot",
            field_name="width",
            permission_level=FieldPermission.NONE,
            role=self.role,
            instance=self.instance,
        )

        iuser = InstanceUser(instance=self.instance, user=self.user, role=self.role)
        iuser.save_with_user(self.user)

        inst_role = Role(name="inst def role", instance=self.instance, rep_thresh=0)
        inst_role.save()

        self.inst_perm, _ = FieldPermission.objects.get_or_create(
            model_name="Plot",
            field_name="width",
            permission_level=FieldPermission.NONE,
            role=inst_role,
            instance=self.instance,
        )

        self.instance.default_role = inst_role
        self.instance.save()

        self.plot = Plot(instance=self.instance)

    basic_template = Template(
        """
        {% load auth_extras %}
        {% usercanread plot "width" as w %}
        plot width {{ w }}
        {% endusercanread %}
        """
    )

    def _render_basic_template_with_vars(self, user, plot):
        return UserCanReadTagTest.basic_template.render(Context({"request": {"user": user}, "plot": plot})).strip()

    def test_works_with_empty_user_no_perm(self):
        self.assertEqual(self._render_basic_template_with_vars(None, self.plot), "")

    def test_works_with_empty_user_with_perm(self):
        perms = [FieldPermission.READ_ONLY, FieldPermission.WRITE_WITH_AUDIT, FieldPermission.WRITE_DIRECTLY]

        self.plot.width = 9

        for plevel in perms:
            self.inst_perm.permission_level = plevel
            self.inst_perm.save()

            self.assertEqual(self._render_basic_template_with_vars(None, self.plot), "plot width 9")

    def test_works_with_user_with_role_no_perm(self):
        self.assertEqual(self._render_basic_template_with_vars(self.user, self.plot), "")

    def test_works_with_user_with_role_with_perm(self):
        perms = [FieldPermission.READ_ONLY, FieldPermission.WRITE_WITH_AUDIT, FieldPermission.WRITE_DIRECTLY]

        self.plot.width = 9

        for plevel in perms:
            self.user_perm.permission_level = plevel
            self.user_perm.save()

            self.assertEqual(self._render_basic_template_with_vars(self.user, self.plot), "plot width 9")

    def test_works_with_udf(self):
        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type="Plot",
            datatype=json.dumps({"type": "choice", "choices": ["a", "b", "c"]}),
            iscollection=False,
            name="Test choice",
        )

        udf_perm, _ = FieldPermission.objects.get_or_create(
            model_name="Plot",
            field_name="udf:Test choice",
            permission_level=FieldPermission.NONE,
            role=self.role,
            instance=self.instance,
        )
        udf_perm.save()

        plot = self.plot
        plot.udfs["Test choice"] = "b"

        def render():
            return (
                Template(
                    """
                {% load auth_extras %}
                {% usercanread plot the_key as w %}
                plot udf {{ w }}
                {% endusercanread %}
                """
                )
                .render(Context({"request": {"user": self.user}, "plot": plot, "the_key": "udf:Test choice"}))
                .strip()
            )

        self.assertEqual(render(), "")

        udf_perm.permission_level = FieldPermission.READ_ONLY
        udf_perm.save()

        self.assertEqual(render(), "plot udf b")
Beispiel #29
0
class ModelUnicodeTests(OTMTestCase):

    def setUp(self):
        self.instance = make_instance(name='Test Instance')

        self.species = Species(instance=self.instance,
                               common_name='Test Common Name',
                               genus='Test Genus',
                               cultivar='Test Cultivar',
                               species='Test Species')
        self.species.save_base()

        self.user = make_user(username='******', password='******')

        self.plot = Plot(geom=Point(1, 1), instance=self.instance,
                         address_street="123 Main Street")

        self.plot.save_base()

        self.tree = Tree(plot=self.plot, instance=self.instance)

        self.tree.save_base()

        self.boundary = make_simple_boundary("Test Boundary")

        self.role = Role(instance=self.instance, name='Test Role',
                         rep_thresh=2)
        self.role.save()

        self.field_permission = FieldPermission(
            model_name="Tree",
            field_name="readonly",
            permission_level=FieldPermission.READ_ONLY,
            role=self.role,
            instance=self.instance)
        self.field_permission.save_base()

        self.audit = Audit(action=Audit.Type.Update,
                           model="Tree",
                           field="readonly",
                           model_id=1,
                           user=self.user,
                           previous_value=True,
                           current_value=False)
        self.audit.save_base()

        self.reputation_metric = ReputationMetric(instance=self.instance,
                                                  model_name="Tree",
                                                  action="Test Action")
        self.reputation_metric.save_base()

    def test_instance_model(self):
        self.assertEqual(unicode(self.instance), "Test Instance")

    def test_species_model(self):
        self.assertEqual(
            unicode(self.species),
            "Test Common Name [Test Genus Test Species 'Test Cultivar']")

    def test_user_model(self):
        self.assertEqual(unicode(self.user), 'commander')

    def test_plot_model(self):
        self.assertEqual(unicode(self.plot),
                         'Plot (1.0, 1.0) 123 Main Street')

    def test_tree_model(self):
        self.assertEqual(unicode(self.tree), '')

    def test_boundary_model(self):
        self.assertEqual(unicode(self.boundary), 'Test Boundary')

    def test_role_model(self):
        self.assertEqual(unicode(self.role), 'Test Role (%s)' % self.role.pk)

    def test_field_permission_model(self):
        self.assertEqual(unicode(self.field_permission),
                         'Tree.readonly - Test Role (%s) - Read Only'
                         % self.role.pk)

    def test_audit_model(self):
        self.assertEqual(
            unicode(self.audit),
            'pk=%s - action=Update - Tree.readonly:(1) - True => False'
            % self.audit.pk)

    def test_reputation_metric_model(self):
        self.assertEqual(unicode(self.reputation_metric),
                         'Test Instance - Tree - Test Action')
Beispiel #30
0
class FieldPermMgmtTest(OTMTestCase):
    def setUp(self):
        self.instance = make_instance()
        self.commander = make_commander_user(self.instance)

        self.new_role = Role(name='Ambassador',
                             instance=self.instance,
                             rep_thresh=0)
        self.new_role.save()

        self.factory = RequestFactory()

    def make_updates(self, role_id, field_json):
        return {role_id: {'fields': field_json, 'models': {}}}

    def test_updates(self):

        # TODO: For now, don't use '2', which is pending
        updates = self.make_updates(self.new_role.pk, {'Tree.diameter': 3})

        json_updates = json.dumps(updates)
        request = make_request(method='PUT', body=json_updates)
        roles_update(request, self.instance)

        #requery new_role
        self.new_role = Role.objects.get(pk=self.new_role.pk)

        self.assertEqual(
            1,
            FieldPermission.objects.filter(model_name='Tree',
                                           field_name='diameter',
                                           instance=self.instance,
                                           role=self.new_role,
                                           permission_level=3).count())

    def test_no_updates(self):
        updates = {}

        json_updates = json.dumps(updates)
        request = make_request(method='PUT', body=json_updates)
        roles_update(request, self.instance)

    def assertUpdatesRaisesValidation(self, updates):
        json_updates = json.dumps(updates)
        request = make_request(method='PUT', body=json_updates)
        self.assertRaises(ValidationError, roles_update, request,
                          self.instance)

    def test_invalid_model_does_not_exist_integration(self):
        updates = self.make_updates(self.new_role.pk, {'Gethen.model_name': 2})
        self.assertUpdatesRaisesValidation(updates)

    def test_invalid_model_not_authorizable_integration(self):
        updates = self.make_updates(self.new_role.pk,
                                    {'FieldPermission.model_name': 2})
        self.assertUpdatesRaisesValidation(updates)

    def test_invalid_field_name_integration(self):
        updates = self.make_updates(self.new_role.pk, {'Tree.model_name': 2})
        self.assertUpdatesRaisesValidation(updates)

    def test_invalid_role_id_integration(self):
        updates = self.make_updates(100, {'Tree.readonly': 2})
        self.assertUpdatesRaisesValidation(updates)