class TestDownloadReport(MyReportsTestCase): """Tests that reports can be downloaded.""" def setUp(self): super(TestDownloadReport, self).setUp() self.client = TestClient(path=reverse("download_report")) self.client.login_user(self.user) ContactRecordFactory.create_batch(5, partner__owner=self.company) ContactRecordFactory.create_batch(5, contact_type="job", job_applications=1, partner__owner=self.company) ContactRecordFactory.create_batch(5, contact_type="job", job_hires=1, partner__owner=self.company) def test_download_csv(self): """Test that a report can be downloaded in CSV format.""" # create a report whose results is for all contact records in the # company response = self.client.post(path=reverse("reports", kwargs={"app": "mypartners", "model": "contactrecord"})) report_name = response.content report = Report.objects.get(name=report_name) python = report.python # download the report response = self.client.get(data={"id": report.pk, "values": ["contact", "contact_email", "contact_phone"]}) self.assertEqual(response["Content-Type"], "text/csv") # specifying export values shouldn't modify the underlying report self.assertEqual(len(python[0].keys()), len(report.python[0].keys()))
def setUp(self): super(TestDownloads, self).setUp() self.client = TestClient(path=reverse('downloads'), HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.client.login_user(self.user) ContactRecordFactory.create_batch(10, partner__owner=self.company)
class TestDownloadReport(MyReportsTestCase): """Tests that reports can be downloaded.""" def setUp(self): super(TestDownloadReport, self).setUp() self.client = TestClient(path=reverse('download_report')) self.client.login_user(self.user) ContactRecordFactory.create_batch(5, partner__owner=self.company) ContactRecordFactory.create_batch( 5, contact_type='job', job_applications=1, partner__owner=self.company) ContactRecordFactory.create_batch( 5, contact_type='job', job_hires=1, partner__owner=self.company) def test_download_csv(self): """Test that a report can be downloaded in CSV format.""" # create a report whose results is for all contact records in the # company response = self.client.post(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord'})) report_name = response.content report = Report.objects.get(name=report_name) # download the report response = self.client.get(data={'id': report.pk}) self.assertEqual(response['Content-Type'], 'text/csv')
def setUp(self): super(TestSecureBlocks, self).setUp() self.staff_user = UserFactory(is_staff=True) self.client = TestClient() self.client.login_user(self.staff_user) self.sb_url = reverse('secure_blocks') SeoSiteFactory(domain='jobs.example.com')
class TestDownloads(MyReportsTestCase): """Tests the reports view.""" def setUp(self): super(TestDownloads, self).setUp() self.client = TestClient(path=reverse('downloads'), HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.client.login_user(self.user) ContactRecordFactory.create_batch(10, partner__owner=self.company) def test_column_order(self): """Tests that column order is preserved""" # create a report whose results is for all contact records in the # company response = self.client.post( path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord'}), data={'values': ['partner', 'contact__name', 'contact_type']}) report_name = response.content report = Report.objects.get(name=report_name) response = self.client.get(data={'id': report.id}) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['columns'], { 'Partner': True, 'Contact Name': True, 'Contact Type': True})
class RemoteAccessRequestModelTests(MyJobsBase): def setUp(self): super(RemoteAccessRequestModelTests, self).setUp() self.password = '******' self.client = TestClient() self.client.login(email=self.user.email, password=self.password) self.account_owner = UserFactory(email='*****@*****.**', password=self.password) self.impersonate_url = reverse('impersonate-start', kwargs={ 'uid': self.account_owner.pk}) self.site = SeoSite.objects.first() def test_create_request_sends_messages(self): """ The requesting of remote access should send both a My.jobs message and an email to the account owner. """ msg = "User had %s messages, expected %s" mail.outbox = [] spar = SecondPartyAccessRequest.objects.create( account_owner=self.account_owner, second_party=self.user, site=self.site, reason='just cuz') self.assertEqual(len(mail.outbox), 1) # We're logged in as the requesting user at this point and should # not have any messages. response = self.client.get(reverse('home')) self.assertEqual(len(response.context['new_messages']), 0, msg=msg % (len(response.context['new_messages']), 0)) response = self.client.get(reverse('impersonate-approve', kwargs={'access_id': spar.id})) self.assertEqual(response.status_code, 403, msg=("Unauthorized approval of a request should not " "happen but did")) # Log out then log in as the account owner. self.client.get(reverse('auth_logout')) self.client.login(email=self.account_owner.email, password=self.password) response = self.client.get(reverse('home')) # We should now have one My.jobs message. messages = response.context['new_messages'] self.assertEqual(len(messages), 1, msg=msg % (len(response.context['new_messages']), 1)) message = messages[0] email = mail.outbox[0] self.assertEqual(message.message.body, email.body, msg="Message and email bodies were not identical") for text in ['>Allow<', '>Deny<', spar.reason, self.user.get_full_name(default=self.user.email)]: self.assertTrue(text in email.body, msg="%s not in email body" % text) response = self.client.get(reverse('impersonate-approve', kwargs={'access_id': spar.id})) spar = SecondPartyAccessRequest.objects.get(pk=spar.pk) self.assertEqual(spar.accepted, True, msg="Acceptance status was not updated")
def setUp(self): super(MyJobsHelpersTests, self).setUp() self.client = TestClient() self.login_params = { 'username': '******', 'password': '******', 'action': 'login' }
def setUp(self): super(TestViewRecords, self).setUp() self.client = TestClient(path='/reports/ajax/mypartners', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.client.login_user(self.user) ContactRecordFactory.create_batch(10, partner=self.partner, contact__name='Joe Shmoe')
def setUp(self): super(UserResourceTestCase, self).setUp() create_api_key(User, instance=self.user, created=True) self.client = TestClient(path='/api/v1/user/', data={ 'email': '*****@*****.**', 'username': self.user.email, 'api_key': self.user.api_key.key })
def setUp(self): super(TestRegenerate, self).setUp() self.client = TestClient(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord' })) self.client.login_user(self.user) ContactRecordFactory.create_batch(10, partner__owner=self.company)
def setUp(self): super(SavedSearchResourceTestCase, self).setUp() self.client = TestClient(path='/api/v1/savedsearch/', data={ 'email': '*****@*****.**', 'url': 'www.my.jobs/jobs' }) create_api_key(User, instance=self.user, created=True) self.client.data['username'] = self.user.email self.client.data['api_key'] = self.user.api_key.key
def setUp(self): super(MessageViewTests, self).setUp() self.message = Message.objects.create(subject='subject', body='body', message_type='success') for group in Group.objects.all(): self.message.group.add(group.pk) self.messageinfo = MessageInfo.objects.create(user=self.user, message=self.message) self.client = TestClient() self.client.login_user(self.user)
def setUp(self): super(RemoteAccessRequestModelTests, self).setUp() self.password = '******' self.client = TestClient() self.client.login(email=self.user.email, password=self.password) self.account_owner = UserFactory(email='*****@*****.**', password=self.password) self.impersonate_url = reverse('impersonate-start', kwargs={'uid': self.account_owner.pk}) self.site = SeoSite.objects.first()
def setUp(self): super(TestDownloadReport, self).setUp() self.client = TestClient(path=reverse('download_report')) self.client.login_user(self.user) ContactRecordFactory.create_batch(5, partner__owner=self.company) ContactRecordFactory.create_batch(5, contact_type='job', job_applications=1, partner__owner=self.company) ContactRecordFactory.create_batch(5, contact_type='job', job_hires=1, partner__owner=self.company)
class TestReportView(MyReportsTestCase): """ Tests the ReportView class, which is used to create and retrieve reports. """ def setUp(self): super(TestReportView, self).setUp() self.client = TestClient(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord'})) self.client.login_user(self.user) ContactRecordFactory.create_batch(5, partner__owner=self.company) ContactRecordFactory.create_batch( 5, contact_type='job', job_applications=1, partner__owner=self.company) ContactRecordFactory.create_batch( 5, contact_type='job', job_hires=1, partner__owner=self.company) def test_create_report(self): """Test that a report model instance is properly created.""" # create a report whose results is for all contact records in the # company response = self.client.post() report_name = response.content report = Report.objects.get(name=report_name) self.assertEqual(len(report.python), 15) # we use this in other tests return report_name def test_get_report(self): """Test that chart data is retreived from record results.""" report_name = self.test_create_report() report = Report.objects.get(name=report_name) response = self.client.get(data={'id': report.pk}) data = json.loads(response.content) # check contact record stats for key in ['applications', 'hires', 'communications', 'emails']: self.assertEqual(data[key], 5) # check contact stats self.assertEqual(data['contacts'][0]['records'], 1) self.assertEqual(data['contacts'][0]['referrals'], 10)
def test_not_disabled(self): """ An anonymous user who provides the :verify: query string or user with is_disabled set to True should be redirected to the home page. An anonymous user who does not should see a 404. A user with is_active set to False should proceed to their destination. """ client = TestClient() user = UserFactory(email="*****@*****.**") # Anonymous user resp = client.get(reverse('view_profile')) path = resp.request.get('PATH_INFO') self.assertRedirects(resp, reverse('home') + '?next=' + path) # This is ugly, but it is an artifact of the way Django redirects # users who fail the `user_passes_test` decorator. qs = '?verify=%s' % user.user_guid next_qs = '?next=' + urlquote('/profile/view/%s' % qs) # Anonymous user navigates to url with :verify: in query string resp = client.get(reverse('view_profile') + qs) # Old path + qs is urlquoted and added to the url as the :next: param self.assertRedirects(resp, "http://testserver/" + next_qs) # Active user client.login_user(user) resp = client.get(reverse('view_profile')) self.assertTrue(resp.status_code, 200) # Disabled user user.is_disabled = True user.save() resp = client.get(reverse('view_profile')) self.assertRedirects(resp, "http://testserver/?next=/profile/view/")
class MyReportsTestCase(TestCase): """ Base class for all MyReports Tests. Identical to `django.test.TestCase` except that it provides a MyJobs TestClient instance and a logged in user. """ def setUp(self): self.client = TestClient() self.user = UserFactory(email='*****@*****.**') self.company = CompanyFactory(name='Test Company') self.partner = PartnerFactory(name='Test Partner', owner=self.company) # associate company to user CompanyUserFactory(user=self.user, company=self.company) self.client.login_user(self.user)
class MyJobsHelpersTests(MyJobsBase): def setUp(self): super(MyJobsHelpersTests, self).setUp() self.user = UserFactory() self.client = TestClient() self.login_params = {'username': '******', 'password': '******', 'action': 'login'} def test_login_dont_remember_me(self): self.assertEqual(Session.objects.count(), 0) response = self.client.post(reverse('home'), data=self.login_params) self.assertEqual(Session.objects.count(), 1) session = Session.objects.all()[0] session_dict = session.get_decoded() user_id = session_dict['_auth_user_id'] self.assertEqual(user_id, self.user.id) # session.expire_date is tz aware; datetime.datetime.now is naive # It probably isn't worth it to bring in pytz just for tests now = datetime.datetime.now(session.expire_date.tzinfo) diff = session.expire_date - now # Due to the delay between the post at the top of this test # and reaching this line, this can't be an assertEquals; self.assertTrue(880 <= diff.total_seconds() <= 900) def test_login_remember_me(self): self.assertEqual(Session.objects.count(), 0) self.login_params['remember_me'] = True response = self.client.post(reverse('home'), data=self.login_params) self.assertEqual(Session.objects.count(), 1) session = Session.objects.all()[0] session_dict = session.get_decoded() user_id = session_dict['_auth_user_id'] self.assertEqual(user_id, self.user.id) weeks = (datetime.datetime.now() + datetime.timedelta(days=14)) # Session expiration should be two weeks from now - comparing number # of days should be good enough self.assertEqual(session.expire_date.toordinal(), weeks.toordinal())
def setUp(self): super(TestRegenerate, self).setUp() self.client = TestClient(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord'})) self.client.login_user(self.user) ContactRecordFactory.create_batch(10, partner__owner=self.company)
def setUp(self): super(MySearchViewTests, self).setUp() self.client = TestClient() self.user = UserFactory() self.client.login_user(self.user) self.new_form_data = { 'url': 'www.my.jobs/jobs', 'feed': 'http://www.my.jobs/jobsfeed/rss?', 'label': 'Jobs Label', 'email': self.user.email, 'frequency': 'D', 'is_active': 'True', 'jobs_per_email': 5, 'sort_by': 'Relevance', } self.new_digest_data = { 'is_active': 'True', 'user': self.user, 'email': self.user.email, 'frequency': 'M', 'day_of_month': 1, } self.new_form = forms.SavedSearchForm(user=self.user, data=self.new_form_data) self.patcher = patch('urllib2.urlopen', return_file()) self.patcher.start()
def setUp(self): super(MyJobsHelpersTests, self).setUp() self.client = TestClient() self.login_params = {'username': '******', 'password': '******', 'action': 'login'}
def setUp(self): super(MyDashboardViewsTests, self).setUp() self.staff_user = UserFactory() group = Group.objects.get(name=CompanyUser.GROUP_NAME) self.staff_user.groups.add(group) self.business_unit = BusinessUnitFactory() self.company = CompanyFactory(id=1) self.company.job_source_ids.add(self.business_unit) self.admin = CompanyUserFactory(user=self.staff_user, company=self.company) self.microsite = SeoSiteFactory() self.microsite.business_units.add(self.business_unit) self.client = TestClient() self.client.login_user(self.staff_user) self.candidate_user = UserFactory(email="*****@*****.**") SavedSearchFactory(user=self.candidate_user, feed='http://test.jobs/jobs/feed/rss?', url='http://test.jobs/search?q=django', label='test Jobs') for i in range(5): # Create 5 new users user = UserFactory(email='*****@*****.**' % i) for search in SEARCH_OPTS: # Create 15 new searches and assign three per user SavedSearchFactory(user=user, url='http://test.jobs/search?q=%s' % search, feed='http://test.jobs/jobs/feed/rss?', label='%s Jobs' % search) update_solr_task(settings.TEST_SOLR_INSTANCE)
def setUp(self): super(UserResourceTestCase, self).setUp() create_api_key(User, instance=self.user, created=True) self.client = TestClient( path="/api/v1/user/", data={"email": "*****@*****.**", "username": self.user.email, "api_key": self.user.api_key.key}, )
def setUp(self): super(TestViewRecords, self).setUp() self.client = TestClient(path='/reports/ajax/mypartners', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.client.login_user(self.user) ContactRecordFactory.create_batch( 10, partner=self.partner, contact__name='Joe Shmoe')
def setUp(self): super(UserResourceTests, self).setUp() create_api_key(User, instance=self.user, created=True) self.client = TestClient( path='/api/v1/user/', data={'email': '*****@*****.**', 'username': self.user.email, 'api_key': self.user.api_key.key})
def setUp(self): super(TestReportView, self).setUp() self.client = TestClient(path=reverse("reports", kwargs={"app": "mypartners", "model": "contactrecord"})) self.client.login_user(self.user) ContactRecordFactory.create_batch(5, partner__owner=self.company) ContactRecordFactory.create_batch(5, contact_type="job", job_applications=1, partner__owner=self.company) ContactRecordFactory.create_batch(5, contact_type="job", job_hires=1, partner__owner=self.company)
def setUp(self): super(SavedSearchResourceTestCase, self).setUp() self.client = TestClient( path="/api/v1/savedsearch/", data={"email": "*****@*****.**", "url": "www.my.jobs/jobs"} ) create_api_key(User, instance=self.user, created=True) self.client.data["username"] = self.user.email self.client.data["api_key"] = self.user.api_key.key
def setUp(self): super(TestDownloadReport, self).setUp() self.client = TestClient(path=reverse("download_report")) self.client.login_user(self.user) ContactRecordFactory.create_batch(5, partner__owner=self.company) ContactRecordFactory.create_batch(5, contact_type="job", job_applications=1, partner__owner=self.company) ContactRecordFactory.create_batch(5, contact_type="job", job_hires=1, partner__owner=self.company)
def test_not_disabled(self): """ An anonymous user who provides the :verify: query string or user with is_disabled set to True should be redirected to the home page. An anonymous user who does not should see a 404. A user with is_active set to False should proceed to their destination. """ client = TestClient() user = UserFactory() #Anonymous user resp = client.get(reverse('view_profile')) path = resp.request.get('PATH_INFO') self.assertRedirects(resp, reverse('home') + '?next=' + path) # This is ugly, but it is an artifact of the way Django redirects # users who fail the `user_passes_test` decorator. qs = '?verify=%s' % user.user_guid next_qs = '?next=' + urlquote('/profile/view/%s' % qs) # Anonymous user navigates to url with :verify: in query string resp = client.get(reverse('view_profile') + qs) # Old path + qs is urlquoted and added to the url as the :next: param self.assertRedirects(resp, "http://testserver/" + next_qs) # Active user client.login_user(user) resp = client.get(reverse('view_profile')) self.assertTrue(resp.status_code, 200) #Disabled user user.is_disabled = True user.save() resp = client.get(reverse('view_profile')) self.assertRedirects(resp, "http://testserver/?next=/profile/view/")
def setUp(self): super(SavedSearchResourceTests, self).setUp() self.client = TestClient( path='/api/v1/savedsearch/', data={'email': '*****@*****.**', 'url': 'www.my.jobs/jobs'}) create_api_key(User, instance=self.user, created=True) self.client.data['username'] = self.user.email self.client.data['api_key'] = self.user.api_key.key
def setUp(self): super(MySignOn, self).setUp() self.user = UserFactory() self.auth_callback_url = 'https://secure.my.jobs/account' self.auth_callback = '?auth_callback=%s' % self.auth_callback_url self.key_qs = '%s&key=%s' self.client = TestClient() self.client.login_user(self.user)
class UserResourceTestCase(MyJobsBase): def setUp(self): super(UserResourceTestCase, self).setUp() create_api_key(User, instance=self.user, created=True) self.client = TestClient(path='/api/v1/user/', data={ 'email': '*****@*****.**', 'username': self.user.email, 'api_key': self.user.api_key.key }) def test_create_new_user(self): self.assertEqual(len(mail.outbox), 0) response = self.client.get() self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Account Activation for my.jobs') content = json.loads(response.content) self.assertEqual(content, { 'user_created': True, 'email': '*****@*****.**' }) self.assertEqual(response.status_code, 200) self.assertEqual(User.objects.count(), 2) user = User.objects.get(email=self.client.data['email']) for field, value in [('is_active', True), ('is_verified', False)]: self.assertEqual(getattr(user, field), value) def test_no_email(self): self.client.data['email'] = '' response = self.client.get() content = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(content['email'], 'No email provided') def test_existing_user(self): for email in [self.user.email, self.user.email.upper()]: self.client.data['email'] = email response = self.client.get() content = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertFalse(content['user_created']) self.assertEqual(content['email'].lower(), '*****@*****.**')
def setUp(self): super(MergeUserTests, self).setUp() self.client = TestClient() self.password = '******' self.key = '56effea3df2bcdcfe377ca4bf30f2844be47d012' self.existing = User.objects.create(email="*****@*****.**", user_guid="a") self.existing.set_password(self.password) self.new_user = User.objects.create(email="*****@*****.**", user_guid="b") self.activation_profile = ActivationProfile.objects.create( user=self.new_user, email="*****@*****.**") self.activation_profile.activation_key = self.key self.activation_profile.save() self.partner = PartnerFactory() for _ in range(0, 10): Contact.objects.create(user=self.new_user, partner=self.partner) SavedSearch.objects.create(user=self.new_user)
def setUp(self): self.client = TestClient() self.user = UserFactory(email='*****@*****.**') self.company = CompanyFactory(name='Test Company') self.partner = PartnerFactory(name='Test Partner', owner=self.company) # associate company to user CompanyUserFactory(user=self.user, company=self.company) self.client.login_user(self.user)
def test_inactive_user_sees_message(self): """ A user with is_verified or is_active set to False should see an activation message instead of the content they were originally meaning to see. """ client = TestClient(path=reverse('saved_search_main')) user = UserFactory() # Active user client.login_user(user) resp = client.get() self.assertIn('Saved Search', resp.content) # Inactive user user.is_verified= False user.save() resp = client.get() self.assertIn('unavailable', resp.content)
class TestDownloadReport(MyReportsTestCase): """Tests that reports can be downloaded.""" def setUp(self): super(TestDownloadReport, self).setUp() self.client = TestClient(path=reverse('download_report')) self.client.login_user(self.user) ContactRecordFactory.create_batch(5, partner__owner=self.company) ContactRecordFactory.create_batch(5, contact_type='job', job_applications=1, partner__owner=self.company) ContactRecordFactory.create_batch(5, contact_type='job', job_hires=1, partner__owner=self.company) def test_download_csv(self): """Test that a report can be downloaded in CSV format.""" # create a report whose results is for all contact records in the # company response = self.client.post(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord' })) report_name = response.content report = Report.objects.get(name=report_name) python = report.python # download the report response = self.client.get( data={ 'id': report.pk, 'values': ['contact', 'contact_email', 'contact_phone'] }) self.assertEqual(response['Content-Type'], 'text/csv') # specifying export values shouldn't modify the underlying report self.assertEqual(len(python[0].keys()), len(report.python[0].keys()))
class UserResourceTests(MyJobsBase): def setUp(self): super(UserResourceTests, self).setUp() self.user = UserFactory() create_api_key(User, instance=self.user, created=True) self.client = TestClient( path='/api/v1/user/', data={'email': '*****@*****.**', 'username': self.user.email, 'api_key': self.user.api_key.key}) def test_create_new_user(self): self.assertEqual(len(mail.outbox), 0) response = self.client.get() self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Account Activation for my.jobs') content = json.loads(response.content) self.assertEqual(content, {'user_created': True, 'email': '*****@*****.**'}) self.assertEqual(response.status_code, 200) self.assertEqual(User.objects.count(), 2) user = User.objects.get(email=self.client.data['email']) for field, value in [('is_active', True), ('is_verified', False)]: self.assertEqual(getattr(user, field), value) def test_no_email(self): self.client.data['email'] = '' response = self.client.get() content = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(content['email'], 'No email provided') def test_existing_user(self): for email in [self.user.email, self.user.email.upper()]: self.client.data['email'] = email response = self.client.get() content = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertFalse(content['user_created']) self.assertEqual(content['email'].lower(), '*****@*****.**')
def setUp(self): super(RemoteAccessRequestModelTests, self).setUp() self.password = '******' self.client = TestClient() self.client.login(email=self.user.email, password=self.password) self.account_owner = UserFactory(email='*****@*****.**', password=self.password) self.impersonate_url = reverse('impersonate-start', kwargs={ 'uid': self.account_owner.pk}) self.site = SeoSite.objects.first()
def setUp(self): super(SavedSearchResourceTests, self).setUp() self.user = UserFactory() self.client = TestClient( path='/api/v1/savedsearch/', data={'email': '*****@*****.**', 'url': 'www.my.jobs/jobs'}) create_api_key(User, instance=self.user, created=True) self.credentials = (self.user.email, self.user.api_key.key) self.patcher = patch('urllib2.urlopen', return_file()) self.patcher.start()
def setUp(self): super(TestReportView, self).setUp() self.client = TestClient(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord'})) self.client.login_user(self.user) ContactRecordFactory.create_batch(5, partner__owner=self.company) ContactRecordFactory.create_batch( 5, contact_type='job', job_applications=1, partner__owner=self.company) ContactRecordFactory.create_batch( 5, contact_type='job', job_hires=1, partner__owner=self.company)
def setUp(self): super(TestReportView, self).setUp() self.client = TestClient(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord' })) self.client.login_user(self.user) ContactRecordFactory.create_batch(5, partner=self.partner) ContactRecordFactory.create_batch(5, contact_type='job', job_applications="1", job_interviews="0", job_hires="0", partner=self.partner) ContactRecordFactory.create_batch(5, contact_type='job', job_applications="0", job_interviews="0", job_hires="1", partner=self.partner)
class UserResourceTestCase(MyJobsBase): def setUp(self): super(UserResourceTestCase, self).setUp() create_api_key(User, instance=self.user, created=True) self.client = TestClient( path="/api/v1/user/", data={"email": "*****@*****.**", "username": self.user.email, "api_key": self.user.api_key.key}, ) def test_create_new_user(self): self.assertEqual(len(mail.outbox), 0) response = self.client.get() self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Account Activation for my.jobs") content = json.loads(response.content) self.assertEqual(content, {"user_created": True, "email": "*****@*****.**"}) self.assertEqual(response.status_code, 200) self.assertEqual(User.objects.count(), 2) user = User.objects.get(email=self.client.data["email"]) for field, value in [("is_active", True), ("is_verified", False)]: self.assertEqual(getattr(user, field), value) def test_no_email(self): self.client.data["email"] = "" response = self.client.get() content = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(content["email"], "No email provided") def test_existing_user(self): for email in [self.user.email, self.user.email.upper()]: self.client.data["email"] = email response = self.client.get() content = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertFalse(content["user_created"]) self.assertEqual(content["email"].lower(), "*****@*****.**")
class TestDownloads(MyReportsTestCase): """Tests the reports view.""" def setUp(self): super(TestDownloads, self).setUp() self.client = TestClient(path=reverse('downloads'), HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.client.login_user(self.user) ContactRecordFactory.create_batch(10, partner__owner=self.company) def test_column_order(self): """Tests that column order is preserved""" # create a report whose results is for all contact records in the # company response = self.client.post(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord' })) report_name = response.content report = Report.objects.get(name=report_name) report.values = json.dumps(['partner', 'contact name', 'contact_type']) report.save() response = self.client.get(data={'id': report.id}) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['columns'].items()[:3], [('Partner', True), ('Contact Name', True), ('Communication Type', True)]) def test_blacklisted_columns(self): """Test that blacklisted columns aren't visible.""" blacklist = ['pk', 'approval_status'] response = self.client.post( path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord' }), data={'values': ['partner', 'contact__name', 'contact_type']}) report_name = response.content report = Report.objects.get(name=report_name) response = self.client.get(data={'id': report.id}) self.assertFalse( set(response.context['columns']).intersection(blacklist))
def test_inactive_user_sees_message(self): """ A user with is_verified or is_active set to False should see an activation message instead of the content they were originally meaning to see. """ client = TestClient(path=reverse('saved_search_main')) user = UserFactory(email="*****@*****.**") # Active user client.login_user(user) resp = client.get() self.assertIn('Saved Search', resp.content) # Inactive user user.is_verified = False user.save() resp = client.get() self.assertIn('unavailable', resp.content)
class RemoteAccessRequestModelTests(MyJobsBase): def setUp(self): super(RemoteAccessRequestModelTests, self).setUp() self.password = '******' self.client = TestClient() self.client.login(email=self.user.email, password=self.password) self.account_owner = UserFactory(email='*****@*****.**', password=self.password) self.impersonate_url = reverse('impersonate-start', kwargs={'uid': self.account_owner.pk}) self.site = SeoSite.objects.first() def test_create_request_sends_messages(self): """ The requesting of remote access should send both a My.jobs message and an email to the account owner. """ msg = "User had %s messages, expected %s" mail.outbox = [] spar = SecondPartyAccessRequest.objects.create( account_owner=self.account_owner, second_party=self.user, site=self.site, reason='just cuz') self.assertEqual(len(mail.outbox), 1) # We're logged in as the requesting user at this point and should # not have any messages. response = self.client.get(reverse('home')) self.assertEqual(len(response.context['new_messages']), 0, msg=msg % (len(response.context['new_messages']), 0)) response = self.client.get( reverse('impersonate-approve', kwargs={'access_id': spar.id})) self.assertEqual(response.status_code, 403, msg=("Unauthorized approval of a request should not " "happen but did")) # Log out then log in as the account owner. self.client.get(reverse('auth_logout')) self.client.login(email=self.account_owner.email, password=self.password) response = self.client.get(reverse('home')) # We should now have one My.jobs message. messages = response.context['new_messages'] self.assertEqual(len(messages), 1, msg=msg % (len(response.context['new_messages']), 1)) message = messages[0] email = mail.outbox[0] self.assertEqual(message.message.body, email.body, msg="Message and email bodies were not identical") for text in [ '>Allow<', '>Deny<', spar.reason, self.user.get_full_name(default=self.user.email) ]: self.assertTrue(text in email.body, msg="%s not in email body" % text) response = self.client.get( reverse('impersonate-approve', kwargs={'access_id': spar.id})) spar = SecondPartyAccessRequest.objects.get(pk=spar.pk) self.assertEqual(spar.accepted, True, msg="Acceptance status was not updated")
class TestReportView(MyReportsTestCase): """ Tests the ReportView class, which is used to create and retrieve reports. """ def setUp(self): super(TestReportView, self).setUp() self.client = TestClient(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord' })) self.client.login_user(self.user) ContactRecordFactory.create_batch(5, partner=self.partner) ContactRecordFactory.create_batch(5, contact_type='job', job_applications="1", job_interviews="0", job_hires="0", partner=self.partner) ContactRecordFactory.create_batch(5, contact_type='job', job_applications="0", job_interviews="0", job_hires="1", partner=self.partner) def test_create_report(self): """Test that a report model instance is properly created.""" # create a report whose results is for all contact records in the # company response = self.client.post() report_name = response.content report = Report.objects.get(name=report_name) self.assertEqual(len(report.python), 15) # we use this in other tests return report_name def test_get_report(self): """Test that chart data is retreived from record results.""" report_name = self.test_create_report() report = Report.objects.get(name=report_name) response = self.client.get(data={'id': report.pk}) data = json.loads(response.content) # check contact record stats for key in ['applications', 'hires', 'communications', 'emails']: self.assertEqual(data[key], 5) for contact in data['contacts']: self.assertTrue(contact['records'] < 2) self.assertTrue(contact['referrals'] < 2) total = contact['records'] + contact['referrals'] self.assertEqual(total, 1) def test_reports_exclude_archived(self): """ Test that reports exclude archived records as appropriate. This includes non-archived records associated with archived records. """ self.client.path = reverse('view_records', kwargs={ 'app': 'mypartners', 'model': 'contactrecord' }) response = self.client.post(HTTP_X_REQUESTED_WITH='XMLHttpRequest') content = json.loads(response.content) self.assertEqual(len(content), 15) ContactRecord.objects.last().archive() # Archiving one communication record should result in one fewer entry # in the returned json. response = self.client.post(HTTP_X_REQUESTED_WITH='XMLHttpRequest') content = json.loads(response.content) self.assertEqual(len(content), 14) Partner.objects.last().archive() # Archiving the partner governing these communication records should # exclude all of them from the returned json even if they aren't # archived. response = self.client.post(HTTP_X_REQUESTED_WITH='XMLHttpRequest') content = json.loads(response.content) self.assertEqual(len(content), 0)
class MyJobsHelpersTests(MyJobsBase): def setUp(self): super(MyJobsHelpersTests, self).setUp() self.client = TestClient() self.login_params = { 'username': '******', 'password': '******', 'action': 'login' } def test_login_dont_remember_me(self): # MyJobsBase logs in a user, so we're clearing that session first self.client.logout() Session.objects.all().delete() self.assertEqual(Session.objects.count(), 0) self.client.post(reverse('home'), data=self.login_params) self.assertEqual(Session.objects.count(), 1) session = Session.objects.all()[0] session_dict = session.get_decoded() user_id = session_dict['_auth_user_id'] self.assertEqual(user_id, self.user.id) # session.expire_date is tz aware; datetime.datetime.now is naive # It probably isn't worth it to bring in pytz just for tests now = datetime.datetime.now(session.expire_date.tzinfo) diff = session.expire_date - now # Due to the delay between the post at the top of this test # and reaching this line, this can't be an assertEquals; self.assertTrue(880 <= diff.total_seconds() <= 900) def test_login_remember_me(self): # MyJobsBase logs in a user, so we're clearing that session first self.client.logout() Session.objects.all().delete() self.assertEqual(Session.objects.count(), 0) self.login_params['remember_me'] = True self.client.post(reverse('home'), data=self.login_params) self.assertEqual(Session.objects.count(), 1) session = Session.objects.all()[0] session_dict = session.get_decoded() user_id = session_dict['_auth_user_id'] self.assertEqual(user_id, self.user.id) weeks = (datetime.datetime.now() + datetime.timedelta(days=14)) # Session expiration should be two weeks from now - comparing number # of days should be good enough self.assertEqual(session.expire_date.toordinal(), weeks.toordinal()) def test_extract_value(self): """Tests that the proper values are extracted from an object.""" class Foo(object): value = 'foo' class Bar(object): value = 'bar' foo = Foo() foo = Foo() bar = Bar() # single-level object traversal self.assertEqual(extract_value(foo, 'value'), 'foo') self.assertEqual(extract_value(foo, 'bar'), None) # default values self.assertEqual(extract_value(foo, 'bar', default='bar'), 'bar') self.assertEqual(extract_value(foo, 'value', default='bar'), 'foo') # multiple-level object traversal self.assertEqual(extract_value(bar, 'foo', 'value'), 'foo') self.assertEqual(extract_value(bar, 'foo', 'buz'), None)
class TestRegenerate(MyReportsTestCase): """Tests the reports can be regenerated.""" def setUp(self): super(TestRegenerate, self).setUp() self.client = TestClient(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord' })) self.client.login_user(self.user) ContactRecordFactory.create_batch(10, partner__owner=self.company) def test_regenerate(self): # create a new report response = self.client.post(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord' })) report_name = response.content report = Report.objects.get(name=report_name) response = self.client.get(data={'id': report.id}) self.assertEqual(response.status_code, 200) # remove report results and ensure we can still get a reasonable # response report.results.delete() report.save() self.assertFalse(report.results) response = self.client.get(data={'id': report.id}) self.assertEqual(response.status_code, 200) # regenerate results and ensure they are the same as the original response = self.client.get(path=reverse('regenerate'), data={'id': report.pk}) report = Report.objects.get(name=report_name) self.assertEqual(response.status_code, 200) self.assertTrue(report.results) # regenerate report without deleting the report prior # see if it overwrites other report. results = report.results response = self.client.get(path=reverse('regenerate'), data={'id': report.pk}) report = Report.objects.get(name=report_name) self.assertEqual(response.status_code, 200) self.assertEqual(results.name, report.results.name) def test_regenerating_missing_file(self): """Tests that a report can be regenerated when file is missing.""" # create a new report response = self.client.post(path=reverse('reports', kwargs={ 'app': 'mypartners', 'model': 'contactrecord' })) report_name = response.content report = Report.objects.get(name=report_name) # report should have results self.assertTrue(report.results) # delete physical file and ensure that json reflects the missing link os.remove(report.results.file.name) report = Report.objects.get(pk=report.pk) self.assertEqual(report.json, u'{}') self.assertEqual(report.python, {}) # regenerate the report even though the file is physically missing report.regenerate() self.assertTrue(report.results)
def setUp(self): super(MyProfileViewsTests, self).setUp() self.client = TestClient() self.client.login_user(self.user) self.name = PrimaryNameFactory(user=self.user)
class TestViewRecords(MyReportsTestCase): """ Tests the `view_records` view which is used to query various models. """ def setUp(self): super(TestViewRecords, self).setUp() self.client = TestClient(path='/reports/ajax/mypartners', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.client.login_user(self.user) ContactRecordFactory.create_batch(10, partner=self.partner, contact__name='Joe Shmoe') def test_restricted_to_ajax(self): """View should only be reachable through AJAX.""" self.client.path += '/partner' self.client.defaults.pop('HTTP_X_REQUESTED_WITH') response = self.client.post() self.assertEqual(response.status_code, 404) def test_restricted_to_post(self): """POST requests should raise a 404.""" self.client.path += '/partner' response = self.client.get() self.assertEqual(response.status_code, 404) def test_json_output(self): """Test that filtering contact records through ajax works properly.""" # records to be filtered out ContactRecordFactory.create_batch(10, contact__name='John Doe') self.client.path += '/contactrecord' filters = json.dumps({'contact': {'name': {'icontains': 'Joe Shmoe'}}}) response = self.client.post(data={'filters': filters}) output = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(len(output), 10) def test_only_user_results_returned(self): """Results should only contain records user has access to.""" # records not owned by user partner = PartnerFactory(name="Wrong Partner") ContactRecordFactory.create_batch(10, partner=partner) self.client.path += '/contactrecord' response = self.client.post() output = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(len(output), 10) def test_filtering_on_model(self): """Test the ability to filter on a model's field's.""" # we already have one because of self.partner PartnerFactory.create_batch(9, name='Test Partner', owner=self.company) self.client.path += '/partner' filters = json.dumps({'name': {'icontains': 'Test Partner'}}) response = self.client.post(data={'filters': filters}) output = json.loads(response.content) # ContactRecordFactory creates 10 partners in setUp self.assertEqual(response.status_code, 200) self.assertEqual(len(output), 10) def test_filtering_on_foreign_key(self): """Test the ability to filter on a model's foreign key fields.""" PartnerFactory.create_batch(5, name='Test Partner', owner=self.company) ContactRecordFactory.create_batch(5, partner=self.partner, contact__name='Jane Doe') self.client.path += '/partner' filters = json.dumps({ 'name': { 'icontains': 'Test Partner', }, 'contactrecord': { 'contact': { 'name': { 'icontains': 'Jane Doe' } } } }) response = self.client.post(data={'filters': filters}) output = json.loads(response.content) self.assertEqual(response.status_code, 200) # We look for distinct records self.assertEqual(len(output), 1) def test_list_query_params(self): """Test that query parameters that are lists are parsed correctly.""" contacts = ContactFactory.create_batch(10, partner__owner=self.company) pks = [contact.pk for contact in contacts[:5]] self.client.path += '/partner' filters = json.dumps({'contact': {'in': pks}}) response = self.client.post(data={'filters': filters}) output = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(len(output), 5)
class MergeUserTests(MyJobsBase): def setUp(self): super(MergeUserTests, self).setUp() self.client = TestClient() self.password = '******' self.key = '56effea3df2bcdcfe377ca4bf30f2844be47d012' self.existing = User.objects.create(email="*****@*****.**", user_guid="a") self.existing.set_password(self.password) self.new_user = User.objects.create(email="*****@*****.**", user_guid="b") self.activation_profile = ActivationProfile.objects.create( user=self.new_user, email="*****@*****.**") self.activation_profile.activation_key = self.key self.activation_profile.save() self.partner = PartnerFactory() for _ in range(0, 10): Contact.objects.create(user=self.new_user, partner=self.partner) SavedSearch.objects.create(user=self.new_user) def test_expired_key_doesnt_merge(self): expired_request = self.activation_profile expired_request.sent -= datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS) expired_request.save() self.client.login_user(self.existing) merge_url = reverse('merge_accounts', kwargs={'activation_key': self.key}) response = self.client.get(merge_url) self.assertTrue( User.objects.filter(email=self.new_user.email).exists(), msg="The new user should not have been deleted.") self.assertEqual(response.status_code, 200, msg=("The page should have returned a 200 code." \ "Instead received %s" % response.status_code)) phrases = [ 'Something went wrong while merging your account.', "The activation code was wrong", "Your account has already been merged", "You waited longer than 2 weeks to activate your account" ] for phrase in phrases: self.assertIn(phrase, response.content, msg=\ "The phrase '%s' is missing from the final response" % phrase) def test_invalid_key_doesnt_merge(self): self.client.login_user(self.existing) key = self.key.replace('5', 'b') merge_url = reverse('merge_accounts', kwargs={'activation_key': key}) response = self.client.get(merge_url) self.assertTrue( User.objects.filter(email=self.new_user.email).exists(), msg="The new user should not have been deleted.") self.assertEqual(response.status_code, 200, msg=("The page should have returned a 200 code." \ "Instead received %s" % response.status_code)) phrases = [ 'Something went wrong while merging your account.', "The activation code was wrong", "Your account has already been merged", "You waited longer than 2 weeks to activate your account" ] for phrase in phrases: self.assertIn(phrase, response.content, msg=\ "The phrase '%s' is missing from the final response" % phrase) def test_successfully_merged_account(self): self.client.login_user(self.existing) # Access the merge URL merge_url = reverse('merge_accounts', kwargs={'activation_key': self.key}) response = self.client.get(merge_url) self.assertEqual(response.status_code, 200, msg=("The page should have returned a 200 code." "Instead received %s" % response.status_code)) # Assert the correct text is displayed. phrases = [ 'Your account has been successfully merged, and you are'\ ' now logged in.', "Add to your profile", "Manage your saved searches", "Manage your account"] for phrase in phrases: self.assertIn(phrase, response.content, msg=\ "The phrase '%s' is missing from the final response" % phrase) # Assert the new user doesn't exist. self.assertFalse( User.objects.filter(email=self.new_user.email).exists(), msg="The new user should have been deleted.") # Assert the new email address is associated with the existing user self.assertTrue( SecondaryEmail.objects.filter(user=self.existing, email=self.activation_profile.email).exists(), msg="A secondary email should have been added "\ "for the deleted user account") # Assert the contacts associated with the new user now point to the # existing user self.assertEqual(Contact.objects.all().count(), 10, msg="The Contacts should not have been deleted.") for contact in Contact.objects.all(): self.assertEqual( contact.user, self.existing, msg="The contacts were not moved to the existing contact") # Assert the saved searches associated with the new user now point to # the existing user self.assertEqual(SavedSearch.objects.all().count(), 10, msg="The SavedSearches should not have been deleted.") for search in SavedSearch.objects.all(): self.assertEqual( search.user, self.existing, msg="The contacts were not moved to the existing contact")
class MyProfileViewsTests(MyJobsBase): def setUp(self): super(MyProfileViewsTests, self).setUp() self.client = TestClient() self.client.login_user(self.user) self.name = PrimaryNameFactory(user=self.user) def test_edit_profile(self): """ Going to the edit_profile view generates a list of existing profile items in the main content section and a list of profile sections that don't have data filled out in the sidebar. """ resp = self.client.get(reverse('view_profile')) soup = BeautifulSoup(resp.content) item_id = self.name.id # The existing name object should be rendered on the main content # section self.assertIsNotNone( soup.find('div', id='name-' + str(item_id) + '-item')) # profile-section contains the name of a profile section that has no # information filled out yet and shows up in the sidebar self.assertTrue(soup.findAll('tr', {'class': 'profile-section'})) def test_edit_summary(self): """ See test_edit_profile """ summary = SummaryFactory(user=self.user) resp = self.client.get(reverse('view_profile')) soup = BeautifulSoup(resp.content) item = soup.find('div', id='summary-' + str(summary.id) + '-item') self.assertIsNotNone(item) link = item.find('a').attrs['href'] resp = self.client.get(link) self.assertEqual(resp.status_code, 200) def test_handle_form_get_new(self): """ Invoking the handle_form view without an id parameter returns an empty form with the correct form id """ resp = self.client.get(reverse('handle_form'), data={'module': 'Name'}) self.assertTemplateUsed(resp, 'myprofile/profile_form.html') soup = BeautifulSoup(resp.content) self.assertEquals(soup.form.attrs['id'], 'profile-unit-form') with self.assertRaises(KeyError): soup.find('input', id='id_name-given_name').attrs['value'] def test_handle_form_get_existing(self): """ Invoking the handle_form view with and id paraemeter returns a form filled out with the corresponding profile/ID combination """ resp = self.client.get(reverse('handle_form'), data={ 'module': 'Name', 'id': self.name.id }) self.assertTemplateUsed(resp, 'myprofile/profile_form.html') soup = BeautifulSoup(resp.content) self.assertEquals(soup.form.attrs['id'], 'profile-unit-form') self.assertEquals( soup.find('input', id='id_name-given_name').attrs['value'], 'Alice') self.assertEquals( soup.find('input', id='id_name-family_name').attrs['value'], 'Smith') self.assertEquals( soup.find('input', id='id_name-primary').attrs['checked'], 'checked') def test_handle_form_post_new_valid(self): """ Invoking the handle_form view as a POST request for a new item creates that object in the database and returns the item snippet to be rendered on the page. """ resp = self.client.post(reverse('handle_form'), data={ 'module': 'Name', 'id': 'new', 'given_name': 'Susy', 'family_name': 'Smith' }) self.assertRedirects(resp, reverse('view_profile')) self.assertEqual( Name.objects.filter(given_name='Susy', family_name='Smith').count(), 1) def test_handle_form_post_invalid(self): """ Invoking the handle_form view as a POST request with an invalid form returns the list of form errors. """ resp = self.client.post(reverse('handle_form'), data={ 'module': 'Name', 'id': 'new', 'given_name': 'Susy' }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(json.loads(resp.content), {u'family_name': [u'This field is required.']}) def test_handle_form_post_existing_valid(self): """ Invoking the handle_form view as a POST request for an existing item updates that item and returns the update item snippet. """ resp = self.client.post(reverse('handle_form'), data={ 'module': 'Name', 'id': self.name.id, 'given_name': 'Susy', 'family_name': 'Smith' }) self.assertRedirects(resp, reverse('view_profile')) self.assertEqual( Name.objects.filter(given_name='Susy', family_name='Smith').count(), 1) def test_handle_form_redirect_summary(self): """ When a user has a summary already if they try to make a new summary handle form should redirect the user to edit the summary they already have. User is only allowed one summary per account. """ summary_instance = SummaryFactory(user=self.user) summary_instance.save() resp = self.client.get(reverse('handle_form'), data={'module': 'Summary'}) self.assertRedirects( resp, reverse('handle_form') + '?id=%s&module=Summary' % summary_instance.id) def test_delete_item(self): """ Invoking the delete_item view deletes the item and returns the 'Deleted!' HttpResponse """ resp = self.client.post( reverse('delete_item') + '?item=' + str(self.name.id)) self.assertEqual(resp.content, '') self.assertEqual(Name.objects.filter(id=self.name.id).count(), 0) def test_add_duplicate_primary_email(self): """ Attempting to add a secondary email with a value equal to the user's current primary email results in an error. Due to how the instance is constructed, this validation is form-level rather than model-level. """ resp = self.client.post(reverse('handle_form'), data={ 'module': 'SecondaryEmail', 'id': 'new', 'email': self.user.email }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(json.loads(resp.content), {u'email': [u'This email is already registered.']}) def test_default_country_changes(self): """ The displayed country when editing an address should update to reflect the chosen country. """ resp = self.client.get(reverse('handle_form'), data={'module': 'Address'}) content = BeautifulSoup(resp.content) selected = content.find('option', attrs={'selected': True}) self.assertEqual(selected.attrs['value'], 'USA') address = AddressFactory(user=self.user, country_code='AFG') resp = self.client.get(reverse('handle_form'), data={ 'module': 'Address', 'id': address.id }) content = BeautifulSoup(resp.content) selected = content.find('option', attrs={'selected': True}) self.assertEqual(selected.attrs['value'], 'AFG')
class MessageViewTests(MyJobsBase): def setUp(self): super(MessageViewTests, self).setUp() self.message = Message.objects.create(subject='subject', body='body', message_type='success') for group in Group.objects.all(): self.message.group.add(group.pk) self.messageinfo = MessageInfo.objects.create(user=self.user, message=self.message) self.client = TestClient() self.client.login_user(self.user) def test_user_post_mark_message_read(self): self.client.get(reverse('read'), data={ 'name': 'message-read-' + str(self.message.id) + '-' + str(self.user.id) }, follow=True, HTTP_X_REQUESTED_WITH='XMLHttpRequest') m = MessageInfo.objects.get(user=self.user, message=self.message) self.assertTrue(m.read) self.assertTrue(m.read_at) def test_delete_message(self): """ Deleting a MessageInfo should instead mark it as deleted. """ self.assertTrue(self.messageinfo.deleted_on is None) self.client.get(reverse('delete'), data={ 'name': 'message-delete-' + str(self.message.id) + '-' + str(self.user.id) }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.messageinfo = MessageInfo.objects.get(pk=self.messageinfo.pk) self.assertIsNotNone(self.messageinfo.deleted_on) def test_auto_page_inbox(self): """ If a "message=%d" parameter is passed on an inbox view, we should detect which page that message appears on and select it. """ infos = MessageInfoFactory.create_batch(11, user=self.user) request = self.client.get(reverse('inbox')) self.assertTrue('Page 1 of 2' in request.content) # Messages are displayed in reverse creation order, so the first item # in the list is the last item on the last page. request = self.client.get( reverse('inbox') + '?message=%s' % infos[0].message.pk) self.assertTrue('Page 2 of 2' in request.content) def test_system_message_as_alert(self): """ Only system messages should show as alerts. """ button_class = 'mymessage-read-{message}-{user}'.format( message=self.message.pk, user=self.user.pk) response = self.client.get(reverse('home')) self.assertNotIn(button_class, response.content) self.message.system = True self.message.save() response = self.client.get(reverse('home')) self.assertIn(button_class, response.content)
class MyProfileViewsTests(MyJobsBase): def setUp(self): super(MyProfileViewsTests, self).setUp() self.client = TestClient() self.client.login_user(self.user) self.name = PrimaryNameFactory(user=self.user) def test_edit_profile(self): """ Going to the edit_profile view generates a list of existing profile items in the main content section and a list of profile sections that don't have data filled out in the sidebar. """ resp = self.client.get(reverse('view_profile')) soup = BeautifulSoup(resp.content) item = soup.find('div', id='profileTitleBar') # Page should have fake user's email as title self.assertIsNotNone(soup.find_all('h3', text="*****@*****.**")) # The only module that is complete at this point is 'Name'. So there # should only be one module displayed in the moduleColumn div self.assertEquals(1, len(soup.findAll("div", {"class": "card-wrapper"}))) # The 'Add a New Section' section should have many items # Check for each one self.assertEquals( 10, len(soup.findAll("tr", {"class": "profile-section"}))) self.assertEquals( 1, len(soup.findAll("a", {"id": "Education-new-section"}))) self.assertEquals( 1, len(soup.findAll("a", {"id": "Address-new-section"}))) self.assertEquals( 1, len(soup.findAll("a", {"id": "Telephone-new-section"}))) self.assertEquals( 1, len(soup.findAll("a", {"id": "Employment History-new-section"}))) self.assertEquals( 1, len(soup.findAll("a", {"id": "Secondary Email-new-section"}))) self.assertEquals( 1, len(soup.findAll("a", {"id": "Military Service-new-section"}))) self.assertEquals( 1, len(soup.findAll("a", {"id": "Website-new-section"}))) self.assertEquals( 1, len(soup.findAll("a", {"id": "License-new-section"}))) self.assertEquals( 1, len(soup.findAll("a", {"id": "Summary-new-section"}))) self.assertEquals( 1, len(soup.findAll("a", {"id": "Volunteer History-new-section"}))) self.assertEquals( 1, len(soup.findAll("a", {"id": "Summary-new-section"}))) def test_handle_form_post_new_valid(self): """ Invoking the handle_form view as a POST request for a new item creates that object in the database and returns the item snippet to be rendered on the page. """ resp = self.client.post(reverse('handle_form'), data={ 'module': 'Name', 'id': 'new', 'given_name': 'Susy', 'family_name': 'Smith' }) self.assertRedirects(resp, reverse('view_profile')) self.assertEqual( Name.objects.filter(given_name='Susy', family_name='Smith').count(), 1) def test_delete_item(self): """ Invoking the delete_item view deletes the item and returns the 'Deleted!' HttpResponse """ resp = self.client.post( reverse('delete_item') + '?item=' + str(self.name.id)) self.assertEqual(resp.content, '') self.assertEqual(Name.objects.filter(id=self.name.id).count(), 0) def test_edit_summary(self): """ See test_edit_profile """ summary = SummaryFactory(user=self.user) resp = self.client.get(reverse('view_profile')) soup = BeautifulSoup(resp.content) item = soup.find('div', id='summary-' + str(summary.id) + '-item') self.assertIsNotNone(item) link = item.find('a').attrs['href'] resp = self.client.get(link) self.assertEqual(resp.status_code, 200) def test_handle_form_post_invalid(self): """ Invoking the handle_form view as a POST request with an invalid form returns the list of form errors. """ resp = self.client.post(reverse('handle_form'), data={ 'module': 'Name', 'id': 'new', 'given_name': 'Susy' }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(json.loads(resp.content), {u'family_name': [u'This field is required.']}) resp = self.client.post(reverse('handle_form'), data={ 'module': 'Name', 'id': 'new', 'family_name': 'Smithers' }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(json.loads(resp.content), {u'given_name': [u'This field is required.']}) def test_handle_form_post_existing_valid(self): """ Invoking the handle_form view as a POST request for an existing item updates that item and returns the update item snippet. """ resp = self.client.post(reverse('handle_form'), data={ 'module': 'Name', 'id': self.name.id, 'given_name': 'Susy', 'family_name': 'Smith' }) self.assertRedirects(resp, reverse('view_profile')) self.assertEqual( Name.objects.filter(given_name='Susy', family_name='Smith').count(), 1) def test_handle_form_json_serialize_get(self): """When an ajax requests wants to GET json, serialize the form.""" resp = self.client.get(reverse('handle_form'), HTTP_ACCEPT='application/json', data={'module': 'Name'}) self.assertEquals(200, resp.status_code) self.assertIn('application/json', resp['content-type']) data = json.loads(resp.content) self.assertEquals(3, len(data['ordered_fields'])) self.assertIsInstance(data['ordered_fields'], list) self.assertEquals(3, len(data['fields'])) self.assertIsInstance(data['fields'], dict) self.assertIsInstance(data['fields']['family_name'], dict) self.assertIsInstance(data['fields']['given_name'], dict) self.assertIsInstance(data['fields']['primary'], dict) self.assertEquals(3, len(data['data'])) self.assertIsInstance(data['data'], dict) def test_add_duplicate_primary_email(self): """ Attempting to add a secondary email with a value equal to the user's current primary email results in an error. Due to how the instance is constructed, this validation is form-level rather than model-level. """ resp = self.client.post(reverse('handle_form'), data={ 'module': 'SecondaryEmail', 'id': 'new', 'email': self.user.email }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(json.loads(resp.content), {u'email': [u'This email is already registered.']})
class SavedSearchResourceTestCase(MyJobsBase): def setUp(self): super(SavedSearchResourceTestCase, self).setUp() self.client = TestClient(path='/api/v1/savedsearch/', data={ 'email': '*****@*****.**', 'url': 'www.my.jobs/jobs' }) create_api_key(User, instance=self.user, created=True) self.client.data['username'] = self.user.email self.client.data['api_key'] = self.user.api_key.key def test_special_characters_in_url(self): """ Magic happens before control is handed to our view, resulting in quoted things becoming unquoted. We should not unquote said things inside our views as bad things can happen (%23 unquoting to # and becoming a fragment). """ self.client.data['url'] = 'www.my.jobs/search?q=c%23' response = self.client.get() self.assertEqual(response.status_code, 200) search = SavedSearch.objects.last() self.assertFalse(search.feed.endswith('#')) self.assertTrue(search.feed.endswith('%23')) def test_new_search_existing_user(self): for data in [('*****@*****.**', 'www.my.jobs/search?q=django'), ('*****@*****.**', 'www.my.jobs/search?q=python')]: self.client.data['email'] = data[0] self.client.data['url'] = data[1] response = self.client.get() self.assertEqual(response.status_code, 200) search = SavedSearch.objects.all()[0] self.assertEqual(search.user, self.user) content = json.loads(response.content) self.assertEqual(len(content), 3) self.assertTrue(content['new_search']) self.assertEqual(SavedSearch.objects.filter(user=self.user).count(), 2) self.client.data['url'] = 'http://www.my.jobs/jobs' self.client.get() for search in SavedSearch.objects.all(): self.assertTrue('www.my.jobs' in search.notes) def test_new_search_new_user(self): self.client.data['email'] = '*****@*****.**' response = self.client.get() self.assertEqual(response.status_code, 200) self.assertEqual(SavedSearch.objects.count(), 0) self.assertEqual(User.objects.count(), 1) content = json.loads(response.content) self.assertEqual( content['error'], 'No user with email %s exists' % self.client.data['email']) self.assertEqual(len(content), 1) def test_new_search_secondary_email(self): SecondaryEmail.objects.create(user=self.user, email='*****@*****.**') self.client.data['email'] = '*****@*****.**' response = self.client.get() self.assertEqual(response.status_code, 200) self.assertEqual(SavedSearch.objects.count(), 1) self.assertEqual(User.objects.count(), 1) search = SavedSearch.objects.all()[0] self.assertEqual(search.user, self.user) self.assertEqual(search.email, '*****@*****.**') content = json.loads(response.content) self.assertEqual(len(content), 3) def test_new_search_invalid_url(self): self.client.data['url'] = 'google.com' response = self.client.get() self.assertEqual(response.status_code, 200) content = json.loads(response.content) self.assertEqual(len(content), 1) self.assertEqual(content['error'], 'This is not a valid .JOBS feed') self.assertEqual(SavedSearch.objects.count(), 0) def test_new_search_no_url(self): del self.client.data['url'] response = self.client.get() self.assertEqual(response.status_code, 200) content = json.loads(response.content) self.assertEqual(len(content), 1) self.assertEqual(content['error'], 'No .JOBS feed provided') self.assertEqual(SavedSearch.objects.count(), 0) def test_no_email(self): del self.client.data['email'] response = self.client.get() self.assertEqual(response.status_code, 200) content = json.loads(response.content) self.assertEqual(len(content), 1) self.assertEqual(content['error'], 'No email provided') self.assertEqual(SavedSearch.objects.count(), 0) def test_no_auth(self): del self.client.data['username'] del self.client.data['api_key'] response = self.client.get() self.assertEqual(response.status_code, 401) self.assertEqual(response.content, '') self.assertEqual(SavedSearch.objects.count(), 0) def test_invalid_auth(self): headers = [(self.user.email, 'invalid_key'), ('*****@*****.**', self.user.api_key.key), ('*****@*****.**', 'invalid_key')] for header in headers: self.client.data['username'] = header[0] self.client.data['api_key'] = header[1] response = self.client.get() self.assertEqual(response.status_code, 401) self.assertEqual(response.content, '') self.assertEqual(SavedSearch.objects.count(), 0) def test_existing_search(self): response = self.client.get() self.assertEqual(response.status_code, 200) content = json.loads(response.content) self.assertEqual(content['new_search'], True) for email in [self.user.email, self.user.email.upper()]: self.client.data['email'] = email response = self.client.get() content = json.loads(response.content) self.assertEqual(len(content), 3) self.assertFalse(content['new_search']) self.assertEqual(SavedSearch.objects.count(), 1) def test_user_creation_source_override(self): """ Providing a source parameter to the account creation API should override user.source with its value. """ self.client.get( reverse('topbar') + '?site_name=Indianapolis%20Jobs&site=http%3A%2F%2Findianapolis.jobs&callback=foo', HTTP_REFERER='http://indianapolis.jobs') self.client.data['source'] = 'redirect' self.client.get() user = User.objects.get(email=self.client.data['email']) self.assertTrue(user.source, self.client.data['source'])
class TestSecureBlocks(DirectSEOBase): """ Tests that the secure blocks api view in various circumstances. """ fixtures = ['login_page.json'] def setUp(self): super(TestSecureBlocks, self).setUp() self.staff_user = UserFactory(is_staff=True) self.client = TestClient() self.client.login_user(self.staff_user) self.sb_url = reverse('secure_blocks') SeoSiteFactory(domain='jobs.example.com') def test_secure_blocks_empty(self): """Browser asks for no blocks.""" resp = make_cors_request(self.client, self.sb_url, '{"blocks": {}}') self.assertEqual(200, resp.status_code) result = json.loads(resp.content) self.assertEqual( {u'errors': {}}, result, msg="got %s! secure block returned block when none was" " requested" % result) def test_secure_blocks_bad_parse(self): """Handle unparseable JSON.""" resp = make_cors_request(self.client, self.sb_url, '@@@@@@@@@') self.assertEqual( 400, resp.status_code, msg="got %s! block request allowed unparseable json, check" " secure block json parser" % resp.status_code) def test_secure_blocks_render(self): """Ask for a real block.""" body = '{"blocks": {"my-jobs-logo-1": {}}}' resp = make_cors_request(self.client, self.sb_url, body) result = json.loads(resp.content) self.assertTrue( 'my-jobs-logo-1' in result, msg="block request not found in response. check fixture, " "secure blocks logic") def test_secure_blocks_bad_origin(self): """Check that secure blocks do not load from invalid origins""" body = '{"blocks": {"my-jobs-logo-1": {}}}' resp = make_cors_request(self.client, self.sb_url, body, http_origin='http://notparent.com/') self.assertEqual( resp.status_code, 404, msg="got %s! secure block call responded despite bad origin." " check cross site verify logic" % resp.status_code) def test_saved_search_includes_required_js(self): """ Ensure requests for saved search widget includes required js """ savedsearch = (SavedSearchWidgetBlock.objects.get( element_id='test_saved_search')) body = '{"blocks": {"test_saved_search": {}}}' resp = make_cors_request(self.client, self.sb_url, body) self.assertEqual(resp.status_code, 200, msg="Expected 200, got %s. User was not able to " "retrieve blocks for test" % resp.status_code) for js in savedsearch.required_js(): self.assertContains(resp, js, msg_prefix="Did not find %s in response," "missing required js" % js) def test_topbar_includes_cookies(self): body = '{"blocks": {"test_tools_widget": {}}}' resp = make_cors_request(self.client, self.sb_url, body) self.assertEqual(resp.status_code, 200, msg="Expected 200, got %s. User was not able to " "retrieve blocks for test" % resp.status_code) self.assertEqual(resp.cookies['lastmicrosite'].value, 'http://jobs.example.com')