예제 #1
0
    def test_company_admin_role_table(self):
        """
        Tests the "User Roles" section of the Company admin.
        """
        def make_request_and_initial_checks():
            """
            Both tests in the parent function involve making a GET request,
            parsing the HTML, and doing a small amount of checking.
            """
            response = self.client.get(reverse('admin:seo_company_change',
                                               args=(company.pk, )))
            soup = BeautifulSoup(response.content)
            user_roles = soup.find('div', {'class': 'field-user_roles'})
            self.assertTrue(user_roles, "Expected to find a div with class "
                            "'field-user_roles' but did not.")
            return user_roles.find('table').text

        company = CompanyFactory()
        role = RoleFactory(company=company)
        role.activities = Activity.objects.all()

        # Test once with no roles assigned.
        table_text = make_request_and_initial_checks()
        self.assertFalse(table_text, "User roles table should be empty when "
                         "no users have roles.")

        self.user.roles.add(role)

        # Test again with a role assigned to a user.
        table_text = make_request_and_initial_checks()
        self.assertTrue(table_text, "User roles table should contain data "
                        "when there are users with roles assigned.")
        for text in [self.user.email, role.name]:
            self.assertTrue(text in table_text, 'Expected "%s" to be in '
                            'table text but it was not.' % (text, ))
예제 #2
0
 def setUp(self):
     super(ManageUsersTests, self).setUp()
     self.role.activities = self.activities
     self.otherCompany = CompanyFactory(app_access=[self.app_access])
     self.otherRole = RoleFactory(company=self.company, name="OtherRole")
     self.otherRoleAtOtherCompany = RoleFactory(
         company=self.otherCompany, name="otherRoleAtOtherCompany")
     self.user.roles.add(self.otherRole, self.otherRoleAtOtherCompany)
예제 #3
0
    def setUp(self):
        super(TestPasswordExpiration, self).setUp()

        (self.user, _) = User.objects.create_user(password='******',
                                                  email='*****@*****.**')
        self.strict = CompanyFactory(password_expiration=True, name='strict')
        self.strict_role = RoleFactory(company=self.strict, name="Admin")
        self.loose = CompanyFactory(password_expiration=False, name='loose')
        self.loose_role = RoleFactory(company=self.loose, name="Admin")
        self.user.roles.add(self.strict_role)
        self.user.roles.add(self.loose_role)

        # Reload from db to get correct password state.
        self.user = User.objects.get(pk=self.user.pk)
예제 #4
0
    def test_role_unique_to_company(self):
        """Roles should be unique to company by name."""

        try:
            # This should be allowed since the company is different
            RoleFactory(name=self.role.name)
        except IntegrityError:
            self.fail("Creating a similar role for a different company should "
                      "be allowed, but it isn't.")

        # we shouldn't be allowed to create a role wit the same name in the
        # same company
        with self.assertRaises(IntegrityError):
            RoleFactory(name=self.role.name, company=self.role.company)
예제 #5
0
    def test_invoice_filter_by_sites(self):
        role = RoleFactory(company=self.company)
        self.user.roles.add(role)
        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=self.user)
                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)
예제 #6
0
    def test_offlinepurchase_create_purchased_products(self):
        role = RoleFactory(company=self.company)
        self.user.roles.add(role)
        offline_purchase = OfflinePurchaseFactory(owner=self.company,
                                                  created_by=self.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)
예제 #7
0
    def test_invoice_sent_to_admins_and_others(self):
        """
        If a company has postajob admins and `other_recipients` is specified,
        emails should be sent to both groups.

        """
        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)

        role = RoleFactory(company=self.company)
        self.user.roles.add(role)
        self.user.groups.add(group)

        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, '*****@*****.**')
예제 #8
0
    def test_invoice_sent_to_admins(self):
        """
        When a company has postajob admins, invoices should be sent to each of
        them, unless the behavior is disabled by passing
        `send_to_admins=False`.

        """

        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 recipients are admins.
        role = RoleFactory(company=self.company)
        self.user.roles.add(role)
        self.user.groups.add(group)
        self.purchased_product.invoice.send_invoice_email()
        self.assertItemsEqual(mail.outbox[0].to, [u'*****@*****.**'])
        self.assertItemsEqual(mail.outbox[0].from_email, '*****@*****.**')

        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[1].to), 1)
        self.assertItemsEqual(mail.outbox[1].to, ['*****@*****.**'])
예제 #9
0
    def test_company_user_has_access(self):
        """
        Test that a user has access if the user can be tied to a company.
        """

        # user not assigned a role in company, so shouldn't have access
        self.assertFalse(self.company.user_has_access(self.user))

        role = RoleFactory(company=self.company)
        self.user.roles.add(role)
        self.assertTrue(self.company.user_has_access(self.user))
예제 #10
0
    def test_seosite_user_has_access(self):
        """
        Tests that a user has access if that user can be tied back to one of
        the companies associated with an seo site's business units.
        """

        # user not assigned a role in company, so shouldn't have access
        self.assertFalse(self.site.user_has_access(self.user))

        role = RoleFactory(company=self.company)
        self.user.roles.add(role)
        self.assertTrue(self.site.user_has_access(self.user))
예제 #11
0
 def test_role_invitation_context(self):
     """
     Test that reating an invitation context from a role instance produces
     a context with a message and the role itself.
     """
     role = RoleFactory()
     context = invitation_context(role)
     self.assertEqual(
         context, {
             "message": " as a(n) %s for %s." % (role.name, role.company),
             "role": role
         })
예제 #12
0
    def test_number_of_invitations_sent_on_role_addition(self):
        """
        Adding roles to a user should only send invitations for each of
        the new roles, not roles that were already attached.
        """
        new_role = RoleFactory(company=self.company)

        mail.outbox = []
        to_post = {
            'email': '*****@*****.**',
            'roles': [self.role.name, new_role.name]
        }
        self.client.post(reverse('api_add_user'), to_post)
        message = "Expected {} invitations, found {}"
        self.assertEqual(len(mail.outbox), 2,
                         message.format(2, len(mail.outbox)))

        to_post['roles'].append(
            RoleFactory(company=self.company).name)
        self.client.post(reverse('api_add_user'), to_post)
        self.assertEqual(len(mail.outbox), 3,
                         message.format(3, len(mail.outbox)))
예제 #13
0
    def setUp(self):
        super(EventTests, self).setUp()
        self.product = posting_factories.ProductFactory()
        role = RoleFactory(company=self.product.owner)
        self.user.roles.add(role)

        self.purchased_product = posting_factories.PurchasedProductFactory(
            product=self.product, owner=self.product.owner)

        ct = ContentType.objects.get_for_model(Invoice)
        self.created_event = factories.EventFactory(model=ct,
                                                    owner=self.product.owner)

        self.created_template = factories.EmailTemplateFactory(
            event=self.created_event, is_active=True)
예제 #14
0
    def test_create_user_keeps_roles(self):
        """
        Regression test. When attempting to add a user who already exists, that
        users existing roles would be overwritten. Instead, they should be
        added to.

        """
        self.user.roles = [self.role]
        self.assertItemsEqual(self.user.roles.all(), [self.role])
        role = RoleFactory(name='Test Role', company=self.company)

        self.client.post(reverse('api_add_user'), {
            'email': self.user.email,
            'roles': [role.name]
        })
        self.assertItemsEqual(self.user.roles.all(), [self.role, role])
예제 #15
0
    def test_edit_user(self):
        """
        Tests editing a user
        Edit user
        """
        expected_user_pk = self.user.pk

        role = RoleFactory(company=self.company, name='Test')

        response = self.client.post(
            reverse('api_edit_user', args=[self.user.pk]), {
                'add': [role.name],
            }
        )
        output = json.loads(response.content)
        self.assertEqual(
            output['errors'], [],"Editing a user shouldn't result in errors")
예제 #16
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)
예제 #17
0
    def test_offlinepurchase_filter_by_sites(self):
        role = RoleFactory(company=self.company)
        self.user.roles.add(role)
        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=self.user)
                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)
예제 #18
0
    def test_removing_admin_role_from_last_admin(self):
        """
        Tests that it's not possible to remove the Admin role from a user if
        that user is the last Admin for a company.

        """
        self.assertEqual(self.role.user_set.all().count(), 1)
        empty_role = RoleFactory.build(company=self.company, name="Empty")

        response = self.client.post(
            path="/manage-users/api/users/%s/" % self.user.id, data={"add": ["Empty"], "remove": ["Admin"]}
        )
        self.assertEqual(self.role.user_set.all().count(), 1, "Removed last User from Admin Role")
        response_data = json.loads(response.content)
        self.assertIn(
            "Operation failed, as completing it would have removed the last "
            "Admin from the company. Is another Admin also editing users?",
            response_data["errors"],
        )
예제 #19
0
    def test_invoice_from_offlinepurchase_filter_by_site_multiple_sites(self):
        role = RoleFactory(company=self.company)
        self.user.roles.add(role)
        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=self.user)
        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=self.user)
        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)
예제 #20
0
    def test_assigning_activities_in_bulk(self):
        """
        Assigning a list of activities to a bunch of roles should only in a
        single query.
        """

        roles = [
            RoleFactory(name="Admin", company=company)
            for company in self.companies
        ]

        with self.assertNumQueries(1):
            RoleActivities = Role.activities.through
            RoleActivities.objects.bulk_create([
                RoleActivities(role=role, activity=activity) for role in roles
                for activity in self.activities
            ])

        for role in Role.objects.all():
            self.assertEqual(role.activities.count(), 20)
예제 #21
0
    def test_admin_count(self):
        """
        SeoSite.admins.count() should return the number of users who can be
        tied back to that company as an admin.

        """


        # can't use create_batch since emails need to be unique and
        # updating the User model disrupts other tests
        users = [factories.UserFactory(email="*****@*****.**" % i)
                 for i in range(10)]

        # When activities are enabled, company user count is determined by
        # the number distinct users assigned a role within that company
        role = RoleFactory(company=self.company, name='Admin')
        self.assertEqual(self.company.admins.count(), 0)

        for user in users:
            user.roles = [role]
        self.assertEqual(self.company.admins.count(), 10)
예제 #22
0
    def test_request_generation(self):
        role = RoleFactory(company=self.company)
        self.user.roles.add(role)
        self.user.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)
예제 #23
0
    def test_removing_admin_role_from_last_admin(self):
        """
        Tests that it's not possible to remove the Admin role from a user if
        that user is the last Admin for a company.

        """
        self.assertEqual(self.role.user_set.all().count(), 1)
        empty_role = RoleFactory.build(company=self.company, name="Empty")

        response = self.client.post(path='/manage-users/api/users/%s/' %
                                    self.user.id,
                                    data={
                                        'add': ['Empty'],
                                        'remove': ['Admin']
                                    })
        self.assertEqual(self.role.user_set.all().count(), 1,
                         "Removed last User from Admin Role")
        response_data = json.loads(response.content)
        self.assertIn(
            'Operation failed, as completing it would have removed the last '
            'Admin from the company. Is another Admin also editing users?',
            response_data['errors'])
예제 #24
0
    def test_automatic_role_admin_activities(self):
        """
        New activities should be added to all Admin roles automatically.
        """

        # add role to existing company
        RoleFactory(company=self.company, name="Admin",
                    activities=self.activities)
        role_admins = RoleFactory.create_batch(
            50, name="Admin", activities=self.activities)

        # sanity check for initial numbers
        for admin in Role.objects.filter(name="Admin"):
            self.assertEqual(admin.activities.count(), 5)

        new_activity =  ActivityFactory(
            name="new activity", description="Just a new test activity.")

        # new activity should be available for admins
        for admin in Role.objects.filter(name="Admin"):
            self.assertIn(new_activity, admin.activities.all())

        # existing role should not have new activity
        self.assertNotIn(new_activity, self.role.activities.all())
예제 #25
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)