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))
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)
def test_plot_history_shows_all_trees(self): p = Plot(instance=self.instance, geom=self.p) p.save_with_user(self.user) self.assertEqual(len(p.get_tree_history()), 0) t = Tree(plot=p, instance=self.instance) t.save_with_user(self.user) tpk = t.pk self.assertEqual(list(p.get_tree_history()), [tpk]) t.delete_with_user(self.user) self.assertEqual(list(p.get_tree_history()), [tpk]) t2 = Tree(plot=p, instance=self.instance) t2.save_with_user(self.user) self.assertEqual(list(p.get_tree_history()), [t2.pk, tpk]) t3 = Tree(plot=p, instance=self.instance) t3.save_with_user(self.user) self.assertEqual(list(p.get_tree_history()), [t3.pk, t2.pk, tpk])
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))
def test_within_radius_integration(self): test_point = Point(-7615443.0, 5953520.0) near_point = Point(-7615444.0, 5953521.0) far_point = Point(-9615444.0, 8953521.0) near_plot = Plot(geom=near_point, instance=self.instance) near_plot.save_with_user(self.commander) near_tree = Tree(plot=near_plot, instance=self.instance) near_tree.save_with_user(self.commander) # just to make sure that the geospatial # query actually filters by distance far_plot = Plot(geom=far_point, instance=self.instance) far_plot.save_with_user(self.commander) far_tree = Tree(plot=far_plot, instance=self.instance) far_tree.save_with_user(self.commander) radius_filter = json.dumps( {'plot.geom': { 'WITHIN_RADIUS': { 'POINT': {'x': test_point.x, 'y': test_point.y}, 'RADIUS': 10 } }}) ids = {p.pk for p in _execute_filter( self.instance, radius_filter)} self.assertEqual(ids, {near_plot.pk})
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)
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))
def test_within_radius_integration(self): test_point = Point(0, 0) near_point = Point(1, 1) far_point = Point(250, 250) near_plot = Plot(geom=near_point, instance=self.instance) near_plot.save_with_user(self.commander) near_tree = Tree(plot=near_plot, instance=self.instance) near_tree.save_with_user(self.commander) # just to make sure that the geospatial # query actually filters by distance far_plot = Plot(geom=far_point, instance=self.instance) far_plot.save_with_user(self.commander) far_tree = Tree(plot=far_plot, instance=self.instance) far_tree.save_with_user(self.commander) radius_filter = json.dumps( {'plot.geom': { 'WITHIN_RADIUS': { 'POINT': {'x': test_point.x, 'y': test_point.y}, 'RADIUS': 10 } }}) plots = search.Filter(radius_filter, '', self.instance)\ .get_objects(Plot) ids = {p.pk for p in plots} self.assertEqual(ids, {near_plot.pk})
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)
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)
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()
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)
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())
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
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)
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)
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)
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)
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)
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)
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}
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
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)
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)
class UserExportsTestCase(OTMTestCase): def assertUserJSON(self, data, expectations): for key, expectation in expectations.items(): value = data[key] self.assertEqual( expectation, value, "failure for key '%s': expected '%s', found '%s'" % (key, expectation, value)) def setUp(self): self.instance = make_instance() self.commander = make_commander_user(self.instance, "comm") # Note unicode '⅀' is on purpose self.user1 = User(username='******', password='******', email='*****@*****.**', organization='karhide', first_name='therem', last_name='⅀straven') self.user1.save_with_user(self.commander) self.user2 = User(username='******', password='******', email='*****@*****.**', first_name='genly', last_name='ai', allow_email_contact=True) self.user2.save_with_user(self.commander) self.user3 = User(username='******', password='******', email='*****@*****.**') self.user3.save_with_user(self.commander) role = make_commander_role(self.instance) iuser1 = InstanceUser(instance=self.instance, user=self.user1, role=role) iuser1.save_with_user(self.user1) iuser2 = InstanceUser(instance=self.instance, user=self.user2, role=role) iuser2.save_with_user(self.user2) self.plot = Plot(geom=self.instance.center, readonly=False, instance=self.instance, width=4) self.plot.save_with_user(self.user1) self.tree = Tree(instance=self.instance, plot=self.plot, diameter=3) self.tree.save_with_user(self.user2)
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)
def test_plot_filter(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})
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 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})
def test_user_can_create_tree_photo(self): self._add_builtin_permission(self.role_yes, TreePhoto, 'add_treephoto') commander = make_commander_user(self.instance) plot = Plot(instance=self.instance, geom=self.p) plot.save_with_user(commander) tree = Tree(plot=plot, instance=self.instance) tree.save_with_user(commander) user_yes = make_user(instance=self.instance, make_role=lambda inst: self.role_yes) photo = TreePhoto(instance=self.instance, map_feature=plot, tree=tree) photo.set_image(self.load_resource('tree1.gif')) self.assertTrue(photo.user_can_create(user_yes))
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)
def test_basic_audit(self): p = Point(-8515222.0, 4953200.0) plot = Plot(geom=p, instance=self.instance) plot.save_with_user(self.user1) self.assertAuditsEqual([ self.make_audit(plot.pk, 'id', None, str(plot.pk), model='Plot'), self.make_audit(plot.pk, 'readonly', None, 'False', model='Plot'), self.make_audit( plot.pk, 'geom', None, str(plot.geom), model='Plot') ], plot.audits()) t = Tree(plot=plot, instance=self.instance, readonly=True) t.save_with_user(self.user1) expected_audits = [ self.make_audit(t.pk, 'id', None, str(t.pk)), self.make_audit(t.pk, 'readonly', None, True), self.make_audit(t.pk, 'plot', None, plot.pk) ] self.assertAuditsEqual(expected_audits, t.audits()) t.readonly = False t.save_with_user(self.user2) expected_audits.insert( 0, self.make_audit(t.pk, 'readonly', 'True', 'False', action=Audit.Type.Update, user=self.user2)) self.assertAuditsEqual(expected_audits, t.audits()) old_pk = t.pk t.delete_with_user(self.user1) expected_audits.insert( 0, self.make_audit(old_pk, None, None, None, action=Audit.Type.Delete, user=self.user1)) self.assertAuditsEqual( expected_audits, Audit.audits_for_model('Tree', self.instance, old_pk))
class SaveWithoutVerifyingTest(MultiUserTestCase): def setUp(self): super(SaveWithoutVerifyingTest, self).setUp() self.plot = Plot(geom=self.p1, instance=self.instance) self.plot.save_with_user(self.direct_user) def tests_works_when_normal_save_fails(self): self.plot = self.plot self.plot.width = 444 with self.assertRaises(AuthorizeException): self.plot.save_with_user(User.system_user()) self.plot.save_with_system_user_bypass_auth()
def test_user_cannot_delete_tree_photo(self): commander = make_commander_user(self.instance) plot = Plot(instance=self.instance, geom=self.p) plot.save_with_user(commander) tree = Tree(plot=plot, instance=self.instance) tree.save_with_user(commander) image = self.load_resource('tree1.gif') photo = tree.add_photo(image, commander) user_no = make_user(instance=self.instance, make_role=lambda inst: self.role_no) self.assertFalse(photo.user_can_delete(user_no))
class AuditDetailTagTest(OTMTestCase): def setUp(self): self.p1 = Point(-8515222.0, 4953200.0) self.instance = make_instance(point=self.p1) self.user = make_commander_user(self.instance) self.plot = Plot(geom=self.p1, instance=self.instance) self.plot.save_with_user(self.user) self.tree = Tree(plot=self.plot, instance=self.instance, readonly=False) self.tree.save_with_user(self.user) def test_tree_link(self): audit = self.tree.audits()[0] link = audit_detail_link(audit) target = reverse('tree_detail', kwargs={ 'instance_url_name': self.instance.url_name, 'feature_id': self.tree.plot.pk, 'tree_id': self.tree.pk }) self.assertEqual(link, target) def test_plot_link(self): audit = self.plot.audits()[0] link = audit_detail_link(audit) target = reverse('map_feature_detail', kwargs={ 'instance_url_name': self.instance.url_name, 'feature_id': self.plot.pk }) self.assertEqual(link, target) def test_bad_model_returns_none(self): audit = self.plot.audits()[0] audit.model = 'invaild' self.assertIsNone(audit_detail_link(audit)) def test_bad_id_returns_none(self): audit = self.plot.audits()[0] audit.model_id = -1000 self.assertIsNone(audit_detail_link(audit))
def test_pending_udf_audits(self): UserDefinedFieldDefinition.objects.create( instance=self.instance, model_type='Plot', datatype=json.dumps({'type': 'choice', 'choices': ['1', '2', '3']}), iscollection=False, name='times climbed') set_write_permissions(self.instance, self.commander_user, 'Plot', ['udf:times climbed']) FieldPermission.objects.create( model_name='Plot', field_name='udf:times climbed', permission_level=FieldPermission.WRITE_WITH_AUDIT, role=self.pending_user.get_instance_user(self.instance).role, instance=self.instance) initial_plot = Plot(geom=self.p1, instance=self.instance) initial_plot.udfs['times climbed'] = '2' initial_plot.save_with_user(self.pending_user) udf_audit = Audit.objects.get(model='Plot', field='udf:times climbed', model_id=initial_plot.pk) approve_or_reject_audit_and_apply(udf_audit, self.commander_user, approved=True) geom_audit = Audit.objects.get(model='Plot', field='geom', model_id=initial_plot.pk) approve_or_reject_audit_and_apply(geom_audit, self.commander_user, approved=True) readonly_audit = Audit.objects.get(model='Plot', field='readonly', model_id=initial_plot.pk) approve_or_reject_audit_and_apply(readonly_audit, self.commander_user, approved=True) insert_audit = Audit.objects.get(model='Plot', field='id', model_id=initial_plot.pk) approve_or_reject_audit_and_apply(insert_audit, self.commander_user, approved=True) new_plot = Plot.objects.get(pk=initial_plot.pk) self.assertEqual(new_plot.pk, initial_plot.pk) self.assertEqual(new_plot.readonly, False) self.assertEqual(new_plot.geom, self.p1) self.assertEqual(new_plot.udfs['times climbed'], '2')
def test_user_can_delete_tree_photo(self): commander = make_commander_user(self.instance) plot = Plot(instance=self.instance, geom=self.p) plot.save_with_user(commander) tree = Tree(plot=plot, instance=self.instance) tree.save_with_user(commander) image = self.load_resource('tree1.gif') photo = tree.add_photo(image, commander) self._add_builtin_permission(self.role_yes, TreePhoto, 'delete_treephoto') user_yes = make_user(instance=self.instance, make_role=lambda inst: self.role_yes) self.assertTrue(photo.user_can_delete(user_yes))
class UserExportsTestCase(TestCase): def setUp(self): self.instance = make_instance() self.commander = make_commander_user(self.instance, "comm") # Note unicode '⅀' is on purpose self.user1 = User(username='******', password='******', email='*****@*****.**', organization='org111', first_name='therem', last_name='⅀straven') self.user1.save_with_user(self.commander) self.user2 = User(username='******', password='******', email='*****@*****.**', first_name='genly', last_name='ai', allow_email_contact=True) self.user2.save_with_user(self.commander) self.user3 = User(username='******', password='******', email='*****@*****.**') self.user3.save_with_user(self.commander) role = make_commander_role(self.instance) iuser1 = InstanceUser(instance=self.instance, user=self.user1, role=role) iuser1.save_with_user(self.user1) iuser2 = InstanceUser(instance=self.instance, user=self.user2, role=role) iuser2.save_with_user(self.user2) pt = Point(0, 0) self.plot = Plot(geom=pt, readonly=False, instance=self.instance, width=4) self.plot.save_with_user(self.user1) self.tree = Tree(instance=self.instance, plot=self.plot, diameter=3) self.tree.save_with_user(self.user2)
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_feature_detail(plot.pk, edit=True) self.click('#add-tree') self.click('#cancel-edit-plot') self.wait_until_visible('#edit-plot') with self.assertRaises(ElementNotVisibleException): self.click('#tree-details') self.assertFalse(Tree.objects.filter(plot=plot).exists())
def create_tree_and_plot(self, plotudfs=None, treeudfs=None): plot = Plot(geom=self.p1, instance=self.instance) if plotudfs: for k, v in plotudfs.iteritems(): plot.udfs[k] = v plot.save_with_user(self.commander) tree = Tree(plot=plot, instance=self.instance) if treeudfs: for k, v in treeudfs.iteritems(): tree.udfs[k] = v tree.save_with_user(self.commander) return plot, tree
def test_insert_writes_when_approved(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) new_tree.save_with_user(self.pending_user) self.assertEquals(Plot.objects.count(), 0) self.assertEquals(Tree.objects.count(), 0) approve_or_reject_audits_and_apply( list(new_tree.audits()) + list(new_plot.audits()), self.commander_user, True) self.assertEqual(Plot.objects.all().count(), 1) self.assertEqual(Tree.objects.all().count(), 1)
def _create_tree_and_plot(instance, user, point, plotudfs=None, treeudfs=None): plot = Plot(geom=point, instance=instance) if plotudfs: for k, v in plotudfs.iteritems(): plot.udfs[k] = v plot.save_with_user(user) tree = Tree(plot=plot, instance=instance) if treeudfs: for k, v in treeudfs.iteritems(): tree.udfs[k] = v tree.save_with_user(user) return plot, tree
def test_can_create_obj_even_if_some_fields_are_pending(self): # Give pending user permissions on all of the required # fields for a plot role = self.pending_user.get_instance_user(self.instance).role role.fieldpermission_set\ .filter(field_name__in=['id', 'geom', 'readonly'])\ .update(permission_level=FieldPermission.WRITE_DIRECTLY) self.assertEquals(Plot.objects.count(), 0) # new_plot should be created, but there should be # a pending record for length (and it should not be # applied) new_plot = Plot(geom=self.p1, instance=self.instance, length=4) new_plot.save_with_user(self.pending_user) self.assertEquals(Plot.objects.count(), 1)
def test_all_ecobenefits(self): p = self._center_as_3857() plot = Plot(geom=p, instance=self.instance) plot.save_with_user(self.user) tree = Tree(plot=plot, instance=self.instance, readonly=False, species=self.species, diameter=1630) tree.save_with_user(self.user) p.x += 1.1 p.y += 1.1 box = self._box_around_point(p) bioswale = Bioswale(instance=self.instance, geom=p, polygon=box, feature_type='Bioswale', drainage_area=100.0) bioswale.save_with_user(self.user) filter = Filter('', '', self.instance) benefits, basis = get_benefits_for_filter(filter) self.assertIn('plot', benefits) plot_benefits = benefits['plot'] plot_categories = set(plot_benefits.keys()) self.assertSetEqual(plot_categories, set(BenefitCategory.GROUPS)) plot_currencies = { cat: benefit.get('currency', None) for cat, benefit in plot_benefits.items() } self.assertIsNotNone(min(plot_currencies.values())) expected_total_currency = sum( [benefit['currency'] for benefit in plot_benefits.values()]) - \ plot_benefits[BenefitCategory.CO2STORAGE]['currency'] + \ benefits['resource'][BenefitCategory.STORMWATER]['currency'] formatted = format_benefits(self.instance, benefits, basis, digits=0) self.assertAlmostEqual(formatted['benefits_total_currency'], expected_total_currency, 3)
def test_tree_add_cancel(self): """ This is an old test, written around #943 on github. It has since been more or less duplicated in add.py, but remains around for diagnostics. """ plot = Plot(instance=self.instance, geom=self.instance.center) plot.save_with_user(self.user) self.login_workflow() self.go_to_feature_detail(plot.pk, edit=True) self._select_elements() self.begin_add_tree.click() self.cancel_edit.click() self.wait_until_visible(self.edit_plot) self.assertElementVisibility(self.tree_details_section, False) self.assertFalse(Tree.objects.filter(plot=plot).exists())
def test_search_suffixes(self): plot1 = Plot(geom=self.p, instance=self.instance) plot1.udfs['Test string'] = 'this is a test' plot1.save_with_user(self.commander_user) plot2 = Plot(geom=self.p, instance=self.instance) plot2.udfs['Test string'] = 'this is aLsO' plot2.save_with_user(self.commander_user) def run(sfx, val): return { plot.pk for plot in Plot.objects.filter( **{'udf:Test string' + sfx: val}) } self.assertEqual(set(), run('', 'also')) self.assertEqual({plot1.pk, plot2.pk}, run('__contains', 'this is a')) self.assertEqual({plot2.pk}, run('__icontains', 'this is al'))
class UpdatedAtTest(OTMTestCase): 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 def test_update_sets_updated(self): self.plot.width = 22 self.plot.save_with_user(self.user) self.assertGreater(self.plot.updated_at, self.initial_updated) def test_add_tree_sets_updated(self): tree = Tree(diameter=10, plot=self.plot, instance=self.instance) tree.save_with_user(self.user) self.assertGreater(self.plot.updated_at, self.initial_updated) def test_update_tree_sets_updated(self): tree = Tree(diameter=10, plot=self.plot, instance=self.instance) tree.save_with_user(self.user) self.plot = Plot.objects.get(pk=self.plot.pk) self.inital_updated = self.plot.updated_at tree.height = 22 tree.save_with_user(self.user) self.assertGreater(self.plot.updated_at, self.initial_updated) def test_delete_tree_sets_updated(self): tree = Tree(diameter=10, plot=self.plot, instance=self.instance) tree.save_with_user(self.user) self.plot = Plot.objects.get(pk=self.plot.pk) self.inital_updated = self.plot.updated_at tree.delete_with_user(self.user) self.assertGreater(self.plot.updated_at, self.initial_updated)
class EcoRevIncr(OTMTestCase): def setUp(self): self.instance = make_instance() self.user = make_commander_user(self.instance) self.plot = Plot(geom=Point(0, 0), instance=self.instance) self.plot.save_with_user(self.user) def _get_eco_rev(self): i = Instance.objects.get(pk=self.instance.pk) return i.eco_rev @contextmanager def _assert_updates_eco_rev(self, update_expected=True): rev1 = self._get_eco_rev() yield rev2 = self._get_eco_rev() if update_expected: self.assertEqual(rev1 + 1, rev2) else: self.assertEqual(rev1, rev2) def test_update_diameter(self): with self._assert_updates_eco_rev(True): tree = Tree(instance=self.instance, plot=self.plot, diameter=3) tree.save_with_user(self.user) request_dict = {'tree.diameter': '5'} update_map_feature(request_dict, self.user, self.plot) def test_update_species(self): with self._assert_updates_eco_rev(True): tree = Tree(instance=self.instance, plot=self.plot) tree.save_with_user(self.user) species = Species(common_name='foo', instance=self.instance) species.save_with_user(self.user) request_dict = {'tree.species': species.pk} update_map_feature(request_dict, self.user, self.plot)
class PlotDetailUITestCase(TreemapUITestCase): 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) def _select_elements(self): self.delete_begin = self.find_id('delete-plot-or-tree') self.delete_confirm = self.find_id('delete-confirm') self.delete_cancel = self.find_id('delete-cancel') self.begin_add_tree = self.find_id('begin-add-tree') self.diameter_input = self.find('input[data-class="diameter-input"]') self.save_edit = self.find_id('save-edit-plot') self.cancel_edit = self.find_id('cancel-edit-plot') self.edit_plot = self.find_id('edit-plot') self.tree_details_section = self.find_id('tree-details') def _assert_plot_and_tree_counts(self, nplots, ntrees): self.assertEqual(Plot.objects.count(), nplots) self.assertEqual(Tree.objects.count(), ntrees)
def test_tree_dict_to_model(self): test_plot = Plot(geom=self.instance.center, instance=self.instance) test_plot.id = 95 test_plot.save_with_user(self.commander) test_species = Species(instance=self.instance, otm_code="1", common_name="asdfa", genus="sdfs") test_species.id = 85 test_species.save_with_user(self.commander) tree_dict = json.loads(self.tree_blob) tree = dict_to_model(MIGRATION_RULES, 'tree', tree_dict, self.instance) tree.save_with_user(self.commander) tree = Tree.objects.get(pk=tree.pk) self.assertEqual(tree.plot, test_plot) self.assertEqual(tree.species, test_species) self.assertEqual(tree.readonly, True) self.assertEqual(tree.diameter, 0.2900001566) self.assertEqual(tree.canopy_height, None) self.assertEqual(tree.date_planted, None) self.assertEqual(tree.date_removed, None)
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=Point(0, 0), 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)
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))
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)
class ConvertibleTest(OTMTestCase): 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) def test_save_converts_width_when_units_differ(self): set_attr_on_json_field(self.instance, 'config.value_display.plot.width.units', 'in') self.plot.convert_to_display_units() self.plot.width = 12 self.plot.convert_to_database_units() self.plot.save_with_user(self.user) updated_plot = Plot.objects.get(pk=self.plot.pk) self.assertAlmostEqual(1, updated_plot.width) def test_save_converts_diameter_when_units_differ(self): set_attr_on_json_field(self.instance, 'config.value_display.tree.diameter.units', 'ft') self.tree.convert_to_display_units() self.tree.diameter = 1 self.tree.convert_to_database_units() self.tree.save_with_user(self.user) updated_tree = Tree.objects.get(pk=self.tree.pk) self.assertAlmostEqual(12, updated_tree.diameter) def test_save_does_not_convert_width_when_units_same(self): set_attr_on_json_field(self.instance, 'config.value_display.plot.width.units', 'ft') self.plot.width = 12 self.plot.save_with_user(self.user) updated_plot = Plot.objects.get(pk=self.plot.pk) self.assertEqual(12, updated_plot.width) def test_save_does_not_convert_diameter_when_units_same(self): set_attr_on_json_field(self.instance, 'config.value_display.tree.diameter.units', 'in') self.tree.diameter = 1 self.tree.save_with_user(self.user) updated_tree = Tree.objects.get(pk=self.tree.pk) self.assertEqual(1, updated_tree.diameter)
class GeoRevIncr(OTMTestCase): def setUp(self): self.instance = make_instance() self.user = make_commander_user(self.instance) self.plot = Plot(geom=Point(0, 0), instance=self.instance) self.plot.save_with_user(self.user) def _hash_and_rev(self): i = Instance.objects.get(pk=self.instance.pk) return [i.geo_rev_hash, i.geo_rev] @contextmanager def _assert_updates_geo_rev(self, update_expected=True): rev1h, rev1 = self._hash_and_rev() yield rev2h, rev2 = self._hash_and_rev() if update_expected: self.assertNotEqual(rev1h, rev2h) self.assertEqual(rev1 + 1, rev2) else: self.assertEqual(rev1h, rev2h) self.assertEqual(rev1, rev2) def test_create(self): with self._assert_updates_geo_rev(): plot = Plot(instance=self.instance) request_dict = {'plot.geom': {'x': 0, 'y': 0}} update_map_feature(request_dict, self.user, plot) plot.save_with_user(self.user) def test_move(self): with self._assert_updates_geo_rev(): request_dict = {'plot.geom': {'x': 5, 'y': 5}} update_map_feature(request_dict, self.user, self.plot) self.plot.save_with_user(self.user) def test_update_without_move(self): with self._assert_updates_geo_rev(False): request_dict = {'plot.address_zip': '19119'} update_map_feature(request_dict, self.user, self.plot) self.plot.save_with_user(self.user) def test_delete(self): with self._assert_updates_geo_rev(): self.plot.delete_with_user(self.user)