def test_annual_rainfall_config_validation(self): request_key = 'instance.config.annual_rainfall_inches' updates = {request_key: 'x'} json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) with self.assertRaises(ValidationError): green_infrastructure(request, self.instance) updates[request_key] = '-10' json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) with self.assertRaises(ValidationError): green_infrastructure(request, self.instance) updates[request_key] = '10' json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) green_infrastructure(request, self.instance) self.assertEqual(self.instance.annual_rainfall_inches, 10.0)
def test_user_roles_updated(self): iuser = InstanceUser(user=self.user2, instance=self.instance, role=self.instance.default_role) iuser.save_with_user(self.commander) new_role = Role(name='Ambassador', instance=self.instance, rep_thresh=0) new_role.save() body = {'users': {iuser.pk: {'role': new_role.pk, 'admin': False}}} update_user_roles( make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance) #requery iuser iuser = InstanceUser.objects.get(pk=iuser.pk) self.assertEqual(iuser.role, new_role) self.assertEqual(iuser.admin, False) body = {'users': {iuser.pk: {'role': new_role.pk, 'admin': True}}} update_user_roles( make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance) #requery iuser iuser = InstanceUser.objects.get(pk=iuser.pk) self.assertEqual(iuser.role, new_role) self.assertEqual(iuser.admin, True)
def test_can_change_admin_without_feature(self): iuser = InstanceUser(user=self.user2, instance=self.instance, role=self.instance.default_role) iuser.save_with_user(self.commander) body = {'users': {iuser.pk: {'admin': False}}} update_user_roles( make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance) #requery iuser iuser = InstanceUser.objects.get(pk=iuser.pk) self.assertEqual(iuser.admin, False) body = {'users': {iuser.pk: {'admin': True}}} update_user_roles( make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance) #requery iuser iuser = InstanceUser.objects.get(pk=iuser.pk) self.assertEqual(iuser.admin, True)
def test_annual_rainfall_unit_conversion(self): rainfall_unit_key, rainfall_unit = get_value_display_attr( self.instance, 'greenInfrastructure', 'rainfall', 'units') self.assertEqual(rainfall_unit, 'in') __, __, unit_key = dotted_split(rainfall_unit_key, 3, maxsplit=2) self.assertEqual(rainfall_unit, 'in') config_key = 'annual_rainfall_inches' request_key = 'instance.config.annual_rainfall_inches' updates = {request_key: 10} json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) green_infrastructure(request, self.instance) self.assertEqual(self.instance.config[config_key], 10.0) self.instance.config[unit_key] = 'cm' config_key = 'annual_rainfall_inches' request_key = 'instance.config.{}'.format(config_key) updates = {request_key: 25.4} json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) green_infrastructure(request, self.instance) self.assertEqual(self.instance.config[config_key], 10.0)
def test_delete_udf_deletes_perms(self): body = { 'udf.name': 'cool udf', 'udf.model': 'Plot', 'udf.type': 'string' } qs = FieldPermission.objects.filter(field_name='udf:cool udf', model_name='Plot') resp = _do_create_udf_request(body, self.instance) self.assertTrue(qs.exists()) resp = udf_delete(make_request(), self.instance, resp['udf'].pk) self.assertFalse(qs.exists()) body = { 'udf.name': 'cool udf', 'udf.model': 'Plot', 'udf.type': 'choice', 'udf.choices': ['a', 'b', 'c'] } resp = _do_create_udf_request(body, self.instance) self.assertTrue(qs.exists()) resp = udf_delete(make_request(), self.instance, resp['udf'].pk) self.assertFalse(qs.exists())
def test_email_not_found_creates_invite(self): self.assertEqual(InstanceInvitation.objects.count(), 0) mail.outbox = [] email = '*****@*****.**' body = {'email': email} create_user_role( make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance) self.assertEqual(InstanceInvitation.objects.count(), 1) ii = InstanceInvitation.objects.all()[0] # Should have email and default role self.assertEqual(ii.email, email) self.assertEqual(ii.instance, self.instance) self.assertEqual(ii.role, self.instance.default_role) # Should have sent an email to the user self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] # Just make sure we have some chars and the # correct receiver self.assertGreater(len(msg.subject), 10) self.assertGreater(len(msg.body), 10) self.assertEquals(tuple(msg.to), (email, ))
def test_error_on_negative(self): updates = { 'benefitCurrencyConversion.currency_symbol': '$', 'benefitCurrencyConversion.electricity_kwh_to_currency': '1.0', 'benefitCurrencyConversion.natural_gas_kbtu_to_currency': '2.0', 'benefitCurrencyConversion.h20_gal_to_currency': '3.0', 'benefitCurrencyConversion.co2_lb_to_currency': '-4.0', 'benefitCurrencyConversion.o3_lb_to_currency': '5.0', 'benefitCurrencyConversion.nox_lb_to_currency': '6.0', 'benefitCurrencyConversion.pm10_lb_to_currency': '7.0', 'benefitCurrencyConversion.sox_lb_to_currency': '8.0', 'benefitCurrencyConversion.voc_lb_to_currency': '9.0', } json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) with self.assertRaises(ValidationError): update_benefits(request, self.instance) updated_instance = Instance.objects.get(pk=self.instance.pk) self.assertEqual(updated_instance.eco_benefits_conversion, self.conversions)
def test_export_view_permission_failure(self): request = make_request(user=self.unprivileged_user) begin_ctx = begin_export(request, self.instance, 'tree') check_ctx = check_export(request, self.instance, begin_ctx['job_id']) self.assertEqual(check_ctx['status'], 'MODEL_PERMISSION_ERROR') self.assertEqual(check_ctx['message'], 'User has no permissions on this model')
def test_export_users_json(self): resp = users_json(make_request(), self.instance) data = json.loads(resp.content) commander, user1data, user2data = data self.assertEquals(commander['username'], self.commander.username) self.assertEquals(user1data['username'], self.user1.username) self.assertEquals(user1data.get('email'), None) self.assertEquals(user1data['email_hash'], self.user1.email_hash) self.assertEquals(user1data['first_name'], self.user1.first_name) self.assertEquals(user1data['last_name'], self.user1.last_name) self.assertEquals(user1data['organization'], self.user1.organization) self.assertEquals(user1data['allow_email_contact'], 'False') self.assertEquals(user1data['role'], 'commander') self.assertEquals(user1data['created'], str(self.user1.created)) self.assertEquals(user1data['last_edit_model'], 'Plot') self.assertEquals(user1data['last_edit_model_id'], str(self.plot.pk)) self.assertEquals(user1data['last_edit_instance_id'], str(self.instance.pk)) self.assertEquals(user1data['last_edit_user_id'], str(self.user1.pk)) self.assertEquals(user2data['email'], '*****@*****.**') self.assertEquals(user2data['email_hash'], self.user2.email_hash) self.assertEquals(user2data['last_edit_model'], 'Tree') self.assertEquals(user2data['last_edit_model_id'], str(self.tree.pk)) self.assertEquals(user2data['last_edit_instance_id'], str(self.instance.pk)) self.assertEquals(user2data['last_edit_user_id'], str(self.user2.pk))
def get_csv_data_with_base_assertions(self): resp = users_csv(make_request(), self.instance) reader = csv.reader(resp) # Skip BOM and entry line reader.next() reader.next() header = reader.next() data = [dict(zip(header, [x.decode('utf8') for x in row])) for row in reader] commander, user1data, user2data = data self.assertEquals(commander['username'], self.commander.username) self.assertUserJSON(user1data, {'username': self.user1.username, 'email': '', 'email_hash': self.user1.email_hash, 'allow_email_contact': 'False', 'role': 'commander', 'created': str(self.user1.created), 'last_edit_model': 'Plot', 'last_edit_model_id': str(self.plot.pk), 'last_edit_instance_id': str(self.instance.pk), 'last_edit_user_id': str(self.user1.pk)}) self.assertUserJSON(user2data, {'email': '*****@*****.**', 'email_hash': self.user2.email_hash, 'last_edit_model': 'Tree', 'last_edit_model_id': str(self.tree.pk), 'last_edit_instance_id': str(self.instance.pk), 'last_edit_user_id': str(self.user2.pk)}) return data
def test_email_not_found_creates_invite(self): self.assertEqual(InstanceInvitation.objects.count(), 0) mail.outbox = [] email = '*****@*****.**' body = {'email': email} create_user_role( make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance) self.assertEqual(InstanceInvitation.objects.count(), 1) ii = InstanceInvitation.objects.all()[0] # Should have email and default role self.assertEqual(ii.email, email) self.assertEqual(ii.instance, self.instance) self.assertEqual(ii.role, self.instance.default_role) # Should have sent an email to the user self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] # Just make sure we have some chars and the # correct receiver self.assertGreater(len(msg.subject), 10) self.assertGreater(len(msg.body), 10) self.assertEquals(tuple(msg.to), (email,))
def _add_user_to_instance_view(self, email): body = {'email': email} return create_user_role( make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance)
def test_export_users_json_make_info_public(self): self.user1.make_info_public = True self.user1.save() resp = users_json(make_request(), self.instance) data = json.loads(resp.content) commander, user1data, user2data = data self.assertEquals(commander['username'], self.commander.username) self.assertEquals(user1data.get('email'), None) self.assertUserJSON(user1data, {'username': self.user1.username, 'email_hash': self.user1.email_hash, 'first_name': self.user1.first_name, 'last_name': self.user1.last_name, 'organization': self.user1.organization, 'allow_email_contact': 'False', 'role': 'commander', 'created': str(self.user1.created)}) self.assertUserJSON(user2data, {'last_edit_model': 'Tree', 'last_edit_model_id': str(self.tree.pk), 'last_edit_instance_id': str(self.instance.pk), 'last_edit_user_id': str(self.user2.pk), 'email': '*****@*****.**', 'email_hash': self.user2.email_hash})
def test_invites_updated(self): email = "*****@*****.**" invite = InstanceInvitation(email=email, instance=self.instance, created_by=self.user4, role=self.instance.default_role) invite.save() new_role = Role(name='Ambassador', instance=self.instance, rep_thresh=0) new_role.save() body = {'invites': {invite.pk: {'role': new_role.pk}}} update_user_roles( make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance) # requery invite invite = InstanceInvitation.objects.get(pk=invite.pk) self.assertEqual(invite.role, new_role)
def test_min_join_date(self): last_week = now() - datetime.timedelta(days=7) two_days_ago = now() - datetime.timedelta(days=2) yesterday = now() - datetime.timedelta(days=1) tda_ts = two_days_ago.strftime(DATETIME_FORMAT) Audit.objects.filter(model='InstanceUser')\ .filter(model_id=self.user1.get_instance_user(self.instance).pk)\ .update(created=last_week) Audit.objects.filter(model='InstanceUser')\ .filter(model_id= self.commander.get_instance_user(self.instance).pk)\ .update(created=last_week) Audit.objects.filter(model='InstanceUser')\ .filter(model_id=self.user2.get_instance_user(self.instance).pk)\ .update(created=yesterday) resp = users_json(make_request({'minJoinDate': tda_ts}), self.instance) data = json.loads(resp.content) self.assertEquals(len(data), 1) self.assertEquals(data[0]['username'], self.user2.username)
def test_invalid_email(self): body = {'email': 'asdfasdf@'} self.assertRaises( ValidationError, create_user_role, make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance)
def _set_search(self, **config): json_updates = json.dumps({ 'search_config': config, 'mobile_search_fields': {} }) request = make_request(method='PUT', body=json_updates) set_search_config(request, self.instance)
def test_export_users_json_keep_info_private(self): resp = users_json(make_request(), self.instance) data = json.loads(resp.content) commander, user1data, user2data = data self.assertFalse('first_name' in user1data)
def test_update_some_values(self): updates = { 'benefitCurrencyConversion.currency_symbol': '$', 'benefitCurrencyConversion.electricity_kwh_to_currency': '1.0', 'benefitCurrencyConversion.natural_gas_kbtu_to_currency': '2.0', 'benefitCurrencyConversion.h20_gal_to_currency': '3.0', 'benefitCurrencyConversion.co2_lb_to_currency': '4.0', 'benefitCurrencyConversion.o3_lb_to_currency': '5.0', 'benefitCurrencyConversion.nox_lb_to_currency': '6.0', 'benefitCurrencyConversion.pm10_lb_to_currency': '7.0', 'benefitCurrencyConversion.sox_lb_to_currency': '8.0', 'benefitCurrencyConversion.voc_lb_to_currency': '9.0', } json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) update_benefits(request, self.instance) conv = self.instance.eco_benefits_conversion self.assertEqual(conv.currency_symbol, '$') self.assertEqual(conv.electricity_kwh_to_currency, 1.0) self.assertEqual(conv.natural_gas_kbtu_to_currency, 2.0) self.assertEqual(conv.h20_gal_to_currency, 3.0) self.assertEqual(conv.co2_lb_to_currency, 4.0) self.assertEqual(conv.o3_lb_to_currency, 5.0) self.assertEqual(conv.nox_lb_to_currency, 6.0) self.assertEqual(conv.pm10_lb_to_currency, 7.0) self.assertEqual(conv.sox_lb_to_currency, 8.) self.assertEqual(conv.voc_lb_to_currency, 9.0)
def test_export_users_json_make_info_public(self): self.user1.make_info_public = True self.user1.save() resp = users_json(make_request(), self.instance) data = json.loads(resp.content) commander, user1data, user2data = data self.assertEquals(commander['username'], self.commander.username) self.assertEquals(user1data.get('email'), None) self.assertUserJSON(user1data, {'username': self.user1.username, 'email_hash': self.user1.email_hash, 'first_name': self.user1.first_name, 'last_name': self.user1.last_name, 'organization': self.user1.organization, 'allow_email_contact': 'False', 'role': 'commander', 'created': str(self.user1.created)}) self.assertUserJSON(user2data, {'last_edit_model': 'Plot', 'last_edit_model_id': str(self.plot.pk), 'last_edit_instance_id': str(self.instance.pk), 'last_edit_user_id': str(self.user1.pk), 'email': '*****@*****.**', 'email_hash': self.user2.email_hash, 'last_edit_model': 'Tree', 'last_edit_model_id': str(self.tree.pk), 'last_edit_instance_id': str(self.instance.pk), 'last_edit_user_id': str(self.user2.pk)})
def test_cant_delete_collection_udf(self): stew_record = { 'Action': 'Enlarged', 'Date': datetime.date.today().strftime('%Y-%m-%d') } self.plot.udfs['Stewardship'] = [stew_record] self.plot.save_with_user(self.user) self.assertTrue( Audit.objects.filter(instance=self.instance).filter( model='udf:%s' % self.cudf.pk).exists()) resp = udf_delete(make_request(), self.instance, self.cudf.pk) self.assertEquals(resp.status_code, 400) self.assertTrue( Audit.objects.filter(instance=self.instance).filter( model='udf:%s' % self.cudf.pk).exists()) self.assertTrue( UserDefinedFieldDefinition.objects.filter( pk=self.cudf.pk).exists()) updated_plot = Plot.objects.get(pk=self.plot.pk) self.assertIn(self.cudf.name, updated_plot.udfs)
def test_invalid_email(self): body = {'email': 'asdfasdf@'} self.assertRaises(ValidationError, create_user_role, make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance)
def test_batch_hide(self): self.assertFalse(self.comment.is_removed) self.assertFalse(self.comment2.is_removed) params = _comment_ids_to_params(self.comment.id, self.comment2.id) req = make_request(params, user=self.user, method='POST') hide(req, self.instance) updated_comments = EnhancedThreadedComment.objects.all() for updated_comment in updated_comments: self.assertTrue(updated_comment.is_removed)
def test_hide(self): self.assertFalse(self.comment.is_removed) req = make_request(_comment_ids_to_params(self.comment.id), user=self.user, method='POST') hide(req, self.instance) updated_comment = EnhancedThreadedComment.objects.get( pk=self.comment.id) self.assertTrue(updated_comment.is_removed)
def testSearchBenefits(self): request = make_request( {'q': json.dumps({'tree.readonly': {'IS': False}})}) # all trees request.instance_supports_ecobenefits = self.instance\ .has_itree_region() result = search_tree_benefits(request, self.instance) benefits = result['benefits'] self.assertTrue(len(benefits) > 0)
def test_map_feature_applicable_constant_validation(self): self._activate('Bioswale') request_key = 'instance.config.map_feature_config.Bioswale'\ '.diversion_rate' updates = {request_key: 'x'} json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) with self.assertRaises(ValidationError): green_infrastructure(request, self.instance) updates = {request_key: -.166} json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) with self.assertRaises(ValidationError): green_infrastructure(request, self.instance) updates = {request_key: 1.66} json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) with self.assertRaises(ValidationError): green_infrastructure(request, self.instance) updates = {request_key: .166} json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) green_infrastructure(request, self.instance) bioswale_config = Bioswale.get_config(self.instance) self.assertEqual(bioswale_config.get('diversion_rate', None), 0.166)
def testSearchBenefits(self): request = make_request( {'q': json.dumps({'tree.readonly': { 'IS': False }})}) # all trees request.instance_supports_ecobenefits = self.instance\ .has_itree_region() result = search_tree_benefits(request, self.instance) benefits = result['benefits'] self.assertTrue(len(benefits) > 0)
def test_email_already_bound(self): iuser = InstanceUser(user=self.user1, instance=self.instance, role=self.instance.default_role) iuser.save_with_user(self.commander) body = {'email': self.user1.email} self.assertRaises( ValidationError, create_user_role, make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance)
def test_email_already_bound(self): iuser = InstanceUser(user=self.user1, instance=self.instance, role=self.instance.default_role) iuser.save_with_user(self.commander) body = {'email': self.user1.email} self.assertRaises(ValidationError, create_user_role, make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance)
def test_get_udfs(self): resp = udf_list(make_request(), self.instance) self.assertIn('udf_models', resp) plot_udfs = [m for m in resp['udf_models'] if m['name'] == 'Plot'] self.assertEqual(len(plot_udfs), 1) self.assertIn('specs', plot_udfs[0]) plain_udfs = [s['udf'] for s in plot_udfs[0]['specs'] if not s['udf'].iscollection] self.assertEqual(len(plain_udfs), 1) self.assertEqual(plain_udfs[0].pk, self.udf.pk)
def _update_plan(self, updates, user=None, force=False): user = user or self.user # Need to match the client, which places the force parameter in the # query string, not the request body path = '/hello?force=1' if force else '/hello' request = make_request(path=path, method='PUT', user=user, body=json.dumps(updates)) result = update_plan(request, self.instance, self.plan_id) if isinstance(result, HttpResponse): return result # there was an error else: return self._get_plan(self.user)
def test_map_feature_inapplicable_config_validation(self): self._activate('RainBarrel') request_key = 'instance.config.map_feature_config.RainBarrel'\ '.should_show_eco' updates = {request_key: True} json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) with self.assertRaises(ValidationError): green_infrastructure(request, self.instance)
def test_get_udfs(self): resp = udf_list(make_request(), self.instance) self.assertIn('udf_models', resp) plot_udfs = [m for m in resp['udf_models'] if m['name'] == 'Plot'] self.assertEqual(len(plot_udfs), 1) self.assertIn('specs', plot_udfs[0]) plain_udfs = [ s['udf'] for s in plot_udfs[0]['specs'] if not s['udf'].iscollection ] self.assertEqual(len(plain_udfs), 1) self.assertEqual(plain_udfs[0].pk, self.udf.pk)
def test_email_already_bound_to_invite(self): email = "*****@*****.**" invite = InstanceInvitation(email=email, instance=self.instance, created_by=self.user4, role=self.instance.default_role) invite.save() body = {'email': email} self.assertRaises( ValidationError, create_user_role, make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance)
def test_remove_map_feature_types(self): mft = 'Bioswale' key = 'map_feature_types' request_key = 'instance.config.{}.{}'.format(key, mft) updates = {request_key: True} json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) green_infrastructure(request, self.instance) updates[request_key] = False json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) green_infrastructure(request, self.instance) map_feature_types = self.instance.config.get(key) self.assertNotIn(mft, map_feature_types)
def test_flag_hide_flags_flag_makes_two_rows(self): self.hit_flag_endpoint(user=self.user) self.assertEqual(1, EnhancedThreadedCommentFlag.objects.all().count(), "There should be 1 comment flag row created") req = make_request(_comment_ids_to_params(self.comment.id), user=self.admin, method='POST') hide_flags(req, self.instance) self.assertEqual(1, EnhancedThreadedCommentFlag.objects.all().count(), "There should still 1 comment flag row after unflag") self.hit_flag_endpoint(user=self.user) self.assertEqual(2, EnhancedThreadedCommentFlag.objects.all().count(), "There should be 2 comment flag rows")
def test_email_already_bound_to_invite(self): email = "*****@*****.**" invite = InstanceInvitation(email=email, instance=self.instance, created_by=self.user4, role=self.instance.default_role) invite.save() body = {'email': email} self.assertRaises(ValidationError, create_user_role, make_request(method='POST', body=json.dumps(body), user=self.commander), self.instance)
def test_delete_udf_deletes_perms(self): body = {'udf.name': 'cool udf', 'udf.model': 'Plot', 'udf.type': 'string'} qs = FieldPermission.objects.filter( field_name='udf:cool udf', model_name='Plot') resp = _do_create_udf_request(body, self.instance) self.assertTrue(qs.exists()) resp = udf_delete(make_request(), self.instance, resp['udf'].pk) self.assertFalse(qs.exists()) body = {'udf.name': 'cool udf', 'udf.model': 'Plot', 'udf.type': 'choice', 'udf.choices': ['a', 'b', 'c']} resp = _do_create_udf_request(body, self.instance) self.assertTrue(qs.exists()) resp = udf_delete(make_request(), self.instance, resp['udf'].pk) self.assertFalse(qs.exists())
def test_add_map_feature_types(self): mft = 'Bioswale' key = 'map_feature_types' updates = {'instance.config.{}.{}'.format(key, mft): True} json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) green_infrastructure(request, self.instance) map_feature_types = self.instance.config.get(key) self.assertGreater(len(map_feature_types), 0) self.assertIn(mft, map_feature_types)
def test_show_eco_without_constant(self): self._activate('Bioswale') self.instance.annual_rainfall_inches = 8.0 Bioswale.set_config_property(self.instance, 'diversion_rate', None) request_key = 'instance.config.map_feature_config.Bioswale'\ '.should_show_eco' updates = {request_key: True} json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates, user=self.commander) with self.assertRaises(ValidationError): green_infrastructure(request, self.instance)
def test_batch_hide_flags(self): self.hit_flag_endpoint(user=self.admin) self.hit_flag_endpoint(user=self.user) self.assertEqual(2, EnhancedThreadedCommentFlag.objects .filter(hidden=False).count(), "There should be 2 non-hidden comment flag rows") params = _comment_ids_to_params(self.comment.id, self.comment2.id) req = make_request(params, user=self.admin, method='POST') hide_flags(req, self.instance) self.assertEqual(2, EnhancedThreadedCommentFlag.objects .filter(hidden=True).count(), "There should be 2 hidden comment flag rows")
def assertPsuedoAsyncTaskWorks(self, model, user, assertion_field, assertion_value, assertion_filename): request = make_request(user=user) ctx = begin_export(request, self.instance, model) self.assertIn("job_id", ctx.keys()) self.assertEqual(ctx["start_status"], "OK") job_id = ctx["job_id"] job = ExportJob.objects.get(pk=job_id) self.assertCSVRowValue(job.outfile, 1, {assertion_field: assertion_value}) ctx = check_export(request, self.instance, job_id) self.assertIn(".csv", ctx["url"]) self.assertEqual(ctx["status"], "COMPLETE") self.assertRegexpMatches(job.outfile.name, assertion_filename)
def test_batch_hide_flags(self): self.hit_flag_endpoint(user=self.admin) self.hit_flag_endpoint(user=self.user) self.assertEqual( 2, EnhancedThreadedCommentFlag.objects.filter(hidden=False).count(), "There should be 2 non-hidden comment flag rows") params = _comment_ids_to_params(self.comment.id, self.comment2.id) req = make_request(params, user=self.admin, method='POST') hide_flags(req, self.instance) self.assertEqual( 2, EnhancedThreadedCommentFlag.objects.filter(hidden=True).count(), "There should be 2 hidden comment flag rows")
def setUp(self): self.instance = make_instance() self.user = make_plain_user('a', 'a') self.user2 = make_plain_user('b', 'b') self.plan_spec = { 'name': 'My Plan', 'description': 'A fascinating plan', 'is_published': True, 'scenarios': { 'scenarios': [], 'currentScenarioId': None } } request = make_request(method='POST', user=self.user, body=json.dumps(self.plan_spec)), result = add_plan(request[0], self.instance) self.plan_id = result['id']
def test_min_edit_date(self): last_week = now() - datetime.timedelta(days=7) two_days_ago = now() - datetime.timedelta(days=2) yesterday = now() - datetime.timedelta(days=1) tda_ts = two_days_ago.strftime(DATETIME_FORMAT) Audit.objects.filter(user=self.user1).update(created=last_week, updated=last_week) Audit.objects.filter(user=self.commander).update(created=last_week, updated=last_week) Audit.objects.filter(user=self.user2).update(created=yesterday, updated=yesterday) resp = users_json(make_request({"minEditDate": tda_ts}), self.instance) data = json.loads(resp.content) self.assertEquals(len(data), 1) self.assertEquals(data[0]["username"], self.user2.username)
def get_csv_data_with_base_assertions(self): resp = users_csv(make_request(), self.instance) reader = csv.reader(resp) # Skip BOM and entry line reader.next() reader.next() header = reader.next() data = [dict(zip(header, [x.decode("utf8") for x in row])) for row in reader] commander, user1data, user2data = data self.assertEquals(commander["username"], self.commander.username) self.assertUserJSON( user1data, { "username": self.user1.username, "email": "", "email_hash": self.user1.email_hash, "allow_email_contact": "False", "role": "commander", "created": str(self.user1.created), "last_edit_model": "Plot", "last_edit_model_id": str(self.plot.pk), "last_edit_instance_id": str(self.instance.pk), "last_edit_user_id": str(self.user1.pk), }, ) self.assertUserJSON( user2data, { "email": "*****@*****.**", "email_hash": self.user2.email_hash, "last_edit_model": "Tree", "last_edit_model_id": str(self.tree.pk), "last_edit_instance_id": str(self.instance.pk), "last_edit_user_id": str(self.user2.pk), }, ) return data
def test_export_users_csv(self): resp = users_csv(make_request(), self.instance) reader = csv.reader(resp) # Skip BOM and entry line reader.next() reader.next() header = reader.next() data = [dict(zip(header, [x.decode('utf8') for x in row])) for row in reader] commander, user1data, user2data = data self.assertEquals(commander['username'], self.commander.username) self.assertEquals(user1data['username'], self.user1.username) self.assertEquals(user1data['email'], '') self.assertEquals(user1data['email_hash'], self.user1.email_hash) self.assertEquals(user1data['first_name'], self.user1.first_name) self.assertEquals(user1data['last_name'], self.user1.last_name) self.assertEquals(user1data['organization'], self.user1.organization) self.assertEquals(user1data['allow_email_contact'], 'False') self.assertEquals(user1data['role'], 'commander') self.assertEquals(user1data['created'], str(self.user1.created)) self.assertEquals(user1data['last_edit_model'], 'Plot') self.assertEquals(user1data['last_edit_model_id'], str(self.plot.pk)) self.assertEquals(user1data['last_edit_instance_id'], str(self.instance.pk)) self.assertEquals(user1data['last_edit_user_id'], str(self.user1.pk)) self.assertEquals(user2data['email'], '*****@*****.**') self.assertEquals(user2data['email_hash'], self.user2.email_hash) self.assertEquals(user2data['last_edit_model'], 'Tree') self.assertEquals(user2data['last_edit_model_id'], str(self.tree.pk)) self.assertEquals(user2data['last_edit_instance_id'], str(self.instance.pk)) self.assertEquals(user2data['last_edit_user_id'], str(self.user2.pk))
def assertPsuedoAsyncTaskWorks(self, model, user, assertion_field, assertion_value, assertion_filename): request = make_request(user=user) ctx = begin_export(request, self.instance, model) self.assertIn('job_id', ctx.keys()) self.assertEqual(ctx['start_status'], 'OK') job_id = ctx['job_id'] job = ExportJob.objects.get(pk=job_id) self.assertCSVRowValue(job.outfile, 1, {assertion_field: assertion_value}) ctx = check_export(request, self.instance, job_id) self.assertIn('.csv', ctx['url']) self.assertEqual(ctx['status'], 'COMPLETE') self.assertRegexpMatches(job.outfile.name, assertion_filename)
def test_updates(self): # TODO: For now, don't use '2', which is pending updates = self.make_updates( self.new_role.pk, {'Tree.diameter': 3}) json_updates = json.dumps(updates) request = make_request(method='PUT', body=json_updates) roles_update(request, self.instance) #requery new_role self.new_role = Role.objects.get(pk=self.new_role.pk) self.assertEqual(1, FieldPermission.objects.filter( model_name='Tree', field_name='diameter', instance=self.instance, role=self.new_role, permission_level=3).count())
def test_export_users_json_make_info_public(self): self.user1.make_info_public = True self.user1.save() resp = users_json(make_request(), self.instance) data = json.loads(resp.content) commander, user1data, user2data = data self.assertEquals(commander["username"], self.commander.username) self.assertEquals(user1data.get("email"), None) self.assertUserJSON( user1data, { "username": self.user1.username, "email_hash": self.user1.email_hash, "first_name": self.user1.first_name, "last_name": self.user1.last_name, "organization": self.user1.organization, "allow_email_contact": "False", "role": "commander", "created": str(self.user1.created), }, ) self.assertUserJSON( user2data, { "last_edit_model": "Plot", "last_edit_model_id": str(self.plot.pk), "last_edit_instance_id": str(self.instance.pk), "last_edit_user_id": str(self.user1.pk), "email": "*****@*****.**", "email_hash": self.user2.email_hash, "last_edit_model": "Tree", "last_edit_model_id": str(self.tree.pk), "last_edit_instance_id": str(self.instance.pk), "last_edit_user_id": str(self.user2.pk), }, )