def setUp(self):
        super(TestScout, self).setUp()
        # insert departments
        self.department1 = DepartmentFactory()

        # insert the users/roles
        self.admin_role = insert_a_role('admin')
        self.superadmin_role = insert_a_role('superadmin')
        self.admin_user = insert_a_user(
            email='*****@*****.**', role=self.admin_role, department=self.department1
        )
        self.superadmin_user = insert_a_user(
            email='*****@*****.**', role=self.superadmin_role, department=self.department1
        )

        # insert the companies/contracts
        self.company1 = insert_a_company(name='ship', insert_contract=False)
        self.company2 = insert_a_company(name='boat', insert_contract=False)
        insert_a_contract(
            description='vessel', companies=[self.company2], line_items=[LineItem(description='NAVY')]
        )
        self.contract1 = insert_a_contract(
            description='sail', financial_id=123, companies=[self.company1],
            line_items=[LineItem(description='sunfish')]
        )
        self.contract2 = insert_a_contract(
            description='sunfish', financial_id=456
        )
 def setUp(self):
     super(TestPublic, self).setUp()
     # create a conductor and general staff person
     self.conductor_role_id = insert_a_role('conductor')
     self.staff_role_id = insert_a_role('staff')
     self.conductor = insert_a_user(role=self.conductor_role_id)
     self.staff = insert_a_user(email='*****@*****.**', role=self.staff_role_id)
示例#3
0
    def setUp(self):
        super(TestScout, self).setUp()
        # insert departments
        self.department1 = DepartmentFactory()

        # insert the users/roles
        self.admin_role = insert_a_role('admin')
        self.superadmin_role = insert_a_role('superadmin')
        self.admin_user = insert_a_user(email='*****@*****.**',
                                        role=self.admin_role,
                                        department=self.department1)
        self.superadmin_user = insert_a_user(email='*****@*****.**',
                                             role=self.superadmin_role,
                                             department=self.department1)

        # insert the companies/contracts
        self.company1 = insert_a_company(name='ship', insert_contract=False)
        self.company2 = insert_a_company(name='boat', insert_contract=False)
        insert_a_contract(description='vessel',
                          companies=[self.company2],
                          line_items=[LineItem(description='NAVY')])
        self.contract1 = insert_a_contract(
            description='sail',
            financial_id=123,
            companies=[self.company1],
            line_items=[LineItem(description='sunfish')])
        self.contract2 = insert_a_contract(description='sunfish',
                                           financial_id=456)
 def setUp(self):
     super(TestAdmin, self).setUp()
     self.email = '*****@*****.**'
     self.email2 = '*****@*****.**'
     self.admin_role = insert_a_role('admin')
     self.superadmin_role = insert_a_role('superadmin')
     self.admin_user = insert_a_user(email=self.email, role=self.admin_role)
     self.superadmin_user = insert_a_user(email=self.email2, role=self.superadmin_role)
示例#5
0
 def setUp(self):
     super(TestPublic, self).setUp()
     # create a conductor and general staff person
     self.conductor_role_id = insert_a_role('conductor')
     self.staff_role_id = insert_a_role('staff')
     self.conductor = insert_a_user(role=self.conductor_role_id)
     self.staff = insert_a_user(email='*****@*****.**',
                                role=self.staff_role_id)
示例#6
0
 def setUp(self):
     super(TestAdmin, self).setUp()
     self.email = '*****@*****.**'
     self.email2 = '*****@*****.**'
     self.admin_role = insert_a_role('admin')
     self.superadmin_role = insert_a_role('superadmin')
     self.admin_user = insert_a_user(email=self.email, role=self.admin_role)
     self.superadmin_user = insert_a_user(email=self.email2,
                                          role=self.superadmin_role)
示例#7
0
    def setUp(self):
        super(TestOpportunitiesAdminBase, self).setUp()
        try:
            mkdir(current_app.config.get('UPLOAD_DESTINATION'))
        except OSError:
            rmtree(current_app.config.get('UPLOAD_DESTINATION'))
            mkdir(current_app.config.get('UPLOAD_DESTINATION'))

        import_nigp(current_app.config.get('PROJECT_ROOT') + '/purchasing_test/mock/nigp.csv')

        self.admin_role = insert_a_role('admin')
        self.staff_role = insert_a_role('staff')
        self.department1 = DepartmentFactory(name='test')
        self.opportunity_type = ContractTypeFactory.create(allow_opportunities=True)

        self.admin = insert_a_user(email='*****@*****.**', role=self.admin_role)
        self.staff = insert_a_user(email='*****@*****.**', role=self.staff_role)

        self.document = insert_a_document()

        self.vendor = Vendor.create(email='*****@*****.**', business_name='foo2')

        self.opportunity1 = insert_an_opportunity(
            contact=self.admin, created_by=self.staff,
            title=u'tést unïcode title', description=u'tést unïcode déscription',
            is_public=True, is_archived=False, planned_publish=datetime.date.today() + datetime.timedelta(1),
            planned_submission_start=datetime.date.today() + datetime.timedelta(2),
            planned_submission_end=datetime.datetime.today() + datetime.timedelta(2),
            documents=[self.document.id], categories=set([Category.query.first()])
        )
        self.opportunity2 = insert_an_opportunity(
            contact=self.admin, created_by=self.staff,
            is_public=True, is_archived=False, planned_publish=datetime.date.today(),
            planned_submission_start=datetime.date.today() + datetime.timedelta(2),
            planned_submission_end=datetime.datetime.today() + datetime.timedelta(2),
            categories=set([Category.query.first()])
        )
        self.opportunity3 = insert_an_opportunity(
            contact=self.admin, created_by=self.staff,
            is_public=True, is_archived=False, planned_publish=datetime.date.today() - datetime.timedelta(2),
            planned_submission_start=datetime.date.today() - datetime.timedelta(2),
            planned_submission_end=datetime.datetime.today() - datetime.timedelta(1),
            categories=set([Category.query.first()])
        )
        self.opportunity4 = insert_an_opportunity(
            contact=self.admin, created_by=self.staff,
            is_public=True, is_archived=False, planned_publish=datetime.date.today() - datetime.timedelta(1),
            planned_submission_start=datetime.date.today(),
            planned_submission_end=datetime.datetime.today() + datetime.timedelta(2),
            title='TEST TITLE!', categories=set([Category.query.first()])
        )
    def test_templates(self):
        # insert our opportunity, users
        admin_role = insert_a_role('admin')
        admin = insert_a_user(role=admin_role)

        opportunity = insert_an_opportunity(
            contact=admin, created_by=admin,
            is_public=True, planned_publish=datetime.date.today() - datetime.timedelta(1),
            planned_submission_start=datetime.date.today() + datetime.timedelta(2),
            planned_submission_end=datetime.datetime.today() + datetime.timedelta(2)
        )

        for rule in current_app.url_map.iter_rules():

            _endpoint = rule.endpoint.split('.')
            # filters out non-beacon endpoints
            if (len(_endpoint) > 1 and _endpoint[1] == 'static') or \
                _endpoint[0] != ('opportunities', 'opportunities_admin'):
                    continue
            else:
                if '<int:' in rule.rule:
                    response = self.client.get(url_for(rule.endpoint, opportunity_id=opportunity.id))
                else:
                    response = self.client.get(rule.rule)
                self.assert200(response)
    def test_templates(self):
        '''Test templates used, return 200
        '''
        # insert our opportunity, users
        admin_role = insert_a_role('admin')
        admin = insert_a_user(role=admin_role)

        opportunity = insert_an_opportunity(
            contact=admin, created_by=admin,
            is_public=True, planned_publish=datetime.date.today() - datetime.timedelta(1),
            planned_submission_start=datetime.date.today() + datetime.timedelta(2),
            planned_submission_end=datetime.date.today() + datetime.timedelta(2)
        )

        for rule in current_app.url_map.iter_rules():

            _endpoint = rule.endpoint.split('.')
            # filters out non-beacon endpoints
            if (len(_endpoint) > 1 and _endpoint[1] == 'static') or \
                _endpoint[0] != ('opportunities', 'opportunities_admin'):
                    continue
            else:
                if '<int:' in rule.rule:
                    response = self.client.get(url_for(rule.endpoint, opportunity_id=opportunity.id))
                else:
                    response = self.client.get(rule.rule)
                self.assert200(response)
    def setUp(self):
        super(TestOpportunitiesAdminBase, self).setUp()

        try:
            mkdir(current_app.config.get('UPLOAD_DESTINATION'))
        except OSError:
            rmtree(current_app.config.get('UPLOAD_DESTINATION'))
            mkdir(current_app.config.get('UPLOAD_DESTINATION'))

        import_nigp(current_app.config.get('PROJECT_ROOT') + '/purchasing_test/mock/nigp.csv')

        self.admin_role = insert_a_role('admin')
        self.staff_role = insert_a_role('staff')
        self.department1 = DepartmentFactory(name='test')

        self.admin = insert_a_user(email='*****@*****.**', role=self.admin_role)
        self.staff = insert_a_user(email='*****@*****.**', role=self.staff_role)

        self.opportunity1 = insert_an_opportunity(
            contact=self.admin, created_by=self.staff,
            is_public=True, planned_publish=datetime.date.today() + datetime.timedelta(1),
            planned_submission_start=datetime.date.today() + datetime.timedelta(2),
            planned_submission_end=datetime.date.today() + datetime.timedelta(2)
        )
        self.opportunity2 = insert_an_opportunity(
            contact=self.admin, created_by=self.staff,
            is_public=True, planned_publish=datetime.date.today(),
            planned_submission_start=datetime.date.today() + datetime.timedelta(2),
            planned_submission_end=datetime.date.today() + datetime.timedelta(2),
            categories=set([Category.query.first()])
        )
        self.opportunity3 = insert_an_opportunity(
            contact=self.admin, created_by=self.staff,
            is_public=True, planned_publish=datetime.date.today() - datetime.timedelta(2),
            planned_submission_start=datetime.date.today() - datetime.timedelta(2),
            planned_submission_end=datetime.date.today() - datetime.timedelta(1)
        )
        self.opportunity4 = insert_an_opportunity(
            contact=self.admin, created_by=self.staff,
            is_public=True, planned_publish=datetime.date.today() - datetime.timedelta(1),
            planned_submission_start=datetime.date.today(),
            planned_submission_end=datetime.date.today() + datetime.timedelta(2),
            title='TEST TITLE!'
        )
    def setUp(self):
        super(TestConductorSetup, self).setUp()
        # create a conductor and general staff person
        self.county_type = ContractTypeFactory.create(**{
            'name': 'County', 'allow_opportunities': True, 'managed_by_conductor': True
        })
        self.department = DepartmentFactory.create(**{'name': 'test department'})

        self.conductor_role_id = insert_a_role('conductor')
        self.staff_role_id = insert_a_role('staff')
        self.conductor = insert_a_user(email='*****@*****.**', role=self.conductor_role_id)
        self.staff = insert_a_user(email='*****@*****.**', role=self.staff_role_id)
        self.conductor2 = insert_a_user(email='*****@*****.**', role=self.conductor_role_id)

        # create three stages, and set up a flow between them
        self.stage1 = insert_a_stage(
            name='stage1', send_notifs=True, post_opportunities=True,
            default_message='i am a default message'
        )
        self.stage2 = insert_a_stage(name='stage2', send_notifs=True, post_opportunities=False)
        self.stage3 = insert_a_stage(name='stage3', send_notifs=False, post_opportunities=False)

        self.flow = insert_a_flow(stage_ids=[self.stage1.id, self.stage2.id, self.stage3.id])
        self.flow2 = insert_a_flow(name='test2', stage_ids=[self.stage1.id, self.stage3.id, self.stage2.id])
        self.simple_flow = insert_a_flow(name='simple', stage_ids=[self.stage1.id])

        # create two contracts
        self.contract1 = insert_a_contract(
            contract_type=self.county_type, description='scuba supplies', financial_id=123,
            expiration_date=datetime.date.today(), properties=[{'key': 'Spec Number', 'value': '123'}],
            is_visible=True, department=self.department, has_metrics=True
        )
        self.contract2 = insert_a_contract(
            contract_type=self.county_type, description='scuba repair', financial_id=456,
            expiration_date=datetime.date.today() + datetime.timedelta(120),
            properties=[{'key': 'Spec Number', 'value': '456'}],
            is_visible=True, has_metrics=True
        )

        self.category = CategoryFactory.create()

        self.login_user(self.conductor)
        self.detail_view = '/conductor/contract/{}/stage/{}'
        self.transition_view = '/conductor/contract/{}/stage/{}/'
    def setUp(self):
        super(TestUploadBase, self).setUp()

        try:
            mkdir(current_app.config.get('UPLOAD_DESTINATION'))
        except OSError:
            rmtree(current_app.config.get('UPLOAD_DESTINATION'))
            mkdir(current_app.config.get('UPLOAD_DESTINATION'))

        self.conductor_role_id = insert_a_role('conductor')
        self.conductor = insert_a_user(role=self.conductor_role_id, email='*****@*****.**')

        self.admin_role_id = insert_a_role('admin')
        self.admin = insert_a_user(role=self.admin_role_id, email='*****@*****.**')

        self.superadmin_role_id = insert_a_role('superadmin')
        self.superadmin = insert_a_user(role=self.superadmin_role_id, email='*****@*****.**')

        self.staff_role_id = insert_a_role('staff')
        self.staff = insert_a_user(email='*****@*****.**', role=self.staff_role_id)
    def setUp(self):
        super(TestUploadBase, self).setUp()

        try:
            mkdir(current_app.config.get('UPLOAD_DESTINATION'))
        except OSError:
            rmtree(current_app.config.get('UPLOAD_DESTINATION'))
            mkdir(current_app.config.get('UPLOAD_DESTINATION'))

        self.conductor_role_id = insert_a_role('conductor')
        self.conductor = insert_a_user(role=self.conductor_role_id,
                                       email='*****@*****.**')

        self.admin_role_id = insert_a_role('admin')
        self.admin = insert_a_user(role=self.admin_role_id,
                                   email='*****@*****.**')

        self.superadmin_role_id = insert_a_role('superadmin')
        self.superadmin = insert_a_user(role=self.superadmin_role_id,
                                        email='*****@*****.**')

        self.staff_role_id = insert_a_role('staff')
        self.staff = insert_a_user(email='*****@*****.**',
                                   role=self.staff_role_id)
    def test_new_user_success(self, urlopen):
        # insert all of our roles
        insert_a_role('superadmin')
        insert_a_role('admin')
        insert_a_role('staff')

        # assert we have only one user
        self.assertEquals(User.query.count(), 1)

        mock_open = Mock()
        mock_open.read.side_effect = [
            '{"status": "okay", "email": "*****@*****.**"}'
        ]
        urlopen.return_value = mock_open

        post = self.client.post('/users/auth?next=/explore/',
                                data=dict(assertion='test'))

        # assert we add a new user and redirect to the register page
        self.assertEquals(User.query.count(), 2)
        self.assertEquals(post.status_code, 200)
        self.assertEquals(post.data, '/users/profile')

        # assert we get the new user message
        register = self.client.get('/users/profile')
        self.assertTrue(
            'Welcome to the Pittsbugh Purchasing Suite!' in register.data)
        self.assert_template_used('users/profile.html')

        # assert that you cannot update with junk information
        bad_update = self.client.post(
            '/users/profile',
            data=dict(department='THIS IS NOT A VALID DEPARTMENT'),
            follow_redirects=True)
        self.assertTrue('THIS IS NOT A VALID DEPARTMENT' not in
                        [i.department for i in User.query.all()])
        self.assertTrue('Not a valid choice' in bad_update.data)

        # update the user successfully
        update = self.client.post('/users/profile',
                                  data=dict(first_name='foo',
                                            last_name='bar',
                                            department=str(
                                                self.department1.id)))

        # assert we successfully update
        self.assertEquals(update.status_code, 302)
        self.assertEquals(update.location, 'http://localhost/users/profile')
        self.assert_flashes('Updated your profile!', 'alert-success')

        # make sure the new user message is gone
        updated = self.client.get('/users/profile')

        self.assertTrue(
            'Welcome to the Pittsbugh Purchasing Suite!' not in updated.data)
        self.assert_template_used('users/profile.html')
    def test_new_user_success(self, urlopen):
        # insert all of our roles
        insert_a_role('superadmin')
        insert_a_role('admin')
        insert_a_role('staff')

        # assert we have only one user
        self.assertEquals(User.query.count(), 1)

        mock_open = Mock()
        mock_open.read.side_effect = [
            '{"status": "okay", "email": "*****@*****.**"}'
        ]
        urlopen.return_value = mock_open

        post = self.client.post('/users/auth?next=/explore/', data=dict(
            assertion='test'
        ))

        # assert we add a new user and redirect to the register page
        self.assertEquals(User.query.count(), 2)
        self.assertEquals(post.status_code, 200)
        self.assertEquals(post.data, '/users/profile')

        # assert we get the new user message
        register = self.client.get('/users/profile')
        self.assertTrue('Welcome to the Pittsbugh Purchasing Suite!' in register.data)
        self.assert_template_used('users/profile.html')

        # assert that you cannot update with junk information
        bad_update = self.client.post('/users/profile', data=dict(
            department='THIS IS NOT A VALID DEPARTMENT'
        ), follow_redirects=True)
        self.assertTrue(
            'THIS IS NOT A VALID DEPARTMENT' not in [i.department for i in User.query.all()]
        )
        self.assertTrue('Not a valid choice' in bad_update.data)

        # update the user successfully
        update = self.client.post('/users/profile', data=dict(
            first_name='foo', last_name='bar', department=str(self.department1.id)
        ))

        # assert we successfully update
        self.assertEquals(update.status_code, 302)
        self.assertEquals(update.location, 'http://localhost/users/profile')
        self.assert_flashes('Updated your profile!', 'alert-success')

        # make sure the new user message is gone
        updated = self.client.get('/users/profile')

        self.assertTrue('Welcome to the Pittsbugh Purchasing Suite!' not in updated.data)
        self.assert_template_used('users/profile.html')
示例#16
0
    def test_profile_update(self):
        admin = insert_a_role('admin')
        department1 = DepartmentFactory.create()
        department2 = DepartmentFactory.create()
        user = insert_a_user(role=admin, department=department1)

        self.assertEquals(user.department, department1)
        self.login_user(user)

        self.client.post('/users/profile', data=dict(
            first_name='foo',
            last_name='bar',
            department=department2.id
        ))

        self.assertEquals(user.first_name, 'foo')
        self.assertEquals(user.last_name, 'bar')
        self.assertEquals(user.department, department2)
        self.assert_flashes('Updated your profile!', 'alert-success')
    def test_new_user_success(self, urlopen):
        """Test that we properly register and onboard new users with a city domain
        """
        # insert all of our roles
        insert_a_role("superadmin")
        insert_a_role("admin")
        insert_a_role("staff")

        # assert we have only one user
        self.assertEquals(User.query.count(), 1)

        mock_open = Mock()
        mock_open.read.side_effect = ['{"status": "okay", "email": "*****@*****.**"}']
        urlopen.return_value = mock_open

        post = self.client.post("/users/auth?next=/explore/", data=dict(assertion="test"))

        # assert we add a new user and redirect to the register page
        self.assertEquals(User.query.count(), 2)
        self.assertEquals(post.status_code, 200)
        self.assertEquals(post.data, "/users/profile")

        # assert we get the new user message
        register = self.client.get("/users/profile")
        self.assertTrue("Welcome to the Pittsbugh Purchasing Suite!" in register.data)
        self.assert_template_used("users/profile.html")

        # assert that you cannot update with junk information
        bad_update = self.client.post(
            "/users/profile", data=dict(department="THIS IS NOT A VALID DEPARTMENT"), follow_redirects=True
        )
        self.assertTrue("THIS IS NOT A VALID DEPARTMENT" not in [i.department for i in User.query.all()])
        self.assertTrue("Not a valid choice" in bad_update.data)

        # update the user successfully
        update = self.client.post(
            "/users/profile", data=dict(first_name="foo", last_name="bar", department=str(self.department1.id))
        )

        # assert we successfully update
        self.assertEquals(update.status_code, 302)
        self.assertEquals(update.location, "http://localhost/users/profile")
        self.assert_flashes("Updated your profile!", "alert-success")

        # make sure the new user message is gone
        updated = self.client.get("/users/profile")

        self.assertTrue("Welcome to the Pittsbugh Purchasing Suite!" not in updated.data)
        self.assert_template_used("users/profile.html")
    def test_signup(self):
        admin_role = insert_a_role('admin')
        superadmin_role = insert_a_role('superadmin')

        insert_a_user(role=admin_role)
        insert_a_user(email='*****@*****.**', role=superadmin_role)

        response = self.client.get('/beacon/signup')
        self.assert200(response)
        subcats = json.loads(self.get_context_variable('subcategories'))

        # assert three categories (plus the total category)
        self.assertEquals(len(subcats.keys()), 4)
        # assert five total subcatgories (plus 5 in the total field)
        self.assertEquals(
            len([item for sublist in subcats.values() for item in sublist]),
            10)

        # assert email, business, categories needed
        no_email_post = self.client.post('/beacon/signup',
                                         data=dict(first_name='foo'))

        self.assert200(no_email_post)
        self.assertTrue(no_email_post.data.count('alert-danger'), 3)
        # ensure that there are two required field notes
        self.assertTrue(no_email_post.data.count('This field is required'), 2)

        # assert valid email address
        invalid_email_post = self.client.post('/beacon/signup',
                                              data=dict(email='INVALID',
                                                        business_name='test'))

        self.assert200(invalid_email_post)
        self.assertTrue(invalid_email_post.data.count('alert-danger'), 1)
        self.assertTrue(
            invalid_email_post.data.count('Invalid email address.'), 1)

        # assert you need at least one category
        invalid_no_categories = self.client.post('/beacon/signup',
                                                 data=dict(
                                                     email='*****@*****.**',
                                                     business_name='foo'))
        self.assert200(invalid_no_categories)
        self.assertTrue(invalid_no_categories.data.count('alert-danger'), 1)
        self.assertTrue(
            invalid_no_categories.data.count('You must select at least one!'),
            1)

        # assert valid categories

        with mail.record_messages() as outbox:

            # successful post with only one set of subcategories
            success_post = self.client.post('/beacon/signup',
                                            data={
                                                'email': '*****@*****.**',
                                                'business_name': 'foo',
                                                'subcategories-1': 'on',
                                                'categories': 'Apparel',
                                                'subscribed_to_newsletter':
                                                True
                                            })

            with self.client.session_transaction() as session:
                assert 'email' in session
                assert 'business_name' in session
                self.assertEquals(session['email'], '*****@*****.**')
                self.assertEquals(session['business_name'], 'foo')

            self.assertEquals(success_post.status_code, 302)
            self.assertEquals(success_post.location,
                              'http://localhost/beacon/')
            # should send three emails
            # one to the vendor, one to the admins
            self.assertEquals(len(outbox), 2)
            self.assertEquals(Vendor.query.count(), 1)
            self.assertTrue(Vendor.query.first().subscribed_to_newsletter)
            self.assertEquals(len(Vendor.query.first().categories), 1)
            self.assert_flashes(
                'Thank you for signing up! Check your email for more information',
                'alert-success')

            # successful post with two sets of subcategories
            success_post_everything = self.client.post(
                '/beacon/signup',
                data={
                    'email': '*****@*****.**',
                    'business_name': 'foo',
                    'subcategories-1': 'on',
                    'subcategories-2': 'on',
                    'subcategories-3': 'on',
                    'subcategories-4': 'on',
                    'subcategories-5': 'on',
                    'categories': 'Apparel',
                    'subscribed_to_newsletter': True
                })

            self.assertEquals(success_post_everything.status_code, 302)
            self.assertEquals(success_post_everything.location,
                              'http://localhost/beacon/')
            self.assertEquals(len(outbox), 4)
            self.assertEquals(Vendor.query.count(), 2)
            self.assertEquals(
                len(
                    Vendor.query.filter(
                        Vendor.email == '*****@*****.**').first().categories), 5)
            self.assert_flashes(
                'Thank you for signing up! Check your email for more information',
                'alert-success')

            # successful post with existing email should update the profile, not send message
            success_post_old_email = self.client.post(
                '/beacon/signup',
                data={
                    'email': '*****@*****.**',
                    'business_name': 'foo',
                    'subcategories-1': 'on',
                    'subcategories-2': 'on',
                    'subcategories-3': 'on',
                    'categories': 'Apparel',
                    'subscribed_to_newsletter': True
                })

            self.assertEquals(success_post_old_email.status_code, 302)
            self.assertEquals(success_post_old_email.location,
                              'http://localhost/beacon/')
            self.assertEquals(len(outbox), 4)
            self.assertEquals(Vendor.query.count(), 2)
            self.assertEquals(
                len(
                    Vendor.query.filter(
                        Vendor.email == '*****@*****.**').first().categories), 5)
            self.assert_flashes(
                "You are already signed up! Your profile was updated with this new information",
                'alert-info')

            admin_mail, vendor_mail = 0, 0
            for _mail in outbox:
                if 'new vendor has signed up on beacon' in _mail.subject:
                    admin_mail += 1
                if 'Thank you for signing up' in _mail.subject:
                    vendor_mail += 1

            self.assertEquals(admin_mail, 2)
            self.assertEquals(vendor_mail, 2)

            with self.client.session_transaction() as session:
                assert 'email' in session
                assert 'business_name' in session
                self.assertEquals(session['email'], '*****@*****.**')
                self.assertEquals(session['business_name'], 'foo')
 def setUp(self):
     super(TestSherpa, self).setUp()
     self.staff_role = insert_a_role('staff')
     self.email = '*****@*****.**'
     self.user = insert_a_user(email=self.email, role=self.staff_role)
    def test_signup(self):
        '''Test signups work as expected including validation errors, signups, etc.
        '''
        admin_role = insert_a_role('admin')
        superadmin_role = insert_a_role('superadmin')

        insert_a_user(role=admin_role)
        insert_a_user(email='*****@*****.**', role=superadmin_role)

        response = self.client.get('/beacon/signup')
        self.assert200(response)
        subcats = json.loads(self.get_context_variable('subcategories'))

        # assert three categories (plus the total category)
        self.assertEquals(len(subcats.keys()), 4)
        # assert five total subcatgories (plus 5 in the total field)
        self.assertEquals(len([item for sublist in subcats.values() for item in sublist]), 10)

        # assert email, business, categories needed
        no_email_post = self.client.post('/beacon/signup', data=dict(
            first_name='foo'
        ))

        self.assert200(no_email_post)
        self.assertTrue(no_email_post.data.count('alert-danger'), 3)
        # ensure that there are two required field notes
        self.assertTrue(no_email_post.data.count('This field is required'), 2)

        # assert valid email address
        invalid_email_post = self.client.post('/beacon/signup', data=dict(
            email='INVALID',
            business_name='test'
        ))

        self.assert200(invalid_email_post)
        self.assertTrue(invalid_email_post.data.count('alert-danger'), 1)
        self.assertTrue(invalid_email_post.data.count('Invalid email address.'), 1)

        # assert valid categories

        with mail.record_messages() as outbox:

            # successful post with only one set of subcategories
            success_post = self.client.post('/beacon/signup', data={
                'email': '*****@*****.**',
                'business_name': 'foo',
                'subcategories-1': 'on',
                'categories': 'Apparel',
                'subscribed_to_newsletter': True
            })

            with self.client.session_transaction() as session:
                assert 'email' in session
                assert 'business_name' in session
                self.assertEquals(session['email'], '*****@*****.**')
                self.assertEquals(session['business_name'], 'foo')

            self.assertEquals(success_post.status_code, 302)
            self.assertEquals(success_post.location, 'http://localhost/beacon/')
            # should send three emails
            # one to the vendor, one to the admins
            self.assertEquals(len(outbox), 2)
            self.assertEquals(Vendor.query.count(), 1)
            self.assertTrue(Vendor.query.first().subscribed_to_newsletter)
            self.assertEquals(len(Vendor.query.first().categories), 1)
            self.assert_flashes(
                'Thank you for signing up! Check your email for more information', 'alert-success'
            )

            # successful post with two sets of subcategories
            success_post_everything = self.client.post('/beacon/signup', data={
                'email': '*****@*****.**',
                'business_name': 'foo',
                'subcategories-1': 'on',
                'subcategories-2': 'on',
                'subcategories-3': 'on',
                'subcategories-4': 'on',
                'subcategories-5': 'on',
                'categories': 'Apparel',
                'subscribed_to_newsletter': True
            })

            self.assertEquals(success_post_everything.status_code, 302)
            self.assertEquals(success_post_everything.location, 'http://localhost/beacon/')
            self.assertEquals(len(outbox), 4)
            self.assertEquals(Vendor.query.count(), 2)
            self.assertEquals(len(Vendor.query.filter(Vendor.email == '*****@*****.**').first().categories), 5)
            self.assert_flashes('Thank you for signing up! Check your email for more information', 'alert-success')

            # successful post with existing email should update the profile, not send message
            success_post_old_email = self.client.post('/beacon/signup', data={
                'email': '*****@*****.**',
                'business_name': 'foo',
                'subcategories-1': 'on',
                'subcategories-2': 'on',
                'subcategories-3': 'on',
                'categories': 'Apparel',
                'subscribed_to_newsletter': True
            })

            self.assertEquals(success_post_old_email.status_code, 302)
            self.assertEquals(success_post_old_email.location, 'http://localhost/beacon/')
            self.assertEquals(len(outbox), 4)
            self.assertEquals(Vendor.query.count(), 2)
            self.assertEquals(len(Vendor.query.filter(Vendor.email == '*****@*****.**').first().categories), 5)
            self.assert_flashes(
                "You are already signed up! Your profile was updated with this new information", 'alert-info'
            )

            admin_mail, vendor_mail = 0, 0
            for _mail in outbox:
                if 'new vendor has signed up on beacon' in _mail.subject:
                    admin_mail += 1
                if 'Thank you for signing up' in _mail.subject:
                    vendor_mail += 1

            self.assertEquals(admin_mail, 2)
            self.assertEquals(vendor_mail, 2)

            with self.client.session_transaction() as session:
                assert 'email' in session
                assert 'business_name' in session
                self.assertEquals(session['email'], '*****@*****.**')
                self.assertEquals(session['business_name'], 'foo')