Example #1
0
    def setUp(self):
        self.staff_user = UserFactory()
        group = Group.objects.get(name=CompanyUser.GROUP_NAME)
        self.staff_user.groups.add(group)
        self.staff_user.save()

        self.company = CompanyFactory()
        self.company.save()
        self.admin = CompanyUserFactory(user=self.staff_user,
                                        company=self.company)
        self.admin.save()
        self.microsite = MicrositeFactory(company=self.company)
        self.microsite.save()

        self.client = TestClient()
        self.client.login_user(self.staff_user)

        self.candidate_user = UserFactory(email="*****@*****.**")
        SavedSearchFactory(user=self.candidate_user,
                           url='http://test.jobs/search?q=django',
                           label='test Jobs')
        self.candidate_user.save()

        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,
                                   label='%s Jobs' % search)
Example #2
0
    def test_search_updates_facet_counts(self):
        # Add ProfileData to the candidate_user
        EducationFactory(user=self.candidate_user)
        AddressFactory(user=self.candidate_user)
        LicenseFactory(user=self.candidate_user)
        self.candidate_user.save()

        # Create a new user with ProfileData
        user = UserFactory(email="*****@*****.**")
        SavedSearchFactory(user=user,
                           url='http://test.jobs/search?q=python',
                           feed='http://test.jobs/jobs/feed/rss?',
                           label='Python Jobs')
        EducationFactory(user=user)
        AddressFactory(user=user)
        LicenseFactory(user=user)
        user.save()

        update_solr_task(settings.TEST_SOLR_INSTANCE)

        # Assert there are two users with country codes
        country_tag = '#Country-details-table .facet-count'
        q = '?company={company}'
        q = q.format(company=str(self.company.id))
        response = self.client.post(reverse('dashboard') + q)
        soup = BeautifulSoup(response.content)
        self.assertEqual(int(soup.select(country_tag)[0].text), 2)

        # When we search, the facet count updates.
        q = '?company={company}&search={search}'
        q = q.format(company=str(self.company.id), search='find')
        response = self.client.post(reverse('dashboard') + q)
        soup = BeautifulSoup(response.content)
        self.assertEqual(int(soup.select(country_tag)[0].text), 1)
 def test_non_staff_user(self):
     self.client.logout()
     user = UserFactory(email='*****@*****.**')
     user.set_password('secret')
     self.client.login(username=user.email, password='******')
     response = self.client.get(reverse('source_code_upload'))
     self.assertTrue('Log in' in response.content)
Example #4
0
    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/")
Example #5
0
    def test_bad_events_deactivate_user(self):
        now = datetime.datetime.now()
        for event in STOP_SENDING + BAD_EMAIL:
            u = UserFactory(email="*****@*****.**",
                            is_verified=True, opt_in_myjobs=True)
            self.make_email_logs(u.email, event, now, False, 3)
            process_batch_events()

            u = User.objects.get(pk=u.pk)
            self.assertEqual(u.deactivate_type, event)
            # Users start this test case with is_verified=True
            # is_verified should only change if the modifying event
            # is a block or drop
            self.assertEqual(u.is_verified, event in STOP_SENDING)
            self.assertFalse(u.opt_in_myjobs)

            infos = u.messageinfo_set.all()
            self.assertEqual(len(infos), 1)
            message = infos[0].message

            if u.deactivate_type in STOP_SENDING:
                text = 'stop communications'
            else:
                text = 'Attempts to send messages to'
            self.assertTrue(text in message.body)

            EmailLog.objects.all().delete()
            u.delete()
Example #6
0
class SavedSearchDeletionTests(MyJobsBase):
    # Creating an entire test class for this is kind of overkill but it doesn't
    # fit with any of the others.
    def setUp(self):
        super(SavedSearchDeletionTests, self).setUp()
        self.user = UserFactory()
        self.creator = UserFactory(email='*****@*****.**')
        self.search = SavedSearchFactory(user=self.user)
        self.partner_search = PartnerSavedSearchFactory(user=self.user,
                                                        created_by=self.creator)

    def test_deletion_and_preservation(self):
        """
        When a user is deleted, that user's saved searches should be deleted.
        Partner saved searches should be left alone with the exception of
        nullifying the recipient.
        """
        mail.outbox = []
        self.assertEqual(MessageInfo.objects.count(), 0)
        self.user.delete()
        with self.assertRaises(SavedSearch.DoesNotExist):
            SavedSearch.objects.get(pk=self.search.pk)
        SavedSearch.objects.get(pk=self.partner_search.pk)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(MessageInfo.objects.count(), 1)
class SavedSearchTemplateTagTests(MyJobsBase):
    def setUp(self):
        super(SavedSearchTemplateTagTests, self).setUp()
        self.user = UserFactory(is_active=True)
        self.search = SavedSearchFactory(user=self.user)

    def test_confirm_creation_active_user(self):
        expected = reverse('view_full_feed') + '?id={id}&verify={guid}'.format(
            id=self.search.pk, guid=self.user.user_guid)
        actual = get_created_url(self.search)

        self.assertEqual(actual, expected)

    def test_confirm_creation_inactive_user(self):
        self.user.is_active = False
        self.user.save()

        user_with_profile = UserFactory(email='*****@*****.**',
                                        is_active=False)
        profile_search = SavedSearchFactory(user=user_with_profile)
        ActivationProfile.objects.create(user=user_with_profile,
                                         email=user_with_profile.email)

        for saved_search in [self.search, profile_search]:
            actual = get_created_url(saved_search)

            profile = ActivationProfile.objects.get(user=saved_search.user)
            expected = reverse('registration_activate',
                               args=[profile.activation_key]) + \
                '?verify={guid}'.format(guid=saved_search.user.user_guid)
            self.assertEqual(actual, expected)
Example #8
0
 def test_message_made_sent_to_multiple(self):
     """
     Test that one message can be received by multiple users.
     """
     user = UserFactory(email="*****@*****.**")
     user.groups.add(Group.objects.get(id=1))
     user.claim_messages()
     self.assertEqual(Message.objects.count(), 1)
     self.assertEqual(MessageInfo.objects.count(), 2)
     self.assertEqual(self.message,
                      self.user.messageinfo_set.get().message)
class NewUserTests(SeleniumTestCase):

    """Tests Account creation"""

    def setUp(self):
        self.user = UserFactory(first_name="John", last_name="Doe")

    def test_home_page_works(self):
        """
        As John, navigating to https://secure.my.jobs should send me to a page
        titled "My.jobs".
        """
        self.browser.get(self.live_server_url)
        self.assertIn(self.browser.title, 'My.jobs')

    def test_cant_log_in_without_account(self):
        """
        As John, I shouldn't be able to log into My.jobs without registering
        first.
        """
        self.browser.get('/'.join([self.live_server_url, 'prm', 'view']))

        # attempt to log in
        username = self.find('id_username')
        username.send_keys(self.user.email)
        self.find('id_password').send_keys(self.user.password)
        self.find('login').click()

        self.assertEqual(username.get_attribute('placeholder'),
                         'Please enter a correct email.')

    def test_user_registration(self):
        """
        As John, I should be able to register on My.jobs and log in.
        """
        user = UserFactory.build(email='*****@*****.**')
        self.browser.get('/'.join([self.live_server_url, 'prm', 'view']))

        # register
        self.find('id_email').send_keys(user.email)
        self.find('id_password1').send_keys(user.password)
        self.find('id_password2').send_keys(user.password)
        self.find('register').click()

        self.assertEqual(self.find('profile').get_attribute(
            'innerHTML'),
            'Skip: Take me to my profile')

    def test_user_login(self):
        self.user.set_password("test")
        self.user.save()
        self.find('id_username').send_keys(self.user.email)
        self.find('id_password').send_keys("test")
        self.find('login').click()
Example #10
0
class MessageManagerTests(MyJobsBase):
    def setUp(self):
        super(MessageManagerTests, self).setUp()
        self.user = UserFactory()
        self.user.groups.add(Group.objects.get(pk=1))

    def test_create_message_by_group(self):
        message = Message.objects.create_message(
            subject='subject', body='message body',
            groups=Group.objects.all())

        self.user.claim_messages()

        infos = self.user.messageinfo_set.all()
        self.assertEqual(len(infos), 1)
        self.assertEqual(infos[0].message, message)

    def test_create_message_creates_messageinfo(self):
        message = Message.objects.create_message(
            users=self.user, subject='subject', body='message body')

        infos = MessageInfo.objects.all()
        self.assertEqual(infos.count(), 1)
        self.assertEqual(infos[0].user, self.user)
        self.assertEqual(infos[0].message, message)

    def test_create_message_with_users_and_groups(self):
        new_user = UserFactory(email='*****@*****.**')
        message = Message.objects.create_message(
            users=new_user, subject='subject', body='message body',
            groups=Group.objects.get(pk=1))

        [user.claim_messages() for user in [new_user, self.user]]
        get_messages = lambda u: list(u.message_set.all())

        group_user_messages = get_messages(self.user)
        new_user_messages = get_messages(new_user)

        self.assertEqual(group_user_messages, new_user_messages)
        self.assertEqual(len(group_user_messages), 1)
        self.assertEqual(group_user_messages[0], message)

    def test_create_message_sets_expiration(self):
        message = Message.objects.create_message(
            subject='subject', body='message body',
            groups=Group.objects.get(pk=1), expires=False)

        self.assertTrue(message.expire_at is None)
        self.user.claim_messages()
        info = self.user.messageinfo_set.first()
        self.assertFalse(info.expired_time())
Example #11
0
    def test_activities(self):
        """
        `User.get_activities(company)` should return a list of activities
        associated with this user and company.

        """
        user = UserFactory(email="*****@*****.**")

        self.assertItemsEqual(user.get_activities(self.company), [])

        user.roles.add(self.role)
        activities = self.role.activities.values_list('name', flat=True)

        self.assertItemsEqual(user.get_activities(self.company), activities)
Example #12
0
    def test_deleting_user_does_not_cascade(self):
        """
        Deleting a user shouldn't delete related objects such as partner saved
        searches and reports.
        """

        user = UserFactory(email="*****@*****.**")
        company = CompanyFactory()
        pss = PartnerSavedSearchFactory(created_by=user)
        report = Report.objects.create(created_by=user, owner=company)

        user.delete()
        self.assertIn(pss, PartnerSavedSearch.objects.all())
        self.assertIn(report, Report.objects.all())
Example #13
0
 def test_gravatar_url(self):
     """
     Test that email is hashed correctly and returns a 200 response
     """
     user = UserFactory()
     gravatar_url = "http://www.gravatar.com/avatar/c160f8cc69a4f0b" \
                           "f2b0362752353d060?s=20&d=mm"
     no_gravatar_url = ("<div class='gravatar-blank gravatar-danger' "
                            "style='height: 20px; width: 20px'>"
                            "<span class='gravatar-text' "
                            "style='font-size:13.0px;'>A</span></div>")
     generated_gravatar_url = user.get_gravatar_url()
     self.assertEqual(no_gravatar_url, generated_gravatar_url)
     status_code = urllib.urlopen(gravatar_url).getcode()
     self.assertEqual(status_code, 200)
class RedirectMiddlewareTests(MyJobsBase):
    def setUp(self):
        super(RedirectMiddlewareTests, self).setUp()
        self.user = UserFactory()
        self.redirect_middleware = PasswordChangeRedirectMiddleware()
        self.request_factory = RequestFactory()

    def test_logged_in_no_redirect(self):
        """
        A logged in user whose password_change flag is not set
        should proceed to their original destination
        """
        request = self.request_factory.get(reverse('edit_account'))
        request.user = self.user
        response = self.redirect_middleware.process_request(request)
        self.assertEqual(response, None)

    def test_logged_in_autocreated_user_redirects(self):
        """
        A logged in user whose password_change flag is set should
        be redirected to the password change form
        """
        self.user.password_change = True
        self.user.save()

        request = self.request_factory.get(reverse('saved_search_main'))
        request.user = self.user

        response = self.redirect_middleware.process_request(request)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.get('location'),
                         reverse('edit_account')+"#as-password")

    def test_not_logged_in_returns_forbidden(self):
        """
        An anonymous user that tries to post to a private url should
        receive a 403 Forbidden status
        """
        request = self.request_factory.get(reverse('saved_search_main'),
                                           HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        new_request = request.GET.copy()
        new_request['next'] = reverse('home')
        request.GET = new_request
        request.REQUEST.dicts = (new_request, request.POST)
        request.user = AnonymousUser()
        response = self.redirect_middleware.process_request(request)
        self.assertEqual(response.status_code, 403)
Example #15
0
 def setUp(self):
     super(AdminTests, self).setUp()
     self.site = AdminSite()
     settings.SITE = SeoSite.objects.first()
     self.request = RequestFactory().get("/")
     self.user = UserFactory(is_superuser=True)
     self.request.user = self.user
Example #16
0
    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()
Example #17
0
class AccountFormTests(MyJobsBase):
    def setUp(self):
        super(AccountFormTests, self).setUp()
        self.user = UserFactory()
        self.name = PrimaryNameFactory(user=self.user)
        
    def test_password_form(self):
        invalid_data = [
            { 'data': {'password': '******',
                       'new_password1': '7dY=Ybtk',
                       'new_password2': '7dY=Ybtk'},
              u'errors': [['password', [u"Wrong password."]]]},
            { 'data': {'password': '******',
                       'new_password1': '7dY=Ybtk',
                       'new_password2': 'notnewpassword'},
                u'errors':
                    [[u'new_password2', [u'The new password fields did not match.']],
                    [u'new_password1', [u'The new password fields did not match.']]],
            
            },
        ]

        for item in invalid_data:
            form = ChangePasswordForm(user=self.user, data=item['data'])
            self.failIf(form.is_valid())
            self.assertEqual(form.errors[item[u'errors'][0][0]],
                             item[u'errors'][0][1])

        form = ChangePasswordForm(user=self.user,data={'password': '******',
                                                       'new_password1': '7dY=Ybtk',
                                                       'new_password2': '7dY=Ybtk'})
        
        self.failUnless(form.is_valid())
        form.save()
        self.failUnless(self.user.check_password('7dY=Ybtk'))
Example #18
0
    def setUp(self):
        super(EmailForwardTests, self).setUp()
        self.redirect_guid = JOB['guid']
        self.redirect = RedirectFactory(buid=JOB['buid'],
                                        guid='{%s}' %
                                             uuid.UUID(self.redirect_guid))

        self.password = '******'
        self.user = UserFactory(email='*****@*****.**')
        self.user.set_password(self.password)
        self.user.save()

        self.contact = CompanyEmail.objects.create(
            buid=self.redirect.buid,
            email=self.user.email)

        self.email = self.user.email.replace('@', '%40')
        self.auth = {
            'bad': [
                '',
                'Basic %s' % base64.b64encode('bad%40email:wrong_pass')],
            'good':
                'Basic %s' % base64.b64encode('%s:%s' % (self.user.email.\
                                                         replace('@', '%40'),
                                                         self.password))}
        self.post_dict = {'to': '*****@*****.**',
                          'from': '*****@*****.**',
                          'text': 'Questions about stuff',
                          'html': '<b>Questions about stuff</b>',
                          'subject': 'Bad Email',
                          'attachments': 0}

        self.r = Replacer()
        self.r.replace('pysolr.Solr.search', mock_search)
Example #19
0
    def setUp(self):
        super(MyDashboardViewsTests, self).setUp()
        group = Group.objects.get(name=CompanyUser.GROUP_NAME)
        self.user.groups.add(group)

        self.business_unit = BusinessUnitFactory()

        self.company.job_source_ids.add(self.business_unit)
        self.admin = CompanyUserFactory(user=self.user,
                                        company=self.company)
        self.microsite = SeoSiteFactory()
        self.microsite.business_units.add(self.business_unit)

        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)
Example #20
0
    def setUp(self):
        super(PartnerSavedSearchTests, self).setUp()
        self.user = UserFactory()
        self.digest = SavedSearchDigestFactory(user=self.user)
        self.company = CompanyFactory()
        self.partner = PartnerFactory(owner=self.company)
        self.contact = ContactFactory(user=self.user,
                                      partner=self.partner)
        self.partner_search = PartnerSavedSearchFactory(user=self.user,
                                                        created_by=self.user,
                                                        provider=self.company,
                                                        partner=self.partner)
        # Partner searches are normally created with a form, which creates
        # invitations as a side effect. We're not testing the form, so we
        # can fake an invitation here.
        Invitation(invitee_email=self.partner_search.email,
                   invitee=self.partner_search.user,
                   inviting_user=self.partner_search.created_by,
                   inviting_company=self.partner_search.partner.owner,
                   added_saved_search=self.partner_search).save()

        self.patcher = patch('urllib2.urlopen', return_file())
        self.mock_urlopen = self.patcher.start()
        self.num_occurrences = lambda text, search_str: [match.start()
                                                         for match
                                                         in re.finditer(
                                                             search_str, text)]
        # classes and ids may get stripped out when pynliner inlines css.
        # all jobs contain a default (blank) icon, so we can search for that if
        # we want a job count
        self.job_icon = 'http://png.nlx.org/100x50/logo.gif'
Example #21
0
    def setUp(self):
        super(SavedSearchHelperTests, self).setUp()
        self.user = UserFactory()
        self.valid_url = 'http://www.my.jobs/jobs?location=chicago&q=nurse'

        self.patcher = patch('urllib2.urlopen', return_file())
        self.patcher.start()
Example #22
0
 def setUp(self):
     super(SavedSearchDeletionTests, self).setUp()
     self.user = UserFactory()
     self.creator = UserFactory(email='*****@*****.**')
     self.search = SavedSearchFactory(user=self.user)
     self.partner_search = PartnerSavedSearchFactory(user=self.user,
                                                     created_by=self.creator)
Example #23
0
    def test_search_domain(self):
        """We should be able to search for domain."""
        user = UserFactory(email="*****@*****.**")
        SavedSearchFactory(user=user,
                           url='http://test.jobs/search?q=python',
                           feed='http://test.jobs/jobs/feed/rss?',
                           label='Python Jobs')
        user.save()
        update_solr_task(settings.TEST_SOLR_INSTANCE)

        q = '?company={company}&search={search}'
        q = q.format(company=str(self.company.id), search='shouldWork.com')
        url = reverse('dashboard') + q

        response = self.client.post(url)
        soup = BeautifulSoup(response.content)
        self.assertEqual(len(soup.select('#row-link-table tr')), 1)
Example #24
0
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.user.set_password('aa')
        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)

        create_full_fixture()
Example #25
0
    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)
Example #26
0
    def test_is_active(self):
        """
        A user with is_active set to False should be redirected to the home
        page, while a user with is_active set to True should proceed to their
        destination.
        """
        client = TestClient()
        user = UserFactory()
        quoted_email = urllib.quote(user.email)

        # Active user
        client.login_user(user)
        resp = client.get(reverse('saved_search_main'))
        self.assertTrue(resp.status_code, 200)

        # Inactive user
        user.is_active = False
        user.save()
        resp = client.get(reverse('saved_search_main'))
        self.assertRedirects(resp, "http://testserver/?next=/saved-search/view/")
Example #27
0
    def setUp(self):
        super(MyJobsAdminTests, self).setUp()
        self.user.set_password('5UuYquA@')
        self.user.is_superuser = True
        self.user.save()
        self.account_owner = UserFactory(email='*****@*****.**')
        SeoSiteFactory(domain='secure.my.jobs')
        mail.outbox = []

        self.data = {'_selected_action': [unicode(self.account_owner.pk)],
                     'action': 'request_account_access'}
Example #28
0
    def test_can_method_with_app_access(self):
        """
        ``User.can`` should return False when a user isn't associated with the
        correct activities and True when they are.
        """

        user = UserFactory(email="*****@*****.**", roles=[self.role])
        self.role.activities = self.activities
        activities = self.role.activities.values_list('name', flat=True)

        # check for a single activity
        self.assertTrue(user.can(self.company, activities[0]))

        self.assertFalse(user.can(self.company, "eat a burrito"))

        # check for multiple activities
        self.assertTrue(user.can(self.company, *activities))

        self.assertFalse(user.can(
            self.company, activities[0], "eat a burrito"))
Example #29
0
class AdminTests(MyJobsBase):
    def setUp(self):
        super(AdminTests, self).setUp()
        self.site = AdminSite()
        settings.SITE = SeoSite.objects.first()
        self.request = RequestFactory().get("/")
        self.user = UserFactory(is_superuser=True)
        self.request.user = self.user

    def test_admin_request_form(self):
        """
        The forms used by ValueEventAdmin and CronEventAdmin should have the
        current request as attributes.
        """
        for Admin, Model in [(ValueEventAdmin, ValueEvent), (CronEventAdmin, CronEvent)]:
            admin = Admin(Model, self.site)
            form = admin.get_form(self.request)()
            self.assertEqual(form.request, self.request)

    def test_non_superuser_form(self):
        """
        The email_template queryset should have an appropriate WHERE clause
        if the current user is not a company user.
        """
        company = CompanyUserFactory(user=self.user).company
        admin = ValueEventAdmin(ValueEvent, self.site)

        for superuser in [True, False]:
            self.user.is_superuser = superuser
            self.user.save()
            form = admin.get_form(self.request)()
            email_template = form.fields["email_template"]
            query = str(email_template.queryset.query)
            if superuser:
                self.assertFalse("WHERE" in query)
            else:
                if connection.vendor == "sqlite":
                    test = 'WHERE ("myemails_emailtemplate"."owner_id" = %s'
                else:
                    test = "WHERE (`myemails_emailtemplate`.`owner_id` = %s"
                self.assertTrue(test % company.pk in query)
Example #30
0
    def setUp(self):
        super(MyJobsViewsTests, self).setUp()
        self.user = UserFactory()
        self.client = TestClient()
        self.client.login_user(self.user)
        self.events = ['open', 'delivered', 'click']

        self.email_user = UserFactory(email='*****@*****.**')

        self.auth = '%s:%s' % (settings.SENDGRID_BATCH_POST_USER,
                               settings.SENDGRID_BATCH_POST_PASSWORD)
        self.auth = base64.b64encode(self.auth)
Example #31
0
    def test_contact_user_relationship(self):
        """
        Tests adding a User to Contact. Then tests to make sure User cascading
        delete doesn't delete the Contact and instead turns Contact.user to
        None.
        """
        self.contact.user = UserFactory(email=self.contact.email)
        self.contact.save()

        self.assertIsNotNone(self.contact.user)
        self.assertEqual(self.contact.name, self.contact.__unicode__())

        user = User.objects.get(email=self.contact.email)
        user.delete()

        contact = Contact.objects.get(name=self.contact.name)
        self.assertIsNone(contact.user)
Example #32
0
    def test_send_link_respects_permissions(self):
        # The send_saved_search view requires that DEBUG be enabled.
        settings.DEBUG = True
        self.user.is_superuser = True
        self.user.save()
        search = SavedSearchFactory(user=self.user)
        search_2 = SavedSearchFactory(user=UserFactory(email='*****@*****.**'))
        send_url = reverse('send_saved_search') + '?id=%s'

        self.assertEqual(len(mail.outbox), 0)
        response = self.client.get(send_url % search.pk)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(len(mail.outbox), 1)
        response = self.client.get(send_url % search_2.pk)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(len(mail.outbox), 2)
        settings.DEBUG = False
Example #33
0
    def setUp(self):
        super(MyJobsBase, self).setUp()
        settings.ROOT_URLCONF = "myjobs_urls"
        settings.PROJECT = "myjobs"

        self.app_access = AppAccessFactory()
        self.activities = [
            ActivityFactory(name=activity, app_access=self.app_access)
            for activity in [
                "create communication record", "create contact",
                "create partner saved search", "create partner", "create role",
                "create tag", "create user", "delete tag", "delete partner",
                "delete role", "delete user", "read contact",
                "read communication record", "read partner saved search",
                "read partner", "read role", "read user", "read tag",
                "update communication record", "update contact",
                "update partner", "update role", "update tag", "update user",
                "read outreach email address", "create outreach email address",
                "delete outreach email address",
                "update outreach email address", "read outreach record",
                "convert outreach record", "view analytics"
            ]
        ]

        self.company = CompanyFactory(app_access=[self.app_access])
        # this role will be populated by activities on a test-by-test basis
        self.role = RoleFactory(company=self.company, name="Admin")
        self.user = UserFactory(roles=[self.role], is_staff=True)

        cache.clear()
        clear_url_caches()
        self.ms_solr = Solr(settings.SOLR['seo_test'])
        self.ms_solr.delete(q='*:*')

        self.base_context_processors = settings.TEMPLATE_CONTEXT_PROCESSORS
        context_processors = self.base_context_processors + (
            'mymessages.context_processors.message_lists', )
        setattr(settings, 'TEMPLATE_CONTEXT_PROCESSORS', context_processors)
        setattr(settings, 'MEMOIZE', False)

        self.patcher = patch('urllib2.urlopen', return_file())
        self.mock_urlopen = self.patcher.start()

        self.client = TestClient()
        self.client.login_user(self.user)
Example #34
0
    def test_api_returns_error_if_email_is_taken(self):
        """
        Verifies that the secure saved searched API returns an error if the
        provided email is taken by another user

        """
        taken_email = '*****@*****.**'
        UserFactory(email=taken_email)
        request_data = {'email': taken_email, 'url': self.child_url}
        response = make_cors_request(self.client,
                                     self.secure_ss_url,
                                     json.dumps(request_data),
                                     http_origin="http://%s" % self.domain)
        response_msg = json.loads(response.content)
        self.assertTrue(response_msg['error'],
                        msg="Expected an error but none raised! API returned"
                        ": %s" % response_msg['error'])
        self.assertFalse(response_msg['search_activated'])
    def test_confirm_creation_inactive_user(self):
        self.user.is_active = False
        self.user.save()

        user_with_profile = UserFactory(email='*****@*****.**',
                                        is_active=False)
        profile_search = SavedSearchFactory(user=user_with_profile)
        ActivationProfile.objects.create(user=user_with_profile,
                                         email=user_with_profile.email)

        for saved_search in [self.search, profile_search]:
            actual = get_created_url(saved_search)

            profile = ActivationProfile.objects.get(user=saved_search.user)
            expected = reverse('registration_activate',
                               args=[profile.activation_key]) + \
                '?verify={guid}'.format(guid=saved_search.user.user_guid)
            self.assertEqual(actual, expected)
Example #36
0
    def test_delete_all_searches(self):
        """
        Deleting all searches should only remove regular saved searches if the
        partner saved searches weren't created by the user trying to use it.
        """

        user = UserFactory(email='*****@*****.**')
        company = CompanyFactory(id=2423, name="Bacon Factory",
                                 user_created=False)
        SavedSearchFactory(user=self.user)
        pss = PartnerSavedSearchFactory(user=self.user, created_by=user,
                                        provider=company)

        response = self.client.get(reverse('delete_saved_search') +
            '?id=ALL')

        self.assertEqual(response.status_code, 302)
        # partner saved search should still exist...
        self.assertTrue(models.PartnerSavedSearch.objects.filter(
            pk=pss.pk).exists())
        # ... but the regular saved search shouldn't
        self.assertFalse(models.SavedSearch.objects.filter(
            partnersavedsearch__isnull=True).exists())
Example #37
0
    def test_can_method_with_app_access(self):
        """
        ``User.can`` should return False when a user isn't associated with the
        correct activities and True when they are.
        """

        user = UserFactory(email="*****@*****.**", roles=[self.role])
        self.role.activities = self.activities
        activities = self.role.activities.values_list('name', flat=True)

        # check for a single activity
        self.assertTrue(user.can(self.company, activities[0]))

        self.assertFalse(user.can(self.company, "eat a burrito"))

        # check for multiple activities
        self.assertTrue(user.can(self.company, *activities))

        self.assertFalse(user.can(self.company, activities[0],
                                  "eat a burrito"))
    def setUp(self):
        super(TestContactsDataSource, self).setUp()

        # A company to work with
        self.company = CompanyFactory(name='right')
        self.company.save()

        # A separate company that should not show up in results.
        self.other_company = CompanyFactory(name='wrong')
        self.other_company.save()

        self.partner = PartnerFactory(owner=self.company)
        self.other_partner = PartnerFactory(owner=self.other_company)

        self.partner_a = PartnerFactory(owner=self.company, name="aaa")
        self.partner_b = PartnerFactory(owner=self.company, name="bbb")
        # An unapproved parther. Associated data should be filtered out.
        self.partner_unapp = PartnerFactory(
            owner=self.company,
            name="unapproved",
            approval_status__code=Status.UNPROCESSED)
        # An archived parther. Associated data should be filtered out.
        self.partner_archived = PartnerFactory(owner=self.company)

        self.east_tag = TagFactory.create(company=self.company,
                                          name='east',
                                          hex_color="aaaaaa")
        self.west_tag = TagFactory.create(company=self.company,
                                          name='west',
                                          hex_color="bbbbbb")
        self.left_tag = TagFactory.create(company=self.company,
                                          name='left',
                                          hex_color="cccccc")
        self.right_tag = TagFactory.create(company=self.company,
                                           name='right',
                                           hex_color="dddddd")
        self.bad_tag = TagFactory.create(company=self.company,
                                         name='bad',
                                         hex_color="cccccc")

        self.partner_a.tags.add(self.left_tag)
        self.partner_b.tags.add(self.right_tag)

        self.john_user = UserFactory(email="*****@*****.**")
        self.john = ContactFactory(partner=self.partner_a,
                                   name='john adams',
                                   user=self.john_user,
                                   email="*****@*****.**",
                                   last_action_time='2015-10-03')
        self.john.locations.add(
            LocationFactory.create(city="Indianapolis", state="IN"))
        self.john.locations.add(
            LocationFactory.create(city="Chicago", state="IL"))
        self.john.tags.add(self.east_tag)

        self.sue_user = UserFactory(email="*****@*****.**")
        self.sue = ContactFactory(partner=self.partner_b,
                                  name='Sue Baxter',
                                  user=self.sue_user,
                                  email="*****@*****.**",
                                  last_action_time='2015-09-30 13:23')
        self.sue.locations.add(
            LocationFactory.create(address_line_one="123",
                                   city="Los Angeles",
                                   state="CA"))
        self.sue.locations.add(
            LocationFactory.create(address_line_one="234",
                                   city="Los Angeles",
                                   state="CA"))
        self.sue.tags.add(self.west_tag)

        # Poision data. Should never show up.
        self.archived_partner_user = (UserFactory(
            email="*****@*****.**"))
        self.archived_partner = ContactFactory(
            partner=self.partner_archived,
            name='Archived Partner Contact',
            user=self.archived_partner_user,
            email="*****@*****.**",
            last_action_time='2015-09-30 13:23')
        self.archived_partner.locations.add(
            LocationFactory.create(address_line_one="123",
                                   city="Nowhere",
                                   state="NO"))
        self.archived_partner.locations.add(
            LocationFactory.create(address_line_one="234",
                                   city="Nowhere",
                                   state="NO"))
        self.archived_partner.tags.add(self.west_tag)

        # Poision data. Should never show up.
        self.archived_contact_user = (UserFactory(
            email="*****@*****.**"))
        self.archived_contact = ContactFactory(
            partner=self.partner_b,
            name='Archived Contact',
            user=self.archived_contact_user,
            email="*****@*****.**",
            last_action_time='2015-09-30 13:23')
        self.archived_contact.locations.add(
            LocationFactory.create(address_line_one="123",
                                   city="Nowhere",
                                   state="NO"))
        self.archived_contact.locations.add(
            LocationFactory.create(address_line_one="234",
                                   city="Nowhere",
                                   state="NO"))
        self.archived_contact.tags.add(self.west_tag)

        # Poision data. Should never show up.
        self.unapproved_partner_user = (UserFactory(
            email="*****@*****.**"))
        self.unapproved_partner_contact = ContactFactory(
            partner=self.partner_unapp,
            name='Unapproved Partner Contact',
            user=self.unapproved_partner_user,
            email="*****@*****.**",
            last_action_time='2015-09-30 13:23')
        self.unapproved_partner_contact.locations.add(
            LocationFactory.create(address_line_one="123",
                                   city="Nowhere",
                                   state="NO"))
        self.unapproved_partner_contact.locations.add(
            LocationFactory.create(address_line_one="234",
                                   city="Nowhere",
                                   state="NO"))
        self.unapproved_partner_contact.tags.add(self.west_tag)

        # Poision data. Should never show up.
        self.unapproved_contact_user = (UserFactory(
            email="*****@*****.**"))
        self.unapproved_contact = ContactFactory(
            partner=self.partner_b,
            name='Unapproved Contact',
            user=self.unapproved_contact_user,
            email="*****@*****.**",
            last_action_time='2015-09-30 13:23',
            approval_status__code=Status.UNPROCESSED)
        self.unapproved_contact.locations.add(
            LocationFactory.create(address_line_one="123",
                                   city="Nowhere",
                                   state="NO"))
        self.unapproved_contact.locations.add(
            LocationFactory.create(address_line_one="234",
                                   city="Nowhere",
                                   state="NO"))
        self.unapproved_contact.tags.add(self.west_tag)

        # Poision data. Should never show up.
        self.wrong_user = UserFactory(email="*****@*****.**")
        self.wrong = ContactFactory(partner=self.other_partner,
                                    name='wrong person',
                                    user=self.wrong_user,
                                    email="*****@*****.**",
                                    last_action_time='2015-09-03')
        self.wrong.locations.add(
            LocationFactory.create(city="Los Angeles", state="CA"))
        self.wrong.tags.add(self.east_tag)
        self.wrong.tags.add(self.west_tag)
        self.wrong.tags.add(self.bad_tag)

        # Archive archived data here. Doing this earlier in the set up results
        # in odd exceptions.
        self.partner_archived.archive()
        self.archived_contact.archive()
Example #39
0
class MyDashboardViewsTests(TestCase):
    def setUp(self):
        self.staff_user = UserFactory()
        group = Group.objects.get(name=CompanyUser.GROUP_NAME)
        self.staff_user.groups.add(group)
        self.staff_user.save()

        self.company = CompanyFactory()
        self.company.save()
        self.admin = CompanyUserFactory(user=self.staff_user,
                                        company=self.company)
        self.admin.save()
        self.microsite = MicrositeFactory(company=self.company)
        self.microsite.save()

        self.client = TestClient()
        self.client.login_user(self.staff_user)

        self.candidate_user = UserFactory(email="*****@*****.**")
        SavedSearchFactory(user=self.candidate_user,
                           url='http://test.jobs/search?q=django',
                           label='test Jobs')
        self.candidate_user.save()

        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,
                                   label='%s Jobs' % search)

    def test_number_of_searches_and_users_is_correct(self):
        response = self.client.post(
            reverse('dashboard') + '?company=' + str(self.company.id),
            {'microsite': 'test.jobs'})
        soup = BeautifulSoup(response.content)
        # 10 searches total, two rows per search
        self.assertEqual(len(soup.select('#row-link-table tr')), 20)

        old_search = SavedSearch.objects.all()[0]
        old_search.created_on -= timedelta(days=31)
        old_search.save()

        response = self.client.post(
            reverse('dashboard') + '?company=' + str(self.company.id),
            {'microsite': 'test.jobs'})
        soup = BeautifulSoup(response.content)
        self.assertEqual(len(soup.select('#row-link-table tr')), 20)

    # Tests to see if redirect from /candidates/ goes to candidates/view/
    def test_redirect_to_candidates_views_default_page(self):
        response = self.client.post('/candidates/')

        # response returns HttpResponsePermanentRedirect which returns a 301
        # status code instead of the normal 302 redirect status code
        self.assertRedirects(response,
                             '/candidates/view/',
                             status_code=301,
                             target_status_code=200)

        response = self.client.post(reverse('dashboard'))

        self.assertEqual(response.status_code, 200)

        soup = BeautifulSoup(response.content)
        company_name = soup.find('h1')
        company_name = company_name.next

        self.assertEqual(company_name, self.company.name)

    # Eventually these opted-in/out will be changed to
    # track if user is part of company's activity feed
    def test_candidate_has_opted_in(self):
        response = self.client.post(
            reverse('candidate_information', ) + '?company=' +
            str(self.company.id) + '&user='******'candidate_information', ) + '?company=' +
            str(self.company.id) + '&user='******'candidate_information', ) + '?company=' +
            str(self.company.id) + '&user='******'div', {
            'id': 'candidate-content'
        }).findAll('a', {'class': 'accordion-toggle'})
        info = soup.find('div', {'id': 'candidate-content'}).findAll('li')

        self.assertEqual(len(titles), 6)
        self.assertEqual(len(info), 16)
        self.assertEqual(response.status_code, 200)

    def test_candidate_page_load_without_profileunits_with_activites(self):
        response = self.client.post(
            reverse('candidate_information', ) + '?company=' +
            str(self.company.id) + '&user='******'div', {
            'id': 'candidate-content'
        }).findAll('a', {'class': 'accordion-toggle'})
        info = soup.find('div', {'id': 'candidate-content'}).findAll('li')

        self.assertEqual(len(titles), 1)
        self.assertEqual(len(info), 3)
        self.assertEqual(response.status_code, 200)

    def test_candidate_page_load_without_profileunits_and_activites(self):
        saved_search = SavedSearch.objects.get(user=self.candidate_user)
        saved_search.delete()
        response = self.client.post(
            reverse('candidate_information', ) + '?company=' +
            str(self.company.id) + '&user='******'div', {'id': 'candidate-content'})

        self.assertFalse(info)
        self.assertEqual(response.status_code, 404)

    def test_export_csv(self):
        response = self.client.post(
            reverse('export_candidates') + '?company=' + str(self.company.id) +
            '&ex-t=csv')
        self.assertTrue(response.content)
        self.assertEqual(response.status_code, 200)

    def test_export_pdf(self):
        response = self.client.post(
            reverse('export_candidates') + '?company=' + str(self.company.id) +
            '&ex-t=pdf')
        self.assertTrue(response.content.index('PDF'))
        self.assertEqual(response.templates[0].name,
                         'mydashboard/export/candidate_listing.html')
        self.assertEqual(response.status_code, 200)

    def test_export_xml(self):
        response = self.client.post(
            reverse('export_candidates') + '?company=' + str(self.company.id) +
            '&ex-t=xml')
        self.assertTrue(response.content.index('candidates'))
        self.assertEqual(response.status_code, 200)

    def test_export_json(self):
        response = self.client.post(
            reverse('export_candidates') + '?company=' + str(self.company.id) +
            '&ex-t=json')
        self.assertTrue(response.content.index('candidates'))
        self.assertEqual(response.status_code, 200)
Example #40
0
 def setUp(self):
     super(MyProfileTests, self).setUp()
     self.user = UserFactory()
Example #41
0
 def test_staff_user_type(self):
     """Staff user type"""
     user = UserFactory.create(email='*****@*****.**')
     user.is_staff = True
     self.assert_user_type('STAFF', user)
Example #42
0
 def setUp(self):
     self.user = UserFactory()
     self.name = PrimaryNameFactory(user=self.user)
Example #43
0
class AccountFormTests(TestCase):
    def setUp(self):
        self.user = UserFactory()
        self.name = PrimaryNameFactory(user=self.user)

    def test_password_form(self):
        invalid_data = [
            {
                'data': {
                    'password': '******',
                    'new_password1': 'newpassword',
                    'new_password2': 'newpassword'
                },
                u'errors': [['password', [u"Wrong password."]]]
            },
            {
                'data': {
                    'password': '******',
                    'new_password1': 'newpassword',
                    'new_password2': 'notnewpassword'
                },
                u'errors': [[
                    u'new_password2',
                    [u'The new password fields did not match.']
                ],
                            [
                                u'new_password1',
                                [u'The new password fields did not match.']
                            ]],
            },
        ]

        for item in invalid_data:
            form = ChangePasswordForm(user=self.user, data=item['data'])
            self.failIf(form.is_valid())
            self.assertEqual(form.errors[item[u'errors'][0][0]],
                             item[u'errors'][0][1])

        form = ChangePasswordForm(user=self.user,
                                  data={
                                      'password': '******',
                                      'new_password1': 'anothersecret',
                                      'new_password2': 'anothersecret'
                                  })

        self.failUnless(form.is_valid())
        form.save()
        self.failUnless(self.user.check_password('anothersecret'))

    def test_no_name_account_form(self):
        """
        Leaving both the first and last name fields blank produces a valid save.
        It also deletes the primary name object from the Name model.
        """
        data = {"gravatar": "*****@*****.**", "user": self.user}
        form = EditAccountForm(data, **{'user': self.user})
        self.assertTrue(form.is_valid())
        form.save(self.user)
        self.assertEqual(Name.objects.count(), 0)

    def test_both_names_account_form(self):
        """
        Filling out both name fields produces a valid save.
        """

        data = {
            "given_name": "Alicia",
            "family_name": "Smith",
            "gravatar": "*****@*****.**"
        }
        form = EditAccountForm(data, **{'user': self.user})
        self.assertTrue(form.is_valid())

    def test_partial_name_account_form(self):
        """
        Filling out only the first name or only the last name produces an error.
        """
        data = {
            "given_name": "Alicia",
            "gravatar": "*****@*****.**",
            "user": self.user
        }
        form = EditAccountForm(data, **{'user': self.user})
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['family_name'][0],
                         "Both a first and last name required.")
Example #44
0
 def setUp(self):
     super(CommonTagsTests, self).setUp()
     self.user = UserFactory()
     self.context = Context({'user': self.user})
Example #45
0
class AccountFormTests(TestCase):
    def setUp(self):
        self.user = UserFactory()
        self.name = PrimaryNameFactory(user=self.user)
        self.client = TestClient()

    def test_password_form(self):
        invalid_data = [
            {
                'data': {
                    'password': '******',
                    'new_password1': 'newpassword',
                    'new_password2': 'newpassword'
                },
                u'errors': [['password', [u"Wrong password."]]]
            },
            {
                'data': {
                    'password': '******',
                    'new_password1': 'newpassword',
                    'new_password2': 'notnewpassword'
                },
                u'errors': [[
                    u'new_password2',
                    [u'The new password fields did not match.']
                ],
                            [
                                u'new_password1',
                                [u'The new password fields did not match.']
                            ]],
            },
        ]

        for item in invalid_data:
            form = ChangePasswordForm(user=self.user, data=item['data'])
            self.failIf(form.is_valid())
            self.assertEqual(form.errors[item[u'errors'][0][0]],
                             item[u'errors'][0][1])

        form = ChangePasswordForm(user=self.user,
                                  data={
                                      'password': '******',
                                      'new_password1': 'anothersecret',
                                      'new_password2': 'anothersecret'
                                  })

        self.failUnless(form.is_valid())
        form.save()
        self.failUnless(self.user.check_password('anothersecret'))

    def test_no_name_account_form(self):
        """
        Leaving both the first and last name fields blank produces a valid save.
        It also deletes the primary name object from the Name model.
        """
        data = {"gravatar": "*****@*****.**", "user": self.user}
        form = EditAccountForm(data, **{'user': self.user})
        self.assertTrue(form.is_valid())
        form.save(self.user)
        self.assertEqual(Name.objects.count(), 0)

    def test_both_names_account_form(self):
        """
        Filling out both name fields produces a valid save.
        """

        data = {
            "given_name": "Alicia",
            "family_name": "Smith",
            "gravatar": "*****@*****.**"
        }
        form = EditAccountForm(data, **{'user': self.user})
        self.assertTrue(form.is_valid())

    def test_partial_name_account_form(self):
        """
        Filling out only the first name or only the last name produces an error.
        """
        data = {
            "given_name": "Alicia",
            "gravatar": "*****@*****.**",
            "user": self.user
        }
        form = EditAccountForm(data, **{'user': self.user})
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['family_name'][0],
                         "Both a first and last name required.")

    def test_gravatar_email_list(self):
        """
        Dropdowns for selecting the user's preferred Gravatar email should be
        the only dropdowns that include "Do not use Gravatar" as an option -
        others should default to the user's primary email address.
        """
        self.client.login_user(self.user)
        response = self.client.get(reverse('edit_communication'))
        soup = BeautifulSoup(response.content)
        options = soup.select('#id_digest_email option')
        self.assertEqual(len(options), 1)
        self.assertTrue(self.user.gravatar in options[0])

        response = self.client.get(reverse('edit_basic'))
        soup = BeautifulSoup(response.content)
        options = soup.select('#id_gravatar option')
        self.assertEqual(len(options), 2)
        self.assertTrue('Do not use Gravatar' in options[0])
        self.assertTrue(self.user.gravatar in options[1])
Example #46
0
 def setUp(self):
     self.user = UserFactory()
     self.name = PrimaryNameFactory(user=self.user)
     self.client = TestClient()
Example #47
0
class MyProfileTests(TestCase):
    user_info = {
        'password1': 'complicated_password',
        'email': '*****@*****.**'
    }

    def setUp(self):
        super(MyProfileTests, self).setUp()
        self.user = UserFactory()

    def test_primary_name_save(self):
        """
        Saving a primary name when one already exists replaces it with
        the new primary name.
        """

        initial_name = PrimaryNameFactory(user=self.user)

        self.assertTrue(initial_name.primary)
        new_name = NewPrimaryNameFactory(user=self.user)
        initial_name = Name.objects.get(given_name='Alice')
        self.assertTrue(new_name.primary)
        self.assertFalse(initial_name.primary)

    def test_primary_name_save_multiuser(self):
        """
        Saving primary names when multiple users are present accurately
        sets and retrieves the correct name
        """
        self.user_2 = UserFactory(email='*****@*****.**')
        user_2_initial_name = PrimaryNameFactory(user=self.user_2)
        user_2_new_name = NewPrimaryNameFactory(user=self.user_2)

        initial_name = PrimaryNameFactory(user=self.user)
        new_name = NewPrimaryNameFactory(user=self.user)

        user_2_initial_name = Name.objects.get(given_name='Alice',
                                               user=self.user_2)
        user_2_new_name = Name.objects.get(given_name='Alicia',
                                           user=self.user_2)
        initial_name = Name.objects.get(given_name='Alice', user=self.user)

        self.assertTrue(new_name.primary)
        self.assertFalse(initial_name.primary)
        self.assertTrue(user_2_new_name.primary)
        self.assertFalse(user_2_initial_name.primary)

        with self.assertRaises(MultipleObjectsReturned):
            Name.objects.get(primary=True)
            Name.objects.get(primary=False)
            Name.objects.get(given_name='Alice')
            Name.objects.get(given_name='Alicia')
        Name.objects.get(primary=True, user=self.user_2)

    def test_email_activation_creation(self):
        """
        Creating a new secondary email creates a corresponding unactivated
        ActivationProfile.
        """

        secondary_email = SecondaryEmailFactory(user=self.user)
        activation = ActivationProfile.objects.get(email=secondary_email.email)
        self.assertEqual(secondary_email.email, activation.email)

    def test_send_activation(self):
        """
        The send_activation method in SecondaryEmail should send an
        activation link to the email address
        """

        secondary_email = SecondaryEmailFactory(user=self.user)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].to, [secondary_email.email])
        self.assertTrue('secondary email' in mail.outbox[0].body)

    def test_verify_email(self):
        """
        Clicking the activation link sets the ActivationProfile object to
        activated and sets the SecondaryEmail object to verified.
        """

        secondary_email = SecondaryEmailFactory(user=self.user)
        activation = ActivationProfile.objects.get(user=self.user,
                                                   email=secondary_email.email)
        response = self.client.get(
            reverse('registration_activate', args=[activation.activation_key])
            + '?verify-email=%s' % self.user.email)
        secondary_email = SecondaryEmail.objects.get(
            user=self.user, email=secondary_email.email)
        activation = ActivationProfile.objects.get(user=self.user,
                                                   email=secondary_email.email)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(secondary_email.verified)

    def test_set_primary_email(self):
        """
        Calling the set_as_primary method in the SecondaryEmail removes it from
        SecondaryEmail, replaces the current address on the User model, and
        adds the replaced address to the SecondaryEmail table.

        """
        old_primary = self.user.email
        secondary_email = SecondaryEmailFactory(user=self.user)
        new_primary = secondary_email.email

        for email in [old_primary, new_primary]:
            # Emails must be verified to make them primary.
            activation = ActivationProfile.objects.get_or_create(
                user=self.user, email=email)[0]
            ActivationProfile.objects.activate_user(activation.activation_key)

        secondary_email = SecondaryEmail.objects.get(email=new_primary)
        secondary_email.set_as_primary()

        with self.assertRaises(SecondaryEmail.DoesNotExist):
            SecondaryEmail.objects.get(email=new_primary)
        old_email = SecondaryEmail.objects.get(email=old_primary)
        self.assertTrue(old_email.verified)
        user = User.objects.get(email=new_primary)

    def test_duplicate_same_primary_name(self):
        """
        Makes sure that one can not create duplicate primary names.
        """
        primary_name1 = PrimaryNameFactory(user=self.user)
        primary_name2 = PrimaryNameFactory(user=self.user)

        num_results = self.user.profileunits_set.filter(
            content_type__name='name').count()
        self.assertEqual(num_results, 1)

    def test_different_primary_name(self):
        primary_name1 = PrimaryNameFactory(user=self.user)
        primary_name2 = NewPrimaryNameFactory(user=self.user)

        primary_name_count = Name.objects.filter(user=self.user,
                                                 primary=True).count()
        non_primary_name_count = Name.objects.filter(user=self.user,
                                                     primary=False).count()

        self.assertEqual(primary_name_count, 1)
        self.assertEqual(non_primary_name_count, 1)

    def test_non_primary_name_to_primary(self):
        name = NewNameFactory(user=self.user)
        primary_name1 = PrimaryNameFactory(user=self.user)

        primary_name_count = Name.objects.filter(user=self.user,
                                                 primary=True).count()
        non_primary_name_count = Name.objects.filter(user=self.user,
                                                     primary=False).count()

        self.assertEqual(primary_name_count, 1)
        self.assertEqual(non_primary_name_count, 0)

    def test_primary_name_to_non_primary(self):
        primary_name = PrimaryNameFactory(user=self.user)
        primary_name.primary = False
        primary_name.save()

        primary_name_count = Name.objects.filter(user=self.user,
                                                 primary=True).count()
        non_primary_name_count = Name.objects.filter(user=self.user,
                                                     primary=False).count()

        self.assertEqual(primary_name_count, 0)
        self.assertEqual(non_primary_name_count, 1)

    def test_duplicate_name(self):
        """
        Makes sure that duplicate names is not saving.
        """
        name1 = NewNameFactory(user=self.user)
        name2 = NewNameFactory(user=self.user)

        num_results = Name.objects.filter(user=self.user).count()
        self.assertEqual(num_results, 1)

    def test_unverified_primary_email(self):
        """
        Only verified emails can be set as the primary email
        """

        old_primary = self.user.email
        secondary_email = SecondaryEmailFactory(user=self.user)
        primary = secondary_email.set_as_primary()

        with self.assertRaises(SecondaryEmail.DoesNotExist):
            SecondaryEmail.objects.get(email=old_primary)
        self.assertFalse(primary)
        user = User.objects.get(email=old_primary)
        self.assertEqual(user.email, old_primary)

    def test_maintain_verification_state(self):
        """
        For security reasons, the state of verification of the user email
        should be the same as it is when it is transferred into SecondaryEmail
        """

        old_primary = self.user.email
        self.user.is_active = False
        self.user.save()
        secondary_email = SecondaryEmailFactory(user=self.user)
        activation = ActivationProfile.objects.get(user=self.user,
                                                   email=secondary_email.email)
        ActivationProfile.objects.activate_user(activation.activation_key)
        secondary_email = SecondaryEmail.objects.get(
            user=self.user, email=secondary_email.email)
        new_primary = secondary_email.email
        secondary_email.set_as_primary()

        old_email = SecondaryEmail.objects.get(email=old_primary)
        self.assertFalse(old_email.verified)
        user = User.objects.get(email=new_primary)

    def test_same_secondary_email(self):
        """
        All emails are unique. If an email is used as a user's primary email or
        another secondary email, it may not be used as a secondary email again.
        """
        secondary_email = SecondaryEmailFactory(user=self.user)
        with self.assertRaises(IntegrityError):
            new_secondary_email = SecondaryEmailFactory(user=self.user)
        new_secondary_email = SecondaryEmailFactory(user=self.user,
                                                    email='*****@*****.**')

    def test_delete_secondary_email(self):
        """
        Deleting a secondary email should also delete its activation profile
        """
        self.assertEqual(ActivationProfile.objects.count(), 0)
        secondary_email = SecondaryEmailFactory(user=self.user)
        self.assertEqual(ActivationProfile.objects.count(), 1)
        secondary_email.delete()
        self.assertEqual(ActivationProfile.objects.count(), 0)

    def test_add_military_service(self):
        military_service = MilitaryServiceFactory(user=self.user)
        military_service.save()

        ms_object = ProfileUnits.objects.filter(
            content_type__name="military service").count()
        self.assertEqual(ms_object, 1)

    def test_add_license(self):
        license_form = LicenseFactory(user=self.user)
        license_form.save()

        ms_object = ProfileUnits.objects.filter(
            content_type__name="license").count()
        self.assertEqual(ms_object, 1)

    def test_add_website(self):
        website_instance = WebsiteFactory(user=self.user)
        website_instance.save()

        ms_object = ProfileUnits.objects.filter(
            content_type__name="website").count()
        self.assertEqual(ms_object, 1)

    def test_add_summary(self):
        summary_instance = SummaryFactory(user=self.user)
        summary_instance.save()

        ms_object = ProfileUnits.objects.filter(
            content_type__name="summary").count()
        self.assertEqual(ms_object, 1)

    def test_add_volunteer_history(self):
        vh_instance = VolunteerHistoryFactory(user=self.user)
        vh_instance.save()

        ms_object = ProfileUnits.objects.filter(
            content_type__name="volunteer history").count()
        self.assertEqual(ms_object, 1)
Example #48
0
class NewUserTests(SeleniumTestCase):
    """Tests Account creation"""
    def setUp(self):
        super(NewUserTests, self).setUp()
        company = CompanyFactory()
        self.user = UserFactory(first_name="John", last_name="Doe")
        admin_role = RoleFactory(company=company, name='Admin')
        self.user.roles.add(self.admin_role)

    def test_home_page_works(self):
        """
        As John, navigating to https://secure.my.jobs should send me to a page
        titled "My.jobs".
        """
        self.browser.get(self.live_server_url)
        self.assertIn(self.browser.title, 'My.jobs')

    def test_cant_log_in_without_account(self):
        """
        As John, I shouldn't be able to log into My.jobs without registering
        first.
        """
        self.browser.get('/'.join([self.live_server_url, 'prm', 'view']))

        # We're trying to access a private page while unauthenticated, which
        # should result in a next parameter being added.
        self.assertTrue('next=' in self.browser.current_url)

        # attempt to log in
        username = self.find('id_username')
        username.send_keys(self.user.email)
        self.find('id_password').send_keys(self.user.password)
        self.find('login').click()

        # If we've logged in, the next parameter should have went away. We
        # aren't expecting to be logged in right now as the password was bad.
        self.assertTrue('next=' in self.browser.current_url)

    def test_user_registration(self):
        """
        As John, I should be able to register on My.jobs and log in.
        """
        self.browser.get('/'.join([self.live_server_url, 'prm', 'view']))

        # register
        self.find('id_email').send_keys('*****@*****.**')
        self.find('id_password1').send_keys('aaAA11..')
        self.find('id_password2').send_keys('aaAA11..')
        self.find('register').click()

        try:
            WebDriverWait(self.browser, 10).until(
                expected_conditions.presence_of_element_located(
                    (By.ID, 'profile')))
        finally:
            self.assertEqual(
                self.find('profile').get_attribute('innerHTML'),
                'Skip: Take me to my profile')

    def test_user_login(self):
        self.user.set_password("test")
        self.user.save()
        self.find('id_username').send_keys(self.user.email)
        self.find('id_password').send_keys("test")
        self.find('login').click()
Example #49
0
    def setUp(self):
        super(TestCommRecordsDataSource, self).setUp()

        # A company to work with
        self.company = CompanyFactory(name='right')
        self.company.save()

        # A separate company that should not show up in results.
        self.other_company = CompanyFactory(name='wrong')
        self.other_company.save()

        self.partner_a = PartnerFactory(owner=self.company,
                                        uri='http://www.example.com/',
                                        data_source="zap",
                                        name="aaa")
        self.partner_b = PartnerFactory(owner=self.company,
                                        uri='http://www.asdf.com/',
                                        data_source="bcd",
                                        name="bbb")
        # An unapproved parther. Associated data should be filtered out.
        self.partner_unapp = PartnerFactory(
            owner=self.company,
            name="unapproved",
            approval_status__code=Status.UNPROCESSED)
        # An archived parther. Associated data should be filtered out.
        self.partner_archived = PartnerFactory(owner=self.company)

        self.east_tag = TagFactory.create(company=self.company,
                                          name='east',
                                          hex_color="aaaaaa")
        self.west_tag = TagFactory.create(company=self.company,
                                          name='west',
                                          hex_color="bbbbbb")
        self.north_tag = TagFactory.create(company=self.company,
                                           name='north',
                                           hex_color="cccccc")
        self.south_tag = TagFactory.create(company=self.company,
                                           name='south',
                                           hex_color="dddddd")
        self.left_tag = TagFactory.create(company=self.company,
                                          name='left',
                                          hex_color="eeeeee")
        self.right_tag = TagFactory.create(company=self.company,
                                           name='right',
                                           hex_color="ffffff")
        self.bad_tag = TagFactory.create(company=self.company,
                                         name='bad',
                                         hex_color="cccccc")

        self.partner_a.tags.add(self.left_tag)
        self.partner_b.tags.add(self.right_tag)

        self.john_user = UserFactory(email="*****@*****.**")
        self.john = ContactFactory(partner=self.partner_a,
                                   name='john adams',
                                   user=self.john_user,
                                   email="*****@*****.**",
                                   last_action_time='2015-10-03')
        self.john.locations.add(
            LocationFactory.create(city="Indianapolis", state="IN"))
        self.john.locations.add(
            LocationFactory.create(city="Chicago", state="IL"))
        self.john.tags.add(self.north_tag)

        self.sue_user = UserFactory(email="*****@*****.**")
        self.sue = ContactFactory(partner=self.partner_b,
                                  name='Sue Baxter',
                                  user=self.sue_user,
                                  email="*****@*****.**",
                                  last_action_time='2015-09-30 13:23')
        self.sue.locations.add(
            LocationFactory.create(address_line_one="123",
                                   city="Los Angeles",
                                   state="CA"))
        self.sue.locations.add(
            LocationFactory.create(address_line_one="234",
                                   city="Los Angeles",
                                   state="CA"))
        self.sue.tags.add(self.south_tag)

        self.partner_a.primary_contact = self.john
        self.partner_b.primary_contact = self.sue

        self.partner_a.save()
        self.partner_b.save()

        self.record_1 = ContactRecordFactory(subject='record 1',
                                             date_time='2015-09-30 13:23',
                                             contact=self.john,
                                             contact_type="Email",
                                             partner=self.partner_a,
                                             location='Indianapolis, IN',
                                             tags=[self.east_tag])
        self.record_2 = ContactRecordFactory(subject='record 2',
                                             date_time='2015-01-01',
                                             contact=self.john,
                                             contact_type="Meeting Or Event",
                                             partner=self.partner_a,
                                             location='Indianapolis, IN',
                                             tags=[self.east_tag])
        self.record_3 = ContactRecordFactory(subject='record 3',
                                             date_time='2015-10-03',
                                             contact=self.sue,
                                             contact_type="Phone",
                                             partner=self.partner_b,
                                             location='Los Angeles, CA',
                                             tags=[self.west_tag])

        # Archive archived data here. Doing this earlier in the set up results
        # in odd exceptions.
        self.partner_archived.archive()
Example #50
0
 def setUp(self):
     self.user = UserFactory()
     self.company = CompanyFactory()
     self.data = {'user': self.user.id,
                  'company': self.company.id}
Example #51
0
 def setUp(self):
     self.user = UserFactory()
     self.redirect_middleware = RedirectMiddleware()
     self.request_factory = RequestFactory()
Example #52
0
 def test_custom_password_reset_form(self):
     form = CustomPasswordResetForm({'email':self.user.email})
     self.assertTrue(form.is_valid())
     user = UserFactory(email='*****@*****.**', is_active=False)
     form = CustomPasswordResetForm({'email':user.email})
     self.assertTrue(form.is_valid())
Example #53
0
 def setUp(self):
     super(MyProfileViewsTests, self).setUp()
     self.user = UserFactory()
     self.client = TestClient()
     self.client.login_user(self.user)
     self.name = PrimaryNameFactory(user=self.user)
Example #54
0
 def setUp(self):
     super(SavedSearchDeletionTests, self).setUp()
     self.creator = UserFactory(email='*****@*****.**')
     self.search = SavedSearchFactory(user=self.user)
     self.partner_search = PartnerSavedSearchFactory(
         user=self.user, created_by=self.creator)
Example #55
0
 def test_jobseeker(self):
     """User object exists but has no relevant privileges."""
     user = UserFactory.create(email='*****@*****.**')
     self.assert_user_type(None, user)
Example #56
0
    def setUp(self):
        super(BlocksTestBase, self).setUp()
        self.site = SeoSite.objects.get()
        self.config = Configuration.objects.get(status=2)
        self.config.browse_facet_show = True
        self.config.save()

        # Can't do a get_or_create here because we don't
        # care about the date_crawled/date_updated fields,
        # but if the BusinessUnit doesn't exist they will need
        # to be supplied.
        try:
            self.buid = BusinessUnit.objects.get(pk=0)
        except BusinessUnit.DoesNotExist:
            self.buid = BusinessUnitFactory(id=0)
        self.site.business_units.add(0)

        self.commitment = SpecialCommitmentFactory()
        self.site.special_commitments.add(self.commitment)
        self.site.save()

        self.tag = SiteTag.objects.create(site_tag='Test tag')
        self.site.site_tags.add(self.tag)
        self.site.save()

        self.job = SOLR_FIXTURE[1]
        self.conn.add([self.job])

        self.user = UserFactory()

        url = reverse('all_jobs')
        self.search_results_request = RequestFactory().get(url)
        self.search_results_request.user = self.user

        self.q_kwargs = {'q': self.job['title']}
        url = build_url(reverse('all_jobs'), self.q_kwargs)
        self.search_results_with_q_request = RequestFactory().get(url)
        self.search_results_with_q_request.user = self.user

        self.facet = CustomFacetFactory(show_production=True,
                                        name='%s' % self.job['title'],
                                        name_slug='%s' %
                                        self.job['title_slug'],
                                        querystring='*',
                                        blurb='Test')
        self.bad_facet = CustomFacetFactory(show_production=True,
                                            name='Bad Facet',
                                            name_slug='bad-facet',
                                            querystring='asfljasdlfjsadfsdf',
                                            blurb='Test',
                                            always_show=True)
        SeoSiteFacetFactory(customfacet=self.facet, seosite=self.site)
        SeoSiteFacetFactory(customfacet=self.bad_facet, seosite=self.site)

        url = '%s/new-jobs/' % self.job['title_slug']
        self.search_results_with_custom_facet = RequestFactory().get(url)
        self.search_results_with_custom_facet.user = self.user

        self.job_detail_kwargs = {
            'job_id': self.job['guid'],
            'title_slug': self.job['title_slug'],
            'location_slug': slugify(self.job['location']),
        }
        url = reverse('job_detail_by_location_slug_title_slug_job_id',
                      kwargs=self.job_detail_kwargs)
        self.job_detail_request = RequestFactory().get(url)
        self.job_detail_request.user = self.user

        kwargs = {'job_id': self.job['guid']}
        url = reverse('job_detail_by_job_id', kwargs=kwargs)
        self.job_detail_redirect_request = RequestFactory().get(url)
        self.job_detail_redirect_request.user = self.user

        # Send a request through middleware so all the required
        # settings (from MultiHostMiddleware) actually get set.
        self.client.get('/')
Example #57
0
 def test_jobseeker_user_type(self):
     """Jobseeker user type"""
     user = UserFactory.create(email='*****@*****.**')
     self.assert_user_type(None, user)
Example #58
0
 def setUp(self):
     self.user = UserFactory()
Example #59
0
 def setUp(self):
     super(NewUserTests, self).setUp()
     company = CompanyFactory()
     self.user = UserFactory(first_name="John", last_name="Doe")
     admin_role = RoleFactory(company=company, name='Admin')
     self.user.roles.add(self.admin_role)
Example #60
0
class MyJobsAdminTests(MyJobsBase):
    def setUp(self):
        super(MyJobsAdminTests, self).setUp()
        self.user.set_password('5UuYquA@')
        self.user.is_superuser = True
        self.user.save()
        self.account_owner = UserFactory(email='*****@*****.**')
        SeoSiteFactory(domain='secure.my.jobs')
        mail.outbox = []

        self.data = {
            '_selected_action': [unicode(self.account_owner.pk)],
            'action': 'request_account_access'
        }

    def test_request_access_to_staff(self):
        """
        Requesting access to a staff/superuser account is not allowed.
        """
        self.account_owner.is_staff = True
        self.account_owner.save()

        # Selecting the action in the User changelist and pressing "OK" should
        # immediately show a notification at the top of the page.
        response = self.client.post(reverse('admin:myjobs_user_changelist'),
                                    self.data,
                                    follow=True)
        self.assertEqual(len(mail.outbox), 0)
        self.assertContains(response, ("Requesting access to staff or "
                                       "superusers is not supported."))

        # Manually constructing a post to the relevant url should redirect
        # to the User changelist and not send notification emails.
        response = self.client.post(
            reverse('request-account-access',
                    kwargs={'uid': self.account_owner.pk}),
            {'reason': 'reason here'})

        self.assertRedirects(response, reverse('admin:myjobs_user_changelist'))
        self.assertEqual(len(mail.outbox), 0)

    def test_request_access_to_non_staff(self):
        """
        Requesting access to a non-staff/superuser account succeeds if the
        target is not a staff/superuser account and the requesting staff
        member provides a reason.
        """
        # Request access to an account to get to the request form.
        response = self.client.post(reverse('admin:myjobs_user_changelist'),
                                    self.data,
                                    follow=True)
        self.assertContains(response,
                            "What is the nature of this request?",
                            msg_prefix="Did not redirect to the request form")
        url = reverse('request-account-access',
                      kwargs={'uid': self.account_owner.pk})
        last_redirect = response.redirect_chain[-1][0]

        # If the admin action determines that it is valid, it redirects. Ensure
        # we redirected to the expected location.
        self.assertTrue(last_redirect.endswith(url),
                        msg="Did not redirect as expected")

        # Try submitting the request form without a reason.
        response = self.client.post(url)
        self.assertContains(response,
                            "This field is required.",
                            msg_prefix=("Form error not present on invalid "
                                        "submission"))
        self.assertEqual(len(mail.outbox),
                         0,
                         msg="Mail sent despite form errors")

        # # Submit again, providing a reason.
        self.client.post(url, {'reason': 'reason here'})
        self.assertEqual(len(mail.outbox),
                         1,
                         msg="Mail did not send on successful form submission")
        email = mail.outbox[0]
        self.assertTrue(self.account_owner.email in email.to,
                        msg="Email was sent to the wrong user")
        self.assertTrue('reason here' in email.body,
                        msg="Account access reason was not in the sent email")

    def test_export_as_csv_admin_action(self):
        """
        Tests the ability to export the list of destination manipulations as a
        CSV.

        """
        email = '*****@*****.**'
        password = '******'
        UserFactory(email=email,
                    password=password,
                    is_staff=True,
                    is_superuser=True)
        # only superusers are allowed to use Django amin
        self.client.login(username=email, password=password)

        manipulations = [
            DestinationManipulationFactory(view_source=i)
            for i in range(200, 210)
        ]
        # this is the format we expect results to be in if deserializing CSV
        # into a list of dicts
        formatted_manipulations = [{
            u'View Source': unicode(m.view_source),
            u'View Source Name': '',
            u'BUID': unicode(m.buid),
            u'Action Type': unicode(m.action_type),
            u'Value 1': unicode(m.value_1),
            u'Value 2': unicode(m.value_2),
            u'Action': unicode(m.action)
        } for m in manipulations]

        args = {
            'action': 'export_as_csv',
            '_selected_action': [unicode(m.pk) for m in manipulations[:5]]
        }
        changelist_url = reverse(
            "admin:redirect_destinationmanipulation_changelist")

        # asking to export as csv when selected items should serialize only
        # those items
        response = self.client.post(changelist_url, args)
        reader = csv.DictReader(response.content.split('\r\n'))
        self.assertItemsEqual(list(reader), formatted_manipulations[:5])

        args['select_across'] = '1'

        # choosing "select all" should export all records in the queryset,
        # regardless of the list of selected items passed
        response = self.client.post(changelist_url, args)
        reader = csv.DictReader(response.content.split('\r\n'))
        self.assertItemsEqual(list(reader), formatted_manipulations)