def test_optional_email_verification(self): c = Client() # Signup c.get(reverse('account_signup')) resp = c.post( reverse('account_signup'), { 'username': '******', 'email': '*****@*****.**', 'password1': 'johndoe', 'password2': 'johndoe' }) # Logged in self.assertRedirects(resp, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False) self.assertEqual(mail.outbox[0].to, ['*****@*****.**']) self.assertEqual(len(mail.outbox), 1) # Logout & login again c.logout() # Wait for cooldown EmailConfirmation.objects.update(sent=now() - timedelta(days=1)) # Signup resp = c.post(reverse('account_login'), { 'login': '******', 'password': '******' }) self.assertRedirects(resp, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False) self.assertEqual(mail.outbox[0].to, ['*****@*****.**']) # There was an issue that we sent out email confirmation mails # on each login in case of optional verification. Make sure # this is not the case: self.assertEqual(len(mail.outbox), 1)
class ChatPageTest(TestCase): """Test the chat test page.""" # This includes a sample room. fixtures = ['test_jqchat.json'] def setUp(self): self.client = Client() self.client.login(username='******', password='******') def test_chat_page(self): """We have a basic test page for the chat client.""" # Get the room defined in the fixture. response = self.client.get('/jqchat/room/1/') self.assert_(response.status_code == 200, response.status_code) # Basic checks on the content of this page. self.assert_('<div id="chatwindow">' in response.content) self.assert_(response.context[0]['room'].name == 'The first room', response.context[0]['room']) def test_login(self): """Must be logged in to access the chat page.""" self.client.logout() response = self.client.get('/jqchat/room/1/') # Should redirect to login page. self.assert_(response.status_code == 302, response.status_code)
def testQuestion(self): client = Client() client.login(username='******', password='******') resp = client.get('/delphi/create/') self.assertEqual(resp.status_code, 200) resp = client.post('/delphi/create/', {'question': 'How do I internet?', 'more_info': 'I cannot internet. How do I internet? herpderp'}) self.assertEqual(resp.status_code, 302) question1 = Question.objects.get(question='How do I internet?') q1id = str(question1.id) resp1 = client.get('/delphi/' + q1id + '/') self.assertContains(resp1, 'herpderp') client.logout() client.login(username='******', password='******') resp = client.get('/delphi/' + q1id + '/') self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'herpderp') resp = client.get('/delphi/create/') self.assertEqual(resp.status_code, 200) resp = client.post('/delphi/create/', {'question': 'How do I become less of a noob?', 'more_info': 'My name is Noobert Ownian'}) self.assertEqual(resp.status_code, 302) question2 = Question.objects.get(question='How do I become less of a noob?') q2id = str(question2.id) resp = client.get('/delphi/' + q2id + '/') self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'Noobert Ownian') client.logout()
def test_lot_login_middleware_always_valid(self): c = Client() lots = LOT.objects.all().count() response = c.get('/test_url/', {'uuid-login': self.lot3.uuid}) self.assertEqual(response.status_code, 200) self.assertEqual(int(c.session['_auth_user_id']), self.lot3.user_id) c.logout() self.assertFalse("_auth_user_id" in c.session) self.assertEqual(LOT.objects.all().count(), lots) response = c.get('/test_url/', {'uuid-login': self.lot3.uuid}) self.assertEqual(response.status_code, 200) self.assertEqual(int(c.session['_auth_user_id']), self.lot3.user_id) c.logout() self.assertFalse("_auth_user_id" in c.session) self.assertEqual(LOT.objects.all().count(), lots) self.lot3.created = self.lot3.created - datetime.timedelta(days=10000) self.lot3.save(force_modification=True) response = c.get('/test_url/', {'uuid-login': self.lot3.uuid}) self.assertEqual(response.status_code, 200) self.assertEqual(int(c.session['_auth_user_id']), self.lot3.user_id) self.assertEqual(LOT.objects.all().count(), lots)
class Login_TestCase(unittest.TestCase): def setUp(self): self.user = User.objects.create_user(username='******',password='******') self.client = Client() def tearDown(self): self.client.logout() self.user.delete() def test_index(self): """ Test an unauthorized page and after the LOGIN_URL. """ response = self.client.get('/snafu') self.assertEqual(response.status_code, 301) #self.assertRedirects(response, '/snafu/login?next=/snafu/') response = self.client.get('/snafu/login') self.assertEqual(response.status_code, 200) def test_good_login(self): """ Test to access to page as a user. """ self.client.post('/snafu/login', {'username':'******','password':'******'}) T = self.client.login(username='******',password='******') response = self.client.get('/snafu/events') self.assertEqual(response.status_code, 200) def test_bad_login(self): """ Test if site is restricted to anonymous users. """ self.client.post('/snafu/login', {'username':'******','password':'******'}) response = self.client.post('/snafu/events', {'username':'******','password':'******'}) self.assertIn(response.status_code, (301,302))
def test_get_sales_leads_product_data(self): sl = SalesLeads.objects.create(practice="Cancer Busters", rep=self.admin.user, price="99.00") c = Client() # after successful login should get re-direct to / response = c.post('/login/', { 'username': self.admin.user.username, 'password': '******' }) self.assertEqual(response.status_code, 302) # get product data as admin response = c.get( reverse('MHLogin.MHLUsers.Sales.views.sales_getproductdata') + '?id=' + str(sl.id)) self.assertEqual(response.status_code, 200, response.status_code) response = c.logout() self.assertFalse('_auth_user_id' in c.session) c = Client() # after successful login should get re-direct to / response = c.post('/login/', { 'username': self.salesperson.user.username, 'password': '******' }) self.assertEqual(response.status_code, 302) # get product data as regular sales guy who doesn't have permission response = c.get( reverse('MHLogin.MHLUsers.Sales.views.sales_getproductdata') + '?id=' + str(sl.id)) self.assertEqual(response.status_code, 200, response.status_code) response = c.logout()
def test_uf_value(self): c = Client() self.assertTrue(c.login(username='******', password='******')) study_dict = {'full_citation': 'foo et al.', 'short_citation': 'foo_citation', 'summary': 'summary there.'} #check to make sure we can create a new study field response = c.post(reverse('study:new_study', kwargs={'pk': self.assessment_working.pk}), study_dict) pk = re.findall(r'/study/(\d+)/$', response['location']) pk = int(pk[0]) self.assertRedirects(response, reverse('study:detail', kwargs={'pk': pk})) #check to make sure we can't create a new study citation field that already exists response = c.post(reverse('study:new_study', kwargs={'pk': self.assessment_working.pk}), study_dict) self.assertFormError(response, 'form', None, u'Error- short-citation name must be unique for assessment.') #check to make sure we can change an existing study citation field to a different type response = c.post(reverse('study:update', kwargs={'pk': pk}), study_dict) self.assertTrue(response.status_code in [200, 302]) self.assertTemplateUsed('study/study_detail.html') #check to make sure we can create a new study in different assessment c.logout() self.assertTrue(c.login(username='******', password='******')) response = c.post(reverse('study:new_study', kwargs={'pk': self.assessment_final.pk}), study_dict) pk = re.findall(r'/study/(\d+)/$', response['location']) pk = int(pk[0]) self.assertRedirects(response, reverse('study:detail', kwargs={'pk': pk}))
def test_map_metadata(self): """Test that map metadata can be properly rendered """ # first create a map c = Client() # Test successful new map creation c.login(username=self.user, password=self.passwd) new_map = reverse('new_map_json') response = c.post(new_map, data=self.viewer_config,content_type="text/json") self.assertEquals(response.status_code,200) map_id = int(json.loads(response.content)['id']) c.logout() url = reverse('map_metadata', args=(map_id,)) # test unauthenticated user to modify map metadata response = c.post(url) self.assertEquals(response.status_code,302) # test a user without metadata modify permission c.login(username='******', password='******') response = c.post(url) self.assertEquals(response.status_code, 302) c.logout() # Now test with a valid user using GET method c.login(username=self.user, password=self.passwd) response = c.get(url) self.assertEquals(response.status_code, 200) # Now test with a valid user using POST method c.login(username=self.user, password=self.passwd) response = c.post(url) self.assertEquals(response.status_code, 200)
def test_delete_macrogroup_view(self): """ Testing delete macrogroup """ # Create a macrogroup to delete macrogroup_data = { 'name': 'MacroGroup to delete', 'title': 'MacroGroup to delete', 'logo_img': '' } macrogroup = MacroGroup(**macrogroup_data) macrogroup.save() # check 1 macrogroup on db dbgmacrogropus = MacroGroup.objects.all() self.assertEqual(len(dbgmacrogropus), 1) self.assertEqual(dbgmacrogropus[0].name, macrogroup_data['name']) url = reverse('macrogroup-delete', args=[macrogroup.slug]) client = Client() self.assertTrue( client.login(username=self.test_user1.username, password=self.test_user1.username)) response = client.post(url) self.assertEqual(response.status_code, 200) # check no macrogroup into db dbgmacrogropus = MacroGroup.objects.all() self.assertEqual(len(dbgmacrogropus), 0) client.logout()
def test_generasuitedata_view(self): """ Check GeneralDataSuite view """ client = Client() # Check only admin can access # No login: loginrequired return redircte to login page 302 url = reverse('generaldata-update') response = client.get(url) self.assertEqual(response.status_code, 302) # Check editor level 1 # Not permission return 403 self.assertTrue( client.login(username=self.test_editor1.username, password=self.test_editor1.username)) response = client.get(url) self.assertEqual(response.status_code, 403) client.logout() # Check Admin # Has access response 200 self.assertTrue( client.login(username=self.test_user1.username, password=self.test_user1.username)) response = client.get(url) self.assertEqual(response.status_code, 200)
def test_delete_group_view(self): """ Testing delete group """ # Create a group to delete group_data = { 'name': 'Group to delete', 'title': 'Group to delete', 'header_logo_img': '', 'srid': G3WSpatialRefSys.objects.get(auth_srid=4326) } group = Group(**group_data) group.save() # check 1 group on db dbgroups = Group.objects.all() self.assertEqual(len(dbgroups), 1) self.assertEqual(dbgroups[0].name, group_data['name']) url = reverse('group-delete', args=[group.slug]) client = Client() self.assertTrue( client.login(username=self.test_user1.username, password=self.test_user1.username)) response = client.post(url) self.assertEqual(response.status_code, 200) # check no groups into db dbgroups = Group.objects.all() self.assertEqual(len(dbgroups), 0) client.logout()
class AdminTestCase(TestCase): def setUp(self): self.client = Client() def test_admin_login(self): # Get login page response = self.client.get('/admin/login/') # Check response code self.assertEquals(response.status_code, 200) # Log the user in self.client.login(username='******', password="******") response = self.client.get('/admin/login/') self.assertEquals(response.status_code, 200) def test_admin_logout(self): # Log in self.client.login(username='******', password="******") # Check response code response = self.client.get('/admin/login/') self.assertEquals(response.status_code, 200) # Log out self.client.logout() # Check response code response = self.client.get('/admin/') self.assertEquals(response.status_code, 302)
class TopicTest(TestCase): def setUp(self): self.user = User.objects.create(username='******', email='*****@*****.**') self.user.set_password('test_password') self.user.save() self.client = Client() self.client.login(username='******', password='******') def test_topic_client_login(self): topic = Topic.objects.create(name='test_topic', author=self.user) response = self.client.get('/topic/{}/detail/'.format(topic.pk)) self.assertEqual(response.status_code, 200) def test_topic_client_logout(self): self.client.logout() topic = Topic.objects.create(name='test_topic', author=self.user) response = self.client.get('/topic/{}/detail/'.format(topic.pk)) self.assertEqual(response.status_code, 302) def test_topic_list_value(self): topics = {} for i in range(10): topics[i] = RandomTopicFactory.create() response = self.client.get('/topic/list/') content = json.loads(response.content.decode()) for i in range(10): fields = content[i]['fields'] self.assertEqual(fields['author'], topics[i].author.pk) self.assertEqual(fields['name'], topics[i].name) self.assertEqual(fields['text'], topics[i].text)
class TestDomainViews(TestCase): def setUp(self): self.client = Client() self.domain = Domain(name="fandago", is_active=True) self.domain.save() self.username = '******' self.password = '******' self.user = WebUser.create(self.domain.name, self.username, self.password) self.user.set_role(self.domain.name, 'admin') self.user.save() def tearDown(self): self.user.delete() self.domain.delete() def test_add_repeater(self): forwarding_url = 'https://example.com/forwarding' self.client.login(username=self.username, password=self.password) post_url = reverse('add_repeater', kwargs={'domain': self.domain.name, 'repeater_type': 'AppStructureRepeater'}) response = self.client.post(post_url, {'url': forwarding_url}, follow=True) self.assertEqual(response.status_code, 200) self.client.logout() app_structure_repeaters = AppStructureRepeater.by_domain(self.domain.name) self.assertEqual(len(app_structure_repeaters), 1) for app_structure_repeater in app_structure_repeaters: app_structure_repeater.delete()
class TestDataRetention(TestCase): def setUp(self): self.c = Client() self.user = User.objects.create_user(password='******', email='*****@*****.**') self.c.login(username='******', password='******') def tearDown(self): self.c.logout() User.objects.all().delete() def test_data_retention_form(self): url = reverse('settings_data') response = self.c.post(url, {'check_every': 60, 'keep_data': 30}) result = data_retention_model.get_one() assert result['check_every'] == 60 assert result['keep_data'] == 30 response = self.c.post(url, {'check_every': 300, 'keep_data': 60}) result = data_retention_model.get_one() assert result['check_every'] == 300 assert result['keep_data'] == 60
class ViewsTestCase(unittest.TestCase): def setUp(self): self.client = Client() def test_anonymous(self): self.client.logout() self.client.get('/admin/') response = self.client.get('/session_security/ping/?idleFor=1') self.assertEqual(response.content, 'logout') ping_provider = lambda: ( (1, 4, '1'), (3, 2, '2'), (5, 5, '5'), (12, 14, 'logout', False), ) @data_provider(ping_provider) def test_ping(self, server, client, expected, authenticated=True): self.client.login(username='******', password='******') self.client.get('/admin/') now = datetime.now() session = self.client.session session['_session_security'] = now - timedelta(seconds=server) session.save() response = self.client.get('/session_security/ping/?idleFor=%s' % client) self.assertEqual(response.content, expected) self.assertEqual(authenticated, '_auth_user_id' in self.client.session)
class ViewsTestCase(unittest.TestCase): def setUp(self): self.client = Client() def test_anonymous(self): self.client.logout() self.client.get('/admin/') response = self.client.get('/session_security/ping/?idleFor=1') self.assertEqual(response.content, six.b('logout')) ping_provider = lambda x=None: ( (1, 4, '1'), (3, 2, '2'), (5, 5, '5'), (12, 14, 'logout', False), ) @data_provider(ping_provider) def test_ping(self, server, client, expected, authenticated=True): self.client.login(username='******', password='******') self.client.get('/admin/') now = datetime.now() session = self.client.session set_last_activity(session, now - timedelta(seconds=server)) session.save() response = self.client.get('/session_security/ping/?idleFor=%s' % client) self.assertEqual(response.content, six.b(expected)) self.assertEqual(authenticated, '_auth_user_id' in self.client.session)
class TestNotifications(TestCase): def setUp(self): self.c = Client() self.user = User.objects.create_user(password='******', email='*****@*****.**') self.c.login(username='******', password='******') def tearDown(self): self.c.logout() self.user.delete() notifications_model.collection.remove() def _cleanup(self): notifications_model.collection.remove() def test_add_url(self): self._cleanup() url = reverse('notifications_add', kwargs={"provider_id": "pushover"}) response = self.c.post( url, { 'name': 'default', 'user_key': 'somekey', 'application_api_key': 'some' }) self.assertRedirects( response, reverse('notifications_edit', kwargs={'provider_id': 'pushover'})) assert notifications_model.collection.find().count() == 1 result = notifications_model.collection.find_one() edit_url = reverse('notifications_edit', kwargs={ "provider_id": "pushover", 'notification_id': result['_id'] }) response = self.c.post( edit_url, { 'name': 'default', 'user_key': 'changed_user_key', 'application_api_key': 'changed_data' }) self.assertRedirects( response, reverse('notifications_edit', kwargs={ 'provider_id': 'pushover', 'notification_id': result['_id'] })) assert notifications_model.collection.find().count() == 1 for r in notifications_model.collection.find(): assert r['application_api_key'] == 'changed_data' assert r['user_key'] == 'changed_user_key'
class TestModels(TestCase): def setUp(self): """Set up the client.""" self.c = Client() self.user = User.objects.create_user('john', '*****@*****.**', 'password') self.user.save() self.c.login(username='******', password='******') session = self.c.session session.save() re = 'test' Group.objects.get_or_create(name=re) grp_obj = Group.objects.get(name=re) grp_obj.user_set.add(self.user) def test_wod_index_context(self): response = self.c.get(reverse('wod_index'), follow=True) self.assertTrue(response.status_code == 200) self.assertTrue("latest_wod_list" in response.context) self.assertTrue("request" in response.context) self.assertTrue("user" in response.context) self.assertTrue("messages" in response.context) self.assertTemplateUsed(response, "wod/wod_archive.html") def test_wod_details_context(self): response = self.c.get(reverse('wod_index'), follow=True) self.assertTrue(response.status_code == 200) self.assertTemplateUsed(response, "wod/wod_archive.html") management.call_command('load_data') response = self.c.get(reverse('wod_index'), follow=True) self.assertTrue(len(response.context['latest_wod_list'])!= 0) response = self.c.get(reverse('wod_details', kwargs={ 'wod_id': 1, }), follow=True) self.assertTrue(response.status_code == 200) self.assertTemplateUsed(response, "wod/wod_page.html") self.assertContains(response, "<p>Wod page</p>") self.assertContains(response, "Logout") def test_home_context(self): response = self.c.get('/home/') self.assertTrue(response.status_code == 200) self.assertTrue("request" in response.context) self.assertTrue("user" in response.context) self.assertTrue("messages" in response.context) def test_user_home_logout(self): self.c.logout() response = self.c.get('/home/') self.assertTrue(response.status_code == 200) self.assertContains(response, 'login') self.assertContains(response, 'register') def test_intruder(self): self.c.logout() response = self.c.get(reverse('wod_index')) self.assertTrue(response.status_code == 302) self.c.login(username='******', password='******') response = self.c.get(reverse('wod_index'), follow=True) self.assertTrue(response.status_code == 200)
def test_votes_view(self): client = Client() submission = Submission.objects.create(artwork=self.artwork, exhibition=self.exhibition, submitted_by=self.user) vote = Vote.objects.create(submission=submission, status=Vote.THUMBS_UP, voted_by=self.user) # anonymous users don't see others' votes, just the score view_url = reverse("submission-view", kwargs={"pk": submission.id}) response = client.get(view_url) self.assertEqual(response.status_code, 200) self.assertTrue("share_url" in response.context) self.assertEquals(response.context["votes"], {}) self.assertEquals(response.context["submission"].score, 1) # logged-in users see own votes logged_in = client.login(username=self.get_username(), password=self.get_password()) self.assertTrue(logged_in) view_url = reverse("submission-view", kwargs={"pk": submission.id}) response = client.get(view_url) self.assertEqual(response.status_code, 200) self.assertTrue("share_url" in response.context) self.assertEquals(response.context["votes"], {submission.id: vote}) self.assertEquals(response.context["submission"].score, 1) client.logout() logged_in = client.login(username=self.get_username("staff"), password=self.get_password("staff")) self.assertTrue(logged_in) view_url = reverse("submission-view", kwargs={"pk": submission.id}) response = client.get(view_url) self.assertEqual(response.status_code, 200) self.assertTrue("share_url" in response.context) self.assertEquals(response.context["votes"], {}) self.assertEquals(response.context["submission"].score, 1)
class AdminViewsTestCase(unittest.TestCase): ''' Testing admin views class ''' def setUp(self): ''' Command run before every test ''' self.u1 = User.objects.create(username='******', email='*****@*****.**', is_staff=True, is_superuser=True) self.u1.set_password('test') self.u1.save() self.c1 = Client() self.assertTrue(self.c1.login(username='******', password='******')) self.key1 = Key.objects.create(name='Key1') def tearDown(self): ''' Command run after every test ''' self.key1.delete() self.c1.logout() User.objects.all().delete() def test_admin_keyvalue(self): response = self.c1.get('/admin/keyvalue/key/') self.assertEqual(response.status_code, 200) def test_admin_keyvalue1(self): response = self.c1.get('/admin/keyvalue/key/%s/' % self.key1.id) self.assertEqual(response.status_code, 200)
class TestPhotosetCreationDeletion(unittest.TestCase): """Tests the ability to create and delete PhotoSets.""" def setUp(self): """Creates two user accounts and a web client.""" self.alice = User.objects.create_user('alice', '*****@*****.**', password='******') self.bob = User.objects.create_user('bob', '*****@*****.**', password='******') self.alice_client = Client() self.bob_client = Client() self.alice_client.login(username='******', password='******') self.bob_client.login(username='******', password='******') def tearDown(self): """Deletes the two user accounts.""" self.alice_client.logout() self.bob_client.logout() self.alice.delete() self.bob.delete() def testCreationDeletion(self): """Checks that Alice can login and create and delete a PhotoSet.""" # check that the photoset does not exist yet self.assertEqual(PhotoSet.objects.filter(slug='alices-photos').count(), 0) # create a photoset response = self.alice_client.post(reverse('clickclick.create_photoset'), {'title': 'Alice\'s Photos', 'slug': 'alices-photos', }) # check that it exists self.assertEqual(PhotoSet.objects.filter(slug='alices-photos').count(), 1) # attempt to delete the photoset as bob response = self.bob_client.post(reverse('clickclick.delete_photoset', args=['alices-photos',])) # check that the photoset still exists (i.e., deletion failed) self.assertEqual(PhotoSet.objects.filter(slug='alices-photos').count(), 1) # delete the photoset as alice response = self.alice_client.post(reverse('clickclick.delete_photoset', args=['alices-photos',])) # check that it no longer still exists self.assertEqual(PhotoSet.objects.filter(slug='alices-photos').count(), 0)
class AlertTest(TestCase): fixtures = ['test_court.json', 'authtest_data.json'] def setUp(self): # Set up some handy variables self.client = Client() self.alert_params = { 'query': 'q=asdf', 'name': 'dummy alert', 'rate': 'dly', 'always_send_email': 'on', } def test_create_alert(self): """Can we create an alert by sending a post?""" self.client.login(username='******', password='******') r = self.client.post('/', self.alert_params, follow=True) self.assertEqual(r.redirect_chain[0][1], 302) self.assertIn('successfully', r.content) self.client.logout() def test_fail_gracefully(self): """Do we fail gracefully when an invalid alert form is sent?""" # Use a copy to shield other tests from changes. bad_alert_params = self.alert_params.copy() # Break the form bad_alert_params.pop('query', None) self.client.login(username='******', password='******') r = self.client.post('/', bad_alert_params, follow=True) self.assertEqual(r.status_code, 200) self.assertIn('error creating your alert', r.content) self.client.logout()
def test_map_save(self): """POST /maps -> Test saving a new map""" c = Client() # Test that saving a map when not logged in gives 401 response = c.post("/maps/", data=MapTest.viewer_config, content_type="text/json") self.assertEqual(response.status_code, 401) # Test successful new map creation log = c.login(username="******", password="******") response = c.post("/maps/", data=MapTest.viewer_config, content_type="text/json") self.assertEquals(response.status_code, 201) map_id = int(response['Location'].split('/')[-1]) c.logout() self.assertEquals(map_id, 2) map = Map.objects.get(id=map_id) self.assertEquals(map.title, "Title") self.assertEquals(map.abstract, "Abstract") self.assertEquals(map.layer_set.all().count(), 1) # Test an invalid map creation request log = c.login(username="******", password="******") response = c.post("/maps/", data="not a valid viewer config", content_type="text/json") self.assertEquals(response.status_code, 400) c.logout()
class Spot1303(TestCase): def test_change_ownership(self): creators, created = Group.objects.get_or_create(name="spacescout_creators") admins, created = Group.objects.get_or_create(name="spacescout_admins") admin_user = User.objects.create_user("admin_user", "*****@*****.**", "ok") admins.user_set.add(admin_user) creator_user1 = User.objects.create_user("creator_user1", "*****@*****.**", "ok") creators.user_set.add(creator_user1) creator_user2 = User.objects.create_user("creator_user2", "*****@*****.**", "ok") creators.user_set.add(creator_user2) # Create the space as a creator user self.client = Client() self.client.login(username="******", password="******") response = self.client.post("/api/v1/space/", '{ "name": "test_space", "manager": "creator_user1" }', content_type="application/json") data = json.loads(response.content) url = "/api/v1/space/%s/" % data["id"] pk = int(data["id"]) space = Space.objects.get(pk = pk) self.assertEqual(space.manager, "creator_user1") # As an admin, change the manager self.client.logout() self.client.login(username="******", password="******") response = self.client.put(url, '{ "manager": "creator_user2" }', content_type="application/json") space = Space.objects.get(pk = pk) self.assertEqual(space.manager, "creator_user2")
def test_optional_email_verification(self): c = Client() # Signup c.get(reverse("account_signup")) resp = c.post( reverse("account_signup"), {"username": "******", "email": "*****@*****.**", "password1": "johndoe", "password2": "johndoe"}, ) # Logged in self.assertEqual(resp["location"], "http://testserver" + settings.LOGIN_REDIRECT_URL) self.assertEqual(resp.status_code, 302) self.assertEqual(mail.outbox[0].to, ["*****@*****.**"]) self.assertEqual(len(mail.outbox), 1) # Logout & login again c.logout() # Wait for cooldown EmailConfirmation.objects.update(sent=now() - timedelta(days=1)) # Signup resp = c.post(reverse("account_login"), {"login": "******", "password": "******"}) self.assertEqual(resp.status_code, 302) self.assertEqual(resp["location"], "http://testserver" + settings.LOGIN_REDIRECT_URL) self.assertEqual(mail.outbox[0].to, ["*****@*****.**"]) # There was an issue that we sent out email confirmation mails # on each login in case of optional verification. Make sure # this is not the case: self.assertEqual(len(mail.outbox), 1)
class AlertTest(TestCase): fixtures = ['test_court.json', 'authtest_data.json'] def setUp(self): # Set up some handy variables self.client = Client() self.alert_params = { 'alertText': 'q=asdf', 'alertName': 'dummy alert', 'alertFrequency': 'dly', 'sendNegativeAlert': 'on', } def test_create_alert(self): """Can we create an alert by sending a post?""" self.client.login(username='******', password='******') r = self.client.post('/', self.alert_params, follow=True) self.assertEqual(r.redirect_chain[0][1], 302) self.assertIn('successfully', r.content) self.client.logout() def test_fail_gracefully(self): """Do we fail gracefully when an invalid alert form is sent?""" # Use a copy to shield other tests from changes. bad_alert_params = self.alert_params.copy() # Break the form bad_alert_params.pop('alertText', None) self.client.login(username='******', password='******') r = self.client.post('/', bad_alert_params, follow=True) self.assertEqual(r.status_code, 200) self.assertIn('error creating your alert', r.content) self.client.logout()
class TestUserAdmin(TransactionTestCase): fixtures = ['init_panda.json', 'test_users.json'] def setUp(self): self.user = utils.get_panda_user() self.client = Client() self.client.login(username='******', password='******') def tearDown(self): self.client.logout() def test_add_user(self): # Test fetching the form response = self.client.get(reverse('admin:panda_userproxy_add')) self.assertEqual(response.status_code, 200) new_user = {'email': '*****@*****.**', 'last_name': 'Barman'} # Test submitting the form response = self.client.post(reverse('admin:panda_userproxy_add'), new_user) self.assertEqual(response.status_code, 302) created_user = UserProxy.objects.get(username='******') self.assertEqual(created_user.last_name, 'Barman')
class ViewsTestCase(unittest.TestCase): def setUp(self): get_or_create_test_admin() self.client = Client() def test_anonymous(self): self.client.logout() self.client.get("/admin/") response = self.client.get("/session_security/ping/?idleFor=1") self.assertEqual(response.content, six.b("logout")) ping_provider = lambda x=None: ((1, 4, "1"), (3, 2, "2"), (5, 5, "5"), (12, 14, "logout", False)) @data_provider(ping_provider) def test_ping(self, server, client, expected, authenticated=True): self.client.login(username="******", password="******") self.client.get("/admin/") now = datetime.now() session = self.client.session set_last_activity(session, now - timedelta(seconds=server)) session.save() response = self.client.get("/session_security/ping/?idleFor=%s" % client) self.assertEqual(response.content, six.b(expected)) self.assertEqual(authenticated, "_auth_user_id" in self.client.session)
def test_favorite_departments_list_view(self): """ Tests the favorite departments list view. """ fd1 = FireDepartment.objects.create(name='Fire Department 1') fd2 = FireDepartment.objects.create(name='Fire Department 2') fd3 = FireDepartment.objects.create(name='Fire Department 3') # add these departments as favorites and remove the last one user = User.objects.get(username='******') Favorite.objects.create(user, fd1) Favorite.objects.create(user, fd2) fav = Favorite.objects.create(user, fd3) fav.delete() c = Client() c.login(**{'username': '******', 'password': '******'}) response = c.get(reverse('firedepartment_list') + '?favorites=true') self.assertTrue(fd1 in response.context['object_list']) self.assertTrue(fd2 in response.context['object_list']) self.assertTrue(fd3 not in response.context['object_list']) self.assertEqual(response.status_code, 200) c.logout() try: response = c.get( reverse('firedepartment_list') + '?favorites=true') except: self.fail( 'Logged-out user triggering favorites search should not throw exception' )
class TestBookmarks(TestCase): def setUp(self): self.c = Client() self.user = User.objects.create_user(password='******', email='*****@*****.**') self.c.login(username='******', password='******') def tearDown(self): self.c.logout() self.user.delete() def _cleanup(self): tags_model.collection.remove() tag_groups_model.collection.remove() bookmarks_model.collection.remove() def add_delete_bookmark_test(self): self._cleanup() url = reverse('bookmarks_add') tags = {'provider': 'digitalocean', 'credentials': 'production'} tag_ids = [str(x) for x in tags_model.create_and_return_ids(tags)] tag_ids_str = ",".join(tag_ids) form_data = {'name': 'test', 'tags': tag_ids_str, 'type': 'server'} response = self.c.post(url, form_data) assert response.status_code == 302 assert bookmarks_model.collection.find().count() == 1
def test_proxy_url(self): no_signals() c = Client() response = c.post('/media/proxy/create/') # Response is JSON, should always be 200 self.assertEqual(200, response.status_code) # Result should be error since we did not provide any credentials data = json.loads(response.content) self.assertEqual('error', data['result']) login = c.login(username='******', password='******') self.assertTrue(login) TrustedSubnet.objects.create(subnet='127.0.0.1') response = c.post('/media/proxy/create/', {'url': self.record.get_thumbnail_url(), 'context': '_1_2'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(200, response.status_code) data = json.loads(response.content) self.assertEqual('ok', data['result']) id = data['id'] c.logout() # try to retrieve content url = '/media/proxy/%s/' % id response = c.get(url, {'context': '_1_2'}) self.assertEqual(200, response.status_code) self.assertEqual('image/jpeg', response['content-type']) # make sure image dimension restrictions took effect image = Image.open(StringIO(response.content)) width, height = image.size self.assertEqual(50, width)
class BaseTest(TestCase): fixtures = [ os.path.join(settings.ROOT, "survey", "tests", "testdump.json") ] def setUp(self): user = User(username=settings.DEBUG_ADMIN_NAME, is_superuser=True, is_staff=True) user.set_password(settings.DEBUG_ADMIN_PASSWORD) user.save() self.client = Client() def tearDown(self): self.logout() def login(self): """ Log the user in. """ is_logged = self.client.login(username=settings.DEBUG_ADMIN_NAME, password=settings.DEBUG_ADMIN_PASSWORD) if not is_logged: # pragma: no cover raise Exception("Login failed for test user! Tests won't work.") def logout(self): """ Log the user out. """ self.client.logout()
def test_map_save(self): """POST /maps/new/data -> Test saving a new map""" c = Client() new_map = reverse("new_map_json") # Test that saving a map when not logged in gives 401 response = c.post(new_map,data=self.viewer_config,content_type="text/json") self.assertEqual(response.status_code,401) # Test successful new map creation c.login(username=self.user, password=self.passwd) response = c.post(new_map,data=self.viewer_config,content_type="text/json") self.assertEquals(response.status_code,200) map_id = int(json.loads(response.content)['id']) c.logout() # We have now 9 maps and 8 layers so the next pk will be 18 self.assertEquals(map_id,18) map_obj = Map.objects.get(id=map_id) self.assertEquals(map_obj.title, "Title") self.assertEquals(map_obj.abstract, "Abstract") self.assertEquals(map_obj.layer_set.all().count(), 1) self.assertEquals(map_obj.keyword_list(), [u"keywords", u"saving"]) # Test an invalid map creation request c.login(username=self.user, password=self.passwd) response = c.post(new_map,data="not a valid viewer config",content_type="text/json") self.assertEquals(response.status_code,400) c.logout()
def test_maps_search(self): """Test maps search can function properly """ # first create two maps c = Client() # Test successful new map creation c.login(username=self.user, password=self.passwd) new_map = reverse('new_map_json') response = c.post(new_map, data=self.viewer_config,content_type="text/json") self.assertEquals(response.status_code,200) map_id = int(json.loads(response.content)['id']) response = c.post(new_map, data=self.viewer_config_alternative,content_type="text/json") self.assertEquals(response.status_code,200) map_id_2 = int(json.loads(response.content)['id']) c.logout() url = reverse('maps_search_api') + '?' # Test GET method response = c.get(url, {'q': '', 'start': 1}, content_type="text/json") self.assertEquals(response.status_code,200) response_dict = json.loads(response.content) self.assertEquals(response_dict['success'], True) # Test POST method response = c.post(url, {'q': '', 'start': 1}, content_type="text/json") self.assertEquals(response.status_code,200) response_dict = json.loads(response.content) self.assertEquals(response_dict['success'], True) # Test methods other than GET or POST response = c.put(url) self.assertEquals(response.status_code,405)
def test_optional_email_verification(self): c = Client() # Signup resp = c.post( reverse('account_signup'), { 'username': '******', 'email': '*****@*****.**', 'password1': 'johndoe', 'password2': 'johndoe' }) # Logged in self.assertEqual(resp['location'], 'http://testserver' + settings.LOGIN_REDIRECT_URL) self.assertEqual(resp.status_code, 302) self.assertEqual(mail.outbox[0].to, ['*****@*****.**']) self.assertEqual(len(mail.outbox), 1) # Logout & login again c.logout() # Wait for cooldown EmailConfirmation.objects.update(sent=now() - timedelta(days=1)) # Signup resp = c.post(reverse('account_login'), { 'login': '******', 'password': '******' }) self.assertEqual(resp.status_code, 302) self.assertEqual(resp['location'], 'http://testserver' + settings.LOGIN_REDIRECT_URL) self.assertEqual(mail.outbox[0].to, ['*****@*****.**']) # There was an issue that we sent out email confirmation mails # on each login in case of optional verification. Make sure # this is not the case: self.assertEqual(len(mail.outbox), 1)
class AdminTestCase(TestCase): def setUp(self): self.admin = User.objects.create_superuser('admin', '*****@*****.**', 'test1234') self.client = Client() def test_admin_login(self): # Get login page response = self.client.get('/admin/login/') # Check response code self.assertEquals(response.status_code, 200) # Log the admin in self.client.post('/admin/login/') self.client.login(username='******', password="******") response = self.client.post('/admin/login/') self.assertEquals(response.status_code, 200) def test_admin_logout(self): # Log in self.client.login(username='******', password="******") # Check response code response = self.client.get('/admin/login/') self.assertEquals(response.status_code, 200) # Log out self.client.logout() # Check response code response = self.client.get('/admin/') self.assertEquals(response.status_code, 302)
class TokenuserDeniedAccessTestCase(TestCase): def setUp(self): self.accounts = [('user1', 'pwd1', 'useronefirstname', 'useronelastname'), ('user2', 'pwd2', 'usertwofirstname', 'usertwolastname'), ('user3', 'pwd3', 'userthreefirstname', 'userthreelastname')] self.token_accounts = [(settings.TOKEN_USERNAME, '', 'Token', 'User')] self.accounts += self.token_accounts for (uname, pwd, first, last) in self.accounts: user = User.objects.create_user(uname, '', pwd) user.first_name = first user.last_name = last user.save() profile = UserProfile(user=user, isDjangoAccount=True) profile.save() self.users = User.objects.all() self.client = Client() login = self.client.login(username=self.accounts[0][0], password=self.accounts[0][1]) self.assertTrue(login) def testGetUserList(self): # Match all response = self.client.get('/ajax/user_list/?q=') self.assertEqual(response.status_code, 200) users_dict = json.loads(response.content) self.assertEqual(len(self.users) - len(self.token_accounts), len(users_dict)) for user in self.users: user_info = [ u for u in users_dict if u['username'] == user.username ] if user.username == settings.TOKEN_USERNAME: self.assertEqual([], user_info) else: self.assertEqual(1, len(user_info)) self.assertEqual(user_info[0]['first_name'], user.first_name) self.assertEqual(user_info[0]['last_name'], user.last_name) # Match on first name response = self.client.get('/ajax/user_list/?q=token') self.assertEqual(response.status_code, 200) users_dict = json.loads(response.content) self.assertEqual(0, len(users_dict)) # Match on last name response = self.client.get('/ajax/user_list/?q=user') self.assertEqual(response.status_code, 200) users_dict = json.loads(response.content) self.assertEqual(len(self.users) - len(self.token_accounts), len(users_dict)) def tearDown(self): self.client.logout()
def test_flag(self): self.q.flagged() self.assertEquals(self.q.flags_count, 1) c = Client() response = c.post(reverse('flag_question', kwargs={'q_id':self.q.id})) self.assertEquals(response.status_code, 200) data = json.loads(response.content) self.assertIn('redirect', data) respone = c.post(data['redirect'], {'username':"******", 'password':"******"}) response = c.post(reverse('flag_question', kwargs={'q_id':self.q.id})) data = json.loads(response.content) self.assertIn('message', data) self.assertEquals(data['message'], 'Thank you for flagging the question. One of our editors will look at it shortly.') self.q = Question.objects.get(pk=self.q.id) self.assertEquals(self.q.flags_count, 2) response = c.get(reverse('home')+"?filter=flagged") self.assertEquals(response.context['questions'].count(), 1) response = c.post(reverse('flag_question', kwargs={'q_id':self.q.id})) data = json.loads(response.content) self.assertIn('message', data) self.assertEquals(data['message'], 'Thanks. You already reported this question') c.logout() self.assertTrue(c.login(username="******", password="******")) response = c.post(reverse('flag_question', kwargs={'q_id':self.q.id})) data = json.loads(response.content) self.assertIn('redirect', data) self.assertEquals(data['redirect'], reverse('qna', args=(self.q.entity.slug, )))
def test_ssl_redirect_by_proxy(self): users.get_user_from_request = self._real_get_user_from_request dogs = horizon.get_dashboard("dogs") puppies = dogs.get_panel("puppies") url = puppies.get_absolute_url() redirect_url = "?".join( [urlresolvers.reverse("horizon:auth_login"), "next=%s" % url]) client = Client() client.logout() resp = client.get(url) self.assertRedirectsNoFollow(resp, redirect_url) # Set SSL settings for test server settings.TESTSERVER = 'https://testserver:80' settings.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') resp = client.get(url, HTTP_X_FORWARDED_PROTOCOL="https") self.assertRedirectsNoFollow(resp, redirect_url) # Restore settings settings.TESTSERVER = 'http://testserver' settings.SECURE_PROXY_SSL_HEADER = None
class ServerTestCases(TestCase): #fixtures = ['serverTestFixtures.json'] loginURL = '/login/' client = Client() STATUS_OK = 200 existingUser = {'id':'id', 'password':'******'} user = User.objects.create_user(existingUser['id'], '*****@*****.**', existingUser['password']) def setUp(self): self.client = Client() self.assertTrue(self.login()) def test_loginPage(self): response = self.client.get('/login/') self.assertEquals(response.status_code, self.STATUS_OK) def test_redirect_loggedIn(self): response = self.client.get('', follow=True) self.assertTrue(len(response.redirect_chain) == 0) def test_redirect_loggedOut(self): self.client.logout() response = self.client.get('', follow=True) self.assertTrue(len(response.redirect_chain) == 1) redirect = response.redirect_chain[0] self.assertIn('/login/?next=/', redirect[0]) self.assertEquals(302, redirect[1]) def login(self): return self.client.login(username=self.existingUser['id'], password=self.existingUser['password'])
def test_lot_login_view_allways_valid(self): c = Client() lots = LOT.objects.all().count() response = c.get('/login/{0}/'.format(self.lot3.uuid)) self.assertEqual(response.status_code, 302) self.assertEqual(c.session['_auth_user_id'], 1) c.logout() self.assertFalse("_auth_user_id" in c.session) self.assertEqual(LOT.objects.all().count(), lots) response = c.get('/login/{0}/'.format(self.lot3.uuid)) self.assertEqual(response.status_code, 302) self.assertEqual(c.session['_auth_user_id'], 1) c.logout() self.assertFalse("_auth_user_id" in c.session) self.assertEqual(LOT.objects.all().count(), lots) self.lot3.created = self.lot3.created - datetime.timedelta(days=10000) self.lot3.save(force_modification=True) response = c.get('/login/{0}/'.format(self.lot3.uuid)) self.assertEqual(response.status_code, 302) self.assertEqual(c.session['_auth_user_id'], 1) self.assertEqual(LOT.objects.all().count(), lots)
class TestAlbumView(TestCase): """Test the album view. The album view displays the title of the album, its description, and thumbnails of all photos in the album. """ fixtures = ['test_auth.json', 'test_photo_manager.json'] def setUp(self): self.client = Client() self.client.login(username='******', password='******') self.url = "/pm/album/{}" self.login_redirect = "/account/login/?next={}".format(self.url) def test_album_view(self): """Test that the album view appears as expected.""" album = Album.objects.get(title="Test Album") response = self.client.get(self.url.format(album.pk)) self.assertEqual(response.status_code, 200) self.assertTemplateUsed('PhotoManager/album.html') def test_album_view_not_logged_in(self): """Try to access the album view when not logged in and assert that we are redirected to the login view. """ self.client.logout() album = Album.objects.get(title="Test Album") response = self.client.get(self.url.format(album.pk)) self.assertRedirects(response, self.login_redirect.format(album.pk)) def test_album_view_wrong_user(self): """Attempt to access an album from a user account that the album doesn't belong to. """ self.client.logout() self.client.login(username='******', password='******') album = Album.objects.get(title="Test Album") response = self.client.get(self.url.format(album.pk)) self.assertEqual(response.status_code, 403) self.assertIn('403 Forbidden', response.content) def test_album_view_no_photos(self): """Verify that an album containing no photos still displays title and description. """ album = Album.objects.get(title="Test Album") response = self.client.get(self.url.format(album.pk)) self.assertEqual(response.status_code, 200) self.assertIn(album.title, response.content) self.assertIn(album.description, response.content) def test_album_view_with_photos(self): """Verify that an album containing photos shows title, description, and thumbnails. """ album = Album.objects.get(title="Another Test Album") response = self.client.get(self.url.format(album.pk)) self.assertEqual(response.status_code, 200) self.assertIn(album.title, response.content) self.assertIn(album.description, response.content) self.assertIn('img', response.content)
def test_lot_login_middleware_always_valid(self): c = Client() lots = LOT.objects.all().count() response = c.get('/test_url/', {'uuid-login': self.lot3.uuid}) self.assertEqual(response.status_code, 200) self.assertEqual(c.session['_auth_user_id'], 1) c.logout() self.assertFalse("_auth_user_id" in c.session) self.assertEqual(LOT.objects.all().count(), lots) response = c.get('/test_url/', {'uuid-login': self.lot3.uuid}) self.assertEqual(response.status_code, 200) self.assertEqual(c.session['_auth_user_id'], 1) c.logout() self.assertFalse("_auth_user_id" in c.session) self.assertEqual(LOT.objects.all().count(), lots) self.lot3.created = self.lot3.created - datetime.timedelta(days=10000) self.lot3.save(force_modification=True) response = c.get('/test_url/', {'uuid-login': self.lot3.uuid}) self.assertEqual(response.status_code, 200) self.assertEqual(c.session['_auth_user_id'], 1) self.assertEqual(LOT.objects.all().count(), lots)
class UserChangePwdTest(TestCase): def setUp(self): self.user = User(username="******") self.user.set_password("111111") self.user.save() self.client = Client() self.client.login(username="******", password="******") def test_change_pwd_with_correct_info(self): self.client.login(username="******", password="******") response = self.client.post(reverse("change_password"), {"old_password": "******", "password1": "123456", "password2": "123456"}) self.assertEqual(json.loads(response.content)["status"], "success") def test_change_pwd_without_login(self): self.client.logout() response = self.client.post(reverse("change_password"), {"old_password": "******", "password1": "123456", "password2": "123456"}) self.assertRedirects(response, reverse("login") + '?next=/account/change_password/') def test_change_pwd_with_error_old_pwd(self): self.client.login(username="******", password="******") response = self.client.post(reverse("change_password"), {"old_password": "******", "password1": "123456", "password2": "123456"}) self.assertEqual(json.loads(response.content)["status"], "error") def test_change_pwd_with_different_new_pwd(self): self.client.login(username="******", password="******") response = self.client.post(reverse("change_password"), {"old_password": "******", "password1": "123456", "password2": "123453"}) self.assertEqual(json.loads(response.content)["status"], "error")
class TestBase(TestCase): def _create_user(self): user = User.objects.create_user('admin', '*****@*****.**', '123') return user def login(self, username='******', password='******'): self._create_user() self.client = Client() self.client.login(username=username, password=password) def logout(self): self.client.logout() def tearDown(self): self.logout() Item.objects.all().delete() ModelClient.objects.all().delete() User.objects.all().delete() Picture.objects.all().delete() Bill.objects.all().delete() def _test_get_logout(self, url): self.logout() self.response = self.client.get(url) self.assertEqual(self.response.status_code, 302)
class TestUserAdmin(TransactionTestCase): fixtures = ['init_panda.json'] def setUp(self): self.user = utils.get_panda_user() self.client = Client() self.client.login(username='******', password='******') def tearDown(self): self.client.logout() def test_add_user(self): # Test fetching the form response = self.client.get(reverse('admin:auth_user_add')) self.assertEqual(response.status_code, 200) new_user = { 'username': '******', 'last_name': 'Barman' } # Test submitting the form response = self.client.post(reverse('admin:auth_user_add'), new_user) self.assertEqual(response.status_code, 302) created_user = User.objects.get(username='******') self.assertEqual(created_user.last_name, 'Barman')
def test_lot_login_view_always_valid(self): c = Client() lots = LOT.objects.all().count() response = c.get('/login/{0}/'.format(self.lot3.uuid)) self.assertEqual(response.status_code, 302) self.assertEqual(int(c.session['_auth_user_id']), self.lot3.user_id) c.logout() self.assertFalse("_auth_user_id" in c.session) self.assertEqual(LOT.objects.all().count(), lots) response = c.get('/login/{0}/'.format(self.lot3.uuid)) self.assertEqual(response.status_code, 302) self.assertEqual(int(c.session['_auth_user_id']), self.lot3.user_id) c.logout() self.assertFalse("_auth_user_id" in c.session) self.assertEqual(LOT.objects.all().count(), lots) self.lot3.created = self.lot3.created - datetime.timedelta(days=10000) self.lot3.save(force_modification=True) response = c.get('/login/{0}/'.format(self.lot3.uuid)) self.assertEqual(response.status_code, 302) self.assertEqual(int(c.session['_auth_user_id']), self.lot3.user_id) self.assertEqual(LOT.objects.all().count(), lots)
class GroupTestCase(unittest.TestCase): def test_login(self): self.client = Client() self.user = User.objects.create_user(username = '******', password = '******') print 'user - ', self.user #login by username status = self.client.login(username = '******', password = '******') print 'login', status response = self.client.get('/login/') self.assertEqual(response.status_code, 200) print 'response.status_code', response.status_code response = self.client.post('/Deanery/group/add/', {'name': 'testGroup', }) self.assertEqual(response.status_code, 302) print 'response.status_code - ', response.status_code response = self.client.get('/Deanery/') g_list = response.context['ls_groups'] print 'g_list - ', smart_unicode(g_list) # add students last = g_list[len(g_list) - 1] gr_num = len(g_list) - 1 print 'last - ', last response = self.client.post('/Deanery/student/add/', {'fio':'testStudent','numticket':'777','groups':gr_num,'datebrd':'1981-01-01' }) print 'response.status_code - ', response.status_code std_list = Students.objects.all() print 'std_list - ', smart_unicode(std_list) self.client.logout()
def test_flag(self): self.q.flagged() self.assertEquals(self.q.flags_count, 1) c = Client() response = c.post(reverse('flag_question', kwargs={'q_id': self.q.id})) self.assertEquals(response.status_code, 200) data = json.loads(response.content) self.assertIn('redirect', data) respone = c.post(data['redirect'], { 'username': "******", 'password': "******" }) response = c.post(reverse('flag_question', kwargs={'q_id': self.q.id})) data = json.loads(response.content) self.assertIn('message', data) self.assertEquals( data['message'], 'Thank you for falgging the question. One of our editors will look at it shortly.' ) self.q = Question.objects.get(pk=self.q.id) self.assertEquals(self.q.flags_count, 2) response = c.post(reverse('flag_question', kwargs={'q_id': self.q.id})) data = json.loads(response.content) self.assertIn('message', data) self.assertEquals(data['message'], 'Thanks. You already reported this question') c.logout() self.assertTrue(c.login(username="******", password="******")) response = c.post(reverse('flag_question', kwargs={'q_id': self.q.id})) data = json.loads(response.content) self.assertIn('redirect', data) self.assertEquals(data['redirect'], reverse('qna', args=(self.q.entity.slug, )))
def test_tilestache_api(self): """Testing titlestache api tile generation""" client = Client() layer = Layer.objects.get( project=self.project.instance, qgs_layer_id='spatialite_points20190604101052075') assign_perm('view_project', self.anonymoususer, self.project.instance) # active caching for layer cachinglayer = G3WCachingLayer.objects.create(app_name='qdjango', layer_id=layer.pk) # init tilestache TilestacheConfig.set_cache_config_dict(TilestacheConfig().config_dict) url = reverse('caching-api-tile', args=[f'qdjango{layer.pk}', 0, 0, 0, 'png']) #url = f'{self.live_server_url}{url}' self.assertTrue( client.login(username=self.test_admin1.username, password=self.test_admin1.username)) res = client.get(url) self.assertEqual(res.status_code, 200) client.logout()
def test_map_save(self): """POST /maps -> Test saving a new map""" c = Client() # Test that saving a map when not logged in gives 401 response = c.post("/maps/",data=MapTest.viewer_config,content_type="text/json") self.assertEqual(response.status_code,401) # Test successful new map creation c.login(username="******", password="******") response = c.post("/maps/",data=MapTest.viewer_config,content_type="text/json") self.assertEquals(response.status_code,201) map_id = int(response['Location'].split('/')[-1]) c.logout() self.assertEquals(map_id,2) map_obj = Map.objects.get(id=map_id) self.assertEquals(map_obj.title, "Title") self.assertEquals(map_obj.abstract, "Abstract") self.assertEquals(map_obj.layer_set.all().count(), 1) self.assertEquals(map_obj.keyword_list(), ["keywords", "saving"]) # Test an invalid map creation request c.login(username="******", password="******") response = c.post("/maps/",data="not a valid viewer config",content_type="text/json") self.assertEquals(response.status_code,400) c.logout()
def test_optional_email_verification(self): c = Client() # Signup c.get(reverse('account_signup')) resp = c.post(reverse('account_signup'), {'username': '******', 'email': '*****@*****.**', 'password1': 'johndoe', 'password2': 'johndoe'}) # Logged in self.assertEqual(resp['location'], 'http://testserver'+settings.LOGIN_REDIRECT_URL) self.assertEqual(resp.status_code, 302) self.assertEqual(mail.outbox[0].to, ['*****@*****.**']) self.assertEqual(len(mail.outbox), 1) # Logout & login again c.logout() # Wait for cooldown EmailConfirmation.objects.update(sent=now() - timedelta(days=1)) # Signup resp = c.post(reverse('account_login'), {'login': '******', 'password': '******'}) self.assertEqual(resp.status_code, 302) self.assertEqual(resp['location'], 'http://testserver'+settings.LOGIN_REDIRECT_URL) self.assertEqual(mail.outbox[0].to, ['*****@*****.**']) # There was an issue that we sent out email confirmation mails # on each login in case of optional verification. Make sure # this is not the case: self.assertEqual(len(mail.outbox), 1)
def test_bobby_cannot_set_all(self): """Test that Bobby can set the permissions only only on the ones for which he has the right""" layer = Layer.objects.all()[0] c = Client() c.login(username='******', password='******') # give bobby the right to change the layer permissions assign_perm('change_resourcebase', Profile.objects.get(username='******'), layer.get_self_resource()) c.logout() c.login(username='******', password='******') layer2 = Layer.objects.all()[1] data = { 'permissions': json.dumps({ "users": { "bobby": ["view_resourcebase"] }, "groups": {} }), 'resources': [layer.id, layer2.id] } resp = c.post(self.bulk_perms_url, data) self.assertTrue( layer2.title in json.loads(resp.content)['not_changed'])