示例#1
0
文件: views.py 项目: jpaezsa/MyJobs
    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)
示例#2
0
class PostajobTestBase(MyJobsBase):
    def setUp(self):
        super(PostajobTestBase, self).setUp()
        self.user = UserFactory(password='******')
        self.company = CompanyFactory(product_access=True, posting_access=True)

        self.site = SeoSiteFactory(canonical_company=self.company)
        self.bu = BusinessUnitFactory()
        self.site.business_units.add(self.bu)
        self.site.save()
        self.company.job_source_ids.add(self.bu)
        self.company.save()
        self.company_user = CompanyUserFactory(user=self.user,
                                               company=self.company)
        SitePackageFactory(owner=self.company)
        self.package = Package.objects.get()
        self.sitepackage = SitePackage.objects.get()
        self.sitepackage.sites.add(self.site)
        self.product = ProductFactory(package=self.package, owner=self.company)

        self.login_user()

    def login_user(self, user=None):
        if not user:
            user = self.user
        self.client.post(reverse('home'),
                         data={
                             'username': user.email,
                             'password': '******',
                             'action': 'login',
                             })
示例#3
0
文件: views.py 项目: jpaezsa/MyJobs
    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)
示例#4
0
    def test_outreach_domain_unique_to_company(self):
        """
        Allowed domains should be unique within a company, but not necessarily
        across PRM.
        """

        OutreachEmailDomain.objects.create(company=self.company, 
                                           domain="foo.bar")

        # duplicate domains allowed between companies
        company = CompanyFactory.create(name="A Whole New World")
        OutreachEmailDomain.objects.create(company=company,
                                           domain="foo.bar")

        # dupliate domains disallowed within the same company
        with self.assertRaises(IntegrityError):
            OutreachEmailDomain.objects.create(company=self.company, 
                                               domain="foo.bar")
示例#5
0
    def setUp(self):
        super(PostajobTestBase, self).setUp()
        self.user = UserFactory(password='******')
        self.company = CompanyFactory(product_access=True, posting_access=True)

        self.site = SeoSiteFactory(canonical_company=self.company)
        self.bu = BusinessUnitFactory()
        self.site.business_units.add(self.bu)
        self.site.save()
        self.company.job_source_ids.add(self.bu)
        self.company.save()
        self.company_user = CompanyUserFactory(user=self.user,
                                               company=self.company)
        SitePackageFactory(owner=self.company)
        self.package = Package.objects.get()
        self.sitepackage = SitePackage.objects.get()
        self.sitepackage.sites.add(self.site)
        self.product = ProductFactory(package=self.package, owner=self.company)

        self.login_user()
示例#6
0
    def setUp(self):
        super(ModelTests, self).setUp()
        self.user = User.objects.create(email='*****@*****.**')
        self.company = CompanyFactory()
        CompanyProfile.objects.create(company=self.company)
        self.site = SeoSiteFactory()
        self.bu = BusinessUnitFactory()
        self.site.business_units.add(self.bu)
        self.site.save()
        self.company.job_source_ids.add(self.bu)
        self.company.save()

        # Use the newly created site for testing instead of secure.my.jobs.
        settings.SITE = self.site

        self.request_data = {
            'title': 'title',
            'company': self.company.id,
            'reqid': '1',
            'description': 'sadfljasdfljasdflasdfj',
            'link': 'www.google.com',
            'on_sites': '0',
            'apply_info': '',
        }

        self.request_location = {
            'city': 'Indianapolis',
            'state': 'Indiana',
            'state_short': 'IN',
            'country': 'United States',
            'country_short': 'USA',
            'zipcode': '46268',
        }

        self.site_package_data = {
            'name': 'Test Site Package',
        }
    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(name='east', hex_color="aaaaaa")
        self.west_tag = TagFactory.create(name='west', hex_color="bbbbbb")
        self.bad_tag = TagFactory.create(name='bad', hex_color="cccccc")

        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.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.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()
class TestCommRecordsDataSource(MyJobsBase):
    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(name='east', hex_color="aaaaaa")
        self.west_tag = TagFactory.create(name='west', hex_color="bbbbbb")
        self.bad_tag = TagFactory.create(name='bad', hex_color="cccccc")

        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.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.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()

    def test_run_unfiltered(self):
        """Make sure we only get data for this user."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(self.company, CommRecordsFilter(), [])
        subjects = set([r['subject'] for r in recs])
        expected = {
            self.record_1.subject,
            self.record_2.subject,
            self.record_3.subject,
        }
        self.assertEqual(expected, subjects)

    def test_filter_by_date_range(self):
        """Should show only commrec with last_action_time in range."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(
                date_time=[datetime(2015, 9, 1), datetime(2015, 9, 30)]),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {self.record_1.subject}
        self.assertEqual(expected, subjects)

    def test_filter_by_date_before(self):
        """Should show only commrec with last_action_time before date."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(
                date_time=[None, datetime(2015, 9, 30)]),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {self.record_1.subject, self.record_2.subject}
        self.assertEqual(expected, subjects)

    def test_filter_by_date_after(self):
        """Should show only commrec with last_action_time after date."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(
                date_time=[datetime(2015, 10, 1), None]),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {self.record_3.subject}
        self.assertEqual(expected, subjects)

    def test_filter_by_state(self):
        """Should show only commrecs with correct state."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(
                locations={
                    'state': 'CA'
                }),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {self.record_3.subject}
        self.assertEqual(expected, subjects)

    def test_filter_by_city(self):
        """Should show only commrecs with correct city."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(
                locations={
                    'city': 'Los Angeles'
                }),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {self.record_3.subject}
        self.assertEqual(expected, subjects)

    def test_filter_by_tags(self):
        """Show only commrec with correct tags."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(tags=[['EaSt']]),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {self.record_1.subject, self.record_2.subject}
        self.assertEqual(expected, subjects)

    def test_filter_by_tags_or(self):
        """Show only commrec with correct tags in 'or' configuration."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(tags=[['EaSt', 'wEsT']]),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {
            self.record_1.subject,
            self.record_2.subject,
            self.record_3.subject,
        }
        self.assertEqual(expected, subjects)

    def test_filter_by_tags_and(self):
        """Show only commrec with correct tags in 'and' configuration."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(tags=[['EaSt'], ['wEsT']]),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = set()
        self.assertEqual(expected, subjects)

        # Now try adding another tag.
        self.record_1.tags.add(self.west_tag)
        self.record_1.save()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(tags=[['EaSt'], ['wEsT']]),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {self.record_1.subject}
        self.assertEqual(expected, subjects)

    def test_filter_by_empty_things(self):
        """Empty filters should not filter, just like missing filters."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(
                locations={'city': '', 'state': ''}),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {
            self.record_1.subject,
            self.record_2.subject,
            self.record_3.subject,
        }
        self.assertEqual(expected, subjects)

    def test_filter_by_communication_type(self):
        """Check communication_type filter works at all."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(communication_type='Email'),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {self.record_1.subject}
        self.assertEqual(expected, subjects)

    def test_filter_by_partner(self):
        """Check partner filter works at all."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(partner=[self.partner_a.pk]),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {self.record_1.subject, self.record_2.subject}
        self.assertEqual(expected, subjects)

    def test_filter_by_contact(self):
        """Check partner filter works at all."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(contact=[self.sue.pk]),
            [])
        subjects = set([r['subject'] for r in recs])
        expected = {self.record_3.subject}
        self.assertEqual(expected, subjects)

    def test_help_city(self):
        """Check city help works and ignores current city filter."""
        ds = CommRecordsDataSource()
        recs = ds.help_city(
            self.company,
            CommRecordsFilter(locations={'city': "zz"}),
            "angel")
        actual = set([r['key'] for r in recs])
        self.assertEqual({'Los Angeles'}, actual)

    def test_help_state(self):
        """Check state help works and ignores current state filter."""
        ds = CommRecordsDataSource()
        recs = ds.help_state(
            self.company,
            CommRecordsFilter(locations={'state': "zz"}),
            "i")
        actual = set([r['key'] for r in recs])
        self.assertEqual({'IL', 'IN'}, actual)

    def test_help_tags(self):
        """Check tags help works at all."""
        ds = CommRecordsDataSource()
        recs = ds.help_tags(self.company, CommRecordsFilter(), "E")
        actual = set([r['key'] for r in recs])
        self.assertEqual({'east', 'west'}, actual)

    def test_help_tags_colors(self):
        """Tags should have colors"""
        ds = CommRecordsDataSource()
        recs = ds.help_tags(self.company, CommRecordsFilter(), "east")
        self.assertEqual("aaaaaa", recs[0]['hexColor'])

    def test_help_communication_types(self):
        """Check communication_types help works at all."""
        ds = CommRecordsDataSource()
        recs = ds.help_communication_type(
            self.company, CommRecordsFilter(), "ph")
        actual = set([r['key'] for r in recs])
        self.assertEqual({'Phone'}, actual)

    def test_help_partner(self):
        """Check partner help works at all."""
        ds = CommRecordsDataSource()
        recs = ds.help_partner(self.company, CommRecordsFilter(), "A")
        self.assertEqual(
            [{'key': self.partner_a.pk, 'display': self.partner_a.name}],
            recs)

    def test_help_contact(self):
        """Check contact help works at all."""
        ds = CommRecordsDataSource()
        recs = ds.help_contact(self.company, CommRecordsFilter(), "U")
        self.assertEqual(
            [{'key': self.sue.pk, 'display': self.sue.name}],
            recs)

    def test_order(self):
        """Check ordering results works at all."""
        ds = CommRecordsDataSource()
        recs = ds.run_unaggregated(
            self.company,
            CommRecordsFilter(),
            ["-subject"])
        subjects = [r['subject'] for r in recs]
        expected = [
            self.record_3.subject,
            self.record_2.subject,
            self.record_1.subject,
        ]
        self.assertEqual(expected, subjects)
示例#9
0
class TestPartnersDataSource(MyJobsBase):
    def setUp(self):
        super(TestPartnersDataSource, 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,
            last_action_time='2015-09-30 13:23',
            uri='http://www.example.com/',
            data_source="zap",
            name="aaa")
        self.partner_b = PartnerFactory(
            owner=self.company,
            last_action_time='2015-10-03',
            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(name='east', hex_color="aaaaaa")
        self.west_tag = TagFactory.create(name='west', hex_color="bbbbbb")
        self.bad_tag = TagFactory.create(name='bad', hex_color="cccccc")

        self.partner_a.tags.add(self.east_tag)
        self.partner_b.tags.add(self.west_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.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.partner_a.primary_contact = self.john
        self.partner_b.primary_contact = self.sue

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

        # Archive archived data here. Doing this earlier in the set up results
        # in odd exceptions.
        self.partner_archived.archive()

    def test_run_unfiltered(self):
        """Make sure we only get data for this user."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(self.company, PartnersFilter(), [])
        names = set([r['name'] for r in recs])
        expected = {self.partner_a.name, self.partner_b.name}
        self.assertEqual(expected, names)
        expected_tags = {
            self.partner_a.pk: {'east'},
            self.partner_b.pk: {'west'},
        }

        def tags_by_pk(rec):
            return (rec['partner_id'], set(t['name'] for t in rec['tags']))

        found_tags = dict(tags_by_pk(r) for r in recs)

        self.assertEqual(expected_tags, found_tags)

    def test_run_count_comm_rec_per_month(self):
        """Make sure we only get data for this user."""
        for (subject, itx) in enumerate(['a', 'b', 'c']):
            for month in [2, 3, 4]:
                self.sue.contactrecord_set.add(
                    ContactRecordFactory(
                        subject=subject,
                        date_time=datetime(2015, month, 1)))

        ds = PartnersDataSource()
        recs = ds.run_count_comm_rec_per_month(
            self.company, PartnersFilter(), ['name', 'year', '-month'])
        data = [
            (r['name'], r['year'], r['month'], r['comm_rec_count'])
            for r in recs
        ]
        expected = [
            (self.partner_a.name, 2015, 12, 0),
            (self.partner_a.name, 2015, 11, 0),
            (self.partner_a.name, 2015, 10, 0),
            (self.partner_a.name, 2015, 9, 0),
            (self.partner_a.name, 2015, 8, 0),
            (self.partner_a.name, 2015, 7, 0),
            (self.partner_a.name, 2015, 6, 0),
            (self.partner_a.name, 2015, 5, 0),
            (self.partner_a.name, 2015, 4, 0),
            (self.partner_a.name, 2015, 3, 0),
            (self.partner_a.name, 2015, 2, 0),
            (self.partner_a.name, 2015, 1, 0),
            (self.partner_b.name, 2015, 12, 0),
            (self.partner_b.name, 2015, 11, 0),
            (self.partner_b.name, 2015, 10, 0),
            (self.partner_b.name, 2015, 9, 0),
            (self.partner_b.name, 2015, 8, 0),
            (self.partner_b.name, 2015, 7, 0),
            (self.partner_b.name, 2015, 6, 0),
            (self.partner_b.name, 2015, 5, 0),
            (self.partner_b.name, 2015, 4, 3),
            (self.partner_b.name, 2015, 3, 3),
            (self.partner_b.name, 2015, 2, 3),
            (self.partner_b.name, 2015, 1, 0),
        ]
        self.assertEqual(expected, data)

    def test_run_count_comm_rec_per_month_one_partner(self):
        """Trip over a bug in the mysql client driver."""
        for (subject, itx) in enumerate(['a', 'b', 'c']):
            for year in [2013, 2015, 2014]:
                for month in [2, 3, 4]:
                    self.sue.contactrecord_set.add(
                        ContactRecordFactory(
                            subject=subject,
                            date_time=datetime(year, month, 1)))

        ds = PartnersDataSource()
        partners_filter = PartnersFilter(tags=[['west']])
        recs = ds.run_count_comm_rec_per_month(
            self.company, partners_filter, ['name', 'year', '-month'])
        data = [
            (r['name'], r['year'], r['month'], r['comm_rec_count'])
            for r in recs
        ]
        self.assertEqual(36, len(data))

    def test_run_count_comm_rec_per_month_no_partners(self):
        """Trip over a bug in the mysql client driver."""
        for (subject, itx) in enumerate(['a', 'b', 'c']):
            for month in [2, 3, 4]:
                self.sue.contactrecord_set.add(
                    ContactRecordFactory(
                        subject=subject,
                        date_time=datetime(2015, month, 1)))

        ds = PartnersDataSource()
        partners_filter = PartnersFilter(tags=[['zzz']])
        recs = ds.run_count_comm_rec_per_month(
            self.company, partners_filter, ['name', 'year', '-month'])
        self.assertEqual(0, len(recs))

    def test_run_count_comm_rec_per_month_empty_partner(self):
        """One partner, no communication records."""
        ds = PartnersDataSource()
        partners_filter = PartnersFilter(tags=[['east']])
        recs = ds.run_count_comm_rec_per_month(
            self.company, partners_filter, ['name', 'year', '-month'])
        data = [
            (r['name'], r['year'], r['month'], r['comm_rec_count'])
            for r in recs
        ]
        self.assertEqual(12, len(data))
        default_year = datetime.now().year
        for item in data:
            self.assertEqual(default_year, item[1])
            self.assertEqual(0, item[3])

    def test_filter_by_date_range(self):
        """Should show only partner with last_action_time in range."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(
                date=[datetime(2015, 9, 1), datetime(2015, 9, 30)]),
            [])
        names = set([r['name'] for r in recs])
        expected = {self.partner_a.name}
        self.assertEqual(expected, names)

    def test_filter_by_date_before(self):
        """Should show only partner with last_action_time before date."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(
                date=[None, datetime(2015, 9, 30)]),
            [])
        names = set([r['name'] for r in recs])
        expected = {self.partner_a.name}
        self.assertEqual(expected, names)

    def test_filter_by_date_after(self):
        """Should show only partner with last_action_time after date."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(
                date=[datetime(2015, 10, 1), None]),
            [])
        names = set([r['name'] for r in recs])
        expected = {self.partner_b.name}
        self.assertEqual(expected, names)

    def test_filter_by_state(self):
        """Should show only partners with correct state."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(
                locations={
                    'state': 'CA'
                }),
            [])
        names = [r['name'] for r in recs]
        expected = [self.partner_b.name]
        self.assertEqual(expected, names)

    def test_filter_by_city(self):
        """Should show only partners with correct city."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(
                locations={
                    'city': 'Los Angeles'
                }),
            [])
        names = [r['name'] for r in recs]
        expected = [self.partner_b.name]
        self.assertEqual(expected, names)

    def test_filter_by_tags(self):
        """Show only partner with correct tags."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(tags=[['EaSt']]),
            [])
        names = set([r['name'] for r in recs])
        expected = {self.partner_a.name}
        self.assertEqual(expected, names)

    def test_filter_by_tags_or(self):
        """Show only partner with correct tags in 'or' configuration."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(tags=[['EaSt', 'wEsT']]),
            [])
        names = set([r['name'] for r in recs])
        expected = {self.partner_a.name, self.partner_b.name}
        self.assertEqual(expected, names)

    def test_filter_by_tags_and(self):
        """Show only partner with correct tags in 'and' configuration."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(tags=[['EaSt'], ['wEsT']]),
            [])
        names = set([r['name'] for r in recs])
        expected = set()
        self.assertEqual(expected, names)

        # Now try adding another tag.
        self.partner_a.tags.add(self.west_tag)
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(tags=[['EaSt'], ['wEsT']]),
            [])
        names = set([r['name'] for r in recs])
        expected = {self.partner_a.name}
        self.assertEqual(expected, names)

    def test_filter_by_data_source(self):
        """Check datasource filter works at all."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(data_source="zap"),
            [])
        names = set([r['name'] for r in recs])
        expected = {self.partner_a.name}
        self.assertEqual(expected, names)

    def test_filter_by_uri(self):
        """Check uri filter works at all."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(uri="http://www.asdf.com/"),
            [])
        names = set([r['name'] for r in recs])
        expected = {self.partner_b.name}
        self.assertEqual(expected, names)

    def test_filter_by_empty_things(self):
        """Empty filters should not filter, just like missing filters."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(
                locations={'city': '', 'state': ''}),
            [])
        names = set([r['name'] for r in recs])
        expected = {self.partner_a.name, self.partner_b.name}
        self.assertEqual(expected, names)

    def test_help_city(self):
        """Check city help works and ignores current city filter."""
        ds = PartnersDataSource()
        recs = ds.help_city(
            self.company,
            PartnersFilter(locations={'city': "zz"}),
            "angel")
        actual = set([r['key'] for r in recs])
        self.assertEqual({'Los Angeles'}, actual)

    def test_help_state(self):
        """Check state help works and ignores current state filter."""
        ds = PartnersDataSource()
        recs = ds.help_state(
            self.company,
            PartnersFilter(locations={'state': "zz"}),
            "i")
        actual = set([r['key'] for r in recs])
        self.assertEqual({'IL', 'IN'}, actual)

    def test_help_tags(self):
        """Check tags help works at all."""
        ds = PartnersDataSource()
        recs = ds.help_tags(self.company, PartnersFilter(), "E")
        actual = set([r['key'] for r in recs])
        self.assertEqual({'east', 'west'}, actual)

    def test_help_tags_colors(self):
        """Tags should have colors"""
        ds = PartnersDataSource()
        recs = ds.help_tags(self.company, PartnersFilter(), "east")
        self.assertEqual("aaaaaa", recs[0]['hexColor'])

    def test_help_uri(self):
        """Check uri help works at all."""
        ds = PartnersDataSource()
        recs = ds.help_uri(
            self.company,
            PartnersFilter(),
            "ex")
        actual = set([r['key'] for r in recs])
        self.assertEqual({'http://www.example.com/'}, actual)

    def test_help_data_source(self):
        """Check data_source help works at all."""
        ds = PartnersDataSource()
        recs = ds.help_data_source(
            self.company,
            PartnersFilter(),
            "z")
        actual = set([r['key'] for r in recs])
        self.assertEqual({'zap'}, actual)

    def test_order(self):
        """Check ordering results works at all."""
        ds = PartnersDataSource()
        recs = ds.run_unaggregated(
            self.company,
            PartnersFilter(),
            ["-name"])
        names = [r['name'] for r in recs]
        expected = [self.partner_b.name, self.partner_a.name]
        self.assertEqual(expected, names)
示例#10
0
class ModelTests(MyJobsBase):
    def setUp(self):
        super(ModelTests, self).setUp()
        self.user = User.objects.create(email='*****@*****.**')
        self.company = CompanyFactory()
        CompanyProfile.objects.create(company=self.company)
        self.site = SeoSiteFactory()
        self.bu = BusinessUnitFactory()
        self.site.business_units.add(self.bu)
        self.site.save()
        self.company.job_source_ids.add(self.bu)
        self.company.save()

        # Use the newly created site for testing instead of secure.my.jobs.
        settings.SITE = self.site

        self.request_data = {
            'title': 'title',
            'company': self.company.id,
            'reqid': '1',
            'description': 'sadfljasdfljasdflasdfj',
            'link': 'www.google.com',
            'on_sites': '0',
            'apply_info': '',
        }

        self.request_location = {
            'city': 'Indianapolis',
            'state': 'Indiana',
            'state_short': 'IN',
            'country': 'United States',
            'country_short': 'USA',
            'zipcode': '46268',
        }

        self.site_package_data = {
            'name': 'Test Site Package',
        }

    def test_job_creation_and_deletion(self):
        locations = JobLocationFactory.create_batch(5)
        job = JobFactory(owner=self.company, created_by=self.user)
        job.locations = locations
        job.save()
        self.assertEqual(Job.objects.all().count(), 1)
        self.assertEqual(JobLocation.objects.all().count(), 5)
        job.delete()
        self.assertEqual(Job.objects.all().count(), 0)
        self.assertEqual(JobLocation.objects.all().count(), 0)

    def test_job_add_to_solr(self):
        job = JobFactory(owner=self.company, created_by=self.user)
        job.locations.add(JobLocationFactory())
        job.add_to_solr()

        guids = " OR ".join(job.guids())
        query = "guid:%s" % guids
        self.assertEqual(self.ms_solr.search(query).hits, 1)

    def test_job_remove_from_solr(self):
        job = JobFactory(owner=self.company, created_by=self.user)
        locations = JobLocationFactory.create_batch(2)
        job.locations = locations
        job.save()
        job.remove_from_solr()

        guids = " OR ".join(job.guids())
        query = "guid:%s" % guids
        self.assertEqual(self.ms_solr.search(query).hits, 0)

    def test_job_generate_guid(self):
        guid = '1'*32

        # Confirm that pre-assigned guids are not being overwritten.
        location = JobLocationFactory(guid=guid)
        self.assertEqual(guid, location.guid)
        location.delete()

        # Confirm that if a guid isn't assigned one is getting assigned
        # to it properly.
        location = JobLocationFactory()
        self.assertIsNotNone(location.guid)
        self.assertNotEqual(location.guid, guid)

    def test_site_package_make_unique_for_site(self):
        package = SitePackage.objects.create(**self.site_package_data)
        package.make_unique_for_site(self.site)
        self.assertEqual(self.site.site_package, package)
        package.delete()

        package = SitePackage.objects.create(**self.site_package_data)
        for x in range(100, 110):
            site = SeoSiteFactory(id=x, domain="%s.jobs" % x)
            package.sites.add(site)

        # Site packages with existing sites associated with it should still
        # only end up with one associated site.
        site = SeoSiteFactory(id=4000, domain="4000.jobs")
        package.make_unique_for_site(site)
        self.assertEqual(site.site_package, package)

    def test_site_package_make_unique_for_company(self):
        package = SitePackage.objects.create(**self.site_package_data)
        package.make_unique_for_company(self.company)
        self.assertEqual(self.company.site_package, package)
        package.delete()

        package = SitePackage.objects.create(**self.site_package_data)
        for x in range(1000, 1003):
            site = SeoSiteFactory(id=x, domain="%s.jobs" % x)
            package.sites.add(site)
        self.assertItemsEqual(package.sites.all().values_list('id', flat=True),
                              [1000, 1001, 1002])
        for x in range(100, 103):
            site = SeoSiteFactory(id=x, domain="%s.jobs" % x)
            site.business_units.add(self.bu)
            site.save()
        # Site packages with existing sites associated with it should
        # only end up with the sites for a company.
        package.make_unique_for_company(self.company)
        self.assertEqual(self.company.site_package, package)
        self.assertItemsEqual(package.sites.all().values_list('id', flat=True),
                              [100, 101, 102, 2])

    def create_purchased_job(self, pk=None):
        if not hasattr(self, 'package'):
            self.package = SitePackageFactory(owner=self.company)
        if not hasattr(self, 'product'):
            self.product = ProductFactory(
                package=self.package, owner=self.company)
        if not hasattr(self, 'purchased_product'):
            self.purchased_product = PurchasedProductFactory(
                product=self.product, owner=self.company)
        exp_date = date.today() + timedelta(self.product.posting_window_length)
        self.assertEqual(self.purchased_product.expiration_date, exp_date)
        return PurchasedJobFactory(
            owner=self.company, created_by=self.user, 
            purchased_product=self.purchased_product, pk=pk)

    def test_purchased_job_add(self):
        self.create_purchased_job()
        self.assertEqual(PurchasedJob.objects.all().count(), 1)
        self.assertEqual(SitePackage.objects.all().count(), 1)
        self.assertEqual(Request.objects.all().count(), 1)
        package = SitePackage.objects.get()
        job = PurchasedJob.objects.get()
        self.assertItemsEqual(job.site_packages.all(), [package])

    def test_purchased_job_add_to_solr(self):
        job = self.create_purchased_job()
        job.locations.add(JobLocationFactory())
        job.save()
        # Add to solr and delete from solr shouldn't be called until
        # the job is approved.
        guids = " OR ".join(job.guids())
        query = "guid:%s" % guids
        self.assertEqual(self.ms_solr.search(query).hits, 0)
        job.is_approved = True

        # Jobs won't be added/deleted until it's confirmed that the
        # purchased product is paid for as well.
        job.purchased_product.paid = True
        job.purchased_product.save()
        job.save()
        # Now that the job is approved, it should've been sent to solr.
        guids = " OR ".join(job.guids())
        query = "guid:%s" % guids
        self.assertEqual(self.ms_solr.search(query).hits, 1)

    def test_purchased_product_jobs_remaining(self):
        num_jobs_allowed = Product._meta.get_field_by_name('num_jobs_allowed')
        expected_num_jobs = num_jobs_allowed[0].default
        for x in range(50, 50 + expected_num_jobs):
            if hasattr(self, 'purchased_product'):
                self.assertTrue(self.purchased_product.can_post_more())
            self.create_purchased_job()
            expected_num_jobs -= 1
            self.assertEqual(self.purchased_product.jobs_remaining,
                             expected_num_jobs)
        self.assertFalse(self.purchased_product.can_post_more())

    def test_invoice_send_invoice_email(self):
        self.create_purchased_job()
        group, _ = Group.objects.get_or_create(name=Product.ADMIN_GROUP_NAME)

        # No one to receive the email.
        self.purchased_product.invoice.send_invoice_email()
        self.assertEqual(len(mail.outbox), 0)

        # Only recipient is specified recipient.
        self.purchased_product.invoice.send_invoice_email(other_recipients=['*****@*****.**'])
        self.assertItemsEqual(mail.outbox[0].to,
                              ['*****@*****.**'])

        mail.outbox = []

        # Only recipients are admins.
        user = CompanyUserFactory(user=self.user, company=self.company)
        user.group.add(group)
        user.save()
        self.purchased_product.invoice.send_invoice_email()
        self.assertItemsEqual(mail.outbox[0].to,
                              [u'*****@*****.**'])
        self.assertItemsEqual(mail.outbox[0].from_email,
                              '*****@*****.**')

        mail.outbox = []

        self.site.email_domain = 'test.domain'
        self.site.save()

        # Recipients are admins + specified recipients.
        self.purchased_product.invoice.send_invoice_email(other_recipients=['*****@*****.**'])
        self.assertItemsEqual(mail.outbox[0].to,
                              ['*****@*****.**', u'*****@*****.**'])
        self.assertEqual(mail.outbox[0].from_email,
                              '*****@*****.**')

        mail.outbox = []

        # Only recipient is [email protected] (no admins)
        self.purchased_product.invoice.send_invoice_email(send_to_admins=False,
                                                          other_recipients=['*****@*****.**'])
        # Only one in .to should be [email protected]
        self.assertEquals(len(mail.outbox[0].to), 1)
        self.assertItemsEqual(mail.outbox[0].to, ['*****@*****.**'])

    def test_invoice_unchanged_after_purchased_product_deletion(self):
        self.create_purchased_job()
        invoice = self.purchased_product.invoice
        invoice.send_invoice_email(other_recipients=['*****@*****.**'])
        old_email = mail.outbox.pop()

        self.purchased_product.delete()
        invoice.send_invoice_email(other_recipients=['*****@*****.**'])
        new_email = mail.outbox.pop()

        self.assertEqual(old_email.body, new_email.body)

    def test_invoice_unchanged_after_product_changed(self):
        self.create_purchased_job()
        invoice = self.purchased_product.invoice
        invoice.send_invoice_email(other_recipients=['*****@*****.**'])
        old_email = mail.outbox.pop()

        self.purchased_product.product.name = 'new name'
        self.purchased_product.product.save()
        invoice.send_invoice_email(other_recipients=['*****@*****.**'])
        new_email = mail.outbox.pop()

        self.assertEqual(old_email.body, new_email.body)

    def test_productgrouping_add_delete(self):
        self.create_purchased_job()
        ProductGrouping.objects.create(display_title='Test Grouping',
                                       explanation='Test Grouping',
                                       name='Test Grouping',
                                       owner=self.company)
        self.assertEqual(ProductGrouping.objects.all().count(), 1)
        grouping = ProductGrouping.objects.get()

        order = ProductOrder.objects.create(product=self.product,
                                            group=grouping)
        grouping_products = grouping.products.all().values_list('pk', flat=True)
        self.assertItemsEqual(grouping_products, [order.product.pk])

        grouping.delete()
        self.assertEqual(ProductGrouping.objects.all().count(), 0)
        self.assertEqual(ProductOrder.objects.all().count(), 0)

    def test_request_generation(self):
        cu = CompanyUserFactory(user=self.user, company=self.company)
        cu.make_purchased_microsite_admin()

        self.create_purchased_job()
        self.assertEqual(PurchasedJob.objects.all().count(), 1)
        self.assertEqual(Request.objects.all().count(), 1)
        self.assertEqual(len(mail.outbox), 1)
        self.assertItemsEqual(mail.outbox[0].from_email,
                              '*****@*****.**')
        mail.outbox = []

        # Already approved jobs should not generate an additional request.
        PurchasedJobFactory(
            owner=self.company, created_by=self.user, 
            purchased_product=self.purchased_product, is_approved=True)

        self.assertEqual(PurchasedJob.objects.all().count(), 2)
        self.assertEqual(Request.objects.all().count(), 1)
        self.assertEqual(len(mail.outbox), 0)

    def test_offlinepurchase_create_purchased_products(self):
        user = CompanyUserFactory(user=self.user, company=self.company)
        offline_purchase = OfflinePurchaseFactory(
            owner=self.company, created_by=user)
        package = SitePackageFactory(owner=self.company)
        product = ProductFactory(package=package, owner=self.company)

        for x in range(1, 15):
            PurchasedProduct.objects.all().delete()
            OfflineProduct.objects.all().delete()
            OfflineProductFactory(
                product=product,
                offline_purchase=offline_purchase,
                product_quantity=x)
            offline_purchase.create_purchased_products(self.company)
            self.assertEqual(PurchasedProduct.objects.all().count(), x)

        product_two = ProductFactory(package=package, owner=self.company)
        for x in range(1, 15):
            PurchasedProduct.objects.all().delete()
            OfflineProduct.objects.all().delete()
            OfflineProductFactory(product=product, 
                                  offline_purchase=offline_purchase,
                                  product_quantity=x)
            OfflineProductFactory(product=product_two,
                                  offline_purchase=offline_purchase,
                                  product_quantity=x)
            offline_purchase.create_purchased_products(self.company)
            self.assertEqual(PurchasedProduct.objects.all().count(), x*2)

    def test_offlinepurchase_filter_by_sites(self):
        cu = CompanyUserFactory(user=self.user, company=self.company)
        for x in range(8800, 8815):
            domain = 'testsite-%s.jobs' % x
            site = SeoSiteFactory(id=x, domain=domain, name=domain)
            site_package = SitePackageFactory(owner=self.company)
            site_package.make_unique_for_site(site)
            product = ProductFactory(package=site_package, owner=self.company)
            for y in range(1, 5):
                purchase = OfflinePurchaseFactory(owner=self.company, created_by=cu)
                OfflineProduct.objects.create(product=product,
                                              offline_purchase=purchase)
            count = OfflinePurchase.objects.filter_by_sites([site]).count()
            self.assertEqual(count, 4)

        self.assertEqual(OfflinePurchase.objects.all().count(), 60)

    def test_invoice_filter_by_sites(self):
        cu = CompanyUserFactory(user=self.user, company=self.company)
        for x in range(8800, 8815):
            domain = 'testsite-%s.jobs' % x
            site = SeoSiteFactory(id=x, domain=domain, name=domain)
            site_package = SitePackageFactory(owner=self.company)
            site_package.make_unique_for_site(site)
            product = ProductFactory(package=site_package, owner=self.company)
            for y in range(1, 5):
                # OfflinePurchaseFactory() automatically creates the invoice.
                purchase = OfflinePurchaseFactory(owner=self.company, created_by=cu)
                OfflineProduct.objects.create(product=product,
                                              offline_purchase=purchase)
            # Confirm it correctly picks up Invoices associated with
            # OfflinePurchases.
            self.assertEqual(Invoice.objects.filter_by_sites([site]).count(), 4)
            for y in range(1, 5):
                # PurchasedProductFactory() also automatically creates
                # the invoice.
                PurchasedProductFactory(product=product, owner=self.company)
            # Confirm it correctly picks up Invoices associated with
            # PurchasedProducts.
            self.assertEqual(Invoice.objects.filter_by_sites([site]).count(), 8)

        self.assertEqual(Invoice.objects.all().count(), 120)

    def test_product_filter_by_sites(self):
        for x in range(8800, 8815):
            domain = 'testsite-%s.jobs' % x
            site = SeoSiteFactory(id=x, domain=domain, name=domain)
            site_package = SitePackageFactory(owner=self.company)
            site_package.make_unique_for_site(site)
            for y in range(1, 5):
                ProductFactory(package=site_package, owner=self.company)
            self.assertEqual(Product.objects.filter_by_sites([site]).count(), 4)

        self.assertEqual(Product.objects.all().count(), 60)

    def test_request_filter_by_sites(self):
        for x in range(8800, 8815):
            domain = 'testsite-%s.jobs' % x
            site = SeoSiteFactory(id=x, domain=domain, name=domain)
            site_package = SitePackageFactory(owner=self.company)
            site_package.make_unique_for_site(site)
            product = ProductFactory(package=site_package, owner=self.company)
            purchased_product = PurchasedProductFactory(product=product,
                                                        owner=self.company)
            for y in range(1, 5):
                # Unapproved purchased jobs should create Requests.
                PurchasedJobFactory(owner=self.company, created_by=self.user,
                                    purchased_product=purchased_product)
            self.assertEqual(Request.objects.filter_by_sites([site]).count(), 4)

        self.assertEqual(Request.objects.all().count(), 60)

    def test_purchasedproduct_filter_by_sites(self):
        for x in range(8800, 8815):
            domain = 'testsite-%s.jobs' % x
            site = SeoSiteFactory(id=x, domain=domain, name=domain)
            site_package = SitePackageFactory(owner=self.company)
            site_package.make_unique_for_site(site)
            for y in range(1, 5):
                product = ProductFactory(package=site_package, owner=self.company)
                PurchasedProductFactory(product=product, owner=self.company)
            count = PurchasedProduct.objects.filter_by_sites([site]).count()
            self.assertEqual(count, 4)

        self.assertEqual(PurchasedProduct.objects.all().count(), 60)

    def test_job_filter_by_sites(self):
        for x in range(8800, 8815):
            domain = 'testsite-%s.jobs' % x
            site = SeoSiteFactory(id=x, domain=domain, name=domain)
            site_package = SitePackageFactory(owner=self.company)
            site_package.make_unique_for_site(site)
            for y in range(1, 5):
                job = JobFactory(owner=self.company, created_by=self.user)
                job.site_packages.add(site_package)
                job.save()
            self.assertEqual(Job.objects.filter_by_sites([site]).count(), 4)

        self.assertEqual(Job.objects.all().count(), 60)

    def test_purchasedjob_filter_by_sites(self):
        for x in range(8800, 8815):
            domain = 'testsite-%s.jobs' % x
            site = SeoSiteFactory(id=x, domain=domain, name=domain)
            site_package = SitePackageFactory(owner=self.company)
            site_package.make_unique_for_site(site)
            product = ProductFactory(package=site_package, owner=self.company)
            purchased_product = PurchasedProductFactory(product=product,
                                                        owner=self.company)
            for y in range(1, 5):
                job = PurchasedJobFactory(owner=self.company,
                                          created_by=self.user,
                                          purchased_product=purchased_product)
                job.site_packages.add(site_package)
                job.save()
            count = PurchasedJob.objects.filter_by_sites([site]).count()
            self.assertEqual(count, 4)

        self.assertEqual(PurchasedJob.objects.all().count(), 60)

    def test_productgrouping_filter_by_sites(self):
        for x in range(8800, 8815):
            domain = 'testsite-%s.jobs' % x
            site = SeoSiteFactory(id=x, domain=domain, name=domain)
            site_package = SitePackageFactory(owner=self.company)
            site_package.make_unique_for_site(site)
            product = ProductFactory(package=site_package, owner=self.company)
            for y in range(1, 5):
                grouping = ProductGroupingFactory(owner=self.company,
                                                  display_order=y)
                ProductOrder.objects.create(product=product, group=grouping,
                                            display_order=y)
            count = ProductGrouping.objects.filter_by_sites([site]).count()
            self.assertEqual(count, 4)

        self.assertEqual(ProductGrouping.objects.all().count(), 60)

    def test_sitepackage_filter_by_sites(self):
        for x in range(8800, 8815):
            domain = 'testsite-%s.jobs' % x
            site = SeoSiteFactory(id=x, domain=domain, name=domain)
            for y in range(1, 5):
                site_package = SitePackageFactory(owner=self.company)
                site_package.sites.add(site)
                site_package.save()
            count = SitePackage.objects.filter_by_sites([site]).count()
            self.assertEqual(count, 4)
            count = Package.objects.filter_by_sites([site]).count()
            self.assertEqual(count, 4)

        self.assertEqual(SitePackage.objects.all().count(), 60)
        self.assertEqual(Package.objects.all().count(), 60)

    def test_product_filter_by_site_multiple_sites(self):
        site_in_both_packages = SeoSiteFactory(domain='secondsite.jobs', id=7)

        single_site_package = SitePackageFactory(owner=self.company)
        single_site_package.make_unique_for_site(site_in_both_packages)

        both_sites_package = SitePackageFactory(owner=self.company)
        both_sites_package.sites.add(site_in_both_packages)
        both_sites_package.sites.add(self.site)
        both_sites_package.save()

        ProductFactory(package=single_site_package, owner=self.company)
        ProductFactory(package=both_sites_package, owner=self.company)

        self.assertEqual(Product.objects.all().count(), 2)

        # Confirm that filtering by both sites gets both jobs.
        both_sites = [site_in_both_packages, self.site]
        count = Product.objects.filter_by_sites(both_sites).count()
        self.assertEqual(count, 2)

        # Confirm that filtering by the site that only has one job only
        # gets one job.
        count = Product.objects.filter_by_sites([self.site]).count()
        self.assertEqual(count, 1)

        # Confirm that filtering by the site the site that has both jobs gets
        # both jobs.
        count = Product.objects.filter_by_sites([site_in_both_packages]).count()
        self.assertEqual(count, 2)

    def test_job_filter_by_site_multiple_sites(self):
        site_in_both_packages = SeoSiteFactory(domain='secondsite.jobs', id=7)

        single_site_package = SitePackageFactory(owner=self.company)
        single_site_package.make_unique_for_site(site_in_both_packages)

        both_sites_package = SitePackageFactory(owner=self.company)
        both_sites_package.sites.add(site_in_both_packages)
        both_sites_package.sites.add(self.site)
        both_sites_package.save()

        job_on_both = JobFactory(owner=self.company, created_by=self.user)
        job_on_both.site_packages.add(both_sites_package)
        job_on_both.save()

        job_on_new_site = JobFactory(owner=self.company, created_by=self.user)
        job_on_new_site.site_packages.add(single_site_package)
        job_on_new_site.save()

        self.assertEqual(Job.objects.all().count(), 2)

        # Confirm that filtering by both sites gets both jobs.
        both_sites = [site_in_both_packages, self.site]
        count = Job.objects.filter_by_sites(both_sites).count()
        self.assertEqual(count, 2)

        # Confirm that filtering by the site that only has one job only
        # gets one job.
        self.assertEqual(Job.objects.filter_by_sites([self.site]).count(), 1)

        # Confirm that filtering by the site the site that has both jobs gets
        # both jobs.
        count = Job.objects.filter_by_sites([site_in_both_packages]).count()
        self.assertEqual(count, 2)

    def test_purchasedproduct_filter_by_site_multiple_sites(self):
        site_in_both_packages = SeoSiteFactory(domain='secondsite.jobs', id=7)

        single_site_package = SitePackageFactory(owner=self.company)
        single_site_package.make_unique_for_site(site_in_both_packages)

        both_sites_package = SitePackageFactory(owner=self.company)
        both_sites_package.sites.add(site_in_both_packages)
        both_sites_package.sites.add(self.site)
        both_sites_package.save()

        single_site_product = ProductFactory(package=single_site_package, owner=self.company)
        PurchasedProductFactory(product=single_site_product, owner=self.company)

        both_sites_product = ProductFactory(package=both_sites_package, owner=self.company)
        PurchasedProductFactory(product=both_sites_product, owner=self.company)

        self.assertEqual(PurchasedProduct.objects.all().count(), 2)

        # Confirm that filtering by both sites gets both products.
        both_sites = [site_in_both_packages, self.site]
        count = PurchasedProduct.objects.filter_by_sites(both_sites).count()
        self.assertEqual(count, 2)

        # Confirm that filtering by the site that only has one product only
        # gets one product.
        count = PurchasedProduct.objects.filter_by_sites([self.site]).count()
        self.assertEqual(count, 1)

        # Confirm that filtering by the site the site that has both products
        #  gets both jobs.
        objs = PurchasedProduct.objects.filter_by_sites([site_in_both_packages])
        count = objs.count()
        self.assertEqual(count, 2)

    def test_purchasedjob_filter_by_site_multiple_sites(self):
        site_in_both_packages = SeoSiteFactory(domain='secondsite.jobs', id=7)

        single_site_package = SitePackageFactory(owner=self.company)
        single_site_package.make_unique_for_site(site_in_both_packages)

        both_sites_package = SitePackageFactory(owner=self.company)
        both_sites_package.sites.add(site_in_both_packages)
        both_sites_package.sites.add(self.site)
        both_sites_package.save()

        single_site_product = ProductFactory(package=single_site_package, owner=self.company)
        single_site_purchasedproduct = PurchasedProductFactory(
            product=single_site_product, owner=self.company)

        both_sites_product = ProductFactory(package=both_sites_package, owner=self.company)
        both_sites_purchasedproduct = PurchasedProductFactory(
            product=both_sites_product, owner=self.company
        )

        PurchasedJobFactory(owner=self.company, created_by=self.user,
                            purchased_product=single_site_purchasedproduct)
        PurchasedJobFactory(owner=self.company, created_by=self.user,
                            purchased_product=both_sites_purchasedproduct)

        self.assertEqual(PurchasedJob.objects.all().count(), 2)

        # Confirm that filtering by both sites gets both jobs.
        both_sites = [site_in_both_packages, self.site]
        count = PurchasedJob.objects.filter_by_sites(both_sites).count()
        self.assertEqual(count, 2)

        # Confirm that filtering by the site that only has one job only
        # gets one job.
        count = PurchasedJob.objects.filter_by_sites([self.site]).count()
        self.assertEqual(count, 1)

        # Confirm that filtering by the site the site that has both jobs gets
        # both jobs.
        objs = PurchasedJob.objects.filter_by_sites([site_in_both_packages])
        count = objs.count()
        self.assertEqual(count, 2)

    def test_sitepackage_filter_by_site_multiple_sites(self):
        site_in_both_packages = SeoSiteFactory(domain='secondsite.jobs', id=7)

        single_site_package = SitePackageFactory(owner=self.company)
        single_site_package.make_unique_for_site(site_in_both_packages)

        both_sites_package = SitePackageFactory(owner=self.company)
        both_sites_package.sites.add(site_in_both_packages)
        both_sites_package.sites.add(self.site)
        both_sites_package.save()

        self.assertEqual(SitePackage.objects.all().count(), 2)
        self.assertEqual(Package.objects.all().count(), 2)

        # Confirm that filtering by both sites gets both packages.
        both_sites = [site_in_both_packages, self.site]
        count = SitePackage.objects.filter_by_sites(both_sites).count()
        self.assertEqual(count, 2)
        count = Package.objects.filter_by_sites(both_sites).count()
        self.assertEqual(count, 2)

        # Confirm that filtering by the site that only has one package only
        # gets one package.
        count = SitePackage.objects.filter_by_sites([self.site]).count()
        self.assertEqual(count, 1)
        count = Package.objects.filter_by_sites([self.site]).count()
        self.assertEqual(count, 1)

        # Confirm that filtering by the site the site that has both packages
        # gets both packages.
        objs = SitePackage.objects.filter_by_sites([site_in_both_packages])
        count = objs.count()
        self.assertEqual(count, 2)
        count = Package.objects.filter_by_sites([site_in_both_packages]).count()
        self.assertEqual(count, 2)

    def test_productgrouping_filter_by_site_multiple_sites(self):
        site_in_both_packages = SeoSiteFactory(domain='secondsite.jobs', id=7)

        single_site_package = SitePackageFactory(owner=self.company)
        single_site_package.make_unique_for_site(site_in_both_packages)

        both_sites_package = SitePackageFactory(owner=self.company)
        both_sites_package.sites.add(site_in_both_packages)
        both_sites_package.sites.add(self.site)
        both_sites_package.save()

        single_site_product = ProductFactory(package=single_site_package, owner=self.company)
        single_site_grouping = ProductGroupingFactory(owner=self.company)
        ProductOrder.objects.create(product=single_site_product,
                                    group=single_site_grouping)

        both_sites_product = ProductFactory(package=both_sites_package, owner=self.company)
        both_sites_grouping = ProductGroupingFactory(owner=self.company)
        ProductOrder.objects.create(product=both_sites_product,
                                    group=both_sites_grouping)

        # Confirm that filtering by both sites gets both groupings.
        both_sites = [site_in_both_packages, self.site]
        count = ProductGrouping.objects.filter_by_sites(both_sites).count()
        self.assertEqual(count, 2)

        # Confirm that filtering by the site that only has one grouping only
        # gets one grouping.
        count = ProductGrouping.objects.filter_by_sites([self.site]).count()
        self.assertEqual(count, 1)

        # Confirm that filtering by the site the site that has both jobs gets
        # both jobs.
        objs = ProductGrouping.objects.filter_by_sites([site_in_both_packages])
        count = objs.count()
        self.assertEqual(count, 2)

    def test_offlinepurchase_filter_by_site_multiple_sites(self):
        cu = CompanyUserFactory(user=self.user, company=self.company)
        site_in_both_packages = SeoSiteFactory(domain='secondsite.jobs', id=7)

        single_site_package = SitePackageFactory(owner=self.company)
        single_site_package.make_unique_for_site(site_in_both_packages)

        both_sites_package = SitePackageFactory(owner=self.company)
        both_sites_package.sites.add(site_in_both_packages)
        both_sites_package.sites.add(self.site)
        both_sites_package.save()

        single_site_product = ProductFactory(package=single_site_package, owner=self.company)
        single_site_purchase = OfflinePurchaseFactory(owner=self.company, created_by=cu)
        OfflineProduct.objects.create(product=single_site_product,
                                      offline_purchase=single_site_purchase)

        both_sites_product = ProductFactory(package=both_sites_package, owner=self.company)
        both_sites_purchase = OfflinePurchaseFactory(owner=self.company, created_by=cu)
        OfflineProduct.objects.create(product=both_sites_product,
                                      offline_purchase=both_sites_purchase)

        # Confirm that filtering by both sites gets both groupings.
        both_sites = [site_in_both_packages, self.site]
        count = OfflinePurchase.objects.filter_by_sites(both_sites).count()
        self.assertEqual(count, 2)

        # Confirm that filtering by the site that only has one grouping only
        # gets one grouping.
        count = OfflinePurchase.objects.filter_by_sites([self.site]).count()
        self.assertEqual(count, 1)

        # Confirm that filtering by the site the site that has both jobs gets
        # both jobs.
        objs = OfflinePurchase.objects.filter_by_sites([site_in_both_packages])
        count = objs.count()
        self.assertEqual(count, 2)

    def test_invoice_from_offlinepurchase_filter_by_site_multiple_sites(self):
        cu = CompanyUserFactory(user=self.user, company=self.company)
        site_in_both_packages = SeoSiteFactory(domain='secondsite.jobs', id=7)

        single_site_package = SitePackageFactory(owner=self.company)
        single_site_package.make_unique_for_site(site_in_both_packages)

        both_sites_package = SitePackageFactory(owner=self.company)
        both_sites_package.sites.add(site_in_both_packages)
        both_sites_package.sites.add(self.site)
        both_sites_package.save()

        single_site_product = ProductFactory(package=single_site_package, owner=self.company)
        single_site_purchase = OfflinePurchaseFactory(owner=self.company, created_by=cu)
        OfflineProduct.objects.create(product=single_site_product,
                                      offline_purchase=single_site_purchase)

        both_sites_product = ProductFactory(package=both_sites_package, owner=self.company)
        both_sites_purchase = OfflinePurchaseFactory(owner=self.company, created_by=cu)
        OfflineProduct.objects.create(product=both_sites_product,
                                      offline_purchase=both_sites_purchase)

        # Confirm that filtering by both sites gets both groupings.
        both_sites = [site_in_both_packages, self.site]
        count = Invoice.objects.filter_by_sites(both_sites).count()
        self.assertEqual(count, 2)

        # Confirm that filtering by the site that only has one grouping only
        # gets one grouping.
        count = Invoice.objects.filter_by_sites([self.site]).count()
        self.assertEqual(count, 1)

        # Confirm that filtering by the site the site that has both jobs gets
        # both jobs.
        count = Invoice.objects.filter_by_sites([site_in_both_packages]).count()
        self.assertEqual(count, 2)

    def test_invoice_from_purchasedproduct_filter_by_site_multiple_sites(self):
        site_in_both_packages = SeoSiteFactory(domain='secondsite.jobs', id=7)

        single_site_package = SitePackageFactory(owner=self.company)
        single_site_package.make_unique_for_site(site_in_both_packages)

        both_sites_package = SitePackageFactory(owner=self.company)
        both_sites_package.sites.add(site_in_both_packages)
        both_sites_package.sites.add(self.site)
        both_sites_package.save()

        single_site_product = ProductFactory(package=single_site_package, owner=self.company)
        PurchasedProductFactory(product=single_site_product, owner=self.company)

        both_sites_product = ProductFactory(package=both_sites_package, owner=self.company)
        PurchasedProductFactory(product=both_sites_product, owner=self.company)

        self.assertEqual(Invoice.objects.all().count(), 2)

        # Confirm that filtering by both sites gets both products.
        both_sites = [site_in_both_packages, self.site]
        count = Invoice.objects.filter_by_sites(both_sites).count()
        self.assertEqual(count, 2)

        # Confirm that filtering by the site that only has one product only
        # gets one product.
        count = Invoice.objects.filter_by_sites([self.site]).count()
        self.assertEqual(count, 1)

        # Confirm that filtering by the site the site that has both products
        #  gets both jobs.
        count = Invoice.objects.filter_by_sites([site_in_both_packages]).count()
        self.assertEqual(count, 2)

    def test_request_filter_by_site_multiple_sites(self):
        site_in_both_packages = SeoSiteFactory(domain='secondsite.jobs', id=7)

        single_site_package = SitePackageFactory(owner=self.company)
        single_site_package.make_unique_for_site(site_in_both_packages)

        both_sites_package = SitePackageFactory(owner=self.company)
        both_sites_package.sites.add(site_in_both_packages)
        both_sites_package.sites.add(self.site)
        both_sites_package.save()

        single_site_product = ProductFactory(package=single_site_package, owner=self.company)
        single_site_purchasedproduct = PurchasedProductFactory(
            product=single_site_product, owner=self.company)
        # Unapproved PurchasedJobs generate Requests.
        PurchasedJobFactory(owner=self.company, created_by=self.user,
                            purchased_product=single_site_purchasedproduct)

        both_sites_product = ProductFactory(package=both_sites_package, owner=self.company)
        both_sites_purchasedproduct = PurchasedProductFactory(
            product=both_sites_product, owner=self.company)
        PurchasedJobFactory(owner=self.company, created_by=self.user,
                            purchased_product=both_sites_purchasedproduct)

        self.assertEqual(Request.objects.all().count(), 2)

        # Confirm that filtering by both sites gets both products.
        both_sites = [site_in_both_packages, self.site]
        count = Request.objects.filter_by_sites(both_sites).count()
        self.assertEqual(count, 2)

        # Confirm that filtering by the site that only has one product only
        # gets one product.
        count = Request.objects.filter_by_sites([self.site]).count()
        self.assertEqual(count, 1)

        # Confirm that filtering by the site the site that has both products
        #  gets both jobs.
        count = Request.objects.filter_by_sites([site_in_both_packages]).count()
        self.assertEqual(count, 2)

    def test_request_on_purchasedjob_update(self):
        # Creating a PurchasedJob for a Product that requires approval
        # creates a Request
        job = PurchasedJobFactory(owner=self.company, created_by=self.user)
        self.assertEqual(Request.objects.count(), 1)

        # Re-saving that job should not create a new request.
        job.save()
        self.assertEqual(Request.objects.count(), 1)

        # Approving the job should also not create a new request.
        job.is_approved = True
        job.save()
        self.assertEqual(Request.objects.count(), 1)

        # Marking the job as not approved and saving it should not create
        # a new request if no action was taken on the old request.
        job.is_approved = False
        job.save()
        self.assertEqual(Request.objects.count(), 1)

        # Marking the job as not approved and saving it should create
        # a new request if there is no pending request.
        request = Request.objects.get()
        request.action_taken = True
        request.save()
        job.save()
        self.assertEqual(Request.objects.count(), 2)
示例#11
0
 def setUp(self):
     self.user = UserFactory()
     self.company = CompanyFactory()
     self.data = {'user': self.user.id,
                  'company': self.company.id}
示例#12
0
文件: views.py 项目: jpaezsa/MyJobs
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)
示例#13
0
文件: views.py 项目: jpaezsa/MyJobs
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)