Esempio n. 1
0
 def make_tree(self, user=None):
     user = user or make_commander_user(self.instance)
     plot = Plot(geom=self.instance.center, instance=self.instance)
     plot.save_with_user(user)
     tree = Tree(instance=self.instance, plot=plot)
     tree.save_with_user(user)
     return tree
Esempio n. 2
0
    def test_delete_tree(self):
        plot = Plot(instance=self.instance,
                    geom=Point(0, 0))
        plot.save_with_user(self.user)
        tree = Tree(instance=self.instance,
                    plot=plot)
        tree.save_with_user(self.user)

        self.assertEqual(Plot.objects.count(), 1)
        self.assertEqual(Tree.objects.count(), 1)

        self._login_workflow()
        self._go_to_plot_detail(plot.pk)
        self.select_buttons()
        self.assertCantClickDeleteOrCancel()
        self.assertEqual(Plot.objects.count(), 1)
        self.assertEqual(Tree.objects.count(), 1)

        self.delete_begin.click()
        self.delete_cancel.click()
        self.assertCantClickDeleteOrCancel()
        self.assertEqual(Plot.objects.count(), 1)
        self.assertEqual(Tree.objects.count(), 1)

        self.select_buttons()
        self.delete_begin.click()
        self.delete_confirm.click()
        sleep(DATABASE_COMMIT_DELAY)
        self.assertEqual(Plot.objects.count(), 1)
        self.assertEqual(Tree.objects.count(), 0)
Esempio n. 3
0
    def setUp(self):
        super(ExportTreeTaskTest, self).setUp()

        set_write_permissions(self.instance, self.user, "Plot", ["udf:Test choice"])
        set_write_permissions(self.instance, self.user, "Tree", ["udf:Test int"])

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

        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type="Tree",
            datatype=json.dumps({"type": "int"}),
            iscollection=False,
            name="Test int",
        )

        p = Plot(geom=self.instance.center, instance=self.instance, address_street="123 Main Street")
        p.udfs["Test choice"] = "a"

        p.save_with_user(self.user)

        t = Tree(plot=p, instance=self.instance, diameter=2)
        t.udfs["Test int"] = 4

        t.save_with_user(self.user)
Esempio n. 4
0
    def test_reject_insert_rejects_updates(self):
        new_plot = Plot(geom=self.p1, instance=self.instance)
        new_plot.save_with_user(self.pending_user)

        insert_audit = Audit.objects.filter(model='Plot')\
                                    .get(field='id')
        field_audits = Audit.objects.filter(model='Plot')\
                                    .exclude(field='id')

        for audit in field_audits:
            approve_or_reject_audit_and_apply(
                audit, self.commander_user, approved=True)

        approve_or_reject_audit_and_apply(insert_audit,
                                          self.commander_user, False)

        # need to refresh the field_audits collection from the db
        # because references are broken
        # why doesn't this work? why are there 5 values in field_audits_ids?
        # field_audit_ids = field_audits.values_list('id', flat=True)
        field_audit_ids = [field_audit.id for field_audit in field_audits]
        field_audits = Audit.objects.filter(pk__in=field_audit_ids)

        for field_audit in field_audits:
            attached_review_audit = Audit.objects.get(pk=field_audit.ref.pk)

            self.assertEqual(attached_review_audit.action,
                             Audit.Type.PendingReject)

            self.assertNotEqual(None,
                                Audit.objects.get(
                                    model=field_audit.model,
                                    field=field_audit.field,
                                    model_id=field_audit.model_id,
                                    action=Audit.Type.PendingApprove))
Esempio n. 5
0
    def test_approve_insert_without_required_raises_integrity_error(self):
        new_plot = Plot(geom=self.p1, instance=self.instance)
        new_plot.save_with_user(self.pending_user)

        new_tree = Tree(plot=new_plot,
                        instance=self.instance,
                        diameter=10,
                        height=10,
                        readonly=False)
        new_tree.save_with_user(self.pending_user)

        approve_or_reject_audits_and_apply(new_plot.audits(),
                                           self.commander_user, True)

        diameter_audit = Audit.objects.get(model='Tree',
                                           field='diameter',
                                           model_id=new_tree.pk)
        insert_audit = Audit.objects.get(model='Tree',
                                         model_id=new_tree.pk,
                                         field='id')

        approve_or_reject_audit_and_apply(diameter_audit,
                                          self.commander_user,
                                          approved=True)

        self.assertRaises(IntegrityError, approve_or_reject_audit_and_apply,
                          insert_audit, self.commander_user, True)
Esempio n. 6
0
    def setUp(self):
        super(ExportTreeTaskTest, self).setUp()

        set_write_permissions(self.instance, self.user,
                              'Plot', ['udf:Test choice'])
        set_write_permissions(self.instance, self.user,
                              'Tree', ['udf:Test int'])

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

        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type='Tree',
            datatype=json.dumps({'type': 'int'}),
            iscollection=False,
            name='Test int')

        p = Plot(geom=self.instance.center, instance=self.instance,
                 address_street="123 Main Street")
        p.udfs['Test choice'] = 'a'

        p.save_with_user(self.user)

        t = Tree(plot=p, instance=self.instance, diameter=2)
        t.udfs['Test int'] = 4

        t.save_with_user(self.user)
Esempio n. 7
0
 def make_tree(self, user=None):
     user = user or make_commander_user(self.instance)
     plot = Plot(geom=self.instance.center, instance=self.instance)
     plot.save_with_user(user)
     tree = Tree(instance=self.instance, plot=plot)
     tree.save_with_user(user)
     return tree
class UpdateTestCase(LocalMediaTestCase):
    def setUp(self):
        super(UpdateTestCase, self).setUp()
        self.image = self.load_resource('tree1.gif')
        self.test_start = timezone.now()
        self.point = Point(-8515941.0, 4953519.0)
        self.instance = make_instance(point=self.point)
        self.user = make_commander_user(self.instance)
        self.plot = Plot(geom=self.point, instance=self.instance)
        self.plot.save_with_user(self.user)

    def max_audit_for_model_type(self, models):
        if isinstance(models, basestring):
            models = [models]
        audits = Audit.objects.filter(model__in=models)\
                              .order_by('-created')

        if audits:
            return audits[0]

    def clear_updated_at(self):
        # to_timestamp(0) is the unix epoch 1970-1-1 00:00
        execute_sql(
            "UPDATE treemap_mapfeature SET updated_at = to_timestamp(0);")

    def clear_and_set_and_reload(self):
        self.clear_updated_at()
        set_map_feature_updated_at()
        self.plot.refresh_from_db()
class UpdateTestCase(LocalMediaTestCase):
    def setUp(self):
        super(UpdateTestCase, self).setUp()
        self.image = self.load_resource('tree1.gif')
        self.test_start = timezone.now()
        self.point = Point(-8515941.0, 4953519.0)
        self.instance = make_instance(point=self.point)
        self.user = make_commander_user(self.instance)
        self.plot = Plot(geom=self.point, instance=self.instance)
        self.plot.save_with_user(self.user)

    def max_audit_for_model_type(self, models):
        if isinstance(models, basestring):
            models = [models]
        audits = Audit.objects.filter(model__in=models)\
                              .order_by('-created')

        if audits:
            return audits[0]

    def clear_updated_at(self):
        # to_timestamp(0) is the unix epoch 1970-1-1 00:00
        execute_sql(
            "UPDATE treemap_mapfeature SET updated_at = to_timestamp(0);")

    def clear_and_set_and_reload(self):
        self.clear_updated_at()
        set_map_feature_updated_at()
        self.plot.refresh_from_db()
Esempio n. 10
0
    def test_treephoto_dict_to_model(self):
        plot = Plot(geom=self.instance.center, instance=self.instance)
        plot.save_with_user(self.commander)
        tree = Tree(plot=plot, instance=self.instance)
        tree.save_with_user(self.commander)

        ipath = self.resource_path('tree1.gif')

        tp_dict = json.loads(self.treephoto_blob % ipath)

        self.assertEqual(TreePhoto.objects.count(), 0)

        save_treephoto_blank = self.default_partial(save_treephoto, '')

        save_objects(MIGRATION_RULES, "treephoto", [tp_dict], {
            'tree': {
                1: tree.pk
            },
            'user': {
                1: self.commander.pk
            }
        }, save_treephoto_blank, self.instance)

        self.assertEqual(TreePhoto.objects.count(), 1)
        photo = TreePhoto.objects.all()[0]

        self.assertIsNotNone(photo.image)
        self.assertIsNotNone(photo.thumbnail)
Esempio n. 11
0
 def setUp(self):
     super(CommentTestMixin, self).setUp()
     self.instance = make_instance()
     self.user = make_commander_user(self.instance)
     self.admin = make_admin_user(self.instance)
     self.plot = Plot(geom=self.instance.center, instance=self.instance)
     self.plot.save_with_user(self.user)
Esempio n. 12
0
    def setUp(self):
        super(PlotDetailUITestCase, self).setUp()
        self.login_workflow()

        self.plot = Plot(instance=self.instance, geom=self.instance.center)
        self.plot.save_with_user(self.user)
        self.assertEqual(Plot.objects.count(), 1)
Esempio n. 13
0
    def test_tree_add_cancel(self):

        plot = Plot(instance=self.instance,
                    geom=Point(0, 0))

        plot.save_with_user(self.user)

        self._login_workflow()
        self._go_to_plot_detail_edit(plot.pk)

        add_tree_button = self.driver.find_element_by_id(
            'add-tree')
        add_tree_button.click()

        cancel_edit_button = self.driver.find_element_by_id(
            'cancel-edit-plot')
        cancel_edit_button.click()

        tree_details_div = self.driver.find_element_by_id(
            'tree-details')

        with self.assertRaises(ElementNotVisibleException):
            tree_details_div.click()

        self.assertFalse(Tree.objects.filter(plot=plot).exists())
Esempio n. 14
0
    def setUp(self):
        self.p = Point(-7615441.0, 5953519.0)

        self.instance = make_instance(point=self.p)
        self.user = make_commander_user(self.instance)

        self.plot = Plot(geom=self.instance.center, instance=self.instance)
Esempio n. 15
0
    def test_record_is_created_when_nullables_are_still_pending(self):
        new_plot = Plot(geom=self.p1, instance=self.instance)
        new_plot.save_with_user(self.pending_user)

        new_tree = Tree(plot=new_plot, instance=self.instance,
                        diameter=10, height=10, readonly=False)

        new_tree.save_with_user(self.pending_user)

        approve_or_reject_audits_and_apply(
            new_plot.audits(),
            self.commander_user, True)

        insert_audit = Audit.objects.filter(model='Tree')\
                                    .get(field='id')
        field_audits = Audit.objects.filter(model='Tree')\
                                    .filter(field__in=['readonly', 'diameter',
                                                       'plot'])
        for audit in field_audits:
            approve_or_reject_audit_and_apply(
                audit, self.commander_user, approved=True)

        approve_or_reject_audit_and_apply(insert_audit,
                                          self.commander_user, True)

        real_tree = Tree.objects.get(pk=new_tree.pk)

        self.assertEqual(real_tree.plot_id, new_plot.pk)
        self.assertEqual(real_tree.diameter, 10)
        self.assertEqual(real_tree.height, None)
        self.assertNotEqual(real_tree.readonly, True)
Esempio n. 16
0
 def setUp(self):
     self.instance = make_instance()
     self.user = make_commander_user(self.instance)
     self.plot = Plot(instance=self.instance, geom=Point(-7615441, 5953519))
     self.plot.save_with_user(self.user)
     self.tree = Tree(instance=self.instance, plot=self.plot)
     self.tree.save_with_user(self.user)
Esempio n. 17
0
    def _setup_tree_and_collection_udf(self):
        instance = make_instance()

        self.plotstew = make_collection_udf(instance,
                                            model='Plot',
                                            datatype=COLLECTION_UDF_DATATYPE)
        self.treestew = make_collection_udf(instance,
                                            model='Tree',
                                            datatype=COLLECTION_UDF_DATATYPE)

        commander = make_commander_user(instance)
        set_write_permissions(instance, commander, 'Plot', ['udf:Stewardship'])
        set_write_permissions(instance, commander, 'Tree', ['udf:Stewardship'])

        d1 = {'action': 'prune', 'date': "2014-05-3 00:00:00"}
        d2 = {'action': 'water', 'date': "2014-04-29 00:00:00"}

        p1 = Point(-7615441.0, 5953519.0)

        self.plot = Plot(instance=instance, geom=p1)
        self.plot.udfs[self.plotstew.name] = [d1]
        self.plot.save_with_user(commander)

        self.tree = Tree(instance=instance, plot=self.plot)
        self.tree.udfs[self.treestew.name] = [d2]
        self.tree.save_with_user(commander)
Esempio n. 18
0
    def test_record_is_created_when_nullables_are_still_pending(self):
        new_plot = Plot(geom=self.p1, instance=self.instance)
        new_plot.save_with_user(self.pending_user)

        new_tree = Tree(plot=new_plot, instance=self.instance,
                        diameter=10, height=10, readonly=False)

        new_tree.save_with_user(self.pending_user)

        approve_or_reject_audits_and_apply(
            new_plot.audits(),
            self.commander_user, True)

        insert_audit = Audit.objects.filter(model='Tree')\
                                    .get(field='id')
        field_audits = Audit.objects.filter(model='Tree')\
                                    .filter(field__in=['readonly', 'diameter',
                                                       'plot'])
        for audit in field_audits:
            approve_or_reject_audit_and_apply(
                audit, self.commander_user, approved=True)

        approve_or_reject_audit_and_apply(insert_audit,
                                          self.commander_user, True)

        real_tree = Tree.objects.get(pk=new_tree.pk)

        self.assertEqual(real_tree.plot_id, new_plot.pk)
        self.assertEqual(real_tree.diameter, 10)
        self.assertEqual(real_tree.height, None)
        self.assertNotEqual(real_tree.readonly, True)
Esempio n. 19
0
class WritableTest(PermissionsTestCase):
    def test_plot_is_writable_if_can_create_tree(self):
        self.commander_user = make_commander_user(self.instance)
        self.commander_role = \
            self.commander_user.get_instance_user(self.instance).role
        self.tree_only_user = make_user(self.instance)
        self.tree_only_role = self.instance.default_role

        content_type = ContentType.objects.get_for_model(Tree)
        add_tree_perm = Permission.objects.get(content_type=content_type,
                                               codename='add_tree')
        self.tree_only_role.instance_permissions.add(add_tree_perm)
        self.tree_only_role.save()

        self.p = Point(-8515941.0, 4953519.0)
        self.plot = Plot(instance=self.instance, width=12, geom=self.p)
        self.plot.save_with_user(self.commander_user)

        plot2 = Plot(instance=self.instance, width=12, geom=self.p)
        self.assertRaises(AuthorizeException,
                          plot2.save_with_user,
                          self.tree_only_user)

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

        self.assertTrue(self.tree.user_can_create(self.tree_only_user))

        # The plot should be writable if the user can create a tree
        self.assertTrue(perms.map_feature_is_writable(
            self.tree_only_role,
            self.plot))
Esempio n. 20
0
    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 + "}}")

        _TEMPLATES[0]['DIRS'] = [self.template_dir]
        with self.settings(TEMPLATES=_TEMPLATES):
            content = template.render(
                Context({
                    'request': {
                        'user': user,
                        'instance': self.instance
                    },
                    'plot': plot
                })).strip()
            self.assertEqual(content, value)
Esempio n. 21
0
    def handle(self, *args, **options):
        """ Create some seed data """
        instance, user = self.setup_env(*args, **options)

        species_qs = instance.scope_model(Species)

        n = options['n']
        self.stdout.write("Will create %s plots" % n)

        get_prob = lambda option: float(min(100, max(0, option))) / 100.0
        tree_prob = get_prob(options['ptree'])
        species_prob = get_prob(options['pspecies'])
        diameter_prob = get_prob(options['pdiameter'])
        max_radius = options['radius']

        center_x = instance.center.x
        center_y = instance.center.y

        import_event = ImportEvent(imported_by=user)
        import_event.save()

        ct = 0
        cp = 0
        for i in xrange(0, n):
            mktree = random.random() < tree_prob
            radius = random.gauss(0.0, max_radius)
            theta = random.random() * 2.0 * math.pi

            x = math.cos(theta) * radius + center_x
            y = math.sin(theta) * radius + center_y

            plot = Plot(instance=instance,
                        geom=Point(x, y),
                        import_event=import_event)

            plot.save_with_user(user)
            cp += 1

            if mktree:
                add_species = random.random() < species_prob
                if add_species:
                    species = random.choice(species_qs)
                else:
                    species = None

                add_diameter = random.random() < diameter_prob
                if add_diameter:
                    diameter = 2 + random.random() * 18
                else:
                    diameter = None

                tree = Tree(plot=plot,
                            import_event=import_event,
                            species=species,
                            diameter=diameter,
                            instance=instance)
                tree.save_with_user(user)
                ct += 1

        self.stdout.write("Created %s trees and %s plots" % (ct, cp))
Esempio n. 22
0
    def test_reject_insert_rejects_updates(self):
        new_plot = Plot(geom=self.p1, instance=self.instance)
        new_plot.save_with_user(self.pending_user)

        insert_audit = Audit.objects.filter(model='Plot')\
                                    .get(field='id')
        field_audits = Audit.objects.filter(model='Plot')\
                                    .exclude(field='id')

        for audit in field_audits:
            approve_or_reject_audit_and_apply(
                audit, self.commander_user, approved=True)

        approve_or_reject_audit_and_apply(insert_audit,
                                          self.commander_user, False)

        # need to refresh the field_audits collection from the db
        # because references are broken
        # why doesn't this work? why are there 5 values in field_audits_ids?
        # field_audit_ids = field_audits.values_list('id', flat=True)
        field_audit_ids = [field_audit.id for field_audit in field_audits]
        field_audits = Audit.objects.filter(pk__in=field_audit_ids)

        for field_audit in field_audits:
            attached_review_audit = Audit.objects.get(pk=field_audit.ref.pk)

            self.assertEqual(attached_review_audit.action,
                             Audit.Type.PendingReject)

            self.assertNotEqual(None,
                                Audit.objects.get(
                                    model=field_audit.model,
                                    field=field_audit.field,
                                    model_id=field_audit.model_id,
                                    action=Audit.Type.PendingApprove))
Esempio n. 23
0
    def setUp(self):
        super(PlotDeleteTest, self).setUp()
        self.login_workflow()

        self.plot = Plot(instance=self.instance, geom=Point(0, 0))
        self.plot.save_with_user(self.user)
        self.assertEqual(Plot.objects.count(), 1)
Esempio n. 24
0
class UserCanDeleteTestCase(OTMTestCase):
    def setUp(self):
        instance = make_instance()

        self.creator_user = make_officer_user(instance)
        self.admin_user = make_admin_user(instance)
        self.other_user = make_officer_user(instance, username='******')

        self.plot = Plot(geom=instance.center, instance=instance)
        self.plot.save_with_user(self.creator_user)

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

        self.rainBarrel = RainBarrel(geom=instance.center, instance=instance,
                                     capacity=5)
        self.rainBarrel.save_with_user(self.creator_user)

    def assert_can_delete(self, user, deletable, should_be_able_to_delete):
        can = deletable.user_can_delete(user)
        self.assertEqual(can, should_be_able_to_delete)

    def test_user_can_delete(self):
        self.assert_can_delete(self.creator_user, self.plot, True)
        self.assert_can_delete(self.admin_user, self.plot, True)
        self.assert_can_delete(self.other_user, self.plot, False)
        self.assert_can_delete(self.creator_user, self.rainBarrel, True)
        self.assert_can_delete(self.admin_user, self.rainBarrel, True)
        self.assert_can_delete(self.other_user, self.rainBarrel, False)
        self.assert_can_delete(self.creator_user, self.tree, True)
        self.assert_can_delete(self.admin_user, self.tree, True)
        self.assert_can_delete(self.other_user, self.tree, False)
Esempio n. 25
0
    def setUp(self):
        super(ExportTreeTaskTest, self).setUp()

        set_write_permissions(self.instance, self.user,
                              'Plot', ['udf:Test choice'])
        set_write_permissions(self.instance, self.user,
                              'Tree', ['udf:Test int'])

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

        UserDefinedFieldDefinition.objects.create(
            instance=self.instance,
            model_type='Tree',
            datatype=json.dumps({'type': 'int'}),
            iscollection=False,
            name='Test int')

        p = Plot(geom=self.instance.center, instance=self.instance,
                 address_street="123 Main Street")
        p.udfs['Test choice'] = 'a'

        p.save_with_user(self.user)

        t = Tree(plot=p, instance=self.instance, diameter=2)
        t.udfs['Test int'] = 4

        t.save_with_user(self.user)
Esempio n. 26
0
    def test_treephoto_hash_to_model(self):
        plot = Plot(geom=Point(0, 0), instance=self.instance)
        plot.save_with_user(self.commander)
        tree = Tree(plot=plot, instance=self.instance)
        tree.save_with_user(self.commander)

        ipath = self.resource_path('tree1.gif')

        tp_dict = json.loads(self.photo_blob % ipath)

        self.assertEqual(TreePhoto.objects.count(), 0)

        save_treephoto_blank = partial(save_treephoto, MIGRATION_RULES, '')

        hashes_to_saved_objects(
            MIGRATION_RULES,
            "treephoto", [tp_dict],
            {'tree': {1: tree.pk},
             'user': {1: self.commander.pk}},
            save_treephoto_blank,
            self.instance)

        self.assertEqual(TreePhoto.objects.count(), 1)
        photo = TreePhoto.objects.all()[0]

        self.assertIsNotNone(photo.image)
        self.assertIsNotNone(photo.thumbnail)
Esempio n. 27
0
    def test_boundary_search(self):
        # Unit Square
        b1 = Boundary.objects.create(
            geom=MultiPolygon(make_simple_polygon(0)),
            name='whatever',
            category='whatever',
            sort_order=1)

        # Unit Square translated by (0.2,0.2)
        b2 = Boundary.objects.create(
            geom=MultiPolygon(make_simple_polygon(0.2)),
            name='whatever',
            category='whatever',
            sort_order=1)

        # Unit square translated by (-1,-1)
        b3 = Boundary.objects.create(
            geom=MultiPolygon(make_simple_polygon(-1)),
            name='whatever',
            category='whatever',
            sort_order=1)

        plot1 = Plot(geom=Point(0.9, 0.9), instance=self.instance)
        plot2 = Plot(geom=Point(1.1, 1.1), instance=self.instance)
        plot3 = Plot(geom=Point(2.5, 2.5), instance=self.instance)

        for p in (plot1, plot2, plot3):
            p.save_with_user(self.commander)

        boundary1_filter = json.dumps({'plot.geom':
                                       {'IN_BOUNDARY': b1.pk}})

        plots = search.Filter(boundary1_filter, '', self.instance)\
                      .get_objects(Plot)

        self.assertEqual(
            {plot1.pk},
            {p.pk
             for p in plots})

        boundary2_filter = json.dumps({'plot.geom':
                                       {'IN_BOUNDARY': b2.pk}})

        plots = search.Filter(boundary2_filter, '', self.instance)\
                      .get_objects(Plot)

        self.assertEqual(
            {plot1.pk, plot2.pk},
            {p.pk
             for p in plots})

        boundary3_filter = json.dumps({'plot.geom':
                                       {'IN_BOUNDARY': b3.pk}})

        plots = search.Filter(boundary3_filter, '', self.instance)\
                      .get_objects(Plot)

        self.assertEqual(
            0, len(plots))
Esempio n. 28
0
    def commit_row(self):
        is_valid = self.validate_row()

        if not is_valid:
            return  # not ready to commit

        if self.status == TreeImportRow.SUCCESS:
            return  # nothing changed so no need to commit

        # Get our data
        data = self.cleaned

        self.convert_units(data, {
            fields.trees.PLOT_WIDTH:
            self.import_event.plot_width_conversion_factor,

            fields.trees.PLOT_LENGTH:
            self.import_event.plot_length_conversion_factor,

            fields.trees.DIAMETER:
            self.import_event.diameter_conversion_factor,

            fields.trees.TREE_HEIGHT:
            self.import_event.tree_height_conversion_factor,

            fields.trees.CANOPY_HEIGHT:
            self.import_event.canopy_height_conversion_factor
        })

        plot_id = data.get(self.model_fields.OPENTREEMAP_PLOT_ID, None)

        # Check for an existing plot, use it if we're not already:
        if plot_id and (self.plot is None or self.plot.pk != plot_id):
            plot = Plot.objects.get(pk=plot_id)
        elif self.plot is not None:
            plot = self.plot
        else:
            plot = Plot(instance=self.import_event.instance)

        self._commit_plot_data(data, plot)

        # TREE_PRESENT handling:
        #   If True, create a tree
        #   If False, don't create a tree
        #   If empty or missing, create a tree if a tree field is specified
        tree = plot.current_tree()
        tree_edited = False
        tree_present = data.get(self.model_fields.TREE_PRESENT, None)
        if tree_present:
            tree_edited = True
            if tree is None:
                tree = Tree(instance=plot.instance)

        if tree_present or tree_present is None:
            self._commit_tree_data(data, plot, tree, tree_edited)

        self.plot = plot
        self.status = TreeImportRow.SUCCESS
        self.save()
Esempio n. 29
0
    def setUp(self):
        super(ExportTreeTaskTest, self).setUp()

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

        t = Tree(plot=p, instance=self.instance, diameter=2)
        t.save_with_user(self.user)
Esempio n. 30
0
 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)
Esempio n. 31
0
    def setUp(self):
        super(UserRoleModelPermissionTest, self).setUp()

        self.plot = Plot(geom=self.p1, instance=self.instance)
        self.plot.save_with_user(self.direct_user)

        self.tree = Tree(plot=self.plot, instance=self.instance)
        self.tree.save_with_user(self.direct_user)
Esempio n. 32
0
 def setUp(self):
     self.point = Point(-8515941.0, 4953519.0)
     self.instance = make_instance(point=self.point)
     self.user = make_commander_user(self.instance)
     self.plot = Plot(geom=self.point, instance=self.instance)
     self.plot.save_with_user(self.user)
     self.plot = Plot.objects.get(pk=self.plot.pk)
     self.initial_updated = self.plot.updated_at
Esempio n. 33
0
class EcoTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

        self.instance, system_user = tm.make_instance_and_system_user()

        self.user = User(username="******")
        self.user.save_with_user(system_user)
        self.user.roles.add(tm.make_commander_role(self.instance))

        self.species = Species(symbol='CEDR',
                               genus='cedrus',
                               species='atlantica',
                               max_dbh=2000,
                               max_height=100)
        self.species.save()

        p1 = Point(-8515941.0, 4953519.0)
        self.plot = Plot(geom=p1,
                         instance=self.instance,
                         created_by=self.user)

        self.plot.save_with_user(self.user)

        self.tree = Tree(plot=self.plot,
                         instance=self.instance,
                         readonly=False,
                         species=self.species,
                         diameter=1630,
                         created_by=self.user)

        self.tree.save_with_user(self.user)

    def test_group_eco(self):
        pass  # TODO: Once filtering has been enabled

    def test_eco_benefit_sanity(self):
        req = self.factory.get('/%s/eco/benefit/tree/%s/' %
                              (self.instance.pk, self.tree.pk))

        response = tree_benefits(req,
                                 instance_id=self.instance.pk,
                                 tree_id=self.tree.pk,
                                 region='NoEastXXX')

        self.assertEqual(response.status_code, 200)
        rslt = json.loads(response.content)

        bens = rslt['benefits']

        def assertBValue(benefit, unit, value):
            self.assertEqual(bens[benefit]['unit'], unit)
            self.assertEqual(int(float(bens[benefit]['value'])), value)

        assertBValue('energy', 'kwh', 1896)
        assertBValue('airquality', 'lbs/year', 6)
        assertBValue('stormwater', 'gal', 3185)
        assertBValue('co2', 'lbs/year', 563)
Esempio n. 34
0
class UserCanDeleteTestCase(OTMTestCase):
    def setUp(self):
        instance = make_instance()
        # Fancy name, but no write, create, or delete permissions
        instance.default_role.name = Role.ADMINISTRATOR

        self.creator_user = make_officer_user(instance)
        self.admin_user = make_admin_user(instance)
        self.other_user = make_observer_user(instance, username='******')
        self.tweaker_user = make_tweaker_user(instance)
        self.conjurer_user = make_conjurer_user(instance)

        self.plot = Plot(geom=instance.center, instance=instance)
        self.plot.save_with_user(self.creator_user)

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

        self.rainBarrel = RainBarrel(geom=instance.center,
                                     instance=instance,
                                     capacity=5)
        self.rainBarrel.save_with_user(self.creator_user)

    def assert_can_delete(self, user, deletable, should_be_able_to_delete):
        can = deletable.user_can_delete(user)
        self.assertEqual(can, should_be_able_to_delete)

    def test_user_can_delete(self):
        self.assert_can_delete(self.conjurer_user, self.plot, True)
        self.assert_can_delete(self.conjurer_user, self.rainBarrel, True)
        self.assert_can_delete(self.conjurer_user, self.tree, True)

        self.assert_can_delete(self.creator_user, self.plot, True)
        self.assert_can_delete(self.creator_user, self.rainBarrel, True)
        self.assert_can_delete(self.creator_user, self.tree, True)

        self.assert_can_delete(self.admin_user, self.plot, True)
        self.assert_can_delete(self.admin_user, self.rainBarrel, True)
        self.assert_can_delete(self.admin_user, self.tree, True)

    def test_user_cannot_delete(self):
        self.assert_can_delete(self.tweaker_user, self.plot, False)
        self.assert_can_delete(self.tweaker_user, self.rainBarrel, False)
        self.assert_can_delete(self.tweaker_user, self.tree, False)

        self.assert_can_delete(self.other_user, self.plot, False)
        self.assert_can_delete(self.other_user, self.rainBarrel, False)
        self.assert_can_delete(self.other_user, self.tree, False)

    def test_admin_cannot_delete_by_flag(self):
        instance = self.tree.get_instance()
        role = self.admin_user.get_role(instance)
        role.instance_permissions.clear()

        self.assertTrue(self.admin_user.get_instance_user(instance).admin)
        self.assertEqual(role.instance_permissions.count(), 0)

        self.assert_can_delete(self.admin_user, self.tree, False)
 def setUp(self):
     super(UpdateTestCase, self).setUp()
     self.image = self.load_resource('tree1.gif')
     self.test_start = timezone.now()
     self.point = Point(-8515941.0, 4953519.0)
     self.instance = make_instance(point=self.point)
     self.user = make_commander_user(self.instance)
     self.plot = Plot(geom=self.point, instance=self.instance)
     self.plot.save_with_user(self.user)
Esempio n. 36
0
    def test_save_new_object_authorized(self):
        '''Save two new objects with authorized user, nothing should happen'''
        plot = Plot(geom=self.p1, instance=self.instance)

        plot.save_with_user(self.officer)

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

        tree.save_with_user(self.officer)
Esempio n. 37
0
        def create_and_save_with_choice(c, n=1):
            plots = []
            for i in xrange(n):
                plot = Plot(geom=self.p, instance=self.instance)
                plot.udfs['Test choice'] = c
                plot.save_with_user(self.commander_user)
                plots.append(plot)

            return {plot.pk for plot in plots}
Esempio n. 38
0
    def test_save_new_object_unauthorized(self):
        plot = Plot(geom=self.p1, instance=self.instance)

        self.assertRaises(AuthorizeException, plot.save_with_user, self.outlaw)

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

        self.assertRaises(AuthorizeException, tree.save_with_user, self.outlaw)
Esempio n. 39
0
    def test_save_new_object_authorized(self):
        '''Save two new objects with authorized user, nothing should happen'''
        plot = Plot(geom=self.p1, instance=self.instance)

        plot.save_with_user(self.officer)

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

        tree.save_with_user(self.officer)
Esempio n. 40
0
class UserCanDeleteTestCase(OTMTestCase):
    def setUp(self):
        instance = make_instance()
        # Fancy name, but no write, create, or delete permissions
        instance.default_role.name = Role.ADMINISTRATOR

        self.creator_user = make_officer_user(instance)
        self.admin_user = make_admin_user(instance)
        self.other_user = make_observer_user(instance, username='******')
        self.tweaker_user = make_tweaker_user(instance)
        self.conjurer_user = make_conjurer_user(instance)

        self.plot = Plot(geom=instance.center, instance=instance)
        self.plot.save_with_user(self.creator_user)

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

        self.rainBarrel = RainBarrel(geom=instance.center, instance=instance,
                                     capacity=5)
        self.rainBarrel.save_with_user(self.creator_user)

    def assert_can_delete(self, user, deletable, should_be_able_to_delete):
        can = deletable.user_can_delete(user)
        self.assertEqual(can, should_be_able_to_delete)

    def test_user_can_delete(self):
        self.assert_can_delete(self.conjurer_user, self.plot, True)
        self.assert_can_delete(self.conjurer_user, self.rainBarrel, True)
        self.assert_can_delete(self.conjurer_user, self.tree, True)

        self.assert_can_delete(self.creator_user, self.plot, True)
        self.assert_can_delete(self.creator_user, self.rainBarrel, True)
        self.assert_can_delete(self.creator_user, self.tree, True)

        self.assert_can_delete(self.admin_user, self.plot, True)
        self.assert_can_delete(self.admin_user, self.rainBarrel, True)
        self.assert_can_delete(self.admin_user, self.tree, True)

    def test_user_cannot_delete(self):
        self.assert_can_delete(self.tweaker_user, self.plot, False)
        self.assert_can_delete(self.tweaker_user, self.rainBarrel, False)
        self.assert_can_delete(self.tweaker_user, self.tree, False)

        self.assert_can_delete(self.other_user, self.plot, False)
        self.assert_can_delete(self.other_user, self.rainBarrel, False)
        self.assert_can_delete(self.other_user, self.tree, False)

    def test_admin_cannot_delete_by_flag(self):
        instance = self.tree.get_instance()
        role = self.admin_user.get_role(instance)
        role.instance_permissions.clear()

        self.assertTrue(self.admin_user.get_instance_user(instance).admin)
        self.assertEqual(role.instance_permissions.count(), 0)

        self.assert_can_delete(self.admin_user, self.tree, False)
Esempio n. 41
0
def mkPlot(u, geom=Point(50, 50)):
    p = Plot(geometry=geom,
             last_updated_by=u,
             import_event=ImportEvent.objects.all()[0],
             present=True,
             data_owner=u)
    p.save()

    return p
Esempio n. 42
0
class CommentTestMixin(object):
    # A mixin class for comment tests, sets up some non-comment related data
    def setUp(self):
        super(CommentTestMixin, self).setUp()
        self.instance = make_instance()
        self.user = make_commander_user(self.instance)
        self.admin = make_admin_user(self.instance)
        self.plot = Plot(geom=self.instance.center, instance=self.instance)
        self.plot.save_with_user(self.user)
Esempio n. 43
0
class CommentTestMixin(object):
    # A mixin class for comment tests, sets up some non-comment related data
    def setUp(self):
        super(CommentTestMixin, self).setUp()
        self.instance = make_instance()
        self.user = make_commander_user(self.instance)
        self.admin = make_admin_user(self.instance)
        self.plot = Plot(geom=self.instance.center, instance=self.instance)
        self.plot.save_with_user(self.user)
Esempio n. 44
0
        def create_and_save_with_choice(c, n=1):
            plots = []
            for i in xrange(n):
                plot = Plot(geom=self.p, instance=self.instance)
                plot.udfs['Test choice'] = c
                plot.save_with_user(self.commander_user)
                plots.append(plot)

            return {plot.pk for plot in plots}
Esempio n. 45
0
    def commit_row(self):
        is_valid = self.validate_row()

        if not is_valid:
            return  # not ready to commit

        if self.status == TreeImportRow.SUCCESS:
            return  # nothing changed so no need to commit

        # Get our data
        data = self.cleaned

        self.convert_units(
            data, {
                fields.trees.PLOT_WIDTH:
                self.import_event.plot_width_conversion_factor,
                fields.trees.PLOT_LENGTH:
                self.import_event.plot_length_conversion_factor,
                fields.trees.DIAMETER:
                self.import_event.diameter_conversion_factor,
                fields.trees.TREE_HEIGHT:
                self.import_event.tree_height_conversion_factor,
                fields.trees.CANOPY_HEIGHT:
                self.import_event.canopy_height_conversion_factor
            })

        plot_id = data.get(self.model_fields.OPENTREEMAP_PLOT_ID, None)

        # Check for an existing plot, use it if we're not already:
        if plot_id and (self.plot is None or self.plot.pk != plot_id):
            plot = Plot.objects.get(pk=plot_id)
        elif self.plot is not None:
            plot = self.plot
        else:
            plot = Plot(instance=self.import_event.instance)

        self._commit_plot_data(data, plot)

        # TREE_PRESENT handling:
        #   If True, create a tree
        #   If False, don't create a tree
        #   If empty or missing, create a tree if a tree field is specified
        tree = plot.current_tree()
        tree_edited = False
        tree_present = data.get(self.model_fields.TREE_PRESENT, None)
        if tree_present:
            tree_edited = True
            if tree is None:
                tree = Tree(instance=plot.instance)

        if tree_present or tree_present is None:
            self._commit_tree_data(data, plot, tree, tree_edited)

        self.plot = plot
        self.status = TreeImportRow.SUCCESS
        self.save()
Esempio n. 46
0
    def handle(self, *args, **options):
        """ Create some seed data """
        instance, user = self.setup_env(*args, **options)

        species_qs = instance.scope_model(Species)

        n = options['n']
        self.stdout.write("Will create %s plots" % n)

        get_prob = lambda option: float(min(100, max(0, option))) / 100.0
        tree_prob = get_prob(options['ptree'])
        species_prob = get_prob(options['pspecies'])
        diameter_prob = get_prob(options['pdiameter'])
        max_radius = options['radius']

        center_x = instance.center.x
        center_y = instance.center.y

        ct = 0
        cp = 0
        for i in xrange(0, n):
            mktree = random.random() < tree_prob
            radius = random.gauss(0.0, max_radius)
            theta = random.random() * 2.0 * math.pi

            x = math.cos(theta) * radius + center_x
            y = math.sin(theta) * radius + center_y

            plot = Plot(instance=instance,
                        geom=Point(x, y))

            plot.save_with_user(user)
            cp += 1

            if mktree:
                add_species = random.random() < species_prob
                if add_species:
                    species = random.choice(species_qs)
                else:
                    species = None

                add_diameter = random.random() < diameter_prob
                if add_diameter:
                    diameter = 2 + random.random() * 18
                else:
                    diameter = None

                tree = Tree(plot=plot,
                            species=species,
                            diameter=diameter,
                            instance=instance)
                tree.save_with_user(user)
                ct += 1

        instance.update_geo_rev()
        self.stdout.write("Created %s trees and %s plots" % (ct, cp))
Esempio n. 47
0
    def test_count_is_cached(self):
        count = get_cached_plot_count(self.filter)
        self.assertEqual(0, count)

        # We save with the old
        plot = Plot(geom=self.instance.center, instance=self.instance)
        plot.save_with_user(self.user)

        count = get_cached_plot_count(self.filter)
        self.assertEqual(0, count)
Esempio n. 48
0
    def test_updating_geo_rev_busts_count_cache(self):
        count = get_cached_plot_count(self.filter)
        self.assertEqual(0, count)

        plot = Plot(geom=self.instance.center, instance=self.instance)
        plot.save_with_user(self.user)
        self.filter.instance.update_geo_rev()

        count = get_cached_plot_count(self.filter)
        self.assertEqual(1, count)
Esempio n. 49
0
def mkPlot(instance, user, geom=None):
    if geom is None:
        geom = instance.center
    elif geom.srs.srid != 3857:
        geom.transform(3857)

    p = Plot(geom=geom, instance=instance)
    p.save_with_user(user)

    return p
Esempio n. 50
0
def mkPlot(instance, user, geom=None):
    if geom is None:
        geom = instance.center
    elif geom.srs.srid != 3857:
        geom.transform(3857)

    p = Plot(geom=geom, instance=instance)
    p.save_with_user(user)

    return p
Esempio n. 51
0
def mkPlot(u, geom=Point(50, 50)):
    p = Plot(
        geometry=geom,
        last_updated_by=u,
        import_event=ImportEvent.objects.all()[0],
        present=True,
        data_owner=u)
    p.save()

    return p
Esempio n. 52
0
    def setUp(self):
        self.p1 = Point(-7615441.0, 5953519.0)
        self.instance = make_instance(point=self.p1)
        self.commander_user = make_commander_user(self.instance)
        self.direct_user = make_officer_user(self.instance)
        self.pending_user = make_apprentice_user(self.instance)
        self.observer_user = make_observer_user(self.instance)

        self.plot = Plot(geom=self.p1, instance=self.instance, length=5.0)
        self.plot.save_with_user(self.commander_user)
Esempio n. 53
0
    def test_updating_geo_rev_busts_count_cache(self):
        count = get_cached_plot_count(self.filter)
        self.assertEqual(0, count)

        plot = Plot(geom=self.instance.center, instance=self.instance)
        plot.save_with_user(self.user)
        self.filter.instance.update_geo_rev()

        count = get_cached_plot_count(self.filter)
        self.assertEqual(1, count)
Esempio n. 54
0
    def test_count_is_cached(self):
        count = get_cached_plot_count(self.filter)
        self.assertEqual(0, count)

        # We save with the old
        plot = Plot(geom=self.instance.center, instance=self.instance)
        plot.save_with_user(self.user)

        count = get_cached_plot_count(self.filter)
        self.assertEqual(0, count)
Esempio n. 55
0
    def setUp(self):
        point = Point(-8515941.0, 4953519.0)
        instance = make_instance(point=point)
        user = make_commander_user(instance)
        plot = Plot(geom=point, instance=instance)
        plot.save_with_user(user)

        self.user = user
        self.instance = instance
        self.plot_obj = Plot.objects.get(instance=instance)
        self.map_feature_obj = MapFeature.objects.get(instance=instance)
 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)
Esempio n. 57
0
class MultiUserTestCase(OTMTestCase):
    def setUp(self):
        self.p1 = Point(-7615441.0, 5953519.0)
        self.instance = make_instance(point=self.p1)
        self.commander_user = make_commander_user(self.instance)
        self.direct_user = make_officer_user(self.instance)
        self.pending_user = make_apprentice_user(self.instance)
        self.observer_user = make_observer_user(self.instance)

        self.plot = Plot(geom=self.p1, instance=self.instance)
        self.plot.save_with_user(self.commander_user)
Esempio n. 58
0
    def test_save_new_object_unauthorized_tweaker(self):
        plot = Plot(geom=self.p1, instance=self.instance)

        self.assertRaises(AuthorizeException,
                          plot.save_with_user, self.tweaker_user)

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

        self.assertRaises(AuthorizeException,
                          tree.save_with_user, self.tweaker_user)
Esempio n. 59
0
    def test_allows_cudf(self):
        plot, tree = self.create_tree_and_plot()
        empty_plot = Plot(geom=self.p1, instance=self.instance)
        empty_plot.save_with_user(self.commander)

        plots = search.Filter('', '["Plot"]', self.instance)\
                      .get_objects(Plot)

        ids = {p.pk for p in plots}

        self.assertEqual(ids, {plot.pk, empty_plot.pk})
Esempio n. 60
0
    def test_plot_with_tree_always_shows_tree_details(self):
        plot = Plot(instance=self.instance, geom=self.instance.center)
        plot.save_with_user(self.user)
        tree = Tree(plot=plot, diameter=10, instance=self.instance)
        tree.save_with_user(self.user)

        self.login_workflow()
        self.go_to_feature_detail(plot.pk)
        self._select_elements()
        self.edit_plot.click()
        self.cancel_edit.click()
        self.assertElementVisibility(self.tree_details_section, visible=True)