Exemplo n.º 1
0
class DocumentDetailTests(TestCase):
    """Test action menu items"""
    def setUp(self):
        self.category = CategoryFactory()
        self.user = UserFactory(
            name='User',
            password='******',
            is_superuser=True,
            category=self.category)
        self.client.login(username=self.user.email, password='******')
        self.doc = DocumentFactory(
            category=self.category,
            revision={
                'leader': self.user,
            }
        )
        self.url = reverse("document_detail", args=[
            self.category.organisation.slug,
            self.category.slug,
            self.doc.document_key
        ])

    def test_admin_can_delete_document(self):
        res = self.client.get(self.url)
        self.assertContains(res, delete_button)

    def test_simple_user_cannot_delete_document(self):
        self.user.is_superuser = False
        self.user.save()

        res = self.client.get(self.url)
        self.assertNotContains(res, delete_button)
Exemplo n.º 2
0
 def create_admin(self):
     # Factory creates simple user, so ``is_staff`` is set later
     self.admin = UserFactory(username='******', password='******')
     self.admin.is_staff = True
     self.admin.is_superuser = True
     self.admin.save()
     print("admin user have been created successfully")
Exemplo n.º 3
0
    def setUp(self):
        Model = ContentType.objects.get_for_model(ContractorDeliverable)
        self.category = CategoryFactory(category_template__metadata_model=Model)

        self.user = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            category=self.category)
        self.user2 = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            category=self.category)
        self.user3 = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            category=self.category)

        self.data = {
            'docclass': 3,
            'purpose_of_issue': 'FR',
            'created_on': '2015-01-01',
            'received_date': '2015-01-01'
        }
Exemplo n.º 4
0
    def test_buy_a_bet(self):
        """
        Buy a bet
        """
        event = EventFactory()
        user = UserFactory(total_cash=event.current_buy_for_price)
        old_price = event.current_buy_for_price
        bet_user, bet_event, bet = Bet.objects.buy_a_bet(user, event.id, Bet.YES,
                                                         event.current_buy_for_price)
        self.assertEqual(user, bet_user)
        self.assertEqual(event, bet_event)
        self.assertEqual(event.current_buy_for_price, bet.bought_avg_price)
        self.assertEqual(1, bet.has)
        self.assertEqual(1, bet.bought)
        self.assertEqual(0, bet_user.total_cash)
        self.assertEqual(old_price, bet_user.portfolio_value)
        self.assertNotEqual(old_price, bet_event.current_buy_for_price)
        self.assertEqual(1, bet_event.turnover)

        with self.assertRaises(PriceMismatch):
            Bet.objects.buy_a_bet(user, event.id, Bet.YES, old_price)

        with self.assertRaises(InsufficientCash):
            Bet.objects.buy_a_bet(user, event.id, Bet.YES, bet_event.current_buy_for_price)

        user.total_cash = bet_event.current_buy_against_price
        user.save()
        # TODO should throw exception
        Bet.objects.buy_a_bet(user, event.id, Bet.NO, bet_event.current_buy_against_price)
Exemplo n.º 5
0
def superuser():
    """Generates a valid and active superuser."""

    user = UserFactory()
    user.is_superuser = True
    user.save()
    return user
Exemplo n.º 6
0
def test_matters_assistant_name_filter(snapshot, request):
    """ Test matters assistant name filter """

    user_instance = UserFactory(first_name='first', last_name='last')

    MatterFactory.create_batch(
        size=5,
        assistant=user_instance,
    )

    staff_member = UserFactory(id=1)
    request.user = staff_member

    client = Client(schema, context=request)
    query = client.execute("""
        query getMatters($assistantName: String) {
            matters(first: 3, assistantName: $assistantName) {
                edges {
                    node {
                        id
                        name
                        client {
                            id
                            name
                        }
                        billableStatus
                    }
                }
            }
        }
    """,
                           variable_values={
                               'assistantName': user_instance.full_name,
                           })
    snapshot.assert_match(query)
Exemplo n.º 7
0
class BatchAckOfTransmittalsTests(TestCase):
    def setUp(self):
        self.trs = create_transmittal()
        self.category = self.trs.document.category
        self.user = UserFactory(email='*****@*****.**',
                                password='******',
                                is_superuser=True,
                                category=self.category)
        self.client.login(email=self.user.email, password='******')
        self.url = reverse('transmittal_batch_ack_of_receipt',
                           args=[
                               self.category.organisation.slug,
                               self.category.slug,
                           ])

    def test_internal_user_cannot_ack_transmittal(self):
        res = self.client.post(self.url,
                               {'document_ids': [self.trs.document_id]})
        self.assertEqual(res.status_code, 403)

    def test_acks_receipt(self):
        self.user.is_external = True
        self.user.save()

        res = self.client.post(self.url,
                               {'document_ids': [self.trs.document_id]},
                               follow=True)
        self.assertEqual(res.status_code, 200)

        self.trs.refresh_from_db()
        self.assertIsNotNone(self.trs.ack_of_receipt_date)
        self.assertEqual(self.trs.ack_of_receipt_author, self.user)
Exemplo n.º 8
0
    def setUpTestData(cls):
        """
        Initialize the class by populating the database.

        Some notes:
          - The 'ignored' company is to make a clear difference in the
            response for management and members of a company.
        """

        cls.company = CompanyFactory()
        cls.ignored = CompanyFactory()

        cls.external = UserFactory(group=Group.objects.create(name="external"))
        cls.employer = UserFactory(group=Group.objects.get(id=Groups.employer))
        cls.employee = UserFactory(group=Group.objects.get(id=Groups.employee))

        cls.external_token = AuthFactory(user=cls.external)
        cls.employer_token = AuthFactory(user=cls.employer)
        cls.employee_token = AuthFactory(user=cls.employee)

        MemberFactory(account=cls.employer, company=cls.company)
        MemberFactory(account=cls.employee, company=cls.company)

        cls.management = UserFactory(group=Group.objects.get(
            id=Groups.management))

        cls.administrator = UserFactory(group=Group.objects.get(
            id=Groups.admin))

        cls.management_token = AuthFactory(user=cls.management)
        cls.administrator_token = AuthFactory(user=cls.administrator)
Exemplo n.º 9
0
    def setUp(self):
        self.category = CategoryFactory()
        user = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            category=self.category)
        self.client.login(email=user.email, password='******')

        user2 = UserFactory(email='*****@*****.**', category=self.category)

        doc = DocumentFactory(
            document_key='hazop-report-1',
            category=self.category,
            revision={
                'leader': user,
            }

        )
        doc.latest_revision.start_review()

        for _ in range(5):
            for u in (user, user2):
                NoteFactory(
                    author=u,
                    document=doc,
                    revision=1)

        review_url = reverse('review_document', args=[doc.document_key])
        self.url = '%s%s' % (self.live_server_url, review_url)
        self.test_file = os.path.join(
            os.path.dirname(__file__),
            'casper_tests',
            'tests.js'
        )
Exemplo n.º 10
0
    def setUpData(self):
        self.past_match = PastMatchFactory.create(home_team='Bordo', away_team='Chelsea')
        self.past_match2 = PastMatchFactory.create(home_team='Bordo', away_team='Ajax')
        self.past_match3 = PastMatchFactory.create(home_team='Chelsea', away_team='Ajax',
                                                   home_score=None, away_score=None)
        self.future_match = FutureMatchFactory.create(home_team='Ajax', away_team='Barcelona',
                                                      datetime="2047-01-09 05:04+00:00")

        self.user1 = UserFactory.create(username='******')
        self.user2 = UserFactory.create(username='******')

        self.bets = [
            [
                BetFactory.create(match=self.future_match, user=self.user1, home_score=2, away_score=1),
                BetFactory.create(match=self.future_match, user=self.user2, home_score=4, away_score=0),
            ],  # future match
            [
                None,
                BetFactory.create(match=self.past_match, user=self.user2, home_score=2, away_score=0),
            ],  # past match
            [
                BetFactory.create(match=self.past_match2, user=self.user1, home_score=1, away_score=3),
                BetFactory.create(match=self.past_match2, user=self.user2, home_score=0, away_score=0),
            ],
            [
                None,
                BetFactory.create(match=self.past_match3, user=self.user2, home_score=0, away_score=0),
            ]
        ]

        self.past_match.set_score(home_score=2, away_score=0)
        self.past_match2.set_score(home_score=0, away_score=0)
Exemplo n.º 11
0
    def setUpTestData(cls):
        employer_group = Group.objects.get(id=Groups.employer)
        employee_group = Group.objects.get(id=Groups.employee)
        managing_group = Group.objects.get(id=Groups.management)

        cls.companyA = CompanyFactory()
        cls.companyB = CompanyFactory()

        cls.employerA = UserFactory(group=employer_group)
        cls.employeeA = UserFactory(group=employee_group)

        cls.employerB = UserFactory(group=employer_group)
        cls.employeeB = UserFactory(group=employee_group)

        cls.management = UserFactory(group=managing_group)

        cls.employee_a_token = AuthFactory(user=cls.employeeA)
        cls.employer_a_token = AuthFactory(user=cls.employerA)
        cls.employee_b_token = AuthFactory(user=cls.employeeB)
        cls.employer_b_token = AuthFactory(user=cls.employerB)
        cls.management_token = AuthFactory(user=cls.management)

        MemberFactory(account=cls.employerA, company=cls.companyA)
        MemberFactory(account=cls.employeeA, company=cls.companyA)
        MemberFactory(account=cls.employerB, company=cls.companyB)
        MemberFactory(account=cls.employeeB, company=cls.companyB)
Exemplo n.º 12
0
class BatchAckOfTransmittalsTests(TestCase):
    def setUp(self):
        self.trs = create_transmittal()
        self.category = self.trs.document.category
        self.user = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            category=self.category)
        self.client.login(email=self.user.email, password='******')
        self.url = reverse('transmittal_batch_ack_of_receipt', args=[
            self.category.organisation.slug,
            self.category.slug,
        ])

    def test_internal_user_cannot_ack_transmittal(self):
        res = self.client.post(self.url, {'document_ids': [self.trs.document_id]})
        self.assertEqual(res.status_code, 403)

    def test_acks_receipt(self):
        self.user.is_external = True
        self.user.save()

        res = self.client.post(
            self.url,
            {'document_ids': [self.trs.document_id]},
            follow=True)
        self.assertEqual(res.status_code, 200)

        self.trs.refresh_from_db()
        self.assertIsNotNone(self.trs.ack_of_receipt_date)
        self.assertEqual(self.trs.ack_of_receipt_author, self.user)
Exemplo n.º 13
0
def test_matter_report_filter_with_value_error(snapshot, request):
    """ Test matter report filter with value error """

    user_instance = UserFactory(first_name='name', last_name='name')

    MatterFactory.create_batch(
        size=5,
        assistant=user_instance,
    )

    staff_member = UserFactory(id=1)
    request.user = staff_member

    client = Client(schema, context=request)
    query = client.execute("""
        query getMatters($matterReport: String) {
            matters(first: 3, matterReport: $matterReport) {
                edges {
                    node {
                        id
                        name
                        client {
                            id
                            name
                        }
                        billableStatus
                    }
                }
            }
        }
    """,
                           variable_values={
                               'matterReport': 'name',
                           })
    snapshot.assert_match(query)
Exemplo n.º 14
0
    def test_plan_restrictions(self):
        corp_account = CorporateAccountFactory.create()
        corp_user = UserFactory.create(account=corp_account)

        plan_1 = PlanFactory()
        plan_2 = PlanFactory()
        plan_3 = PlanFactory()

        account_1 = AccountFactory(plan=plan_1)
        account_2 = AccountFactory(plan=plan_2)
        account_3 = AccountFactory(plan=plan_3)

        user_1 = UserFactory(account=account_1)
        user_2 = UserFactory(account=account_2)
        user_3 = UserFactory(account=account_3)

        flight = FlightFactory(departure=arrow.now().replace(days=+12).datetime)

        self.assertTrue(flight.check_plan_restrictions(corp_user), 'always allow corp users')

        self.assertTrue(flight.check_plan_restrictions(user_1), 'no plan restrictions')
        self.assertTrue(flight.check_plan_restrictions(user_2), 'no plan restrictions')
        self.assertTrue(flight.check_plan_restrictions(user_3), 'no plan restrictions')

        FlightPlanRestrictionFactory(flight=flight, plan=plan_1, days=2)
        FlightPlanRestrictionFactory(flight=flight, plan=plan_2, days=12)
        FlightPlanRestrictionFactory(flight=flight, plan=plan_3, days=16)

        self.assertTrue(flight.check_plan_restrictions(corp_user), 'always allow corp users')

        self.assertFalse(flight.check_plan_restrictions(user_1), 'only 2 days out')
        self.assertTrue(flight.check_plan_restrictions(user_2), 'just now')
        self.assertTrue(flight.check_plan_restrictions(user_3), 'been good')

        flight.departure = arrow.now().replace(days=+13).datetime
        flight.save()

        self.assertTrue(flight.check_plan_restrictions(corp_user), 'always allow corp users')

        self.assertFalse(flight.check_plan_restrictions(user_1), 'only 2 days out')
        self.assertFalse(flight.check_plan_restrictions(user_2), 'just now')
        self.assertTrue(flight.check_plan_restrictions(user_3), 'been good')

        flight.departure = arrow.now().replace(days=+16).datetime
        flight.save()

        self.assertTrue(flight.check_plan_restrictions(corp_user), 'always allow corp users')

        self.assertFalse(flight.check_plan_restrictions(user_1), 'only 2 days out')
        self.assertFalse(flight.check_plan_restrictions(user_2), 'just now')
        self.assertTrue(flight.check_plan_restrictions(user_3), 'been good')

        flight.departure = arrow.now().replace(days=+17).datetime
        flight.save()

        self.assertTrue(flight.check_plan_restrictions(corp_user), 'always allow corp users')

        self.assertFalse(flight.check_plan_restrictions(user_1), 'only 2 days out')
        self.assertFalse(flight.check_plan_restrictions(user_2), 'just now')
        self.assertFalse(flight.check_plan_restrictions(user_3), 'been good')
Exemplo n.º 15
0
    def test_check_user_permissions(self):
        account = AccountFactory.create()
        user_1 = UserFactory.create(account=account)
        user_2 = UserFactory.create(account=account)

        flight = FlightFactory.create()

        self.assertFalse(flight.check_user_permissions(user_1), 'no fly permissions')
        self.assertFalse(flight.check_user_permissions(user_2), 'no fly permissions')

        user_1.user_permissions.add(Permission.objects.get(codename='can_fly'))
        delattr(user_1, '_perm_cache')

        self.assertTrue(flight.check_user_permissions(user_1), 'can fly permissions')
        self.assertFalse(flight.check_user_permissions(user_2), 'no fly permissions')

        user_2.user_permissions.add(Permission.objects.get(codename='can_fly'))
        delattr(user_2, '_perm_cache')
        user_1.user_permissions.add(Permission.objects.get(codename='can_book_promo_flights'))
        delattr(user_1, '_perm_cache')

        promo_flight = FlightFactory.create(flight_type=Flight.TYPE_PROMOTION)

        self.assertTrue(flight.check_user_permissions(user_1), 'regular flight')
        self.assertTrue(flight.check_user_permissions(user_2), 'regular flight')

        self.assertTrue(promo_flight.check_user_permissions(user_1), 'promo flight')
        self.assertFalse(promo_flight.check_user_permissions(user_2), 'promo flight nope')
Exemplo n.º 16
0
    def setUp(self):
        self.category = CategoryFactory()
        self.user = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            category=self.category
        )
        self.other_user = UserFactory(
            email='*****@*****.**',
            password='******',
        )
        self.client.login(email=self.user.email, password='******')

        doc = DocumentFactory(
            document_key='test_key',
            category=self.category,
            revision={
                'reviewers': [],
                'leader': self.user,
                'received_date': datetime.date.today(),
            }
        )
        revision = doc.latest_revision
        revision.start_review()

        self.review = revision.get_review(self.user)
        self.url = self.review.get_comments_url()

        pdf_doc = 'sample_doc_pdf.pdf'
        self.sample_pdf = SimpleUploadedFile(pdf_doc, b'content')
Exemplo n.º 17
0
 def setUp(self):
     self.test_user = UserFactory(username='******')
     self.test_user_2 = UserFactory(username='******')
     self.public_guide_1 = GuideFactory(owner=self.test_user, private=False, name='Public Crane')
     self.public_guide_2 = GuideFactory(owner=self.test_user_2, private=False, name='Public Paper')
     self.private_guide_1 = GuideFactory(owner=self.test_user, private=True, name='Private')
     self.private_guide_2 = GuideFactory(owner=self.test_user_2, private=True, name='Private 2')
Exemplo n.º 18
0
    def setUp(self):
        super().setUp()
        Model = ContentType.objects.get_for_model(ContractorDeliverable)
        self.cat1 = CategoryFactory(category_template__metadata_model=Model)
        self.cat2 = CategoryFactory(category_template__metadata_model=Model)

        self.user1 = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            category=self.cat1,
            send_behind_schedule_alert_mails=True)
        self.user1.categories.add(self.cat2)
        self.user2 = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            category=self.cat2,
            send_behind_schedule_alert_mails=True)

        self.doc1 = DocumentFactory(
            category=self.cat1,
            metadata_factory_class=ContractorDeliverableFactory,
            revision_factory_class=ContractorDeliverableRevisionFactory)
        self.doc2 = DocumentFactory(
            category=self.cat2,
            metadata_factory_class=ContractorDeliverableFactory,
            revision_factory_class=ContractorDeliverableRevisionFactory)

        populate_values_list_cache()
Exemplo n.º 19
0
class UserApiAclTests(APITestCase):
    def setUp(self):
        self.category = CategoryFactory()
        self.user = UserFactory(name='user', password='******', category=self.category)

        self.dc_perms = Permission.objects.filter(codename__endswith='_document')
        self.dc = UserFactory(name='dc', password='******', category=self.category)
        self.dc.user_permissions = self.dc_perms
        self.dc.save()

        self.url = reverse('user-list', args=[
            self.category.organisation.slug,
            self.category.category_template.slug,
        ])

    def test_anonymous_access_forbidden(self):
        """Anonymous cannot access the user api."""
        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 403)

    def test_simple_user_access_forbidden(self):
        """Simple users don't have access to the user api."""
        self.client.login(username=self.user.email, password='******')

        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 403)

    def test_dc_can_access_user_api(self):
        """Document controllers can access the user api."""
        self.client.login(username=self.dc.email, password='******')

        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 200)

    def test_dc_can_only_access_users_from_his_category(self):
        other_category = CategoryFactory()
        user = UserFactory(name='dc2', password='******', category=other_category)
        user.user_permissions = self.dc_perms
        user.save()
        self.client.login(username=user.email, password='******')

        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 403)

    def test_dc_cannot_see_users_from_other_categories(self):
        other_category = CategoryFactory()
        user1 = UserFactory(name='toto', password='******', category=other_category)
        user1.save()

        user2 = UserFactory(name='tata', password='******', category=self.category)
        user2.save()

        self.client.login(username=self.dc.email, password='******')

        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 200)

        self.assertTrue('tata' in res.content)
        self.assertTrue('toto' not in res.content)
Exemplo n.º 20
0
 def setUp(self):
     self.trs = create_transmittal()
     self.trs.recipient.users.add(UserFactory(email='*****@*****.**'))
     self.trs.recipient.users.add(UserFactory(email='*****@*****.**'))
     self.trs.recipient.users.add(UserFactory(email='*****@*****.**'))
     self.trs.recipient.users.add(
         UserFactory(email='*****@*****.**',
                     send_trs_reminders_mails=False))
Exemplo n.º 21
0
 def test_match_update_bets_calls_set_result_for_every_bet(
         self, mock_set_result):
     user1 = UserFactory.create()
     user2 = UserFactory.create()
     match = PastMatchFactory(home_score=1, away_score=2)
     bet1 = BetFactory(match=match, user=user1)
     BetFactory(match=match, user=user2)
     match.update_bets()
     self.assertEqual(mock_set_result.call_count, 2)
Exemplo n.º 22
0
class AdminTest(FunctionalTest):

    def setUp(self):
        super().setUp()

        # Create a superuser
        self.password = '******'
        self.admin_user = UserFactory(password=self.password)
        self.admin_user.is_admin = True
        self.admin_user.save()

        # Create packages and doctypes for the new audit
        PackageFactory(name='TestPackage')
        DoctypeFactory(name='TestDoctype')

    def test_can_create_new_audit_via_admin_site(self):
        # Gertrude opens her web browser, and goes to the admin page
        self.browser.get(self.server_url + '/admin/')

        # She sees the familiar 'Django administration' heading
        body = self.browser.find_element_by_tag_name('body')
        self.assertIn('Django administration', body.text)

        # She inserts her email and password
        email_input = self.browser.find_element_by_id('id_username')
        email_input.send_keys(self.admin_user.email)

        password_input = self.browser.find_element_by_id('id_password')
        password_input.send_keys(self.password + '\n')

        # Aftwer beign logged in, she visits the audit creation page
        audit_section = self.browser.find_element_by_css_selector('.model-audit')
        audit_section.find_element_by_css_selector('.addlink').click()

        # She inserts all the required information in order to create a new audit
        self.browser.find_element_by_id('id_name').send_keys('A new test audit')
        self.browser.find_element_by_id('id_description').send_keys('A text description for our new audit')

        package_dropdown = Select(self.browser.find_element_by_id('id_package'))
        package_dropdown.select_by_visible_text('TestPackage')

        doctype_selection = Select(self.browser.find_element_by_id('id_required_doctypes'))
        doctype_selection.select_by_visible_text('TestDoctype')

        runner_dropdown = Select(self.browser.find_element_by_id('id_runner'))
        runner_dropdown.select_by_visible_text('DummyAudit')

        # She then saves her new audit by clicking on the Save button
        self.browser.find_element_by_css_selector('.default').click()

        # A list page is displayed, and she can see her newly created audit is in there
        self.assertTrue(self.browser.find_element_by_link_text('A new test audit'))

        # Finally, she visits to the home page to check if her new audit is displayed
        self.browser.find_element_by_link_text('VIEW SITE').click()
        page_text = self.browser.find_element_by_tag_name('body').text
        self.assertIn('A new test audit', page_text)
Exemplo n.º 23
0
class PasswordResetTestCase(APITestCase):
    User = get_user_model()

    def setUp(self):
        self.user = UserFactory()

    def send_reset_password_request(self, data):
        """ Send request to reset password """
        response = self.client.post(
            reverse('password_reset:reset-password-request'), data=data)
        return response

    def test_successful_generate_token(self):
        """ Test successful generating token for provided email """
        data = {'email': self.user.email}
        response = self.send_reset_password_request(data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_invalid_email(self):
        """ Test failure generating token for invalid email """
        data = {'email': '*****@*****.**'}
        response = self.send_reset_password_request(data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_successful_validate_token(self):
        """ Test successful validating token """
        data = {'email': self.user.email}
        self.send_reset_password_request(data)
        token = ResetPasswordToken.objects.first().key
        response = self.client.post(
            reverse('password_reset:reset-password-validate'),
            data={'token': token})
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_fail_validating_token(self):
        """ Test unsuccessful validating wrong token """
        response = self.client.post(
            reverse('password_reset:reset-password-validate'),
            data={'token': 'wrong_token'})
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_successful_change_password(self):
        """ Test successful changing password with provided token and password """
        self.send_reset_password_request({'email': self.user.email})
        token = ResetPasswordToken.objects.first().key
        data = {'token': token, 'password': '******'}
        response = self.client.post(
            reverse('password_reset:reset-password-confirm'), data=data)
        self.user.refresh_from_db()
        self.assertTrue(self.user.check_password('exampleNewPassword'))

    def test_fail_change_password(self):
        """ Test fail changing password with provided wrong token """
        data = {'token': 'wrong_token', 'password': '******'}
        self.client.post(reverse('password_reset:reset-password-confirm'),
                         data=data)
        self.assertFalse(self.user.check_password('exampleNewPassword'))
Exemplo n.º 24
0
    def test_dc_can_only_access_users_from_his_category(self):
        other_category = CategoryFactory()
        user = UserFactory(name='dc2', password='******', category=other_category)
        user.user_permissions = self.dc_perms
        user.save()
        self.client.login(username=user.email, password='******')

        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 403)
Exemplo n.º 25
0
def test_user_role_contributor():
    """Users with 'is_contributor' as True are considered as contributors."""

    # user
    UserFactory(is_contributor=False)
    # contributor
    UserFactory(is_contributor=True)

    assert User.objects.count() == 2
    assert User.objects.contributors().count() == 1
Exemplo n.º 26
0
    def test_notification_list(self):
        trs = create_transmittal()
        rev = trs.latest_revision

        trs.recipient.users.add(UserFactory(email='*****@*****.**'))
        trs.recipient.users.add(UserFactory(email='*****@*****.**'))
        trs.recipient.users.add(UserFactory(email='*****@*****.**'))

        send_transmittal_creation_notifications(trs, rev)
        self.assertEqual(len(mail.outbox), 3)
Exemplo n.º 27
0
    def setUp(self):
        self.category = CategoryFactory()
        self.user = UserFactory(email='*****@*****.**',
                                password='******',
                                category=self.category)
        self.client.login(email=self.user.email, password='******')

        self.user2 = UserFactory(email='*****@*****.**',
                                 password='******',
                                 category=self.category)
Exemplo n.º 28
0
class PendingReviewsReminderTests(TestCase):
    def setUp(self):
        self.category = CategoryFactory()
        self.user = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            category=self.category
        )
        self.client.login(email=self.user.email, password='******')
        self.doc1 = DocumentFactory(
            category=self.category,
            revision={
                'leader': self.user,
                'received_date': datetime.date.today(),
            }
        )
        self.doc2 = DocumentFactory(
            category=self.category,
            revision={
                'leader': self.user,
                'received_date': datetime.date.today(),
            }
        )

    def test_empty_reminder_list(self):
        call_command('send_review_reminders')
        self.assertEqual(len(mail.outbox), 0)

    def test_send_reminders(self):
        self.doc1.get_latest_revision().start_review()
        self.assertEqual(Review.objects.all().count(), 1)

        call_command('send_review_reminders')
        self.assertEqual(len(mail.outbox), 1)

    def test_finished_reviews(self):
        rev = self.doc1.get_latest_revision()
        rev.start_review()
        rev.end_review()
        self.assertEqual(Review.objects.all().count(), 1)

        call_command('send_review_reminders')
        self.assertEqual(len(mail.outbox), 0)

    def test_do_not_send_reminder(self):
        """Reminders are not send to users if their mail config says so."""
        self.doc1.get_latest_revision().start_review()
        self.assertEqual(Review.objects.all().count(), 1)

        self.user.send_pending_reviews_mails = False
        self.user.save()

        call_command('send_review_reminders')
        self.assertEqual(len(mail.outbox), 0)
Exemplo n.º 29
0
 def setUp(self):
     cache.clear()
     self.category = CategoryFactory()
     self.user = UserFactory(email='*****@*****.**',
                             password='******',
                             is_superuser=True,
                             category=self.category)
     self.other_user = UserFactory(email='*****@*****.**',
                                   category=self.category)
     self.client.login(email=self.user.email, password='******')
     self.url = reverse('category_list')
Exemplo n.º 30
0
def test_user_role_search_page_admin():
    """Users with linked Search Pages are considered as Search Page administrators."""

    # user
    UserFactory(is_contributor=False)
    # search page administrator
    search_page_administrator = UserFactory(is_contributor=False)
    SearchPageFactory(administrator=search_page_administrator)

    assert User.objects.count() == 2
    assert User.objects.search_page_admins().count() == 1
Exemplo n.º 31
0
    def test_dc_can_only_access_users_from_his_category(self):
        other_category = CategoryFactory()
        user = UserFactory(name='dc2',
                           password='******',
                           category=other_category)
        user.user_permissions = self.dc_perms
        user.save()
        self.client.login(username=user.email, password='******')

        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 403)
Exemplo n.º 32
0
    def test_attendance_data(self):
        user1 = UserFactory(email='*****@*****.**')
        user2 = UserFactory(email='*****@*****.**')
        AttendanceFactory(user=user1, event=self.event)
        AttendanceFactory(user=user2, event=self.event)

        url = reverse('event:detail', kwargs={"pk": self.event.pk})
        self.client.login(email='*****@*****.**', password='******')
        response = self.client.get(url)
        self.assertContains(response, "user1")
        self.assertContains(response, "user2")
Exemplo n.º 33
0
 def test_can_get_images_uploaded_by_a_user(self):
     """
     Tests that the manager can get images specifically uploaded by a user.
     """
     user_1 = UserFactory.create()
     user_2 = UserFactory.create()
     image_1a = ImageFactory.create(uploaded_by=user_1)
     image_1b = ImageFactory.create(uploaded_by=user_1)
     image_2a = ImageFactory.create(uploaded_by=user_2)
     self.assertEquals([image_1b, image_1a], list(Image.objects.filter_uploaded_by(user_1)))
     self.assertEquals([image_2a], list(Image.objects.filter_uploaded_by(user_2)))
Exemplo n.º 34
0
 def setUp(self):
     self.category = CategoryFactory()
     self.user1 = UserFactory(username='******', category=self.category)
     self.user2 = UserFactory(username='******', category=self.category)
     self.user3 = UserFactory(username='******',
                              category=self.category)
     self.doc = DocumentFactory(revision={
         'leader': self.user1,
     })
     self.revision = self.doc.latest_revision
     self.revision.start_review()
Exemplo n.º 35
0
 def test_reviewers_not_in_categories(self):
     form = DistributionListForm({
         'name':
         'test',
         'categories': [self.category.id],
         'leader':
         self.users[0].id,
         'reviewers': [UserFactory().id, UserFactory().id]
     })
     self.assertFalse(form.is_valid())
     self.assertTrue('reviewers' in form.errors)
Exemplo n.º 36
0
 def setUp(self):
     super(ClosedReviewsEmailTests, self).setUp()
     self.today = timezone.now()
     self.yesterday = timezone.now() - datetime.timedelta(days=1)
     self.originator = EntityFactory(
         type='originator',
         users=[
             UserFactory(),
             UserFactory(),
             UserFactory(),
             UserFactory(send_closed_reviews_mails=False),
         ])
Exemplo n.º 37
0
class FileTransmittedDownloadTests(TestCase):
    def setUp(self):
        self.trs = create_transmittal()
        self.rev = self.trs.latest_revision
        self.category = self.trs.document.category
        self.user = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            is_external=True,
            category=self.category)
        self.trs.recipient.users.add(self.user)
        self.client.login(email=self.user.email, password='******')
        self.linked_rev = self.trs.get_revisions()[0]
        self.url = reverse('file_transmitted_download', args=[
            self.category.organisation.slug,
            self.category.slug,
            self.trs.document_number,
            self.linked_rev.metadata.document_key,
            self.linked_rev.revision,
        ])
        pdf_doc = 'sample_doc_pdf.pdf'
        sample_pdf = SimpleUploadedFile(pdf_doc, b'content')
        self.linked_rev.file_transmitted = sample_pdf
        self.linked_rev.save()

    def test_url_is_accessible_to_externals(self):
        u"""This download url is for contractors only."""

        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 200)

        self.user.is_external = False
        self.user.save()
        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 404)

    def test_that_revision_is_linked_to_transmittal(self):
        u"""The file must have been transmitted."""

        self.linked_rev.transmittals.clear()
        self.linked_rev.save()
        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 404)

    def test_that_contractor_is_in_recipients(self):
        u"""The contractor must be allowed to access the transmittal."""

        self.trs.recipient.users.clear()
        self.trs.recipient.save()
        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 404)
Exemplo n.º 38
0
 def test_get_bet_social(self):
     """
     Get bet social
     """
     event = EventFactory()
     users_yes = UserFactory.create_batch(10)
     users_no = UserFactory.create_batch(10)
     bets_yes = [BetFactory(user=u, event=event) for u in users_yes]
     bets_no = [BetFactory(user=u, event=event, outcome=Bet.NO) for u in users_no]
     self.maxDiff = None
     social = event.get_bet_social()
     self.assertEqual(10, social['yes_count'])
     self.assertEqual(bets_yes[:6], list(social['yes_bets']))
     self.assertEqual(10, social['no_count'])
     self.assertEqual(bets_no[:6], list(social['no_bets']))
Exemplo n.º 39
0
 def create_admin(self):
     # Factory creates simple user, so ``is_staff`` is set later
     self.admin = UserFactory(username="******", password="******")
     self.admin.is_staff = True
     self.admin.is_superuser = True
     self.admin.save()
     print("admin user have been created successfully")
Exemplo n.º 40
0
 def setUp(self):
     self.moderator = ModeratorFactory()
     self.standard_user = UserFactory(
         first_name='Firsto',
         last_name='Namo',
     )
     self.invited_pending = InvitedPendingFactory()
     self.requested_pending = RequestedPendingFactory()
Exemplo n.º 41
0
 def test_can_logout(self):
     """
     Tests the logout view.
     """
     user = UserFactory.create()
     self.client.login(**{'username': user.username, 'password': '******'})
     response = self.client.get(reverse('accounts:logout'), follow=True)
     self.assertRedirects(response, '{0}?next={1}'.format(reverse('accounts:login'), reverse('images:upload')))
     self.assertFalse(response.context['user'].is_authenticated())
Exemplo n.º 42
0
class AckReceiptOfTransmittalTests(TestCase):
    def setUp(self):
        self.trs = create_transmittal()
        self.category = self.trs.document.category
        self.user = UserFactory(
            email='*****@*****.**',
            password='******',
            is_superuser=True,
            category=self.category)
        self.client.login(email=self.user.email, password='******')
        self.url = reverse('transmittal_ack_of_receipt', args=[
            self.category.organisation.slug,
            self.category.slug,
            self.trs.document.document_key
        ])

    def test_non_contractor_acks_receipt(self):
        """Non contractor cannot ack receipt of transmittals."""
        res = self.client.post(self.url)
        self.assertEqual(res.status_code, 403)

    def test_acks_receipt(self):
        self.assertIsNone(self.trs.ack_of_receipt_date)
        self.assertIsNone(self.trs.ack_of_receipt_author)

        self.user.is_external = True
        self.user.save()
        res = self.client.post(self.url, follow=True)
        self.assertEqual(res.status_code, 200)

        self.trs.refresh_from_db()
        self.assertIsNotNone(self.trs.ack_of_receipt_date)
        self.assertEqual(self.trs.ack_of_receipt_author, self.user)

    def test_acks_receipt_twice_fails(self):
        self.user.is_external = True
        self.user.save()

        self.trs.ack_receipt(self.user)

        res = self.client.post(self.url, follow=True)
        self.assertEqual(res.status_code, 403)
Exemplo n.º 43
0
class AclTests(TestCase):

    def setUp(self):
        category = CategoryFactory()
        self.user = UserFactory(name='User', password='******', category=category)
        self.home_url = reverse('category_document_list', args=[
            category.organisation.slug,
            category.slug
        ])
        self.create_url = reverse('document_create', args=[
            category.organisation.slug,
            category.slug
        ])
        self.login_url = '/accounts/login/'
        self.dc_perms = Permission.objects.filter(codename__endswith='_document')

    def test_anonymous_access(self):
        res = self.client.get(self.home_url)
        self.assertRedirects(res, '%s?next=%s' % (self.login_url, self.home_url))

        res = self.client.get(self.create_url)
        self.assertRedirects(res, '%s?next=%s' % (self.login_url, self.create_url))

    def test_authenticated_user_access(self):
        self.client.login(username=self.user.email, password='******')

        res = self.client.get(self.home_url)
        self.assertEqual(res.status_code, 200)

        res = self.client.get(self.create_url)
        self.assertRedirects(res, '%s?next=%s' % (self.login_url, self.create_url))

    def test_document_controller_access(self):
        self.user.user_permissions = self.dc_perms
        self.user.save()
        self.client.login(username=self.user.email, password='******')

        res = self.client.get(self.home_url)
        self.assertEqual(res.status_code, 200)

        res = self.client.get(self.create_url)
        self.assertEqual(res.status_code, 200)
Exemplo n.º 44
0
    def setUp(self):

        HospitalFactory.create_batch(5)
        Hospital.objects.filter(id=1).update(is_kamc=True)

        SpecialtyFactory.create_batch(5)

        Department.objects.create(
            hospital=Hospital.objects.first(),
            specialty=Specialty.objects.first(),
            contact_name="",
            contact_position="",
            email="",
            phone="",
            extension="",
        )

        UserFactory.create_batch(10)

        super(ProtractorTests, self).setUp()
Exemplo n.º 45
0
    def setUp(self):
        self.site = get_current_site(self.client.request)
        self.site.config = SiteConfigFactory(site=self.site)

        self.reporting_user = UserFactory()
        self.accused_user = UserFactory()
        self.moderator = ModeratorFactory()
        factory.create_batch(
            ModeratorFactory,
            10,
            moderator=self.moderator,
        )
Exemplo n.º 46
0
 def setUp(self):
     category = CategoryFactory()
     self.user = UserFactory(name='User', password='******', category=category)
     self.url = reverse('category_document_list', args=[
         category.organisation.slug,
         category.slug
     ])
     self.dc_perms = Permission.objects.filter(codename__endswith='_document')
     self.create_url = reverse('document_create', args=[
         category.organisation.slug,
         category.slug
     ])
Exemplo n.º 47
0
 def test_can_login_and_redirect(self):
     """
     Tests a user can login and be redirected back to the homepage.
     """
     user = UserFactory.create()
     response = self.client.post(
         reverse('accounts:login'),
         data={'username': user.username, 'password': '******'},
         follow=True,
     )
     self.assertRedirects(response, reverse('images:upload'))
     self.assertTrue(response.context['user'].is_authenticated())
Exemplo n.º 48
0
 def test_current_event_price(self):
     """
     Current event price
     """
     event = EventFactory()
     users = UserFactory.create_batch(2)
     bet1 = BetFactory(event=event, user=users[0], outcome=Bet.YES)
     bet2 = BetFactory(event=event, user=users[1], outcome=Bet.NO)
     event.current_buy_for_price = 55
     event.current_buy_against_price = 45
     self.assertEqual(55, bet1.current_event_price())
     self.assertEqual(45, bet2.current_event_price())
Exemplo n.º 49
0
    def setUp(self):
        super().setUp()

        # Create a superuser
        self.password = '******'
        self.admin_user = UserFactory(password=self.password)
        self.admin_user.is_admin = True
        self.admin_user.save()

        # Create packages and doctypes for the new audit
        PackageFactory(name='TestPackage')
        DoctypeFactory(name='TestDoctype')
Exemplo n.º 50
0
class TransmittalActionTests(TestCase):

    def setUp(self):
        self.trs = create_transmittal()
        self.doc = self.trs.document
        self.category = self.doc.category
        self.url = reverse("document_detail", args=[
            self.category.organisation.slug,
            self.category.slug,
            self.doc.document_key
        ])
        self.user = UserFactory(
            name='User',
            password='******',
            is_superuser=True,
            category=self.category)
        self.client.login(username=self.user.email, password='******')

    def test_internal_user_cannot_ack_transmittal(self):
        self.assertIsNone(self.trs.ack_of_receipt_date)
        self.assertFalse(self.user.is_external)

        res = self.client.get(self.url)
        self.assertNotContains(res, ack_button)

    def test_external_user_can_ack_transmittal(self):
        self.user.is_external = True
        self.user.save()

        res = self.client.get(self.url)
        self.assertContains(res, ack_button)

    def test_transmittal_cannot_be_acked_twice(self):
        self.user.is_external = True
        self.trs.ack_receipt(self.user)

        self.assertIsNotNone(self.trs.ack_of_receipt_date)

        res = self.client.get(self.url)
        self.assertNotContains(res, ack_button)
Exemplo n.º 51
0
    def setUp(self):
        self.category = CategoryFactory()
        self.user = UserFactory(name='user', password='******', category=self.category)

        self.dc_perms = Permission.objects.filter(codename__endswith='_document')
        self.dc = UserFactory(name='dc', password='******', category=self.category)
        self.dc.user_permissions = self.dc_perms
        self.dc.save()

        self.url = reverse('user-list', args=[
            self.category.organisation.slug,
            self.category.category_template.slug,
        ])
Exemplo n.º 52
0
 def setUp(self):
     self.trs = create_transmittal()
     self.category = self.trs.document.category
     self.user = UserFactory(
         email='*****@*****.**',
         password='******',
         is_superuser=True,
         category=self.category)
     self.client.login(email=self.user.email, password='******')
     self.url = reverse('transmittal_batch_ack_of_receipt', args=[
         self.category.organisation.slug,
         self.category.slug,
     ])
Exemplo n.º 53
0
 def setUp(self):
     self.trs = create_transmittal()
     self.doc = self.trs.document
     self.category = self.doc.category
     self.url = reverse("document_detail", args=[
         self.category.organisation.slug,
         self.category.slug,
         self.doc.document_key
     ])
     self.user = UserFactory(
         name='User',
         password='******',
         is_superuser=True,
         category=self.category)
     self.client.login(username=self.user.email, password='******')
Exemplo n.º 54
0
 def setUp(self):
     self.category = CategoryFactory()
     self.user = UserFactory(
         email='*****@*****.**',
         password='******',
         is_superuser=True,
         category=self.category
     )
     self.url = reverse('feed_new_documents', args=[
         self.category.organisation.slug,
         self.category.slug,
     ])
     DocumentFactory(
         title='document 1',
         category=self.category,
     )
Exemplo n.º 55
0
    def setUp(self):
        self.site = get_current_site(self.client.request)
        self.site.config = SiteConfigFactory(site=self.site)

        self.standard_user = UserFactory()
        self.reporting_user = UserFactory()
        self.accused_user = UserFactory()
        self.moderator = ModeratorFactory()

        self.abuse_report = AbuseReportFactory(
            logged_against=self.accused_user,
            logged_by=self.reporting_user
        )
        self.abuse_warning = AbuseWarningFactory(
            logged_against=self.accused_user
        )
Exemplo n.º 56
0
 def setUp(self):
     self.category = CategoryFactory()
     self.user = UserFactory(
         name='User',
         password='******',
         is_superuser=True,
         category=self.category)
     self.client.login(username=self.user.email, password='******')
     self.doc = DocumentFactory(
         category=self.category,
         revision={
             'leader': self.user,
         }
     )
     self.url = reverse("document_detail", args=[
         self.category.organisation.slug,
         self.category.slug,
         self.doc.document_key
     ])
Exemplo n.º 57
0
    def test_finish_yes(self):
        """
        Finish event with outcome yes
        """
        users = UserFactory.create_batch(3)
        for u in users:
            u.portfolio_value = 1000
            u.total_cash = 2000
        event = EventFactory()
        bets = [BetFactory(event=event, user=user, has=3) for user in users[:2]]
        bets[1].outcome = Bet.NO
        bets[1].save()
        event.finish_yes()

        self.assertIsNotNone(event.end_date)
        self.assertEqual(Event.FINISHED_YES, event.outcome)

        event2 = EventFactory(outcome=Event.FINISHED_NO)
        with self.assertRaises(EventNotInProgress):
            event2.finish_yes()
Exemplo n.º 58
0
    def test_dc_cannot_see_users_from_other_categories(self):
        other_category = CategoryFactory()
        user1 = UserFactory(name='toto', password='******', category=other_category)
        user1.save()

        user2 = UserFactory(name='tata', password='******', category=self.category)
        user2.save()

        self.client.login(username=self.dc.email, password='******')

        res = self.client.get(self.url)
        self.assertEqual(res.status_code, 200)

        self.assertTrue('tata' in res.content)
        self.assertTrue('toto' not in res.content)