def test_detail(self): self.client.logout() petition = Petition(author=self.get_user(), **PETITION) petition.save() response = self.client.get(reverse('petition-detail', args=[petition.id])) self.assertEqual(response.status_code, status.HTTP_200_OK) response_data = json.loads(response.content.decode()) self.assertTrue(isinstance(response_data["author"], dict)) # author is nested object
def test_list(self): petition = Petition(author=self.get_user(), **PETITION) petition.save() self.client.logout() response = self.client.get(reverse('petition-list')) self.assertEqual(response.status_code, status.HTTP_200_OK) response_data = json.loads(response.content.decode()) self.assertTrue(isinstance(response_data["results"][0]["author"], dict))
def test_detail(self): self.client.force_authenticate(self.get_staff_user()) petition = Petition(author=self.get_staff_user(), **PETITION) petition.save() response = self.client.get(reverse('user-detail', args=[self.get_staff_user().id])) self.assertEqual(response.status_code, status.HTTP_200_OK) response_data = json.loads(response.content.decode()) self.assertTrue(isinstance(response_data["petitions"][0], dict)) # petition list consists of objects self.assertTrue("author" not in response_data["petitions"][0]) # petition should not contain author because
def test_detail(self): self.client.logout() petition = Petition(author=self.get_user(), **PETITION) petition.save() response = self.client.get( reverse('petition-detail', args=[petition.id])) self.assertEqual(response.status_code, status.HTTP_200_OK) response_data = json.loads(response.content.decode()) self.assertTrue(isinstance(response_data["author"], dict)) # author is nested object
def test_detail(self): self.client.force_authenticate(self.get_staff_user()) petition = Petition(author=self.get_staff_user(), **PETITION) petition.save() response = self.client.get( reverse('user-detail', args=[self.get_staff_user().id])) self.assertEqual(response.status_code, status.HTTP_200_OK) response_data = json.loads(response.content.decode()) self.assertTrue(isinstance(response_data["petitions"][0], dict)) # petition list consists of objects self.assertTrue("author" not in response_data["petitions"] [0]) # petition should not contain author because
async def test_websocket_consumer_get(django_user_model): username = '******' email = '*****@*****.**' password = '******' django_user_model.objects.create(username=username, password=password, email=email) user = django_user_model.objects.get(username=username) Profile.objects.all().delete() Profile.objects.create(user=user, full_name=username, notifications=Notifications.objects.create()) # Remove all petitions Petition.objects.all().delete() # Create Tag tag = Tag(name='TestTag') tag.save() pet = Petition(title='Test petition', description='This is a test petition', author=user, created_at=timezone.now(), status=0, expires=timezone.now() + timedelta(days=30)) pet.save() pet.tags.add(tag) pet.save() communicator = AuthWebsocketCommunicator(PetitionConsumer, "/ws/", user=user) connected, subprotocol = await communicator.connect() assert connected await communicator.send_json_to({"command": "get", "id": 45}) response = await communicator.receive_json_from() assert response == {"command": "get", "petition": False} """ dump = serialize_petitions([pet], user) await communicator.send_json_to({"command": "get", "id": pet.id}) response = await communicator.receive_json_from() assert response == {"command": "get", "petition": dump} """ await communicator.disconnect()
def petition_create(request): """ Endpoint for creating a new petition. This requires the user be signed in. Note: This endpoint returns the ID of the petition created, in order for JavaScript to redirect to the correct petition. """ # Build the user reference. user = request.user new_user_petitions = user.profile.petitions_created.filter(Q(status=0)) if new_user_petitions.count() > 0: return HttpResponse(new_user_petitions.first().id) last_petition = Petition.objects.all().last() # Create a new blank petition. date = timezone.now() new_petition = Petition( title=PETITION_DEFAULT_TITLE, description=PETITION_DEFAULT_BODY, author=user, signatures=0, created_at=date, expires=date + timedelta(days=30), in_progress=False, id=last_petition.id + 1 if last_petition is not None else 0 ) new_petition.save() # Add the petition's ID to the user's created petitions list. petition_id = new_petition.id user.profile.petitions_created.add(petition_id) # Auto-sign the author to the petition. user.profile.petitions_signed.add(new_petition) user.save() new_petition.last_signed = timezone.now() new_petition.signatures = F('signatures') + 1 new_petition.save() logger.info( "user " + user.email + " created a new petition called " + new_petition.title + " ID: " + str(new_petition.id)) # Return the petition's ID to be used to redirect the user to the new petition. return HttpResponse(str(petition_id))
class EmailTests(TestCase): def setUp(self): self.tag = Tag(name='test') self.tag.save() self.user = User.objects.create_user(username='******', email='*****@*****.**') self.user.save() self.petition = Petition(title='test petition', description='This is a test petition', author=self.user,created_at=timezone.now(),status=1, expires=timezone.now()+timedelta(days=30)) self.petition.save() self.user.profile.petitions_signed.add(self.petition) def test_petition_approved(self): petition_approved(self.petition.id, 'test_path') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, EmailTitles.Petition_Approved) def test_petition_rejected(self): petition_rejected(self.petition.id, 'test_path') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, EmailTitles.Petition_Rejected) def test_petition_update(self): petition_update(self.petition.id, 'test_path') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, EmailTitles.Petition_Update) def test_petition_reached(self): petition_reached(self.petition.id, 'test_path') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, EmailTitles.Petition_Reached) def test_petition_received(self): petition_received(self.petition.id, 'test_path') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'PawPrints - Petition received') def test_petition_needs_approval(self): petition_needs_approval(self.petition.id, 'test_path') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, EmailTitles.Petition_Needs_Approval)
def generate_petitions(self, users, expired, unpub, removed, review, sigs, num_petitions, resp): petitionlst = [] self.stdout.write('Generating Petition objects') text = Text('en') try: with transaction.atomic(): for x in range(0, num_petitions): # Generate/Grab data num_sentences = random.randint(1, 6) title = text.sentence()[0:80] description = text.text(num_sentences) author = random.choice(users) if sigs: signatures = sigs.pop() else: signatures = random.randint(1, len(users)) created_at = timezone.now() - timedelta( days=random.randint(0, 10)) status = 1 expires = created_at + timedelta(days=30) last_signed = created_at + timedelta( days=random.randint(0, 10)) petition = Petition() if expired > 0: created_at = timezone.now() - timedelta(days=31) expires = created_at + timedelta(days=30) last_signed = created_at + timedelta( days=random.randint(1, 30)) expired -= 1 elif unpub > 0: status = 0 unpub -= 1 elif removed > 0: status = 2 removed -= 1 elif review > 0: status = 3 review -= 1 petition.author = author petition.title = title petition.description = description petition.signatures = signatures petition.created_at = created_at petition.status = status petition.expires = expires petition.last_signed = last_signed if resp > 0: petition.has_response = True resp -= 1 petition.save() petitionlst.append(petition) self.stdout.write( self.style.SUCCESS('Successfully created %s Petition objects' % num_petitions)) return petitionlst except Exception as e: self.stdout.write( self.style.ERROR( 'Failed to generate %s Petition objects\n %s' % (len(users), e))) print(traceback.format_exc()) return None
class PetitionTest(TestCase): def setUp(self): self.client = Client() self.factory = RequestFactory() self.superUser = User.objects.create_user(username='******', email='txu1267', is_staff=True) self.superUser.set_password('test') self.superUser.save() self.superUser2 = User.objects.create_user(username='******', email='txu1266', is_superuser=True) self.superUser2.set_password('test') self.superUser2.save() self.user = User.objects.create_user(username='******', email='axu7254') self.user2 = User.objects.create_user(username='******', email='cxl1234') self.user3 = User.objects.create_user(username='******', email='abc4321') self.tag = Tag(name='Test') self.tag.save() self.petition = Petition(title='Test petition', description='This is a test petition', author=self.user, created_at=timezone.now(), status=0, expires=timezone.now() + timedelta(days=30)) self.petition.save() self.petition.tags.add(self.tag) self.petitionPublished = Petition( title='Test petition Published', description='This is a test petition Published', author=self.user2, created_at=timezone.now(), status=1, expires=timezone.now() + timedelta(days=30)) self.petitionPublished.save() def test_about_page(self): response = self.client.get('/about/') assert response.status_code == 200 self.assertTemplateUsed(response, 'about.html') def test_maintenance_page(self): response = self.client.get('/maintenance/') assert response.status_code == 200 self.assertTemplateUsed(response, 'Something_Special.html') def test_index_page(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'index.html') def test_404(self): response = self.client.get('/doesnotexist') self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_petition_edit(self): self.client.force_login(self.superUser) # Change petition title to 'New' obj = {"attribute": "title", "value": "New"} response = self.client.post( '/petition/update/' + str(self.petition.id), obj) # Check that it doesn't 404 self.assertNotEqual(response.status_code, 404) # Check that petition was actually changed pet = Petition.objects.get(pk=self.petition.id) self.assertEqual(pet.title, 'New') def test_petition_publish(self): self.client.force_login(self.user) tag = Tag(name='test tag') tag.save() obj = {"attribute": "publish", "value": "foo"} self.petition.status = 0 self.petition.tags.add(tag) self.petition.save() request = self.factory.post( '/petition/update/' + str(self.petition.id), obj) request.META['HTTP_HOST'] = 'localhost' request.user = self.user response = petition_edit(request, self.petition.id) # Make sure there is no 404 self.assertNotEqual(response.status_code, 404) # Check that petition was published pet = Petition.objects.get(pk=self.petition.id) self.assertEqual(pet.status, 1) def test_sign_petition(self): self.client.force_login(self.superUser) response = self.client.post( '/petition/sign/' + str(self.petitionPublished.id), {'test': 'test'}) pet = Petition.objects.get(pk=self.petitionPublished.id) self.assertEqual(pet.signatures, 1) self.assertEqual(response.status_code, 200) def test_petition_subscribe(self): self.client.force_login(self.user) user = User.objects.get(pk=self.user.id) self.assertEqual( user.profile.subscriptions.filter(pk=self.petition.id).exists(), False) response = self.client.post( '/petition/subscribe/' + str(self.petition.id), {}) user = User.objects.get(pk=self.user.id) self.assertEqual( user.profile.subscriptions.filter(pk=self.petition.id).exists(), True) def test_petition_unsubscribe(self): self.client.force_login(self.user) user = User.objects.get(pk=self.user.id) self.assertEqual( user.profile.subscriptions.filter(pk=self.petition.id).exists(), False) response = self.client.post( '/petition/subscribe/' + str(self.petition.id), {}) user = User.objects.get(pk=self.user.id) self.assertEqual( user.profile.subscriptions.filter(pk=self.petition.id).exists(), True) response = self.client.post( '/petition/unsubscribe/' + str(self.petition.id), {}) user = User.objects.get(pk=self.user.id) self.assertEqual( user.profile.subscriptions.filter(pk=self.petition.id).exists(), False) def test_petition_unpublish(self): self.client.force_login(self.superUser) response = self.client.post('/petition/unpublish/' + str(self.petition.id)) self.assertEqual(response.status_code, 200) pet = Petition.objects.get(pk=self.petition.id) self.assertEqual(pet.status, 2) # Test using not super user self.client.force_login(self.user) pet.status = 1 pet.save() response = self.client.post('/petition/unpublish/' + str(self.petition.id)) pet = Petition.objects.get(pk=self.petition.id) self.assertEqual(pet.status, 1) def test_petition_page(self): response = self.client.get('/petition/' + str(self.petition.id)) self.assertEqual(response.status_code, 200) def test_url_redirect_fail(self): self.client.force_login(self.user) response = self.client.get('/petition/' + str(666)) self.assertEqual(response.status_code, 404) def test_create_petition(self): self.client.force_login(self.user) response = self.client.post('/petition/create/') self.assertEqual(response.status_code, 200) userobj = User.objects.get(pk=self.user.id) self.assertEqual(userobj.profile.petitions_signed.all()[0].title, PETITION_DEFAULT_TITLE) def test_check_edit(self): self.client.force_login(self.user) self.assertEqual(edit_check(self.user, self.petition), True) self.assertEqual(edit_check(self.superUser, self.petition), True) self.assertEqual(edit_check(self.superUser2, self.petition), False) self.assertEqual(edit_check(self.user2, self.petition), False) def test_serialize_petitions(self): petitions = Petition.objects.all() json_response = serialize_petitions(petitions) # TODO: Improve this test to be more thorough self.assertNotEqual(json_response, None) def test_url_redirect(self): self.client.force_login(self.user) response = self.client.get('/petitions/' + str(self.petition.id)) self.assertEqual(response.status_code, 302) self.assertRedirects(response, '/?p=' + str(self.petition.id), status_code=302, target_status_code=200) def test_edit_petition_description(self): self.client.force_login(self.superUser) obj = {"attribute": "description", "value": "test test test"} response = self.client.post( '/petition/update/' + str(self.petition.id), obj) self.assertNotEqual(response.status_code, 404) pet = Petition.objects.get(pk=self.petition.id) self.assertEqual(pet.description, "test test test") def test_petition_add_tag(self): self.client.force_login(self.superUser) tag = Tag(name='test tag2') tag.save() obj = {"attribute": "add-tag", "value": tag.id} response = self.client.post( '/petition/update/' + str(self.petition.id), obj) self.assertNotEqual(response.status_code, 404) pet = Petition.objects.get(pk=self.petition.id) if tag not in pet.tags.all(): self.fail("tag not added") def test_petition_remove_tag(self): self.client.force_login(self.superUser) tag = Tag(name='test tag2') tag.save() self.petition.tags.add(tag) self.petition.save() obj = {"attribute": "remove-tag", "value": tag.id} response = self.client.post( '/petition/update/' + str(self.petition.id), obj) self.assertNotEqual(response.status_code, 404) pet = Petition.objects.get(pk=self.petition.id) if tag in pet.tags.all(): self.fail("tag not removed") def test_petition_add_update(self): self.client.force_login(self.superUser) obj = {"attribute": "add_update", "value": "test update"} request = self.factory.post( '/petition/update/' + str(self.petition.id), obj) request.user = self.superUser request.META['HTTP_HOST'] = "random" response = petition_edit(request, self.petition.id) self.assertNotEqual(response.status_code, 404) pet = Petition.objects.get(pk=self.petition.id) fail = True for update in pet.updates.all(): value = update.description if value == "test update": fail = False if fail: self.fail("did not add update") def test_petition_add_response(self): self.client.force_login(self.superUser) obj = {"attribute": "response", "value": "test response"} request = self.factory.post( '/petition/update/' + str(self.petition.id), obj) request.user = self.superUser request.META['HTTP_HOST'] = "random" response = petition_edit(request, self.petition.id) self.assertNotEqual(response.status_code, 404) pet = Petition.objects.get(pk=self.petition.id) if pet.response.description != "test response": self.fail() def test_petition_mark_work_in_progress(self): self.client.force_login(self.superUser) obj = {"attribute": "mark-in-progress"} self.assertEqual(self.petitionPublished.in_progress, None) response = self.client.post( '/petition/update/' + str(self.petitionPublished.id), obj) self.assertNotEqual(response.status_code, 404) pet = Petition.objects.get(pk=self.petitionPublished.id) self.assertEqual(pet.in_progress, True) def test_petition_unpublish_progress(self): self.client.force_login(self.superUser) obj = {"attribute": "unpublish"} self.assertEqual(self.petitionPublished.status, 1) request = self.factory.post( '/petition/update/' + str(self.petitionPublished.id), obj) request.user = self.superUser request.META['HTTP_HOST'] = "random" response = petition_edit(request, self.petitionPublished.id) self.assertNotEqual(response.status_code, 404) pet = Petition.objects.get(pk=self.petitionPublished.id) self.assertEqual(pet.status, 2) def test_get_petition(self): self.client.force_login(self.superUser) petition = get_petition(self.petition.id, self.user) self.assertEqual(petition, self.petition) def test_get_petition_fail(self): self.client.force_login(self.superUser) petition = get_petition(self.petition.id, self.user2) self.assertEqual(petition, False) def test_petition_str(self): assert str(self.petition) == self.petition.title def test_tag_str(self): assert str(self.tag) == self.tag.name def test_response_str(self): resp = Response.objects.create(description='Response', created_at=timezone.now(), author='Test Author') assert str(resp) == 'Test Author'