Пример #1
0
    def test_initiator_should_see_appropriate_credit_trades(self):
        """
        As a fuel supplier, I should see all credit trades where:
        I'm the initiator, regardless of status
        I'm the respondent, if the status is "submitted" or greater
        """

        # setup some test data
        DataCreationUtilities.create_possible_credit_trades(
            self.users['fs_user_1'].organization,
            self.users['fs_user_2'].organization)

        response = self.clients['fs_user_1'].get('/api/credit_trades')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        fs_credit_trades = response.json()
        for credit_trade in fs_credit_trades:
            correct_view = False

            if credit_trade['initiator']['id'] == \
               self.users['fs_user_1'].organization.id:
                correct_view = True
            elif (credit_trade['respondent']['id']
                  == self.users['fs_user_1'].organization.id
                  and credit_trade['status']['id'] >=
                  self.statuses['submitted'].id):
                correct_view = True

            self.assertTrue(correct_view)
Пример #2
0
    def test_delete(self):
        """
        Test that deleting compliance periods is not a semantically valid
        action
        """

        url = "/api/compliance_periods/{0!s}"

        all_users = self.users

        expected_results = defaultdict(
            lambda: {
                'status': [
                    status.HTTP_405_METHOD_NOT_ALLOWED, status.
                    HTTP_403_FORBIDDEN
                ],
                'reason':
                "Default response should be no access"
            })

        for user in all_users:
            with self.subTest(
                    user=user,
                    expected_statuses=expected_results[(user, )]['status'],
                    reason=expected_results[(user, )]['reason']):
                cp_that_exists = DataCreationUtilities.create_compliance_period(
                )
                response = self.clients[user].delete(
                    url.format(cp_that_exists['id']))
                logging.debug(response)
                self.assertIn(response.status_code,
                              expected_results[(user, )]['status'])
Пример #3
0
    def test_put_or_patch_to_other(self):
        """
        Test that put/patch on users is not a semantically valid action
        This will probably change in future versions
        """
        url = "/api/users/{0!s}"

        all_users = self.users

        expected_results = defaultdict(
            lambda: {
                'status': status.HTTP_403_FORBIDDEN,
                'reason': "Default response should be no access"
            })

        expected_results[('gov_admin', )] = ({
            'status':
            status.HTTP_200_OK,
            'reason':
            "Admin should have write access"
        })

        for index, user in enumerate(all_users):
            with self.subTest(
                    user=user,
                    expected_status=expected_results[(user, )]['status'],
                    reason=expected_results[(user, )]['reason']):
                user_that_exists = DataCreationUtilities.create_test_user()

                payload = {
                    'first_name': 'Test',
                    'last_name': 'Pilot',
                    'email': 'test_pilot_{0!s}@test.com'.format(index),
                    'phone': '5558675309',
                    'username': '******'.format(index),
                    'display_name': 'Canary',
                    'roles': (5, 6),
                    'is_active': True
                }

                response = self.clients[user].put(
                    url.format(user_that_exists['id']),
                    content_type='application/json',
                    data=json.dumps(payload))

                logging.debug(response)

                self.assertEqual(response.status_code,
                                 expected_results[(user, )]['status'], "PUT")

                payload = {'first_name': 'Defaced'}

                response = self.clients[user].patch(
                    url.format(user_that_exists['id']),
                    content_type='application/json',
                    data=json.dumps(payload))
                logging.debug(response)

                self.assertEqual(response.status_code,
                                 expected_results[(user, )]['status'], "PATCH")
Пример #4
0
    def test_get_by_username(self):
        """
        Test that getting another user directly is not a valid action
        unless you have an admin role
        """

        url = "/api/users/by_username?username={0!s}"

        all_users = self.users

        user_that_exists = DataCreationUtilities.create_test_user()

        expected_results = defaultdict(
            lambda: {
                'status': status.HTTP_403_FORBIDDEN,
                'reason': "Default response should be no access"
            })

        expected_results[('gov_admin', )] = {
            'status': status.HTTP_200_OK,
            'reason': 'Admin should have read access to users'
        }

        for user in all_users:
            with self.subTest(
                    user=user,
                    expected_status=expected_results[(user, )]['status'],
                    reason=expected_results[(user, )]['reason']):
                response = self.clients[user].get(
                    url.format(user_that_exists['username']))

                logging.debug(response.content.decode('utf-8'))

                self.assertEqual(response.status_code,
                                 expected_results[(user, )]['status'])
    def test_get_by_id(self):
        """Test that getting another user directly is not a valid action
         unless you have an admin role"""

        url = "/api/compliance_periods/{0!s}"

        all_users = self.users

        cp_that_exists = DataCreationUtilities.create_compliance_period()

        for user in all_users:
            with self.subTest(
                    user=user,
                    expected_status=status.HTTP_200_OK,
                    reason="Everyone should be able to read compliance periods"
            ):
                response = self.clients[user].get(
                    url.format(cp_that_exists['id']))
                logging.debug(response.content.decode('utf-8'))
                self.assertEqual(response.status_code, status.HTTP_200_OK)
Пример #6
0
    def test_link_document_to_credit_transaction(self):
        """
        Test updating a document status to submitted and attempt to
        modify the title (this should fail)
        """
        create_user = self.users['fs_user_1']
        compliance_period = CompliancePeriod.objects.first()
        status_received = DocumentStatus.objects.filter(status="Received").first()
        type_evidence = DocumentType.objects.filter(
            the_type="Evidence").first()

        created_document = Document.objects.create(
            create_user_id=create_user.id,
            compliance_period_id=compliance_period.id,
            status_id=status_received.id,
            title="Test Title",
            type_id=type_evidence.id
        )

        credit_trade = DataCreationUtilities.create_credit_trade(
            initiating_organization=self.users['fs_user_1'].organization,
            responding_organization=self.users['fs_user_2'].organization,
            status=CreditTradeStatus.objects.get_by_natural_key('Approved'),
            is_rescinded=False
        )

        payload = {
            'creditTrade': credit_trade['id']
        }

        # Link the credit transfer

        print('url: ' + "/api/documents/{}/link".format(created_document.id))

        response = self.clients['gov_analyst'].put(
            "/api/documents/{}/link".format(created_document.id),
            content_type='application/json',
            data=json.dumps(payload)
        )

        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)

        response = self.clients['gov_analyst'].get(
            "/api/documents/{}".format(created_document.id)
        )
        response_data = json.loads(response.content.decode("utf-8"))

        # Confirm link
        self.assertEqual(len(response_data['creditTrades']), 1)

        # Unlink it
        payload = {
            'creditTrade': credit_trade['id']
        }

        response = self.clients['gov_analyst'].put(
            "/api/documents/{}/unlink".format(created_document.id),
            content_type='application/json',
            data=json.dumps(payload)
        )

        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)

        # Confirm unlinked

        response = self.clients['gov_analyst'].get(
            "/api/documents/{}".format(created_document.id)
        )
        response_data = json.loads(response.content.decode("utf-8"))

        self.assertEqual(len(response_data['creditTrades']), 0)
    def test_put_or_patch(self):
        """
        Test that updating organizations is not a valid action
        unless you have an admin role
        """

        url = "/api/organizations/{0!s}"

        all_users = self.users

        expected_results = defaultdict(
            lambda: {
                'status': status.HTTP_403_FORBIDDEN,
                'reason': "Default response should be no access"
            })

        expected_results[('gov_admin', )] = {
            'status': status.HTTP_200_OK,
            'reason': 'Admin should have write access for orgs'
        }

        expected_results[('gov_analyst', )] = {
            'status': status.HTTP_200_OK,
            'reason': 'Analyst should have write access for orgs'
        }

        expected_results[('gov_director', )] = {
            'status': status.HTTP_200_OK,
            'reason': 'Director should have write access for orgs'
        }

        expected_results[('gov_manager', )] = {
            'status': status.HTTP_200_OK,
            'reason':
            'Gov Compliance Manager should have write access for orgs'
        }

        expected_results[('gov_multi_role', )] = {
            'status': status.HTTP_200_OK,
            'reason': 'Gov Multi-role should have write access for orgs'
        }

        for _index, user in enumerate(all_users):
            with self.subTest(
                    user=user,
                    expected_status=expected_results[(user, )]['status'],
                    reason=expected_results[(user, )]['reason']):
                org_that_exists = DataCreationUtilities.create_test_organization(
                )

                payload = {
                    'status':
                    OrganizationStatus.objects.get_by_natural_key('Active').id,
                    'type':
                    OrganizationType.objects.get_by_natural_key(
                        'Part3FuelSupplier').id,
                    'name':
                    'Updated org {}'.format(str(uuid.uuid4())),
                    'actions_type':
                    OrganizationActionsType.objects.get_by_natural_key(
                        'Buy And Sell').id,
                    'organization_address': {
                        'address_line_1': 'AL1'
                    }
                }

                response = self.clients[user].put(
                    url.format(org_that_exists['id']),
                    content_type='application/json',
                    data=json.dumps(payload))
                logging.debug(response)

                self.assertEqual(response.status_code,
                                 expected_results[(user, )]['status'], "PUT")

                payload = {
                    'name': 'Patched org {}'.format(str(uuid.uuid4())),
                }

                response = self.clients[user].patch(
                    url.format(org_that_exists['id']),
                    content_type='application/json',
                    data=json.dumps(payload))
                logging.debug(response)

                self.assertEqual(response.status_code,
                                 expected_results[(user, )]['status'], "PATCH")
Пример #8
0
    def test_put(self):
        """
        Test that updating compliance periods is not a valid action
         unless you have an appropriate role
        """
        url = "/api/compliance_periods/{0!s}"

        all_users = self.users

        expected_results = defaultdict(
            lambda: {
                'status': status.HTTP_403_FORBIDDEN,
                'reason': "Default response should be no access"
            })

        expected_results[('gov_admin', )] = {
            'status': status.HTTP_200_OK,
            'reason': 'Admin should have update access for compliance periods'
        }

        expected_results[('gov_director', )] = {
            'status':
            status.HTTP_200_OK,
            'reason':
            'Director should have update access for compliance '
            ' periods'
        }

        expected_results[('gov_multi_role', )] = {
            'status':
            status.HTTP_200_OK,
            'reason':
            'Multi Role should have update access for compliance '
            ' periods'
        }

        for _index, user in enumerate(all_users):
            with self.subTest(
                    user=user,
                    expected_status=expected_results[(user, )]['status'],
                    reason=expected_results[(user, )]['reason']):
                cp_that_exists = DataCreationUtilities.create_compliance_period(
                )

                payload = {
                    'description': 'Updated CP {0!s}'.format(uuid.uuid4()),
                    'display_order': 1
                }

                response = self.clients[user].put(
                    url.format(cp_that_exists['id']),
                    content_type='application/json',
                    data=json.dumps(payload))
                logging.debug(response)

                self.assertEqual(response.status_code,
                                 expected_results[(user, )]['status'], "PUT")

                payload = {
                    'description': 'Patched CP {0!s}'.format(uuid.uuid4())
                }

                response = self.clients[user].patch(
                    url.format(cp_that_exists['id']),
                    content_type='application/json',
                    data=json.dumps(payload))
                logging.debug(response)

                self.assertEqual(response.status_code,
                                 expected_results[(user, )]['status'], "PATCH")
    def test_signing_authority_confirmations(self):
        """Test permissions for signing authority confirmations """

        initiator = \
            self.users[self.user_map[TestSigningAuthorityConfirmations.UserRelationship.INITIATOR]]
        respondent = \
            self.users[self.user_map[TestSigningAuthorityConfirmations.UserRelationship.RESPONDENT]]

        trades = DataCreationUtilities.create_possible_credit_trades(
            initiator.organization,
            respondent.organization
        )

        expected_results = defaultdict(lambda: False)

        # key (relationship, status, rescinded?)

        expected_results[(
            TestSigningAuthorityConfirmations.UserRelationship.INITIATOR,
            self.statuses['draft'].status,
            False
        )] = True

        expected_results[(
            TestSigningAuthorityConfirmations.UserRelationship.INITIATOR,
            self.statuses['submitted'].status,
            False
        )] = True

        expected_results[(
            TestSigningAuthorityConfirmations.UserRelationship.RESPONDENT,
            self.statuses['accepted'].status,
            False
        )] = True

        expected_results[(
            TestSigningAuthorityConfirmations.UserRelationship.RESPONDENT,
            self.statuses['submitted'].status,
            False
        )] = True

        for (trade, relationship) in \
                product(trades, TestSigningAuthorityConfirmations.UserRelationship):

            # Sign an array of assertions, like the frontend does
            with self.subTest(
                "Testing signing confirmation permissions as array",
                relationship=relationship,
                status=trade['status'],
                rescinded=trade['rescinded']
            ):
                payload = list(map(lambda assertion, trade_id=trade['id']: {
                    'hasAccepted': True,
                    'signingAuthorityAssertion': assertion.id,
                    'creditTrade': trade_id
                }, SigningAuthorityAssertion.objects.all()))

                response = self.clients[self.user_map[relationship]].post(
                    '/api/signing_authority_confirmations',
                    content_type='application/json',
                    data=json.dumps(payload)
                )

                valid = status.is_success(response.status_code)

                self.assertEqual(
                    valid,
                    expected_results[(relationship, trade['status'], trade['rescinded'])]
                )

            # also try one at a time (not a JSON array)
            with self.subTest(
                "Testing signing confirmation permissions one at a time",
                relationship=relationship,
                status=trade['status'],
                rescinded=trade['rescinded']
            ):
                assertion_id = SigningAuthorityAssertion.objects.first().id

                payload = {
                    'hasAccepted': True,
                    'signingAuthorityAssertion': assertion_id,
                    'creditTrade': trade['id']
                }

                response = self.clients[self.user_map[relationship]].post(
                    '/api/signing_authority_confirmations',
                    content_type='application/json',
                    data=json.dumps(payload)
                )

                valid = status.is_success(response.status_code)

                self.assertEqual(
                    valid,
                    expected_results[(relationship, trade['status'], trade['rescinded'])]
                )