コード例 #1
0
ファイル: tests.py プロジェクト: majid-cj/django_tenant_react
class TodoTestAPI(APITestCase, DjangoReduxTestCases):
    def setUp(self):
        self.group = {
            'name': 'todo group',
        }
        self.data = {
            'group': None,
            'title': 'todo title',
            'body': 'todo object body',
            'is_done': False,
        }
        self.client = TenantClient(self.tenant)

    @patch.object(DjangoReduxJWTAuthentication, 'authenticate')
    def test_create_todo_api(self, mock):
        mock.return_value = self.account, {}
        response = self.client.post(reverse('todo:todo-group-list'),
                                    self.group)
        self.assertEquals(response.status_code, HTTP_201_CREATED)

        self.data['group'] = response.data['id']
        response = self.client.post(reverse('todo:todo-list'), self.data)
        self.assertEquals(response.status_code, HTTP_201_CREATED)

    @patch.object(DjangoReduxJWTAuthentication, 'authenticate')
    def test_update_todo_api(self, mock):
        mock.return_value = self.account, {}
        response = self.client.post(reverse('todo:todo-group-list'),
                                    self.group)
        self.assertEquals(response.status_code, HTTP_201_CREATED)

        self.data['group'] = response.data['id']
        response = self.client.post(reverse('todo:todo-list'), self.data)
        self.assertEquals(response.status_code, HTTP_201_CREATED)

        id = response.data['id']

        self.data['body'] = 'this is updated todo body'
        response = self.client.put(
            path=reverse('todo:todo-detail', kwargs={'pk': id}),
            data=json.dumps(self.data),
            content_type='application/json',
        )
        self.assertEquals(response.status_code, HTTP_200_OK)
        self.assertEquals(response.data['body'], 'this is updated todo body')
        self.assertFalse(response.data['is_done'])

        self.data['is_done'] = True
        response = self.client.put(
            path=reverse('todo:todo-detail', kwargs={'pk': id}),
            data=json.dumps(self.data),
            content_type='application/json',
        )
        self.assertEquals(response.status_code, HTTP_200_OK)
        self.assertTrue(response.data['is_done'])
class APISendResetPasswordEmailWithSchemaTestCase(APITestCase, TenantTestCase):
    """
    Console:
    python manage.py test shared_api.tests.test_send_reset_password_email_views
    """
    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(APISendResetPasswordEmailWithSchemaTestCase, self).setUp()
        self.c = TenantClient(self.tenant)
        call_command('init_app', verbosity=0)
        call_command('create_shared_account',
                     TEST_USER_EMAIL,
                     TEST_USER_PASSWORD,
                     "Bart",
                     "Mika",
                     verbosity=0)

    @transaction.atomic
    def tearDown(self):
        users = SharedUser.objects.all()
        for user in users.all():
            user.delete()
        del self.c
        super(APISendResetPasswordEmailWithSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_api_send_reset_password_email_with_success(self):
        url = reverse('workery_send_reset_password_email_api_endpoint')
        data = {
            'email_or_username': TEST_USER_EMAIL,
        }
        response = self.c.post(url,
                               json.dumps(data),
                               content_type='application/json')

        # Confirm.
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_api_send_reset_password_email_with_failure(self):
        url = reverse('workery_send_reset_password_email_api_endpoint')
        data = {
            'email_or_username': "******",
        }
        response = self.c.post(url,
                               json.dumps(data),
                               content_type='application/json')

        # Confirm.
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
コード例 #3
0
ファイル: tests.py プロジェクト: majid-cj/django_tenant_react
class TodoGroupTestAPI(APITestCase, DjangoReduxTestCases):
    def setUp(self):
        self.data = {
            'name': 'todo group',
        }
        self.client = TenantClient(self.tenant)

    @patch.object(DjangoReduxJWTAuthentication, 'authenticate')
    def test_create_todo_group_api(self, mock):
        mock.return_value = self.account, {}
        response = self.client.post(reverse('todo:todo-group-list'), self.data)
        self.assertEquals(response.status_code, HTTP_201_CREATED)

    @patch.object(DjangoReduxJWTAuthentication, 'authenticate')
    def test_get_todo_group_by_id_api(self, mock):
        mock.return_value = self.account, {}
        response = self.client.post(reverse('todo:todo-group-list'), self.data)
        self.assertEquals(response.status_code, HTTP_201_CREATED)

        id = response.data['id']
        response = self.client.get(
            reverse('todo:todo-group-detail', kwargs={'pk': id}))
        self.assertEquals(response.status_code, HTTP_200_OK)
        self.assertEquals(response.data['name'], self.data['name'])

    @patch.object(DjangoReduxJWTAuthentication, 'authenticate')
    def test_update_todo_group_api(self, mock):
        mock.return_value = self.account, {}
        response = self.client.post(reverse('todo:todo-group-list'), self.data)
        self.assertEquals(response.status_code, HTTP_201_CREATED)

        id = response.data['id']
        self.data['name'] = 'update todo group'
        response = self.client.put(path=reverse('todo:todo-group-detail',
                                                kwargs={'pk': id}),
                                   data=json.dumps(self.data),
                                   content_type='application/json')
        self.assertEquals(response.status_code, HTTP_200_OK)
        self.assertEquals(response.data['name'], 'update todo group')
コード例 #4
0
class APILogOutWithPublicSchemaTestCase(APITestCase, TenantTestCase):
    """
    Console:
    python manage.py test shared_api.tests.test_logout_views
    """
    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(APILogOutWithPublicSchemaTestCase, self).setUp()
        self.c = TenantClient(self.tenant)
        call_command('init_app', verbosity=0)
        call_command('create_shared_account',
                     TEST_USER_EMAIL,
                     TEST_USER_PASSWORD,
                     "Bart",
                     "Mika",
                     verbosity=0)

    @transaction.atomic
    def tearDown(self):
        users = SharedUser.objects.all()
        for user in users.all():
            user.delete()
        del self.c
        super(APILogOutWithPublicSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_api_logout(self):
        # Log in the the account.
        user = SharedUser.objects.get()
        token, orig_iat = get_jwt_token_and_orig_iat(user)

        # Log out.
        logout_url = reverse('workery_logout_api_endpoint')
        data = {
            'email_or_username': TEST_USER_EMAIL,
            'password': TEST_USER_PASSWORD,
        }
        response = self.c.post(logout_url,
                               json.dumps(data),
                               HTTP_AUTHORIZATION='JWT {0}'.format(token),
                               content_type='application/json')

        # Confirm.
        self.assertEqual(response.status_code, status.HTTP_200_OK)
コード例 #5
0
class APICityOptionWithTenantSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Tenant Schema"""
        tenant.schema_name = 'galacticallianceofhumankind'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_superuser = True
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APICityOptionWithTenantSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant,
                                              HTTP_AUTHORIZATION='Token ' +
                                              token.key)

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

    @transaction.atomic
    def tearDown(self):
        ProvinceOption.objects.delete_all()
        CityOption.objects.delete_all()
        PostalAddress.objects.delete_all()
        ContactPoint.objects.delete_all()
        Me.objects.delete_all()
        users = User.objects.all()
        for user in users.all():
            user.delete()
        # super(APICityOptionWithTenantSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_list(self):
        response = self.unauthorized_client.get('/api/tenantcityoption/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_list_with_authentication(self):
        response = self.authorized_client.get('/api/tenantcityoption/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_post(self):
        data = {
            'name': 'Unit Test',
        }
        response = self.unauthorized_client.post(
            '/api/tenantcityoption/',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_post_with_authentication(self):
        country = CountryOption.objects.create(
            id=1,
            name="Unit Test",
        )
        province = ProvinceOption.objects.create(
            id=1,
            name="Unit Test",
            country=country,
        )
        data = {
            'name': 'Unit Test',
            'country': country.id,
            'province': province.id
        }
        response = self.authorized_client.post('/api/tenantcityoption/',
                                               json.dumps(data),
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    @transaction.atomic
    def test_put(self):
        # Create a new object with our specific test data.
        country = CountryOption.objects.create(
            id=1,
            name="Unit Test",
        )
        province = ProvinceOption.objects.create(
            id=1,
            name="Unit Test",
            country=country,
        )
        city = CityOption.objects.create(
            id=1,
            name="Unit Test",
            country=country,
            province=province,
        )

        # Run the test.
        data = {
            'id': 1,
            'name': 'Unit Test',
            'country': country.id,
            'province': province.id,
            'city': city.id,
        }
        response = self.unauthorized_client.put(
            '/api/tenantcityoption/1/',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_put_with_authorization(self):
        # Create a new object with our specific test data.
        country = CountryOption.objects.create(
            id=1,
            name="Unit Test",
        )
        province = ProvinceOption.objects.create(
            id=1,
            name="Unit Test",
            country=country,
        )
        city = CityOption.objects.create(
            id=1,
            name="Unit Test",
            country=country,
            province=province,
        )

        # Run the test.
        data = {
            'id': 1,
            'name': 'Unit Test',
            'country': country.id,
            'province': province.id,
            'city': city.id,
        }
        response = self.authorized_client.put('/api/tenantcityoption/1/',
                                              json.dumps(data),
                                              content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete(self):
        response = self.unauthorized_client.delete('/api/tenantcityoption/1/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_authentication(self):
        country = CountryOption.objects.create(
            id=1,
            name="Unit Test",
        )
        province = ProvinceOption.objects.create(
            id=1,
            name="Unit Test",
            country=country,
        )
        city = CityOption.objects.create(
            id=1,
            name="Unit Test",
            country=country,
            province=province,
        )
        response = self.authorized_client.delete('/api/tenantcityoption/1/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
コード例 #6
0
class WorkspaceAPIWithTenantSchemaTestCase(APITestCase, FastTenantTestCase):
    fixtures = []

    @staticmethod
    def get_test_schema_name():
        return 'galacticalliance'

    def setup_tenant(self, tenant):
        """Tenant Schema"""
        tenant.schema_name = 'galacticalliance'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_active = True
        user.save()
        group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        user.groups.add(group)

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant,
                                              HTTP_AUTHORIZATION='Token ' +
                                              token.key)

        Workspace.objects.bulk_create([
            Workspace(owner=self.user),
            Workspace(owner=self.user),
            Workspace(owner=self.user),
        ])

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

    @transaction.atomic
    def tearDown(self):
        Workspace.objects.delete_all()
        PostalAddress.objects.delete_all()
        ContactPoint.objects.delete_all()
        Workspace.objects.delete_all()
        FileUpload.objects.delete_all()
        Me.objects.delete_all()
        users = User.objects.all()
        for user in users.all():
            user.delete()
        # super(WorkspaceAPIWithTenantSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_list(self):
        response = self.unauthorized_client.get('/api/tenantworkspace/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_authentication(self):
        response = self.authorized_client.get('/api/tenantworkspace/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_post_with_anonymous_user(self):
        data = {
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.unauthorized_client.post('/api/tenantworkspace/',
                                                 data,
                                                 format="json")
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_post_with_non_management_user(self):
        for group in self.user.groups.all():
            group.delete()

        data = {
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id,
            'type_of': constants.INFO_RESOURCE_INTERAL_URL_TYPE,
            'url': 'http://smegurus.com'
        }
        response = self.authorized_client.post('/api/tenantworkspace/',
                                               data,
                                               format="json")
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_post_with_authentication(self):
        # CASE 1 OF 5: SUCCESS
        data = {
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id,
            'type_of': constants.INFO_RESOURCE_INTERAL_URL_TYPE,
            'url': 'http://smegurus.com'
        }
        response = self.authorized_client.post('/api/tenantworkspace/',
                                               data,
                                               format="json")
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    @transaction.atomic
    def test_put(self):
        # Create a new object with our specific test data.
        Workspace.objects.create(id=999,
                                 name="Unit Test",
                                 description="Used for unit testing purposes.")

        # Run the test.
        data = {
            'id': 999,
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.unauthorized_client.put(
            '/api/tenantworkspace/999/',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_put_with_authorization(self):
        # Create a new object with our specific test data.
        Workspace.objects.create(id=666,
                                 name="Unit Test",
                                 description="Used for unit testing purposes.",
                                 owner_id=self.user.id)

        # Run the test.
        data = {
            'id': 666,
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.authorized_client.put('/api/tenantworkspace/666/',
                                              json.dumps(data),
                                              content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete(self):
        Workspace.objects.create(id=999,
                                 name="Unit Test",
                                 description="Used for unit testing purposes.")
        response = self.unauthorized_client.delete('/api/tenantworkspace/999/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_authentication(self):
        Workspace.objects.create(id=999,
                                 name="Unit Test",
                                 description="Used for unit testing purposes.")
        response = self.authorized_client.delete('/api/tenantworkspace/999/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
コード例 #7
0
class APIIntakeWithTenantSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Tenant Schema"""
        tenant.schema_name = 'galacticalliance'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks=True
        tenant.has_mentors=True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(id=constants.ENTREPRENEUR_GROUP_ID, name="Entreprenuer",),
            Group(id=constants.MENTOR_GROUP_ID, name="Mentor",),
            Group(id=constants.ADVISOR_GROUP_ID, name="Advisor",),
            Group(id=constants.ORGANIZATION_MANAGER_GROUP_ID, name="Org Manager",),
            Group(id=constants.ORGANIZATION_ADMIN_GROUP_ID, name="Org Admin",),
            Group(id=constants.CLIENT_MANAGER_GROUP_ID, name="Client Manager",),
            Group(id=constants.SYSTEM_ADMIN_GROUP_ID, name="System Admin",),
        ])
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        user.is_superuser = True
        user.is_active = True
        user.groups.add(org_admin_group)
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APIIntakeWithTenantSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant, HTTP_AUTHORIZATION='Token ' + token.key)
        self.authorized_client.login(
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        self.tenant.owner = self.user
        self.tenant.save()
        self.me = Me.objects.create(
            owner=self.user,
        )

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

    @transaction.atomic
    def tearDown(self):
        Intake.objects.delete_all()
        Note.objects.delete_all()
        PostalAddress.objects.delete_all()
        ContactPoint.objects.delete_all()
        Me.objects.delete_all()
        items = User.objects.all()
        for item in items.all():
            item.delete()
        items = Group.objects.all()
        for item in items.all():
            item.delete()
        # super(APIIntakeWithTenantSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_list_with_anonymous_user(self):
        response = self.unauthorized_client.get('/api/tenantintake/?format=json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_authenticated__user(self):
        # Change Group that the User belongs in.
        entrepreneur_group = Group.objects.get(id=constants.ENTREPRENEUR_GROUP_ID)
        self.user.groups.add(entrepreneur_group)
        self.user.save()

        # Test and verify.
        response = self.authorized_client.get('/api/tenantintake/?format=json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_list_with_authenticated_management_group_user(self):
        # Change Group that the User belongs in.
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        self.user.groups.remove(org_admin_group)
        self.user.save()

        # Test and verify.
        response = self.authorized_client.get('/api/tenantintake/?format=json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_list_with_authenticated_advisor_group_user(self):
        # Change Group that the User belongs in.
        advisor_group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.add(advisor_group)
        self.user.save()

        # Test and verify.
        response = self.authorized_client.get('/api/tenantintake/?format=json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_post_with_anonymous_user(self):
        data = {
            'me': self.me.id,
        }
        response = self.unauthorized_client.post('/api/tenantintake/?format=json', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_post_with_authenticated_management_group_user(self):
        # Run the test and verify.
        data = {
            'me': self.me.id,
        }
        response = self.authorized_client.post('/api/tenantintake/?format=json', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    @transaction.atomic
    def test_post_with_authenticated_advisor_group_user(self):
        # Change Group that the User belongs in.
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        advisor_group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.remove(org_admin_group)
        self.user.groups.add(advisor_group)
        self.user.save()

        # Test and verify.
        data = {
            'me': self.me.id,
        }
        response = self.authorized_client.post('/api/tenantintake/?format=json', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    @transaction.atomic
    def test_put_with_anonymous_user(self):
        # Create a new object with our specific test data.
        Intake.objects.create(
            id=1,
            me=self.me,
        )

        # Run the test.
        data = {
            'id': 1,
            'me': self.me.id,
        }
        response = self.unauthorized_client.put('/api/tenantintake/1/?format=json', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_put_with_authenticated_management_user(self):
        # Create a new object with our specific test data.
        Intake.objects.create(
            id=1,
            me=self.me,
        )

        # Run the test.
        data = {
            'id': 1,
            'me': self.me.id,
        }
        response = self.authorized_client.put('/api/tenantintake/1/?format=json', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_put_with_authenticated_advisor_user(self):
        # Change Group that the User belongs in.
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        advisor_group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.remove(org_admin_group)
        self.user.groups.add(advisor_group)
        self.user.save()

        # Create a new object with our specific test data.
        Intake.objects.create(
            id=1,
            me=self.me,
        )

        # Run the test.
        data = {
            'id': 1,
            'me': self.me.id,
        }
        response = self.authorized_client.put('/api/tenantintake/1/?format=json', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete_with_anonymous_user(self):
        Intake.objects.create(
            id=1,
            me=self.me,
        )
        response = self.unauthorized_client.delete('/api/tenantintake/1/?format=json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_authenticated_management_user(self):
        Intake.objects.create(
            id=1,
            me=self.me,
            judgement_note=Note.objects.create(
                id=1,
                me=self.me,
            ),
            privacy_note=Note.objects.create(
                id=2,
                me=self.me,
            ),
            terms_note=Note.objects.create(
                id=3,
                me=self.me,
            ),
            confidentiality_note=Note.objects.create(
                id=4,
                me=self.me,
            ),
            collection_note=Note.objects.create(
                id=5,
                me=self.me,
            ),
        )
        response = self.authorized_client.delete('/api/tenantintake/1/?format=json')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    @transaction.atomic
    def test_delete_with_authenticated_advisor_user(self):
        # Create our object to be deleted.

        Intake.objects.create(
            id=1,
            me=self.me,
            status=constants.CREATED_STATUS,
            judgement_note=Note.objects.create(
                id=1,
                me=self.me,
            ),
        )

        # Change Group that the User belongs in.
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        advisor_group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.remove(org_admin_group)
        self.user.groups.add(advisor_group)
        self.user.save()

        # Run test and verify.
        response = self.authorized_client.delete('/api/tenantintake/1/?format=json')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    @transaction.atomic
    def test_complete_intake_with_anonymous_user(self):
        # Setup our object.
        Intake.objects.create(
            id=1,
            me=self.me,
            status=constants.PENDING_REVIEW_STATUS,
            judgement_note=Note.objects.create(
                id=1,
                me=self.me,
            ),
        )

        # Run the test and verify.
        response = self.unauthorized_client.put(
            '/api/tenantintake/1/complete_intake/?format=json',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        me = Intake.objects.get(id=1)
        self.assertEqual(me.status, constants.PENDING_REVIEW_STATUS)
        self.assertEqual(len(mail.outbox), 0)  # Test that one message has not been sent.

    @transaction.atomic
    def test_complete_intake_with_owner_user(self):
        # Setup our object.
        Intake.objects.create(
            id=1,
            me=self.me,
            status=constants.CREATED_STATUS,
        )

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantintake/1/complete_intake/?format=json',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        me = Intake.objects.get(id=1)
        self.assertEqual(me.status, constants.PENDING_REVIEW_STATUS)

        # Test that one email has been sent.
        self.assertEqual(len(mail.outbox), 1)

        # Verify that the subject of the first message is correct.
        self.assertEqual(mail.outbox[0].subject, 'New Entrepreneur Application!')

    @transaction.atomic
    def test_complete_intake_with_different_owner_user(self):
        # Setup our objects.
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        new_user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password='******',
        )
        new_user.is_active = True
        new_user.groups.add(org_admin_group)
        new_user.save()
        new_me = Me.objects.create(
            owner=new_user
        )
        Intake.objects.create(
            id=1,
            me=new_me,
            status=constants.CREATED_STATUS,
        )

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantintake/1/complete_intake/?format=json',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        me = Intake.objects.get(id=1)
        self.assertEqual(me.status, constants.CREATED_STATUS)
        self.assertEqual(len(mail.outbox), 0)  # Test that one message has not been sent.

    @transaction.atomic
    def test_complete_intake_with_owner_user_with_404(self):
        # Setup our object.
        Intake.objects.create(
            id=1,
            me=self.me,
            status=constants.CREATED_STATUS,
        )

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantintake/6666/complete_intake/?format=json',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        me = Intake.objects.get(id=1)
        self.assertEqual(me.status, constants.CREATED_STATUS)
        self.assertEqual(len(mail.outbox), 0)  # Test that one message has not been sent.

    @transaction.atomic
    def test_judge_with_anonymous_user(self):
        # Create a new object with our specific test data.
        # Setup our object.
        Intake.objects.create(
            id=1,
            me=self.me,
            status=constants.CREATED_STATUS,
        )

        # Run the test.
        data = {
            'id': 1,
            'owner': self.user.id,
            'is_employee_created': False,
        }
        response = self.unauthorized_client.put(
            '/api/tenantintake/1/judge/?format=json',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        intake = Intake.objects.get(id=1)
        self.assertEqual(intake.status, constants.CREATED_STATUS)
        self.assertFalse(intake.me.is_in_intake)
        self.assertEqual(len(mail.outbox), 0)  # Test that one message has not been sent.

    @transaction.atomic
    def test_judge_with_employee_user_for_existing_intake_with_note(self):
        # Setup our object.
        Intake.objects.create(
            id=1,
            me=self.me,
            status=constants.CREATED_STATUS,
            judgement_note=Note.objects.create(
                me=self.me,
            ),
        )

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantintake/1/judge/?format=json',
            json.dumps({
                'status': constants.APPROVED_STATUS,
                'comment': 'This is a test comment.',
                'is_employee_created': False,
            }),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        intake = Intake.objects.get(id=1)
        self.assertEqual(intake.status, constants.APPROVED_STATUS)
        self.assertTrue(intake.me.is_in_intake)
        note = Note.objects.get(id=1)
        self.assertIn('This is a test comment.', note.description)
        self.assertEqual(len(mail.outbox), 1)  # Test that one message has been sent.
        self.assertIn('Accepted', mail.outbox[0].subject)

    @transaction.atomic
    def test_judge_with_employee_user_for_existing_intake_without_note(self):
        # Setup our object.
        Intake.objects.create(
            id=1,
            me=self.me,
            status=constants.CREATED_STATUS,
        )

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantintake/1/judge/?format=json',
            json.dumps({
                'status': constants.REJECTED_STATUS,
                'comment': 'This is a test comment.',
                'is_employee_created': False,
            }),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        intake = Intake.objects.get(id=1)
        self.assertEqual(intake.status, constants.REJECTED_STATUS)
        self.assertFalse(intake.me.is_in_intake)
        note = Note.objects.get(id=1)
        self.assertIn('This is a test comment.', note.description)
        self.assertEqual(len(mail.outbox), 1)  # Test that one message has been sent.
        self.assertIn('Rejected', mail.outbox[0].subject)

    @transaction.atomic
    def test_judge_with_employee_user_for_manually_created_intake(self):
        # Setup our object.
        Intake.objects.create(
            id=1,
            me=self.me,
            status=constants.CREATED_STATUS,
        )

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantintake/1/judge/?format=json',
            json.dumps({
                'status': constants.APPROVED_STATUS,
                'comment': 'This is a test comment.',
                'is_employee_created': True,
            }),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        intake = Intake.objects.get(id=1)
        self.assertEqual(intake.status, constants.APPROVED_STATUS)
        self.assertTrue(intake.me.is_in_intake)
        note = Note.objects.get(id=1)
        self.assertIn('This is a test comment.', note.description)
        self.assertEqual(len(mail.outbox), 1)  # Test that one message has been sent.

    @transaction.atomic
    def test_judge_with_non_employee_user(self):
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        self.user.groups.remove(org_admin_group)
        group = Group.objects.get(id=constants.ENTREPRENEUR_GROUP_ID)
        self.user.groups.add(group)
        Intake.objects.create(
            id=1,
            me=self.me,
            status=constants.CREATED_STATUS,
        )

        # Run the test.
        response = self.authorized_client.put(
            '/api/tenantintake/1/judge/?format=json',
            json.dumps({
                'status': constants.APPROVED_STATUS,
                'comment': 'This is a test comment.',
                'is_employee_created': False,
            }),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        intake = Intake.objects.get(id=1)
        self.assertEqual(intake.status, constants.CREATED_STATUS)
        self.assertFalse(intake.me.is_in_intake)
        self.assertEqual(len(mail.outbox), 0)  # Test that one message has not been sent.

    @transaction.atomic
    def test_judge_with_owner_user_with_404(self):
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        self.user.groups.remove(org_admin_group)
        group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.add(group)

        response = self.authorized_client.put(
            '/api/tenantintake/666/judge/?format=json',
            json.dumps({
                'status': constants.APPROVED_STATUS,
                'comment': 'This is a test comment.',
                'is_employee_created': False,
            }),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertIn(b'No Intake matches the given query.', response.content)
        self.assertEqual(len(mail.outbox), 0)  # Test that one message has not been sent.

    @transaction.atomic
    def test_crm_update_with_anonymous_user(self):
        # Setup our object.
        Intake.objects.create(
            id=1,
            me=self.me,
            status=constants.PENDING_REVIEW_STATUS,
            has_signed_with_name="Ledo"
        )

        # Run the test and verify.
        response = self.unauthorized_client.put(
            '/api/tenantintake/1/crm_update/?format=json',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_crm_update_with_owner_user(self):
        # Setup our object.
        Intake.objects.create(
            id=1,
            me=self.me,
            status=constants.CREATED_STATUS,
            has_signed_with_name="Ledo"
        )

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantintake/1/crm_update/?format=json',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_crm_update_with_different_owner_user(self):
        # Setup our objects.
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        new_user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password='******',
        )
        new_user.is_active = True
        new_user.groups.add(org_admin_group)
        new_user.save()
        new_me = Me.objects.create(
            owner=new_user
        )
        Intake.objects.create(
            id=1,
            me=new_me,
            status=constants.CREATED_STATUS,
            has_signed_with_name="Ledo"
        )

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantintake/1/crm_update/?format=json',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_crm_update_with_owner_user_with_404(self):
        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantintake/6666/crm_update/?format=json',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
コード例 #8
0
class APILoginWithPublicSchemaTestCase(APITestCase, TenantTestCase):
    """
    Console:
    python manage.py test shared_api.tests.views.test_login_views
    """
    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English

        self.c = TenantClient(self.tenant)
        call_command('init_app', verbosity=0)
        # Create the account.
        call_command(
            'create_tenant_account',
            TEST_SCHEMA_NAME,
            constants.MANAGEMENT_GROUP_ID,
            TEST_USER_EMAIL,
            TEST_USER_PASSWORD,
            "Bart",
            "Mika",
            TEST_USER_TEL_NUM,
            TEST_USER_TEL_EX_NUM,
            TEST_USER_CELL_NUM,
            "CA",
            "London",
            "Ontario",
            "",  # Post Offic #
            "N6H 1B4",
            "78 Riverside Drive",
            "",  # Extra line.
            verbosity=0)
        super(APILoginWithPublicSchemaTestCase, self).setUp()

    @transaction.atomic
    def tearDown(self):
        # SharedUser.objects.delete_all() # Is this an error?
        del self.c
        super(APILoginWithPublicSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_api_login_with_success(self):
        url = reverse('workery_login_api_endpoint')
        data = {
            'email_or_username': TEST_USER_USERNAME,
            'password': TEST_USER_PASSWORD,
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data['token']) > 0, True)
        self.assertEqual(len(response.data['schema_name']) > 0, True)

    @transaction.atomic
    def test_api_login_with_nonexisting_account(self):
        url = reverse('workery_login_api_endpoint')
        data = {
            'email_or_username': '******',
            'password': '******',
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_api_login_with_inactive_account(self):
        # Get our current user and set the user to be inactive.
        client = SharedUser.objects.get()
        client.is_active = False
        client.save()

        # Run this test.
        url = reverse('workery_login_api_endpoint')
        data = {
            'email_or_username': TEST_USER_USERNAME,
            'password': TEST_USER_PASSWORD,
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_api_login_with_bad_password(self):
        # Get our current user and set the user to be inactive.
        client = SharedUser.objects.get()
        client.save()

        # Run this test.
        url = reverse('workery_login_api_endpoint')
        data = {
            'email_or_username': TEST_USER_USERNAME,
            'password': "******",
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
コード例 #9
0
class APIActivationTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Public Schema"""
        tenant.schema_name = 'test'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks=True
        tenant.has_mentors=True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(id=constants.ENTREPRENEUR_GROUP_ID, name="Entreprenuer",),
            Group(id=constants.MENTOR_GROUP_ID, name="Mentor",),
            Group(id=constants.ADVISOR_GROUP_ID, name="Advisor",),
            Group(id=constants.ORGANIZATION_MANAGER_GROUP_ID, name="Org Manager",),
            Group(id=constants.ORGANIZATION_ADMIN_GROUP_ID, name="Org Admin",),
            Group(id=constants.CLIENT_MANAGER_GROUP_ID, name="Client Manager",),
            Group(id=constants.SYSTEM_ADMIN_GROUP_ID, name="System Admin",),
        ])
        user = User.objects.create_user(  # Create our User.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(APIActivationTestCase, self).setUp()
        self.c = TenantClient(self.tenant)

    @transaction.atomic
    def tearDown(self):
        users = User.objects.all()
        for user in users.all():
            user.delete()
        # super(APIActivationTestCase, self).tearDown()

    @transaction.atomic
    def test_api_activation_with_authentication_success(self):
        user = User.objects.get()
        self.assertIsNotNone(user)
        user.is_active = False
        user.save()
        token = Token.objects.get(user_id=user.id)

        # Activate the user.
        url = reverse('api_activate')
        data = {
            'uid': user.id,
            'token': str(token),
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_api_activation_with_stale_token(self):
        user = User.objects.get()
        self.assertIsNotNone(user)
        token = Token.objects.get(user_id=user.id)

        # Activate the user to generate a "Stale Token" error.
        url = reverse('api_activate')
        data = {
            'uid': user.id,
            'token': str(token),
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_api_activation_with_invalid_uid(self):
        # Activate the user to generate a "Stale Token" error.
        url = reverse('api_activate')
        data = {
            'uid': 666,
            'token': '',
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_api_activation_with_invalid_token_1(self):
        # Get the user.
        user = User.objects.get()

        # Activate the user to generate a "Stale Token" error.
        url = reverse('api_activate')
        data = {
            'uid': user.id,
            'token': '666',
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_api_activation_with_invalid_token_2(self):
        user = User.objects.get()
        user.is_active = False
        user.save()
        token = Token.objects.get(user_id=user.id)

        # Activate the user.
        url = reverse('api_activate')
        data = {
            'uid': user.id,
            'token': str(token),
        }

        # Important: By deleting the token, we are will testing to see
        #            how the system will re-act.
        token.delete()
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
コード例 #10
0
class APIBrandWithTenantSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Tenant Schema"""
        tenant.schema_name = 'galacticalliance'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APIBrandWithTenantSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant,
                                              HTTP_AUTHORIZATION='Token ' +
                                              token.key)

        Brand.objects.bulk_create([
            Brand(owner=self.user),
            Brand(owner=self.user),
            Brand(owner=self.user),
        ])

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

    @transaction.atomic
    def tearDown(self):
        Brand.objects.delete_all()
        PostalAddress.objects.delete_all()
        ContactPoint.objects.delete_all()
        Me.objects.delete_all()
        users = User.objects.all()
        for user in users.all():
            user.delete()
        # super(APIBrandWithTenantSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_to_string(self):
        # Create a new object with our specific test data.
        brand = Brand.objects.create(
            id=2030,
            name="Unit Test",
            description="Used for unit testing purposes.")
        brand.save()
        self.assertEqual(str(brand), "Unit Test")

    @transaction.atomic
    def test_list(self):
        response = self.unauthorized_client.get('/api/tenantbrand/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_authentication(self):
        response = self.authorized_client.get('/api/tenantbrand/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_post(self):
        data = {
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.unauthorized_client.post('/api/tenantbrand/',
                                                 data,
                                                 format="json")
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_post_with_authentication(self):
        data = {
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.authorized_client.post('/api/tenantbrand/',
                                               data,
                                               format="json")
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    @transaction.atomic
    def test_put(self):
        # Delete any previous data.
        brands = Brand.objects.all()
        for brand in brands.all():
            brand.delete()

        # Create a new object with our specific test data.
        Brand.objects.create(id=1,
                             name="Unit Test",
                             description="Used for unit testing purposes.")

        # Run the test.
        data = {
            'id': 1,
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.unauthorized_client.put(
            '/api/tenantbrand/1/',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_put_with_authorization(self):
        # Delete any previous data.
        brands = Brand.objects.all()
        for brand in brands.all():
            brand.delete()

        # Create a new object with our specific test data.
        Brand.objects.create(id=1,
                             name="Unit Test",
                             description="Used for unit testing purposes.",
                             owner_id=self.user.id)

        # Run the test.
        data = {
            'id': 1,
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.authorized_client.put('/api/tenantbrand/1/',
                                              json.dumps(data),
                                              content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete(self):
        response = self.unauthorized_client.delete('/api/tenantbrand/1/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_authentication(self):
        response = self.authorized_client.delete('/api/tenantbrand/1/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
コード例 #11
0
class APIRegistrationWithPublicSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Public Schema"""
        tenant.schema_name = 'test'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks=True
        tenant.has_mentors=True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(id=constants.ENTREPRENEUR_GROUP_ID, name="Entreprenuer",),
            Group(id=constants.MENTOR_GROUP_ID, name="Mentor",),
            Group(id=constants.ADVISOR_GROUP_ID, name="Advisor",),
            Group(id=constants.ORGANIZATION_MANAGER_GROUP_ID, name="Org Manager",),
            Group(id=constants.ORGANIZATION_ADMIN_GROUP_ID, name="Org Admin",),
            Group(id=constants.CLIENT_MANAGER_GROUP_ID, name="Client Manager",),
            Group(id=constants.SYSTEM_ADMIN_GROUP_ID, name="System Admin",),
        ])

        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(APIRegistrationWithPublicSchemaTestCase, self).setUp()
        self.c = TenantClient(self.tenant)

    @transaction.atomic
    def tearDown(self):
        users = User.objects.all()
        for user in users.all():
            user.delete()
        groups = Group.objects.all()
        for group in groups.all():
            group.delete()
        super(APIRegistrationWithPublicSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_api_registration_with_success_for_org_admin(self):
        # Remove the existing user(s) before continuing.
        self.assertEqual(User.objects.count(), 1)
        for user in User.objects.all():
            user.delete()
        self.assertEqual(User.objects.count(), 0)

        # Perform the Unit-Tests
        url = reverse('api_register')
        data = {
            'username': '******',
            'email': '*****@*****.**',
            'password': TEST_USER_PASSWORD,
            'first_name': 'Transhumanist',
            'last_name': '#1'
        }
        response = self.c.post(url, data, format='json')

        # Verify general info.
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(User.objects.count(), 1)
        self.assertEqual(User.objects.get().email, '*****@*****.**')
        group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)

        # Verify group membership.
        is_org_admin = False
        for a_group in User.objects.get().groups.all():
            if a_group == group:
                is_org_admin = True
        self.assertEqual(is_org_admin, True)

        # Test that one message has been sent.
        self.assertEqual(len(mail.outbox), 1)

        # Verify that the subject of the first message is correct.
        self.assertEqual(mail.outbox[0].subject, 'Account Activation - SME Gurus for your Organization')

    @transaction.atomic
    def test_api_registration_with_failure(self):
        self.assertEqual(User.objects.count(), 1)
        url = reverse('api_register')
        data = {
            'username': TEST_USER_USERNAME,
            'email': TEST_USER_EMAIL,
            'password': TEST_USER_PASSWORD,
            'first_name': 'Ledo',
            'last_name': 'Clone #123'
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(User.objects.count(), 1)
        self.assertEqual(User.objects.get().email, TEST_USER_EMAIL)
        self.assertEqual(len(mail.outbox), 0)

    @transaction.atomic
    def test_api_registration_with_banned_domain(self):
        # Create our Banned Domain
        BannedDomain.objects.create(
            name='hideauze.com',
            reason='They are enemies of humankind!',
        )

        # Remove the existing user(s) before continuing.
        self.assertEqual(User.objects.count(), 1)
        for user in User.objects.all():
            user.delete()
        self.assertEqual(User.objects.count(), 0)

        # Perform the Unit-Tests
        url = reverse('api_register')
        data = {
            'username': '******',
            'email': '*****@*****.**',
            'password': TEST_USER_PASSWORD,
            'first_name': 'Transhumanist',
            'last_name': '#1'
        }
        response = self.c.post(url, data, format='json')

        # Verify general info.
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(User.objects.count(), 0)
        self.assertEqual(len(mail.outbox), 0)
コード例 #12
0
class SharedFranchiseListAPIViewWithPublicSchemaTestCase(
        TenantTestCase, TransactionTestCase):
    """
    Console:
    python manage.py test shared_api.tests.views.test_franchise_list_views
    """
    def setUp(self):
        translation.activate('en')  # Set English
        SharedUser.objects.delete_all()
        super(SharedFranchiseListAPIViewWithPublicSchemaTestCase, self).setUp()
        self.anon_client = TenantClient(self.tenant)
        call_command('init_app', verbosity=0)

        # Update the tenant.
        self.tenant.name = 'Over 55 (London) Inc.',
        self.tenant.alternate_name = "Over55",
        self.tenant.description = "Located at the Forks of the Thames in ...",
        self.tenant.address_country = "CA",
        self.tenant.address_locality = "London",
        self.tenant.address_region = "Ontario",
        self.tenant.post_office_box_number = "",  # Post Offic #
        self.tenant.postal_code = "N6H 1B4",
        self.tenant.street_address = "78 Riverside Drive",
        self.tenant.street_address_extra = "",  # Extra line.
        self.tenant.save()

        # Create our test user.
        call_command('create_shared_account',
                     TEST_USER_EMAIL,
                     TEST_USER_PASSWORD,
                     "Bart",
                     "Mika",
                     verbosity=0)

        # Initialize our test data.
        self.user = SharedUser.objects.get(email=TEST_USER_EMAIL)
        token, orig_iat = get_jwt_token_and_orig_iat(self.user)

        self.authorized_client = TenantClient(
            self.tenant, HTTP_AUTHORIZATION='JWT {0}'.format(token))
        self.authorized_client.login(username=TEST_USER_USERNAME,
                                     password=TEST_USER_PASSWORD)

    def tearDown(self):
        SharedUser.objects.delete_all()
        del self.anon_client
        del self.authorized_client
        super(SharedFranchiseListAPIViewWithPublicSchemaTestCase,
              self).tearDown()

    def test_anonymous_get_with_200(self):
        url = reverse('workery_franchise_list_create_api_endpoint')
        response = self.anon_client.get(url,
                                        data=None,
                                        content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("London", str(response.data))
        self.assertIn("Ontario", str(response.data))

    def test_anonymous_search_get_with_200_(self):
        url = reverse('workery_franchise_list_create_api_endpoint'
                      ) + "?format=json&search=London"
        response = self.anon_client.get(url,
                                        data=None,
                                        content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("London", str(response.data))
        self.assertIn("Ontario", str(response.data))

    def test_anonymous_post(self):
        url = reverse('workery_franchise_list_create_api_endpoint')
        post_data = json.dumps({
            "schema_name": "mikasoftware",
            "postal_code": "n6j4x4",
            "name": "Mika Software Corporation",
            "alternate_name": "Mika Software",
            "description": "An open source software company.",
            "url": "https://mikasoftware.com",
            "timezone_name": "America/Toronto",
            "address_country": "Canada",
            "address_locality": "London",
            "address_region": "Ontario",
            "postal_code": "N6J4X4",
            "street_address": "120 Centre Street",
            "street_address_extra": "Unit 102"
        })
        response = self.anon_client.post(url,
                                         data=post_data,
                                         content_type='application/json')
        get_worker().work(
            burst=True
        )  # Processes all BACKGROUND jobs in FOREGROUND then stop. (Note: https://stackoverflow.com/a/12273705)
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
コード例 #13
0
class APINoteWithTenantSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Tenant Schema"""
        tenant.schema_name = 'galacticalliance'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks=True
        tenant.has_mentors=True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(id=constants.ENTREPRENEUR_GROUP_ID, name="Entreprenuer",),
            Group(id=constants.MENTOR_GROUP_ID, name="Mentor",),
            Group(id=constants.ADVISOR_GROUP_ID, name="Advisor",),
            Group(id=constants.ORGANIZATION_MANAGER_GROUP_ID, name="Org Manager",),
            Group(id=constants.ORGANIZATION_ADMIN_GROUP_ID, name="Org Admin",),
            Group(id=constants.CLIENT_MANAGER_GROUP_ID, name="Client Manager",),
            Group(id=constants.SYSTEM_ADMIN_GROUP_ID, name="System Admin",),
        ])
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD,
            first_name=TEST_USER_FIRSTNAME,
            last_name=TEST_USER_LASTNAME,
        )
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APINoteWithTenantSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant, HTTP_AUTHORIZATION='Token ' + token.key)
        self.authorized_client.login(
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        self.tenant.owner = self.user
        self.tenant.save()

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

    @transaction.atomic
    def tearDown(self):
        Note.objects.delete_all()
        PostalAddress.objects.delete_all()
        ContactPoint.objects.delete_all()
        Me.objects.delete_all()
        users = User.objects.all()
        for user in users.all():
            user.delete()
        groups = Group.objects.all()
        for group in groups.all():
            group.delete()
        # super(APINoteWithTenantSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_list_with_anonymous_user(self):
        response = self.unauthorized_client.get('/api/tenantnote/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_authenticated_management_group_user(self):
        group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        self.user.groups.add(group)

        response = self.authorized_client.get('/api/tenantnote/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_list_with_authenticated_advisor_group_user(self):
        group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.add(group)

        response = self.authorized_client.get('/api/tenantnote/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_list_with_authenticated_entrepreneur_group_user(self):
        group = Group.objects.get(id=constants.ENTREPRENEUR_GROUP_ID)
        self.user.groups.add(group)

        response = self.authorized_client.get('/api/tenantnote/')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_post_with_anonymous_user(self):
        data = {
            'name': 'Test Note',
            'description': 'This is a test note',
        }
        response = self.unauthorized_client.post(
            '/api/tenantnote/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_post_with_authenticated_management_group_user(self):
        me = Me.objects.create(
            id=1,
            owner=self.user,
        )
        group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        self.user.groups.add(group)
        data = {
            'name': 'Test Note',
            'description': 'This is a test note',
            'me': me.id,
        }
        response = self.authorized_client.post(
            '/api/tenantnote/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    @transaction.atomic
    def test_post_with_authenticated_advisor_group_user(self):
        me = Me.objects.create(
            id=1,
            owner=self.user,
        )
        group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.add(group)
        data = {
            'name': 'Test Note',
            'description': 'This is a test note',
            'me': me.id,
        }
        response = self.authorized_client.post(
            '/api/tenantnote/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    @transaction.atomic
    def test_post_with_authenticated_entrepreneur_group_user(self):
        me = Me.objects.create(
            id=1,
            owner=self.user,
        )
        group = Group.objects.get(id=constants.ENTREPRENEUR_GROUP_ID)
        self.user.groups.add(group)
        data = {
            'name': 'Test Note',
            'description': 'This is a test note',
            'me': me.id,
        }
        response = self.authorized_client.post(
            '/api/tenantnote/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_put_with_anonymous_user(self):
        Note.objects.create(
            id=1,
            name='Test Note',
            description='This is a test note',
            me = Me.objects.create(
                id=1,
                owner=self.user,
            ),
        )

        data = {
            'id': 1,
            'name': 'Test Note',
            'description': 'This is a test note',
            'me': 1,
        }
        response = self.unauthorized_client.put(
            '/api/tenantnote/1/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_put_with_authenticated_management_group_user(self):
        group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        self.user.groups.add(group)
        Note.objects.create(
            id=1,
            name='Test Note',
            description='This is a test note',
            me = Me.objects.create(
                id=1,
                owner=self.user,
            ),
        )

        data = {
            'id': 1,
            'name': 'Test Note',
            'description': 'This is a test note',
            'me': 1,
        }
        response = self.authorized_client.put(
            '/api/tenantnote/1/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_put_with_authenticated_advisor_group_user(self):
        group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.add(group)
        Note.objects.create(
            id=1,
            name='Test Note',
            description='This is a test note',
            me = Me.objects.create(
                id=1,
                owner=self.user,
            ),
        )

        data = {
            'id': 1,
            'name': 'Test Note',
            'description': 'This is a test note',
            'me': 1,
        }
        response = self.authorized_client.put(
            '/api/tenantnote/1/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_put_with_authenticated_entrepreneur_group_user(self):
        group = Group.objects.get(id=constants.ENTREPRENEUR_GROUP_ID)
        self.user.groups.add(group)
        Note.objects.create(
            id=1,
            name='Test Note',
            description='This is a test note',
            me = Me.objects.create(
                id=1,
                owner=self.user,
            ),
        )

        data = {
            'id': 1,
            'name': 'Test Note',
            'description': 'This is a test note',
            'me': 1,
        }
        response = self.authorized_client.put(
            '/api/tenantnote/1/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_delete_with_anonymous_user(self):
        response = self.unauthorized_client.delete('/api/tenantnote/1/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_authenticated_management_user(self):
        group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        self.user.groups.add(group)
        Note.objects.create(
            id=1,
            name='Test Note',
            description='This is a test note',
            me = Me.objects.create(
                id=1,
                owner=self.user,
            ),
        )

        response = self.authorized_client.delete('/api/tenantnote/1/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    @transaction.atomic
    def test_delete_with_authenticated_advisor_user(self):
        group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.add(group)
        Note.objects.create(
            id=1,
            name='Test Note',
            description='This is a test note',
            me = Me.objects.create(
                id=1,
                owner=self.user,
            ),
        )

        response = self.authorized_client.delete('/api/tenantnote/1/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    @transaction.atomic
    def test_delete_with_authenticated_entrepreneur_user(self):
        group = Group.objects.get(id=constants.ENTREPRENEUR_GROUP_ID)
        self.user.groups.add(group)

        Note.objects.create(
            id=1,
            name='Test Note',
            description='This is a test note',
            me = Me.objects.create(
                id=1,
                owner=self.user,
            ),
        )

        response = self.authorized_client.delete('/api/tenantnote/1/')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
コード例 #14
0
class APIPostalAdressWithTenantSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Tenant Schema"""
        tenant.schema_name = 'galacticalliance'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APIPostalAdressWithTenantSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant,
                                              HTTP_AUTHORIZATION='Token ' +
                                              token.key)

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

    @transaction.atomic
    def tearDown(self):
        CountryOption.objects.delete_all()
        ProvinceOption.objects.delete_all()
        CityOption.objects.delete_all()
        PostalAddress.objects.delete_all()
        users = User.objects.all()
        for user in users.all():
            user.delete()
        # super(APIPostalAdressWithTenantSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_list(self):
        response = self.unauthorized_client.get('/api/tenantpostaladdress/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_authentication(self):
        response = self.authorized_client.get('/api/tenantpostaladdress/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_post(self):
        country = CountryOption.objects.create(id=1, name="Avalon")
        province = ProvinceOption.objects.create(id=1,
                                                 country=country,
                                                 name="Colony Ship #124")
        city = CityOption.objects.create(id=1,
                                         country=country,
                                         province=province,
                                         name="District 9")
        data = {
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id,
            'country': country.id,
            'region': province.id,
            'locality': city.name
        }
        response = self.unauthorized_client.post(
            '/api/tenantpostaladdress/',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_post_with_authentication(self):
        country = CountryOption.objects.create(id=1, name="Avalon")
        province = ProvinceOption.objects.create(id=1,
                                                 country=country,
                                                 name="Colony Ship #124")
        city = CityOption.objects.create(id=1,
                                         country=country,
                                         province=province,
                                         name="District 9")
        data = {
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id,
            'country': country.id,
            'region': province.id,
            'locality': city.name
        }
        response = self.authorized_client.post('/api/tenantpostaladdress/',
                                               json.dumps(data),
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    @transaction.atomic
    def test_put(self):
        country = CountryOption.objects.create(id=1, name="Avalon")
        province = ProvinceOption.objects.create(id=1,
                                                 country=country,
                                                 name="Sector 666")
        city = CityOption.objects.create(id=1,
                                         country=country,
                                         province=province,
                                         name="District 9")
        PostalAddress.objects.create(
            id=1,
            name="Unit Test",
            description="Used for unit testing purposes.",
            owner=self.user,
            country=country,
            region=province,
            locality=city.name,
        )

        data = {
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id,
            'country': country.id,
            'region': province.id,
            'locality': city.name
        }
        response = self.unauthorized_client.put(
            '/api/tenantpostaladdress/1/',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_put_with_authorization(self):
        country = CountryOption.objects.create(id=1, name="Avalon")
        province = ProvinceOption.objects.create(id=1,
                                                 country=country,
                                                 name="Sector 666")
        city = CityOption.objects.create(id=1,
                                         country=country,
                                         province=province,
                                         name="District 9")
        PostalAddress.objects.create(
            id=1,
            name="Unit Test",
            description="Used for unit testing purposes.",
            owner=self.user,
            country=country,
            region=province,
            locality=city.name,
        )
        data = {
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id,
            'country': country.id,
            'region': province.id,
            'locality': city.name
        }
        response = self.authorized_client.put('/api/tenantpostaladdress/1/',
                                              json.dumps(data),
                                              content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete(self):
        country = CountryOption.objects.create(id=1, name="Avalon")
        province = ProvinceOption.objects.create(id=1,
                                                 country=country,
                                                 name="Sector 666")
        city = CityOption.objects.create(id=1,
                                         country=country,
                                         province=province,
                                         name="District 9")
        PostalAddress.objects.create(
            id=1,
            name="Unit Test",
            description="Used for unit testing purposes.",
            owner=self.user,
            country=country,
            region=province,
            locality=city.name,
        )
        response = self.unauthorized_client.delete(
            '/api/tenantpostaladdress/1/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_authentication(self):
        country = CountryOption.objects.create(id=1, name="Avalon")
        province = ProvinceOption.objects.create(id=1,
                                                 country=country,
                                                 name="Sector 666")
        city = CityOption.objects.create(id=1,
                                         country=country,
                                         province=province,
                                         name="District 9")
        PostalAddress.objects.create(
            id=1,
            name="Unit Test",
            description="Used for unit testing purposes.",
            owner=self.user,
            country=country,
            region=province,
            locality=city.name,
        )
        response = self.authorized_client.delete('/api/tenantpostaladdress/1/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    @transaction.atomic
    def test_rebuild_geo_data_with_anonymous_user(self):
        # Create a new object with our specific test data.
        country = CountryOption.objects.create(
            id=1,
            name='Ontario',
        )
        region = ProvinceOption.objects.create(id=1,
                                               name='Canada',
                                               country=country)
        PostalAddress.objects.create(
            id=1,
            name='Test Address',
            owner=self.user,
            street_number='120',
            street_name='Centre Street',
            suite_number='102',
            postal_code='N6J4X4',
            locality='London',
            region=region,
            country=country,
        )

        # Run the test.
        response = self.unauthorized_client.put(
            '/api/tenantpostaladdress/1/rebuild_geo_data/?format=json',
            json.dumps({}),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_rebuild_geo_data_with_authenticated_user(self):
        # Create a new object with our specific test data.
        country = CountryOption.objects.create(
            id=1,
            name='Ontario',
        )
        region = ProvinceOption.objects.create(id=1,
                                               name='Canada',
                                               country=country)
        PostalAddress.objects.create(
            id=1,
            name='Test Address',
            owner=self.user,
            street_number='120',
            street_name='Centre Street',
            suite_number='102',
            postal_code='N6J4X4',
            locality='London',
            region=region,
            country=country,
        )

        # Run the test.
        response = self.authorized_client.put(
            '/api/tenantpostaladdress/1/rebuild_geo_data/?format=json',
            json.dumps({}),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
コード例 #15
0
class APIFunctionViewSetWithTenantSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Public Schema"""
        tenant.schema_name = 'test'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])
        user = User.objects.create_user(  # Create our User.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APIFunctionViewSetWithTenantSchemaTestCase, self).setUp()

        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(
            self.tenant,
            HTTP_AUTHORIZATION='Token ' + token.key,
            format='json',
        )

    @transaction.atomic
    def tearDown(self):
        PostalAddress.objects.delete_all()
        ContactPoint.objects.delete_all()
        Me.objects.delete_all()
        users = User.objects.all()
        for user in users.all():
            user.delete()
        tokens = Token.objects.all()
        # super(APIFunctionViewSetWithTenantSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_api_function_finalize_tenant_with_200(self):
        # Log in the the account.
        user = User.objects.get()
        token = Token.objects.get(user_id=user.id)

        # Make User an Employee.
        group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        user.groups.add(group)

        # Begin this unit test.
        url = reverse('api_function_finalize_tenant')
        response = self.authorized_client.post(url,
                                               json.dumps({}),
                                               HTTP_AUTHORIZATION='Token ' +
                                               token.key,
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_api_function_finalize_tenant_with_403(self):
        # Log in the the account.
        user = User.objects.get()
        token = Token.objects.get(user_id=user.id)

        # Begin this unit test.
        url = reverse('api_function_finalize_tenant')
        response = self.authorized_client.post(url,
                                               json.dumps({}),
                                               HTTP_AUTHORIZATION='Token ' +
                                               token.key,
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_api_function_finalize_tenant_with_401(self):
        # Begin this unit test.
        url = reverse('api_function_finalize_tenant')
        response = self.unauthorized_client.post(
            url, json.dumps({}), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
コード例 #16
0
class APIAuthResetPasswordViewslWithSchemaTestCase(APITestCase, TenantTestCase):
    """
    Console:
    python manage.py test shared_api.tests.views.test_auth_reset_password_views
    """

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(APIAuthResetPasswordViewslWithSchemaTestCase, self).setUp()
        self.c = TenantClient(self.tenant)
        call_command('init_app', verbosity=0)
        call_command(
           'create_shared_account',
           TEST_USER_EMAIL,
           TEST_USER_PASSWORD,
           "Bart",
           "Mika",
           verbosity=0
        )

    @transaction.atomic
    def tearDown(self):
        SharedUser.objects.delete_all()
        del self.c
        super(APIAuthResetPasswordViewslWithSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_api_endpoint_with_success(self):
        # Get credentials
        me = SharedUser.objects.get()
        pr_access_code = me.generate_pr_code()

        # Log out.
        url = reverse('workery_reset_password_api_endpoint')
        data = {
            'password': TEST_USER_PASSWORD,
            'password_repeat': TEST_USER_PASSWORD,
            'pr_access_code': pr_access_code
        }
        response = self.c.post(url, json.dumps(data), content_type='application/json')

        # Confirm.
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_api_endpoint_with_bad_pr_access_code(self):
        # Get credentials
        me = SharedUser.objects.get()
        pr_access_code = me.generate_pr_code()

        # Log out.
        url = reverse('workery_reset_password_api_endpoint')
        data = {
            'password': TEST_USER_PASSWORD,
            'password_repeat': TEST_USER_PASSWORD,
            'pr_access_code': "some-bad-pr-access-code"
        }
        response = self.c.post(url, json.dumps(data), content_type='application/json')

        # Confirm.
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_api_endpoint_with_bad_password(self):
        # Log out.
        url = reverse('workery_reset_password_api_endpoint')
        data = {
            'password': "******",
            'password_repeat': "some-bad-password-plus-mismatching-entry",
            'pr_access_code': "some-bad-pr-access-code"
        }
        response = self.c.post(url, json.dumps(data), content_type='application/json')

        # Confirm.
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        # Verify password error messages.
        self.assertIn("Password", str(response.data))
        self.assertIn("uppercase", str(response.data))
コード例 #17
0
class APIMessageWithTenantSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Tenant Schema"""
        tenant.schema_name = 'galacticalliance'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_superuser = True
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APIMessageWithTenantSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant,
                                              HTTP_AUTHORIZATION='Token ' +
                                              token.key)
        self.authorized_client.login(username=TEST_USER_USERNAME,
                                     password=TEST_USER_PASSWORD)
        self.tenant.owner = self.user
        self.tenant.save()

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

    @transaction.atomic
    def tearDown(self):
        Message.objects.delete_all()
        PostalAddress.objects.delete_all()
        ContactPoint.objects.delete_all()
        Me.objects.delete_all()
        users = User.objects.all()
        for user in users.all():
            user.delete()
        # super(APIMessageWithTenantSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_list_with_anonymous_user(self):
        response = self.unauthorized_client.get(
            '/api/tenantmessage/?format=json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_authenticated_user(self):
        org_admin_group = Group.objects.get(
            id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        self.user.groups.add(org_admin_group)

        response = self.authorized_client.get(
            '/api/tenantmessage/?format=json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_post_with_anonymous_user(self):
        data = {
            'name': 'Unit Test',
            'owner': self.user.id,
        }
        response = self.unauthorized_client.post(
            '/api/tenantmessage/?format=json',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(len(mail.outbox), 0)

    @transaction.atomic
    def test_post_from_sender_to_recipient(self):
        # Create our recipient
        recipient_user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password='******')
        recipient_user.is_active = True
        recipient_user.save()
        recipient = Me.objects.create(owner=recipient_user)

        # Run the test and verify.
        data = {
            'name': 'Unit Test',
            'recipient': recipient.id,
            'description': 'Glory to Galactic Alliance',
        }
        response = self.authorized_client.post(
            '/api/tenantmessage/?format=json',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(len(mail.outbox), 1)

    @transaction.atomic
    def test_put_with_anonymous_user(self):
        # Create a new object with our specific test data.
        Message.objects.create(
            id=666,
            name="Unit Test",
            owner=self.user,
        )

        # Run the test.
        data = {
            'id': 666,
            'name': 'Unit Test',
            'owner': self.user.id,
        }
        response = self.unauthorized_client.put(
            '/api/tenantmessage/666/?format=json',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(len(mail.outbox), 0)

    @transaction.atomic
    def test_put_with_original_sender(self):
        # Create our sender.
        sender = Me.objects.create(owner=self.user, )

        # Create our recipient
        recipient_user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password='******')
        recipient_user.is_active = True
        recipient_user.save()
        recipient = Me.objects.create(owner=recipient_user)

        # Create a new object with our specific test data.
        Message.objects.create(
            id=666,
            name="Unit Test #666",
            recipient=recipient,
            sender=sender,
        )

        # Run the test.
        data = {
            'id': 666,
            'name': 'Unit Test',
            'recipient': recipient.id,
        }
        response = self.authorized_client.put('/api/tenantmessage/666/',
                                              json.dumps(data),
                                              content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(mail.outbox),
                         0)  # Editing does not qualify for email notification.

    @transaction.atomic
    def test_put_with_different_sender(self):
        # Create our CURRENT sender.
        Me.objects.create(owner=self.user, )

        # Create our NEW sender.
        sender_user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password='******')
        sender_user.is_active = True
        sender_user.save()
        sender = Me.objects.create(owner=sender_user)

        # Create our NEW recipient
        recipient_user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password='******')
        recipient_user.is_active = True
        recipient_user.save()
        recipient = Me.objects.create(owner=recipient_user)

        # Create a new object with our specific test data.
        Message.objects.create(
            id=666,
            name="Unit Test #666",
            recipient=recipient,
            sender=sender,
        )

        # Run the test.
        data = {
            'id': 666,
            'name': 'Unit Test',
            'recipient': recipient.id,
        }
        response = self.authorized_client.put('/api/tenantmessage/666/',
                                              json.dumps(data),
                                              content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(len(mail.outbox), 0)

    @transaction.atomic
    def test_delete_with_anonymous_user(self):
        # Create our CURRENT sender.
        sender = Me.objects.create(owner=self.user, )

        # Create a new object with our specific test data.
        message = Message.objects.create(
            id=666,
            name="Unit Test #666",
            sender=sender,
        )
        message.participants.add(sender)
        message.save()

        # Run our test and verify.
        response = self.unauthorized_client.delete(
            '/api/tenantmessage/666/?format=json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(Message.objects.all().count(), 1)
        message = Message.objects.get(id=666)
        self.assertEqual(message.participants.count(), 1)

    @transaction.atomic
    def test_delete_with_sender(self):
        # Create our SENDER user.
        sender = Me.objects.create(owner=self.user, )

        # Create our RECIPIENT user.
        recipient_user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password='******')
        recipient_user.is_active = True
        recipient_user.save()
        recipient = Me.objects.create(owner=recipient_user)

        # Create a new object with our specific test data.
        message = Message.objects.create(
            id=666,
            name="Unit Test #666",
            sender=sender,
            recipient=recipient,
        )
        message.participants.add(sender)
        message.save()

        # Run our test and verify.
        response = self.authorized_client.delete(
            '/api/tenantmessage/666/?format=json')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(Message.objects.all().count(),
                         1)  # Check message has not been deleted
        message = Message.objects.get(id=666)
        self.assertEqual(message.participants.count(), 0)

    @transaction.atomic
    def test_delete_with_recipient(self):
        # Create our CURRENT sender.
        recipient = Me.objects.create(owner=self.user, )

        # Create our NEW recipient
        sender_user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password='******')
        sender_user.is_active = True
        sender_user.save()
        sender = Me.objects.create(owner=sender_user)

        # Create a new object with our specific test data.
        message = Message.objects.create(
            id=666,
            name="Unit Test #666",
            sender=sender,
            recipient=recipient,
        )
        message.participants.add(recipient, sender)
        message.save()

        # Run our test and verify.
        response = self.authorized_client.delete(
            '/api/tenantmessage/666/?format=json')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertEqual(Message.objects.all().count(),
                         1)  # Check message has not been deleted
        message = Message.objects.get(id=666)
        self.assertEqual(message.participants.count(), 1)

    @transaction.atomic
    def test_delete_with_different_sender(self):
        # Create our CURRENT sender.
        Me.objects.create(owner=self.user, )

        # Create our NEW sender.
        sender_user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password='******')
        sender_user.is_active = True
        sender_user.save()
        sender = Me.objects.create(owner=sender_user)

        # Create our NEW recipient
        recipient_user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password='******')
        recipient_user.is_active = True
        recipient_user.save()
        recipient = Me.objects.create(owner=recipient_user)

        # Create a new object with our specific test data.
        message = Message.objects.create(
            id=666,
            name="Unit Test #666",
            recipient=recipient,
            sender=sender,
        )
        message.participants.add(recipient, sender)
        message.save()

        # Run our test and verify.
        response = self.authorized_client.delete(
            '/api/tenantmessage/666/?format=json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(Message.objects.all().count(), 1)
        message = Message.objects.get(id=666)
        self.assertEqual(message.participants.count(), 2)
コード例 #18
0
class APIImageUploadWithTenantSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Tenant Schema"""
        tenant.schema_name = 'galacticalliance'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks=True
        tenant.has_mentors=True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(id=constants.ENTREPRENEUR_GROUP_ID, name="Entreprenuer",),
            Group(id=constants.MENTOR_GROUP_ID, name="Mentor",),
            Group(id=constants.ADVISOR_GROUP_ID, name="Advisor",),
            Group(id=constants.ORGANIZATION_MANAGER_GROUP_ID, name="Org Manager",),
            Group(id=constants.ORGANIZATION_ADMIN_GROUP_ID, name="Org Admin",),
            Group(id=constants.CLIENT_MANAGER_GROUP_ID, name="Client Manager",),
            Group(id=constants.SYSTEM_ADMIN_GROUP_ID, name="System Admin",),
        ])
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APIImageUploadWithTenantSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant, HTTP_AUTHORIZATION='Token ' + token.key)

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

        # Initialize our test data.
        ImageUpload.objects.bulk_create([
            ImageUpload(owner=self.user),
            ImageUpload(owner=self.user),
            ImageUpload(owner=self.user),
        ])

    @transaction.atomic
    def tearDown(self):
        """Delete all the images we uploaded for this Test"""
        ImageUpload.objects.delete_all()
        PostalAddress.objects.delete_all()
        ContactPoint.objects.delete_all()
        Me.objects.delete_all()            
        users = User.objects.all()
        for user in users.all():
            user.delete()
        # super(APIImageUploadWithTenantSchemaTestCase, self).tearDown()

    def _create_test_image(self, path):
        # Create the image.
        from PIL import Image
        width = 2
        height = 2
        img = Image.new('RGB', (width, height))
        img.save(path)

        # Open image.
        f = open(path, 'rb')
        return {'imagefile': f}

    @transaction.atomic
    def test_to_string(self):
        # Create a new object with our specific test data.
        upload = ImageUpload.objects.create(
            id=2030,
            owner=self.user,
        )
        upload.save()
        self.assertEqual(str(upload), "")

    @transaction.atomic
    def test_post_with_authenticated_user(self):
        # Step 1: Set the location variables.
        url = reverse('tenantimageupload-list')
        data = self._create_test_image('/tmp/test_upload.png')
        data['owner'] = self.user.id

        # Step 2: Perform a "multiform" post using AJAX.
        response = self.authorized_client.post(url, data, format='multipart')

        # Step 3: Test & verify.
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIn('created', response.data)

    @transaction.atomic
    def test_post(self):
        # Step 1: Set the location variables.
        url = reverse('tenantimageupload-list')
        data = self._create_test_image('/tmp/test_upload.png')

        # Step 2: Perform a "multiform" post using AJAX.
        response = self.unauthorized_client.post(url, data, format='multipart')

        # Step 3: Test & verify.
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_banning(self):
        # Step 1: Setup variables.
        url = reverse('tenantimageupload-list')

        # Step 2: Ban self.
        BannedIP.objects.create(
            address='127.0.0.1',
            reason='For unit testing purposes.'
        )

        # Step 3: Test & verify.
        response = self.authorized_client.get(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_list_with_authenticated_user(self):
        # Step 1: Setup variables.
        url = reverse('tenantimageupload-list')

        # Step 2: Test & verify.
        response = self.authorized_client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 3)

    @transaction.atomic
    def test_list(self):
        # Step 1: Setup variables.
        url = reverse('tenantimageupload-list')

        # Step 2: Test & verify.
        response = self.unauthorized_client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 3)

    @transaction.atomic
    def test_get_with_authenticated_user(self):
        # Step 1: Setup variables.
        url = reverse('tenantimageupload-list')

        # Step 2: Test & verify.
        response = self.authorized_client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data) > 0, True)

    @transaction.atomic
    def test_get(self):
        # Step 1: Setup variables.
        url = reverse('tenantimageupload-list')

        # Step 2: Test & verify.
        response = self.authorized_client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data) > 0, True)

    @transaction.atomic
    def test_put_with_authenticated_user(self):
        # Delete any previous data.
        uploads = ImageUpload.objects.all()
        for upload in uploads.all():
            upload.delete()

        # Create a new object with our specific test data.
        ImageUpload.objects.create(id=1, owner_id=self.user.id,)

        # Run the test.
        url = reverse('tenantimageupload-list')+'1/'
        response = self.authorized_client.put(url, json.dumps({'id': 1, 'owner': self.user.id}), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_put_with_different_owner(self):
        # Initialize our test user.
        user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password=TEST_USER_PASSWORD
        )
        user.is_active = True
        user.save()
        token = Token.objects.get(user=user)

        # Perform this unit test.
        # Step 1: Log in and get the first ImageUpload object.
        client = TenantClient(self.tenant, HTTP_AUTHORIZATION='Token ' + token.key)

        # Delete any previous data.
        uploads = ImageUpload.objects.all()
        for upload in uploads.all():
            upload.delete()

        # Create a new object with our specific test data.
        ImageUpload.objects.create(id=1, owner_id=self.user.id,)

        # Run the test.
        url = reverse('tenantimageupload-list')+'1/'
        response = client.put(url, json.dumps({'id': 1, 'owner': user.id }), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_put(self):
        # Step 1: Set the location variables.
        url = reverse('tenantimageupload-list')
        data = self._create_test_image('/tmp/test_upload.png')
        kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}

        # Step 2: Perform a "multiform" post using AJAX.
        response = self.unauthorized_client.put(url,{
            'id': 1,
            'imagefile': data,
        }, **kwargs)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_authenticated_user(self):
        # Step 1: Delete any previous data.
        uploads = ImageUpload.objects.all()
        for upload in uploads.all():
            upload.delete()

        # Step 2: Setup variables.
        ImageUpload.objects.create(id=1, owner_id=self.user.id,)
        url = reverse('tenantimageupload-list')+'1/'

        # Step 3: Test & verify.
        response = self.authorized_client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    @transaction.atomic
    def test_delete_with_different_owner(self):
        # Step 1: Delete any previous data.
        uploads = ImageUpload.objects.all()
        for upload in uploads.all():
            upload.delete()

        # Step 2: Initialize our test user.
        ImageUpload.objects.create(id=1, owner_id=self.user.id,)
        user = User.objects.create_user(  # Create our user.
            email='*****@*****.**',
            username='******',
            password=TEST_USER_PASSWORD
        )
        user.is_active = True
        user.save()
        token = Token.objects.get(user=user)

        # Step 3: Connect to the server.
        client = TenantClient(self.tenant, HTTP_AUTHORIZATION='Token ' + token.key)

        # Step 4: Test & verify.
        url = reverse('tenantimageupload-list')+'1/'
        response = client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_delete(self):
        # Step 1: Setup variables.
        url = reverse('tenantimageupload-list')+'1/'

        # Step 2: Test & verify.
        response = self.unauthorized_client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(len(response.data) > 0, True)
コード例 #19
0
class APIEmailActivationTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Public Schema"""
        tenant.schema_name = 'test'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])

        user = User.objects.create_user(  # Create our User.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(APIEmailActivationTestCase, self).setUp()
        self.c = TenantClient(self.tenant)

    @transaction.atomic
    def tearDown(self):
        users = User.objects.all()
        for user in users.all():
            user.delete()
        # super(APIEmailActivationTestCase, self).tearDown()

    @transaction.atomic
    def test_api_send_activation(self):
        url = reverse('api_emailactivation')
        data = {
            'email': TEST_USER_EMAIL,
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        from django.core import mail

        # Test that one message has been sent.
        self.assertEqual(len(mail.outbox), 1)

        # Verify that the subject of the first message is correct.
        self.assertEqual(mail.outbox[0].subject, 'Den Activation')

    @transaction.atomic
    def test_api_send_activation_with_no_email(self):
        url = reverse('api_emailactivation')
        data = {
            'email': '*****@*****.**',
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
コード例 #20
0
class StaffListCreateAPIViewWithTenantTestCase(APITestCase, TenantTestCase):
    """
    Console:
    python manage.py test tenant_api.tests.test_staff_view
    """

    #------------------#
    # Setup Unit Tests #
    #------------------#

    def setup_tenant(tenant):
        """Tenant Schema"""
        tenant.schema_name = TEST_SCHEMA_NAME
        tenant.name='Over 55 (London) Inc.',
        tenant.alternate_name="Over55",
        tenant.description="Located at the Forks of the Thames in ...",
        tenant.address_country="CA",
        tenant.address_locality="London",
        tenant.address_region="Ontario",
        tenant.post_office_box_number="", # Post Offic #
        tenant.postal_code="N6H 1B4",
        tenant.street_address="78 Riverside Drive",
        tenant.street_address_extra="", # Extra line.

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(StaffListCreateAPIViewWithTenantTestCase, self).setUp()

        # Load up the dependat.
        call_command('init_app', verbosity=0)
        call_command('populate_tenant_content', TEST_SCHEMA_NAME, verbosity=0)

        # Create the account.
        call_command(
           'create_tenant_account',
           TEST_SCHEMA_NAME,
           constants.MANAGEMENT_GROUP_ID,
           TEST_USER_EMAIL,
           TEST_USER_PASSWORD,
           "Bart",
           "Mika",
           TEST_USER_TEL_NUM,
           TEST_USER_TEL_EX_NUM,
           TEST_USER_CELL_NUM,
           "CA",
           "London",
           "Ontario",
           "", # Post Offic #
           "N6H 1B4",
           "78 Riverside Drive",
           "", # Extra line.
           verbosity=0
        )

        # Create the account.
        call_command(
           'create_tenant_account',
           TEST_SCHEMA_NAME,
           constants.MANAGEMENT_GROUP_ID,
           TEST_ALERNATE_USER_EMAIL,
           TEST_USER_PASSWORD,
           "Rodolfo",
           "Martinez",
           TEST_USER_TEL_NUM,
           TEST_USER_TEL_EX_NUM,
           TEST_USER_CELL_NUM,
           "CA",
           "London",
           "Ontario",
           "", # Post Offic #
           "N6H 1B4",
           "78 Riverside Drive",
           "", # Extra line.
           verbosity=0
        )

        # Initialize our test data.
        self.user = SharedUser.objects.get(email=TEST_USER_EMAIL)
        self.alternate_user = SharedUser.objects.get(email=TEST_ALERNATE_USER_EMAIL)
        token, orig_iat = get_jwt_token_and_orig_iat(self.user)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant, HTTP_AUTHORIZATION='JWT {0}'.format(token))
        self.authorized_client.login(
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        # Create our staff.
        connection.set_schema(TEST_SCHEMA_NAME, True) # Switch to Tenant.
        self.staff = Staff.objects.create(
            owner=self.user,
            given_name="Bart",
            last_name="Mika"
        )
        self.alernate_staff = Staff.objects.create(
            owner=self.alternate_user,
            given_name="Rodolfo",
            last_name="Martinez"
        )

    @transaction.atomic
    def tearDown(self):
        connection.set_schema(TEST_SCHEMA_NAME, True) # Switch to Tenant.
        Staff.objects.delete_all()
        del self.unauthorized_client
        del self.authorized_client
        super(StaffListCreateAPIViewWithTenantTestCase, self).tearDown()

    #-------------------#
    # List API-endpoint #
    #-------------------#

    @transaction.atomic
    def test_list_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a GET request to the LIST API-endpoint.
        """
        url = reverse('workery_staff_list_create_api_endpoint')+"?format=json"
        response = self.unauthorized_client.get(url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        GET request to the list API-endpoint.
        """
        url = reverse('workery_staff_list_create_api_endpoint')
        url += "?format=json"
        response = self.authorized_client.get(url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Bart", str(response.data))
        self.assertIn("Mika", str(response.data))
        self.assertNotIn("You do not have permission to access this API-endpoint.", str(response.data))

    @transaction.atomic
    def test_list_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a GET request to the list API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_staff_list_create_api_endpoint')
        url += "?format=json"
        response = self.authorized_client.get(url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn("You do not have permission to access this API-endpoint.", str(response.data))

    #---------------------#
    # Create API-endpoint #
    #---------------------#

    @transaction.atomic
    def test_create_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a POST request to the create API-endpoint.
        """
        url = reverse('workery_staff_list_create_api_endpoint')+"?format=json"
        response = self.unauthorized_client.post(url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_create_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        POST request to the create API-endpoint.
        """
        # Perform our tests.
        url = reverse('workery_staff_list_create_api_endpoint')
        url += "?format=json"
        response = self.authorized_client.post(url, data=json.dumps({
            'password': '******',
            'password_repeat': '123Password!',
            'groups': [
                constants.MANAGEMENT_GROUP_ID
            ],
            'email': "*****@*****.**",
            'given_name': 'Bart',
            'middle_name': '',
            'last_name': 'Mika',
            'address_country': 'CA',
            'address_locality': 'London',
            'address_region': 'Ontario',
            'street_address': '78 Riverside Drive',
            'postal_code': 'N6H 1B4',
            'telephone': '(123) 456-7890',
            'telephone_extension': None,
            'fax_number': None,
            'other_telephone': '+19876543210',
            'extra_comment': "This is a friendly staff.",
            'group_membership': 2,
            'is_active': True,
            'password': '******',
            'password_repeat': '123passwordOK!',
            'description': 'Some generic desc.',
            'telephone_type_of': 1,
            'other_telephone_type_of': 1,
            'is_ok_to_email': True,
            'is_ok_to_text': True,
            'tags': [],
            'account_type': constants.FRONTLINE_GROUP_ID
        }), content_type='application/json')
        self.assertIsNotNone(response)
        # print(response.data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIn("Bart", str(response.data))
        self.assertIn("Mika", str(response.data))
        self.assertIn("(123) 456-7890", str(response.data))
        self.assertIn("(987) 654-3210", str(response.data))

    @transaction.atomic
    def test_create_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a POST request to the list API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_staff_list_create_api_endpoint')
        url += "?format=json"
        response = self.authorized_client.post(url, data=json.dumps({}), content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn("You do not have permission to access this API-endpoint.", str(response.data))

    #---------------------#
    # Update API-endpoint #
    #---------------------#

    @transaction.atomic
    def test_update_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a PUT request to the update API-endpoint.
        """
        url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.staff.id])+"?format=json"
        response = self.unauthorized_client.post(url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_update_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        PUT request to the update API-endpoint.
        """
         # Perform our tests.
        url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.alernate_staff.id])+"?format=json"
        response = self.authorized_client.put(url, data=json.dumps({
            # 'email': TEST_ALERNATE_USER_EMAIL,
            'given_name': 'Rodolfo',
            'middle_name': '',
            'last_name': 'Martinez',
            'address_country': 'CA',
            'address_locality': 'Port Frank Herbert',
            'address_region': 'Britich Coloumbia',
            'street_address': '666 Riverside Drive',
            'postal_code': 'N1N 1N1',
            'extra_comment': "This is a helpful staff.",
            'group_membership': 2,
            'is_active': True,
            'password': '******',
            'password_repeat': '123passwordOK!',
            'description': 'Some generic desc.',
            'telephone_type_of': 1,
            'other_telephone_type_of': 1,
            'is_ok_to_email': True,
            'is_ok_to_text': True,
            'tags': [],
            'account_type': constants.FRONTLINE_GROUP_ID
        }), content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Rodolfo", str(response.data))
        self.assertIn("Martinez", str(response.data))
        self.assertIn("666 Riverside Drive", str(response.data))
        self.assertIn("N1N 1N1", str(response.data))
        self.assertIn("Port Frank Herbert", str(response.data))

    # # @transaction.atomic
    # # def test_update_with_403_by_permissions(self):
    # #     """
    # #     Unit test will test authenticated user, who does not have permission, to
    # #     make a PUT request to the update API-endpoint.
    # #     """
    # #     Permission.objects.all().delete()
    # #     url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.alernate_staff.id])+"?format=json"
    # #     response = self.authorized_client.put(url, data=json.dumps({}), content_type='application/json')
    # #     self.assertIsNotNone(response)
    # #     self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
    # #     self.assertIn("You do not have permission to access this API-endpoint.", str(response.data))

    @transaction.atomic
    def test_update_with_200_by_ownership(self):
        # Perform our tests.
        Permission.objects.all().delete()
        url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.staff.id])+"?format=json"
        response = self.authorized_client.put(url, data=json.dumps({
            # 'email': '*****@*****.**',
            'given_name': 'Bartlomiej',
            'middle_name': '',
            'last_name': 'Mika',
            'address_country': 'CA',
            'address_locality': 'Port Bart',
            'address_region': 'Alberta',
            'street_address': '666 Riverside Drive',
            'postal_code': 'N1N 1N1',
            # 'extra_comment': "This is a helpful staff.",
            'group_membership': 2,
            'is_active': True,
            'password': '******',
            'password_repeat': '123passwordOK!',
            'description': 'Some generic desc.',
            'telephone_type_of': 1,
            'other_telephone_type_of': 1,
            'is_ok_to_email': True,
            'is_ok_to_text': True,
            'tags': [],
            'account_type': constants.FRONTLINE_GROUP_ID
        }), content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Bartlomiej", str(response.data))
        self.assertIn("Mika", str(response.data))
        self.assertIn("666 Riverside Drive", str(response.data))
        self.assertIn("N1N 1N1", str(response.data))
        self.assertIn("Port Bart", str(response.data))

    @transaction.atomic
    def test_update_with_200_by_ownership_and_password_change(self):
        # Perform our tests.
        Permission.objects.all().delete()
        url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.staff.id])+"?format=json"
        response = self.authorized_client.put(url, data=json.dumps({
            'password': '******',
            'password_repeat': '123Password!',
            # 'email': '*****@*****.**',
            'given_name': 'Bartlomiej',
            'middle_name': '',
            'last_name': 'Mika',
            'address_country': 'CA',
            'address_locality': 'Port Bart',
            'address_region': 'Alberta',
            'street_address': '666 Riverside Drive',
            'postal_code': 'N1N 1N1',
            # 'extra_comment': "This is a helpful staff.",
            'group_membership': 2,
            'is_active': True,
            'password': '******',
            'password_repeat': '123passwordOK!',
            'description': 'Some generic desc.',
            'telephone_type_of': 1,
            'other_telephone_type_of': 1,
            'is_ok_to_email': True,
            'is_ok_to_text': True,
            'tags': [],
            'account_type': constants.FRONTLINE_GROUP_ID
        }), content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Bartlomiej", str(response.data))
        self.assertIn("Mika", str(response.data))
        self.assertIn("666 Riverside Drive", str(response.data))
        self.assertIn("N1N 1N1", str(response.data))
        self.assertIn("Port Bart", str(response.data))

    #-----------------------#
    # Retrieve API-endpoint #
    #-----------------------#

    @transaction.atomic
    def test_retrieve_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a GET request to the retrieve API-endpoint.
        """
        url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.staff.id])+"?format=json"
        response = self.unauthorized_client.get(url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_retrieve_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        GET request to the retrieve API-endpoint.
        """
        url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.staff.id])+"?format=json"
        response = self.authorized_client.get(url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Bart", str(response.data))
        self.assertIn("Mika", str(response.data))

    @transaction.atomic
    def test_retrieve_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a GET request to the retrieve API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.alernate_staff.id])+"?format=json"
        response = self.authorized_client.get(url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn("You do not have permission to access this API-endpoint.", str(response.data))

    @transaction.atomic
    def test_retrieve_with_200_by_ownership(self):
        """
        Unit test will test authenticated user, who does not have permission,
        but is the OWNER of the object to make a GET request to the retrieve
        API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.staff.id])+"?format=json"
        response = self.authorized_client.get(url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Bart", str(response.data))
        self.assertIn("Mika", str(response.data))

    #-----------------------#
    # Delete API-endpoint #
    #-----------------------#

    @transaction.atomic
    def test_delete_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a DELETE request to the delete API-endpoint.
        """
        url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.staff.id])+"?format=json"
        response = self.unauthorized_client.delete(url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        DELETE request to the delete API-endpoint.
        """
        # Add executive group so you can delete.
        self.user.groups.add(constants.EXECUTIVE_GROUP_ID)

        # Go ahead and delete.
        url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.staff.id])+"?format=json"
        response = self.authorized_client.delete(url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a DELETE request to the delete API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_staff_retrieve_update_destroy_api_endpoint', args=[self.staff.id])+"?format=json"
        response = self.authorized_client.delete(url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn("You do not have permission to access this API-endpoint.", str(response.data))
コード例 #21
0
class APITaskBaseWithTenantSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Tenant Schema"""
        tenant.schema_name = 'galacticalliance'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APITaskBaseWithTenantSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant,
                                              HTTP_AUTHORIZATION='Token ' +
                                              token.key)
        self.authorized_client.login(username=TEST_USER_USERNAME,
                                     password=TEST_USER_PASSWORD)

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

        # Initialize our test data.
        Task.objects.bulk_create([
            Task(owner=self.user),
            Task(owner=self.user),
            Task(owner=self.user),
        ])

    @transaction.atomic
    def tearDown(self):
        PostalAddress.objects.delete_all()  # Must be above Tasks.
        ContactPoint.objects.delete_all()  # Must be above Tasks.
        CalendarEvent.objects.delete_all()
        Task.objects.delete_all()
        SortedLogEventByCreated.objects.delete_all()
        SortedCommentPostByCreated.objects.delete_all()
        Me.objects.delete_all()
        users = User.objects.all()
        for user in users.all():
            user.delete()
        # super(APITaskBaseWithTenantSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_list_with_anonymous_user(self):
        response = self.unauthorized_client.get('/api/tenanttask/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_authenticated_user(self):
        me = Me.objects.create(  # Create our models.
            id=1,
            owner=self.user,
        )
        task = Task.objects.create(
            id=666,
            assigned_by=me,
            assignee=me,
        )
        response = self.authorized_client.get(
            '/api/tenanttask/')  # Run test and verify.
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_post_with_anonymous_user(self):
        me = Me.objects.create(
            id=1,
            owner=self.user,
        )
        data = {
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'assigned_by': me.id,
            'assignee': me.id,
            'status': constants.OPEN_TASK_STATUS,
        }
        response = self.unauthorized_client.post(
            '/api/tenanttask/',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_post_with_authenticated_user(self):
        me = Me.objects.create(
            id=1,
            owner=self.user,
        )
        data = {
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'assigned_by': me.id,
            'assignee': me.id,
            'status': constants.OPEN_TASK_STATUS,
        }
        response = self.authorized_client.post('/api/tenanttask/',
                                               json.dumps(data),
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    @transaction.atomic
    def test_put_with_anonymous_user(self):
        me = Me.objects.create(
            id=1,
            owner=self.user,
        )
        task = Task.objects.create(
            id=666,
            assigned_by=me,
            assignee=me,
        )
        data = {
            'id': task.id,
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'assigned_by': me.id,
            'assignee': me.id,
            'status': constants.OPEN_TASK_STATUS,
        }
        response = self.unauthorized_client.put(
            '/api/tenanttask/666/',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_put_with_owner_user(self):
        me = Me.objects.create(
            id=1,
            owner=self.user,
        )
        task = Task.objects.create(
            id=666,
            owner=self.user,
            assigned_by=me,
            assignee=me,
        )
        data = {
            'id': task.id,
            'name': 'Unit Test',
            'description': 'Used for unit testing purposes.',
            'assigned_by': me.id,
            'assignee': me.id,
            'status': constants.OPEN_TASK_STATUS,
        }
        response = self.authorized_client.put('/api/tenanttask/666/',
                                              json.dumps(data),
                                              content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete_by_anonymous_user(self):
        me = Me.objects.create(
            id=1,
            owner=self.user,
        )
        task = Task.objects.create(
            id=666,
            owner=self.user,
            assigned_by=me,
            assignee=me,
        )
        response = self.unauthorized_client.delete('/api/tenanttask/' +
                                                   str(task.id) + '/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_by_owner_user(self):
        me = Me.objects.create(
            id=1,
            owner=self.user,
        )
        calendar_event = CalendarEvent.objects.create(id=666, owner=self.user)
        task = Task.objects.create(id=666,
                                   owner=self.user,
                                   assigned_by=me,
                                   assignee=me,
                                   calendar_event=calendar_event)
        response = self.authorized_client.delete('/api/tenanttask/' +
                                                 str(task.id) + '/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
コード例 #22
0
class APILoginWithPublicSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Public Schema"""
        tenant.schema_name = 'test'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])
        user = User.objects.create_user(  # Create our User.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(APILoginWithPublicSchemaTestCase, self).setUp()
        self.c = TenantClient(self.tenant)

    @transaction.atomic
    def tearDown(self):
        users = User.objects.all()
        for user in users.all():
            user.delete()
        super(APILoginWithPublicSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_api_login_with_success(self):
        url = reverse('api_login')
        data = {
            'username': TEST_USER_USERNAME,
            'password': TEST_USER_PASSWORD,
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['user'] > 0, True)
        self.assertEqual(len(response.data['auth_token']) > 0, True)

    @transaction.atomic
    def test_api_login_with_nonexisting_account(self):
        url = reverse('api_login')
        data = {
            'username': '******',
            'password': '******',
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_api_login_with_inactive_account(self):
        # Get our current user and set the user to be inactive.
        client = User.objects.get()
        client.is_active = False
        client.save()

        # Run this test.
        url = reverse('api_login')
        data = {
            'username': TEST_USER_USERNAME,
            'password': TEST_USER_PASSWORD,
        }
        response = self.c.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
コード例 #23
0
class APIPublicFileUploadWithPublicSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Public Schema"""
        tenant.schema_name = 'test'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APIPublicFileUploadWithPublicSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant,
                                              HTTP_AUTHORIZATION='Token ' +
                                              token.key)

        PublicFileUpload.objects.bulk_create([
            PublicFileUpload(owner=self.user),
            PublicFileUpload(owner=self.user),
            PublicFileUpload(owner=self.user),
        ])

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

    @transaction.atomic
    def tearDown(self):
        entries = PublicFileUpload.objects.all()
        for entry in entries.all():
            entry.delete()
        users = User.objects.all()
        for user in users.all():
            user.delete()
        super(APIPublicFileUploadWithPublicSchemaTestCase, self).tearDown()

    def _create_test_file(self, path):
        """
        Creates a simulated file.

        Source: https://medium.com/@jxstanford/django-rest-framework-file-upload-e4bc8de669c0#.l8dbmtosq
        """
        f = open(path, 'w')
        f.write('test123\n')
        f.close()
        f = open(path, 'rb')
        return {'datafile': f}

    @transaction.atomic
    def test_to_string(self):
        # Create a new object with our specific test data.
        entry = PublicFileUpload.objects.create(
            id=2030,
            owner=self.user,
        )
        entry.save()
        self.assertEqual(str(entry), "")

    @transaction.atomic
    def test_post_with_authenticated_user(self):
        # Step 1: Set the location variables.
        url = reverse('publicfileupload-list')
        data = self._create_test_file('/tmp/test_upload')
        data['owner'] = self.user.id

        # Step 2: Perform a "multiform" post using AJAX.
        response = self.authorized_client.post(url, data, format='multipart')

        # Step 3: Test & verify.
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIn('created', response.data)

    @transaction.atomic
    def test_post(self):
        # Step 1: Set the location variables.
        url = reverse('publicfileupload-list')
        data = self._create_test_file('/tmp/test_upload')

        # Step 2: Perform a "multiform" post using AJAX.
        response = self.unauthorized_client.post(url, data, format='multipart')

        # Step 3: Test & verify.
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list(self):
        # Step 1: Set the location variables.
        url = reverse('publicfileupload-list')

        # Step 2: Test & verify.
        response = self.unauthorized_client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_list_with_authentication(self):
        # Step 1: Set the location variables.
        url = reverse('publicfileupload-list')

        # Step 2: Test & verify.
        response = self.authorized_client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_list_with_banning(self):
        # Step 1: Setup variables.
        url = reverse('publicfileupload-list')

        # Step 2: Ban self.
        BannedIP.objects.create(address='127.0.0.1',
                                reason='For unit testing purposes.')

        # Step 3: Test & verify.
        response = self.authorized_client.get(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_put(self):
        # Delete any previous data.
        uploads = PublicFileUpload.objects.all()
        for upload in uploads.all():
            upload.delete()

        # Create a new object with our specific test data.
        PublicFileUpload.objects.create(id=1, )

        # Run the test.
        url = reverse('publicfileupload-list') + '1/'
        response = self.unauthorized_client.put(
            url, json.dumps({
                'id': 1,
            }), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_put_with_authorization(self):
        # Delete any previous data.
        uploads = PublicFileUpload.objects.all()
        for upload in uploads.all():
            upload.delete()

        # Create a new object with our specific test data.
        PublicFileUpload.objects.create(
            id=1,
            owner_id=self.user.id,
        )
        data = {'id': 1, 'owner': self.user.id}

        # Run the test.
        url = reverse('publicfileupload-list') + '1/'
        response = self.authorized_client.put(url,
                                              json.dumps(data),
                                              content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete(self):
        # Step 1: Set the location variables.
        url = reverse('publicfileupload-list') + '1/'

        # Step 2: Test & verify.
        response = self.unauthorized_client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_authentication(self):
        # Step 1: Delete any previous data.
        uploads = PublicFileUpload.objects.all()
        for upload in uploads.all():
            upload.delete()

        # Step 2: Set the location variables.
        PublicFileUpload.objects.create(
            id=1,
            owner_id=self.user.id,
        )
        url = reverse('publicfileupload-list') + '1/'

        # Step 3: Test & verify.
        response = self.authorized_client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
コード例 #24
0
class WorkOrderListCreateAPIViewWithTenantTestCase(APITestCase,
                                                   TenantTestCase):
    """
    Console:
    python manage.py test tenant_api.tests.test_order_view
    """

    #------------------#
    # Setup Unit Tests #
    #------------------#

    def setup_tenant(tenant):
        """Tenant Schema"""
        tenant.schema_name = TEST_SCHEMA_NAME
        tenant.name = 'Over 55 (London) Inc.',
        tenant.alternate_name = "Over55",
        tenant.description = "Located at the Forks of the Thames in ...",
        tenant.address_country = "CA",
        tenant.address_locality = "London",
        tenant.address_region = "Ontario",
        tenant.post_office_box_number = "",  # Post Offic #
        tenant.postal_code = "N6H 1B4",
        tenant.street_address = "78 Riverside Drive",
        tenant.street_address_extra = "",  # Extra line.

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(WorkOrderListCreateAPIViewWithTenantTestCase, self).setUp()

        # Load up the dependat.
        call_command('init_app', verbosity=0)
        call_command('populate_tenant_content', TEST_SCHEMA_NAME, verbosity=0)
        call_command('populate_tenant_sample_db',
                     TEST_SCHEMA_NAME,
                     verbosity=0)

        # Get objects.
        self.customer = Customer.objects.get(owner__email='*****@*****.**')
        self.associate = Associate.objects.get(
            owner__email='*****@*****.**')

        # Get users.
        exec_user = SharedUser.objects.get(email='*****@*****.**')
        manager_user = SharedUser.objects.get(email='*****@*****.**')
        frontline_user = SharedUser.objects.get(email='*****@*****.**')
        associate_user = SharedUser.objects.get(email='*****@*****.**')
        customer_user = SharedUser.objects.get(email='*****@*****.**')

        # Get tokens.
        exec_token, exec_orig_iat = get_jwt_token_and_orig_iat(exec_user)
        manager_token, manager_orig_iat = get_jwt_token_and_orig_iat(
            manager_user)
        frontline_token, frontline_orig_iat = get_jwt_token_and_orig_iat(
            frontline_user)
        associate_token, associate_orig_iat = get_jwt_token_and_orig_iat(
            associate_user)
        customer_token, customer_orig_iat = get_jwt_token_and_orig_iat(
            customer_user)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.exec_client = TenantClient(
            self.tenant, HTTP_AUTHORIZATION='JWT {0}'.format(exec_token))
        self.exec_client.login(username='******',
                               password=TEST_USER_PASSWORD)
        self.manager_client = TenantClient(
            self.tenant, HTTP_AUTHORIZATION='JWT {0}'.format(manager_token))
        self.manager_client.login(username='******',
                                  password=TEST_USER_PASSWORD)
        self.staff_client = TenantClient(
            self.tenant, HTTP_AUTHORIZATION='JWT {0}'.format(manager_token))
        self.staff_client.login(username='******',
                                password=TEST_USER_PASSWORD)
        self.customer_client = TenantClient(
            self.tenant, HTTP_AUTHORIZATION='JWT {0}'.format(manager_token))
        self.customer_client.login(username='******',
                                   password=TEST_USER_PASSWORD)

        # Load up the tenant.
        connection.set_schema(TEST_SCHEMA_NAME, True)  # Switch to Tenant.

        # Tag
        self.tag = Tag.objects.create(text="Test Tag")

        # Create our order.
        self.order = WorkOrder.objects.create(
            customer=Customer.objects.get(owner__email="*****@*****.**"),
            associate=Associate.objects.get(
                owner__email="*****@*****.**"),
            assignment_date=timezone.now(),
            created_by=SharedUser.objects.get(email="*****@*****.**"),
            last_modified_by=None)
        self.order.tags.set([self.tag])

    @transaction.atomic
    def tearDown(self):
        connection.set_schema(TEST_SCHEMA_NAME, True)  # Switch to Tenant.
        Tag.objects.delete_all()
        WorkOrder.objects.delete_all()
        del self.unauthorized_client
        del self.exec_client
        del self.manager_client
        del self.staff_client
        del self.customer_client
        super(WorkOrderListCreateAPIViewWithTenantTestCase, self).tearDown()

    #-------------------#
    # List API-endpoint #
    #-------------------#

    @transaction.atomic
    def test_list_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a GET request to the LIST API-endpoint.
        """
        url = reverse(
            'workery_order_list_create_api_endpoint') + "?format=json"
        response = self.unauthorized_client.get(
            url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        GET request to the list API-endpoint.
        """
        url = reverse('workery_order_list_create_api_endpoint')
        url += "?format=json"

        # Executive
        response = self.exec_client.get(url,
                                        data=None,
                                        content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Manager
        response = self.manager_client.get(url,
                                           data=None,
                                           content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Staff
        response = self.staff_client.get(url,
                                         data=None,
                                         content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_list_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a GET request to the list API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_order_list_create_api_endpoint')
        url += "?format=json"
        response = self.customer_client.get(url,
                                            data=None,
                                            content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    #---------------------#
    # Create API-endpoint #
    #---------------------#

    @transaction.atomic
    def test_create_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a POST request to the create API-endpoint.
        """
        url = reverse(
            'workery_order_list_create_api_endpoint') + "?format=json"
        response = self.unauthorized_client.post(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_create_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        POST request to the create API-endpoint.
        """
        # Fetch our `SkillSet` objects.
        skill_set_1 = SkillSet.objects.filter(
            category="Carpentry", sub_category="Carpenter").first()
        skill_set_2 = SkillSet.objects.filter(
            category="Carpentry", sub_category="Deck Construction").first()
        skill_set_3 = SkillSet.objects.filter(
            category="Ceramic Tile", sub_category="Backsplash only").first()

        # Generate the URL.
        url = reverse('workery_order_list_create_api_endpoint')
        url += "?format=json"

        # Executive
        response = self.exec_client.post(
            url,
            data=json.dumps({
                'customer':
                self.customer.id,
                'associate':
                self.associate.id,
                'given_name':
                'Bart',
                'middle_name':
                '',
                'last_name':
                'Mika',
                'address_country':
                'CA',
                'address_locality':
                'London',
                'address_region':
                'Ontario',
                'street_address':
                '78 Riverside Drive',
                'postal_code':
                'N6H 1B4',
                'assignment_date':
                "2018-01-30",
                'tags': [self.tag.id],
                'extra_comment':
                "This is an extra comment.",
                'skill_sets': [skill_set_1.id, skill_set_2.id, skill_set_3.id],
                'invoice_service_fee_amount':
                7.99,
                'invoice_service_fee':
                1
            }),
            content_type='application/json')
        self.assertIsNotNone(response)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIn("Shinji", str(response.data))
        self.assertIn("Ikari", str(response.data))
        self.assertIn("Rei", str(response.data))
        self.assertIn("Ayanami", str(response.data))
        self.assertIn("[1]", str(response.data))  # tags
        # self.assertIn("This is a friendly associate.", str(response.data)) # If comments are included then use this.
        self.assertIn("[1, 2, 3]", str(response.data))  # Verify skill sets.

        # Manager
        response = self.manager_client.post(
            url,
            data=json.dumps({
                'customer':
                self.customer.id,
                'associate':
                self.associate.id,
                'given_name':
                'Bart',
                'middle_name':
                '',
                'last_name':
                'Mika',
                'address_country':
                'CA',
                'address_locality':
                'London',
                'address_region':
                'Ontario',
                'street_address':
                '78 Riverside Drive',
                'postal_code':
                'N6H 1B4',
                'assignment_date':
                "2018-01-30",
                'tags': [],
                'extra_comment':
                "This is an extra comment.",
                'skill_sets': [skill_set_1.id, skill_set_2.id, skill_set_3.id],
                'invoice_service_fee_amount':
                7.99,
                'invoice_service_fee':
                1
            }),
            content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIn("Shinji", str(response.data))
        self.assertIn("Ikari", str(response.data))
        self.assertIn("Rei", str(response.data))
        self.assertIn("Ayanami", str(response.data))
        self.assertIn("[]", str(response.data))  # tags
        # self.assertIn("This is a friendly associate.", str(response.data)) # If comments are included then use this.
        self.assertIn("[1, 2, 3]", str(response.data))  # Verify skill sets.

        # Staff
        response = self.staff_client.post(
            url,
            data=json.dumps({
                'customer':
                self.customer.id,
                'associate':
                self.associate.id,
                'given_name':
                'Bart',
                'middle_name':
                '',
                'last_name':
                'Mika',
                'address_country':
                'CA',
                'address_locality':
                'London',
                'address_region':
                'Ontario',
                'street_address':
                '78 Riverside Drive',
                'postal_code':
                'N6H 1B4',
                'assignment_date':
                "2018-01-30",
                'tags': [],
                'extra_comment':
                "This is an extra comment.",
                'skill_sets': [skill_set_1.id, skill_set_2.id, skill_set_3.id],
                'invoice_service_fee':
                1
            }),
            content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIn("Shinji", str(response.data))
        self.assertIn("Ikari", str(response.data))
        self.assertIn("Rei", str(response.data))
        self.assertIn("Ayanami", str(response.data))
        # self.assertIn("This is a friendly associate.", str(response.data)) # If comments are included then use this.
        self.assertIn("[1, 2, 3]", str(response.data))  # Verify skill sets.

    # @transaction.atomic
    def test_create_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a POST request to the list API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_order_list_create_api_endpoint')
        url += "?format=json"
        response = self.customer_client.post(url,
                                             data=json.dumps({}),
                                             content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    #---------------------#
    # Update API-endpoint #
    #---------------------#

    @transaction.atomic
    def test_update_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a PUT request to the update API-endpoint.
        """
        url = reverse('workery_order_retrieve_update_destroy_api_endpoint',
                      args=[self.order.id]) + "?format=json"
        response = self.unauthorized_client.post(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_update_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        PUT request to the update API-endpoint.
        """
        # Fetch our `SkillSet` objects.
        skill_set_1 = SkillSet.objects.filter(
            category="Carpentry", sub_category="Carpenter").first()
        skill_set_2 = SkillSet.objects.filter(
            category="Carpentry", sub_category="Deck Construction").first()
        skill_set_3 = SkillSet.objects.filter(
            category="Ceramic Tile", sub_category="Backsplash only").first()

        # Generate the URL and data.
        url = reverse('workery_order_retrieve_update_destroy_api_endpoint',
                      args=[self.order.id]) + "?format=json"
        data = json.dumps({
            'customer':
            self.customer.id,
            'associate':
            self.associate.id,
            'completion_date':
            '2019-01-25',
            'assignment_date':
            "2018-01-30",
            'tags': [self.tag.id],
            'extra_comment':
            "This is an extra comment.",
            'skill_sets': [skill_set_1.id, skill_set_2.id, skill_set_3.id],
            'invoice_service_fee':
            1,
            'invoice_service_fee_payment_date':
            "2018-01-30",
        })

        # Executive
        response = self.exec_client.put(url,
                                        data=data,
                                        content_type='application/json')
        self.assertIsNotNone(response)
        # print(response.content)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("2019-01-25", str(response.data))
        self.assertIn("2018-01-30", str(response.data))
        # self.assertIn("This is an extra comment.", str(response.data))

        # Manager
        response = self.manager_client.put(url,
                                           data=data,
                                           content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("2019-01-25", str(response.data))
        self.assertIn("2018-01-30", str(response.data))

        # Staff
        response = self.staff_client.put(url,
                                         data=data,
                                         content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("2019-01-25", str(response.data))
        self.assertIn("2018-01-30", str(response.data))

    @transaction.atomic
    def test_update_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a PUT request to the update API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_order_retrieve_update_destroy_api_endpoint',
                      args=[self.order.id]) + "?format=json"
        data = json.dumps({
            'customer': self.customer.id,
            'associate': self.associate.id,
            'completion_date': '2019-01-25',
            'assignment_date': "2018-01-30",
            'tags': [],
            'comments': []
        })
        response = self.customer_client.put(url,
                                            data=data,
                                            content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    #-----------------------#
    # Retrieve API-endpoint #
    #-----------------------#

    @transaction.atomic
    def test_retrieve_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a GET request to the retrieve API-endpoint.
        """
        url = reverse('workery_order_retrieve_update_destroy_api_endpoint',
                      args=[self.order.id]) + "?format=json"
        response = self.unauthorized_client.get(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_retrieve_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        GET request to the retrieve API-endpoint.
        """
        url = reverse('workery_order_retrieve_update_destroy_api_endpoint',
                      args=[self.order.id]) + "?format=json"

        response = self.exec_client.get(url,
                                        data=None,
                                        content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Rei", str(response.data))
        self.assertIn("Shinji", str(response.data))

        response = self.manager_client.get(url,
                                           data=None,
                                           content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Rei", str(response.data))
        self.assertIn("Shinji", str(response.data))

        response = self.staff_client.get(url,
                                         data=None,
                                         content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Rei", str(response.data))
        self.assertIn("Shinji", str(response.data))

    @transaction.atomic
    def test_retrieve_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a GET request to the retrieve API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_order_retrieve_update_destroy_api_endpoint',
                      args=[self.order.id]) + "?format=json"
        response = self.exec_client.get(url,
                                        data=None,
                                        content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    #-----------------------#
    # Delete API-endpoint #
    #-----------------------#

    @transaction.atomic
    def test_delete_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a DELETE request to the delete API-endpoint.
        """
        url = reverse('workery_order_retrieve_update_destroy_api_endpoint',
                      args=[self.order.id]) + "?format=json"
        response = self.unauthorized_client.delete(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        DELETE request to the delete API-endpoint.
        """
        url = reverse('workery_order_retrieve_update_destroy_api_endpoint',
                      args=[self.order.id]) + "?format=json"
        response = self.exec_client.delete(url,
                                           data=None,
                                           content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a DELETE request to the delete API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_order_retrieve_update_destroy_api_endpoint',
                      args=[self.order.id]) + "?format=json"
        response = self.exec_client.delete(url,
                                           data=None,
                                           content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))
コード例 #25
0
class APITagWithTenantSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Tenant Schema"""
        tenant.schema_name = 'galacticalliance'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks=True
        tenant.has_mentors=True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(id=constants.ENTREPRENEUR_GROUP_ID, name="Entreprenuer",),
            Group(id=constants.MENTOR_GROUP_ID, name="Mentor",),
            Group(id=constants.ADVISOR_GROUP_ID, name="Advisor",),
            Group(id=constants.ORGANIZATION_MANAGER_GROUP_ID, name="Org Manager",),
            Group(id=constants.ORGANIZATION_ADMIN_GROUP_ID, name="Org Admin",),
            Group(id=constants.CLIENT_MANAGER_GROUP_ID, name="Client Manager",),
            Group(id=constants.SYSTEM_ADMIN_GROUP_ID, name="System Admin",),
        ])
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        user.is_superuser = True
        user.is_active = True
        user.groups.add(org_admin_group)
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APITagWithTenantSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant, HTTP_AUTHORIZATION='Token ' + token.key)
        self.authorized_client.login(
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        self.tenant.owner = self.user
        self.tenant.save()

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

        # Initialize our test data.
        Tag.objects.bulk_create([
            Tag(name='1'),
            Tag(name='2'),
            Tag(name='3'),
        ])

    @transaction.atomic
    def tearDown(self):
        Tag.objects.delete_all()
        PostalAddress.objects.delete_all()
        ContactPoint.objects.delete_all()
        Me.objects.delete_all()
        users = User.objects.all()
        for user in users.all():
            user.delete()
        # super(APITagWithTenantSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_list_with_anonymous_user(self):
        response = self.unauthorized_client.get('/api/tenanttag/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_authenticated_management_group_user(self):
        response = self.authorized_client.get('/api/tenanttag/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_list_with_authenticated_advisor_group_user(self):
        # Change Group that the User belongs in.
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        advisor_group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.remove(org_admin_group)
        self.user.groups.add(advisor_group)
        self.user.save()

        # Test and verify.
        response = self.authorized_client.get('/api/tenanttag/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_post_with_anonymous_user(self):
        data = {
            'name': 'Unit Test',
        }
        response = self.unauthorized_client.post('/api/tenanttag/', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_post_with_authenticated_management_group_user(self):
        # Run the test and verify.
        data = {
            'name': 'Unit Test',
        }
        response = self.authorized_client.post('/api/tenanttag/', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    @transaction.atomic
    def test_post_with_authenticated_advisor_group_user(self):
        # Change Group that the User belongs in.
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        advisor_group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.remove(org_admin_group)
        self.user.groups.add(advisor_group)
        self.user.save()

        # Test and verify.
        data = {
            'name': 'Unit Test',
        }
        response = self.authorized_client.post('/api/tenanttag/', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_put_with_anonymous_user(self):
        # Delete any previous data.
        items = Tag.objects.all()
        for item in items.all():
            item.delete()

        # Create a new object with our specific test data.
        Tag.objects.create(
            id=1,
            name="Unit Test",
        )

        # Run the test.
        data = {
            'id': 1,
            'name': 'Unit Test',
        }
        response = self.unauthorized_client.put('/api/tenanttag/1/', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_put_with_authenticated_management_user(self):
        # Delete any previous data.
        items = Tag.objects.all()
        for item in items.all():
            item.delete()

        # Create a new object with our specific test data.
        Tag.objects.create(
            id=1,
            name="Unit Test",
        )

        # Run the test.
        data = {
            'id': 1,
            'name': 'Unit Test',
        }
        response = self.authorized_client.put('/api/tenanttag/1/', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_put_with_authenticated_advisor_user(self):
        # Change Group that the User belongs in.
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        advisor_group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.remove(org_admin_group)
        self.user.groups.add(advisor_group)
        self.user.save()

        # Delete any previous data.
        items = Tag.objects.all()
        for item in items.all():
            item.delete()

        # Create a new object with our specific test data.
        Tag.objects.create(
            id=1,
            name="Unit Test",
        )

        # Run the test.
        data = {
            'id': 1,
            'name': 'Unit Test',
        }
        response = self.authorized_client.put('/api/tenanttag/1/', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def test_delete_with_anonymous_user(self):
        response = self.unauthorized_client.delete('/api/tenanttag/1/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_authenticated_management_user(self):
        response = self.authorized_client.delete('/api/tenanttag/1/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    @transaction.atomic
    def test_delete_with_authenticated_advisor_user(self):
        # Change Group that the User belongs in.
        org_admin_group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        advisor_group = Group.objects.get(id=constants.ADVISOR_GROUP_ID)
        self.user.groups.remove(org_admin_group)
        self.user.groups.add(advisor_group)
        self.user.save()

        # Run test and verify.
        response = self.authorized_client.delete('/api/tenanttag/1/')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
コード例 #26
0
class AssociateListCreateAPIViewWithTenantTestCase(APITestCase,
                                                   TenantTestCase):
    """
    Console:
    python manage.py test tenant_api.tests.test_associate_view
    """

    #------------------#
    # Setup Unit Tests #
    #------------------#

    def setup_tenant(tenant):
        """Tenant Schema"""
        tenant.schema_name = TEST_SCHEMA_NAME
        tenant.name = 'Over 55 (London) Inc.',
        tenant.alternate_name = "Over55",
        tenant.description = "Located at the Forks of the Thames in ...",
        tenant.address_country = "CA",
        tenant.address_locality = "London",
        tenant.address_region = "Ontario",
        tenant.post_office_box_number = "",  # Post Offic #
        tenant.postal_code = "N6H 1B4",
        tenant.street_address = "78 Riverside Drive",
        tenant.street_address_extra = "",  # Extra line.

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(AssociateListCreateAPIViewWithTenantTestCase, self).setUp()

        # Load up the dependat.
        call_command('init_app', verbosity=0)
        call_command('populate_tenant_content', TEST_SCHEMA_NAME, verbosity=0)

        # Create the account.
        call_command(
            'create_tenant_account',
            TEST_SCHEMA_NAME,
            constants.MANAGEMENT_GROUP_ID,
            TEST_USER_EMAIL,
            TEST_USER_PASSWORD,
            "Bart",
            "Mika",
            TEST_USER_TEL_NUM,
            TEST_USER_TEL_EX_NUM,
            TEST_USER_CELL_NUM,
            "CA",
            "London",
            "Ontario",
            "",  # Post Offic #
            "N6H 1B4",
            "78 Riverside Drive",
            "",  # Extra line.
            verbosity=0)

        # Create the account.
        call_command(
            'create_tenant_account',
            TEST_SCHEMA_NAME,
            constants.MANAGEMENT_GROUP_ID,
            TEST_ALERNATE_USER_EMAIL,
            TEST_USER_PASSWORD,
            "Bart",
            "Mika",
            TEST_USER_TEL_NUM,
            TEST_USER_TEL_EX_NUM,
            TEST_USER_CELL_NUM,
            "CA",
            "London",
            "Ontario",
            "",  # Post Offic #
            "N6H 1B4",
            "78 Riverside Drive",
            "",  # Extra line.
            verbosity=0)

        # Initialize our test data.
        self.user = SharedUser.objects.get(email=TEST_USER_EMAIL)
        token, orig_iat = get_jwt_token_and_orig_iat(self.user)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(
            self.tenant, HTTP_AUTHORIZATION='JWT {0}'.format(token))
        self.authorized_client.login(username=TEST_USER_USERNAME,
                                     password=TEST_USER_PASSWORD)
        # Create our associate.
        connection.set_schema(TEST_SCHEMA_NAME, True)  # Switch to Tenant.
        self.associate = Associate.objects.create(owner=self.user,
                                                  given_name="Bart",
                                                  last_name="Mika")
        self.alernate_associate = Associate.objects.create(
            owner=SharedUser.objects.get(email=TEST_ALERNATE_USER_EMAIL),
            given_name="Rodolfo",
            last_name="Martinez")

    @transaction.atomic
    def tearDown(self):
        connection.set_schema(TEST_SCHEMA_NAME, True)  # Switch to Tenant.
        Associate.objects.delete_all()
        del self.unauthorized_client
        del self.authorized_client
        super(AssociateListCreateAPIViewWithTenantTestCase, self).tearDown()

    #-------------------#
    # List API-endpoint #
    #-------------------#

    @transaction.atomic
    def test_list_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a GET request to the LIST API-endpoint.
        """
        url = reverse(
            'workery_associate_list_create_api_endpoint') + "?format=json"
        response = self.unauthorized_client.get(
            url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        GET request to the list API-endpoint.
        """
        url = reverse('workery_associate_list_create_api_endpoint')
        url += "?format=json"
        response = self.authorized_client.get(url,
                                              data=None,
                                              content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Bart", str(response.data))
        self.assertIn("Mika", str(response.data))
        self.assertNotIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    @transaction.atomic
    def test_list_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a GET request to the list API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_associate_list_create_api_endpoint')
        url += "?format=json"
        response = self.authorized_client.get(url,
                                              data=None,
                                              content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    #---------------------#
    # Create API-endpoint #
    #---------------------#

    @transaction.atomic
    def test_create_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a POST request to the create API-endpoint.
        """
        url = reverse(
            'workery_associate_list_create_api_endpoint') + "?format=json"
        response = self.unauthorized_client.post(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_create_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        POST request to the create API-endpoint.
        """
        # Fetch our `SkillSet` objects.
        skill_set_1 = SkillSet.objects.filter(
            category="Carpentry", sub_category="Carpenter").first()
        skill_set_2 = SkillSet.objects.filter(
            category="Carpentry", sub_category="Deck Construction").first()
        skill_set_3 = SkillSet.objects.filter(
            category="Ceramic Tile", sub_category="Backsplash only").first()

        # Perform our tests.
        url = reverse('workery_associate_list_create_api_endpoint')
        url += "?format=json"
        response = self.authorized_client.post(
            url,
            data=json.dumps({
                'email':
                "*****@*****.**",
                'given_name':
                'Bart',
                'middle_name':
                '',
                'last_name':
                'Mika',
                'address_country':
                'CA',
                'address_locality':
                'London',
                'address_region':
                'Ontario',
                'street_address':
                '78 Riverside Drive',
                'postal_code':
                'N6H 1B4',
                'extra_comment':
                "This is a friendly associate.",
                'skill_sets': [skill_set_1.id, skill_set_2.id, skill_set_3.id],
                'telephone':
                '1231231234',
                'is_active':
                True,
                'password':
                '******',
                'password_repeat':
                '123passwordOK!',
                'description':
                'Some generic desc.',
                'telephone_type_of':
                1,
                'other_telephone_type_of':
                1,
                'is_ok_to_email':
                True,
                'is_ok_to_text':
                True,
                'vehicle_types': [],
                'tags': [],
                'hourly_salary_desired':
                666,
                'how_hear':
                1,
                'insurance_requirements': [],
                'join_date':
                '2040-01-01'
            }),
            content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIn("Bart", str(response.data))
        self.assertIn("Mika", str(response.data))
        # self.assertIn("This is a friendly associate.", str(response.data)) # If comments are included then use this.
        self.assertIn("[1, 2, 3]", str(response.data))  # Verify skill sets.

    @transaction.atomic
    def test_create_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a POST request to the list API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_associate_list_create_api_endpoint')
        url += "?format=json"
        response = self.authorized_client.post(url,
                                               data=json.dumps({}),
                                               content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    #---------------------#
    # Update API-endpoint #
    #---------------------#

    @transaction.atomic
    def test_update_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a PUT request to the update API-endpoint.
        """
        url = reverse('workery_associate_retrieve_update_destroy_api_endpoint',
                      args=[self.associate.id]) + "?format=json"
        response = self.unauthorized_client.post(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_update_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        PUT request to the update API-endpoint.
        """
        # Fetch our `SkillSet` objects.
        skill_set_1 = SkillSet.objects.filter(
            category="Carpentry", sub_category="Carpenter").first()
        skill_set_2 = SkillSet.objects.filter(
            category="Carpentry", sub_category="Deck Construction").first()
        skill_set_3 = SkillSet.objects.filter(
            category="Ceramic Tile", sub_category="Backsplash only").first()

        # Perform our tests.
        url = reverse('workery_associate_retrieve_update_destroy_api_endpoint',
                      args=[self.associate.id]) + "?format=json"
        response = self.authorized_client.put(
            url,
            data=json.dumps({
                'given_name':
                'Bartlomiej',
                'middle_name':
                '',
                'last_name':
                'Mika',
                'address_country':
                'CA',
                'address_locality':
                'London',
                'address_region':
                'Ontario',
                'street_address':
                '78 Riverside Drive',
                'postal_code':
                'N6H 1B4',
                'extra_comment':
                "This is a helpful associate.",
                'skill_sets': [skill_set_1.id, skill_set_2.id, skill_set_3.id],
                'telephone':
                '1231231234',
                'is_active':
                True,
                'password':
                '******',
                'password_repeat':
                '123passwordOK!',
                'description':
                'Some generic desc.',
                'telephone_type_of':
                1,
                'other_telephone_type_of':
                1,
                'is_ok_to_email':
                True,
                'is_ok_to_text':
                True,
                'vehicle_types': [],
                'tags': [],
                'email':
                '*****@*****.**',
                'hourly_salary_desired':
                666,
                'how_hear':
                1,
                'insurance_requirements': [],
                'join_date':
                '2040-01-01'
            }),
            content_type='application/json')
        self.assertIsNotNone(response)
        # print(response.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Bartlomiej", str(response.data))
        self.assertIn("Mika", str(response.data))
        # self.assertIn("This is a friendly associate.", str(response.data)) # If comments are included then use this.
        self.assertIn("[1, 2, 3]", str(response.data))  # Verify skill sets.

    @transaction.atomic
    def test_update_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a PUT request to the update API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_associate_retrieve_update_destroy_api_endpoint',
                      args=[self.alernate_associate.id]) + "?format=json"
        response = self.authorized_client.put(url,
                                              data=json.dumps({}),
                                              content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    @transaction.atomic
    def test_update_with_200_by_ownership(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a PUT request to the update API-endpoint but has ownership of the
        object.
        """
        # Fetch our `SkillSet` objects.
        skill_set_1 = SkillSet.objects.filter(
            category="Carpentry", sub_category="Carpenter").first()
        skill_set_2 = SkillSet.objects.filter(
            category="Carpentry", sub_category="Deck Construction").first()
        skill_set_3 = SkillSet.objects.filter(
            category="Ceramic Tile", sub_category="Backsplash only").first()

        # Perform our tests.
        Permission.objects.all().delete()
        url = reverse('workery_associate_retrieve_update_destroy_api_endpoint',
                      args=[self.associate.id]) + "?format=json"
        response = self.authorized_client.put(
            url,
            data=json.dumps({
                'given_name':
                'Bartlomiej',
                'middle_name':
                '',
                'last_name':
                'Mika',
                'address_country':
                'CA',
                'address_locality':
                'London',
                'address_region':
                'Ontario',
                'street_address':
                '78 Riverside Drive',
                'postal_code':
                'N6H 1B4',
                'extra_comment':
                "This is a helpful associate.",
                'skill_sets': [skill_set_1.id, skill_set_2.id, skill_set_3.id],
                'telephone':
                '1231231234',
                'is_active':
                True,
                'password':
                '******',
                'password_repeat':
                '123passwordOK!',
                'description':
                'Some generic desc.',
                'telephone_type_of':
                1,
                'other_telephone_type_of':
                1,
                'is_ok_to_email':
                True,
                'is_ok_to_text':
                True,
                'vehicle_types': [],
                'tags': [],
                'email':
                '*****@*****.**',
                'hourly_salary_desired':
                666,
                'insurance_requirements': [],
                'join_date':
                '2040-01-01'
            }),
            content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Bartlomiej", str(response.data))
        self.assertIn("Mika", str(response.data))
        # self.assertIn("This is a friendly associate.", str(response.data)) # If comments are included then use this.
        self.assertIn("[1, 2, 3]", str(response.data))  # Verify skill sets.

    # # #-----------------------#
    # Retrieve API-endpoint #
    #-----------------------#

    @transaction.atomic
    def test_retrieve_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a GET request to the retrieve API-endpoint.
        """
        url = reverse('workery_associate_retrieve_update_destroy_api_endpoint',
                      args=[self.associate.id]) + "?format=json"
        response = self.unauthorized_client.get(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_retrieve_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        GET request to the retrieve API-endpoint.
        """
        url = reverse('workery_associate_retrieve_update_destroy_api_endpoint',
                      args=[self.associate.id]) + "?format=json"
        response = self.authorized_client.get(url,
                                              data=None,
                                              content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Bart", str(response.data))
        self.assertIn("Mika", str(response.data))

    @transaction.atomic
    def test_retrieve_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a GET request to the retrieve API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_associate_retrieve_update_destroy_api_endpoint',
                      args=[self.alernate_associate.id]) + "?format=json"
        response = self.authorized_client.get(url,
                                              data=None,
                                              content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    @transaction.atomic
    def test_retrieve_with_200_by_ownership(self):
        """
        Unit test will test authenticated user, who does not have permission,
        but is the OWNER of the object to make a GET request to the retrieve
        API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_associate_retrieve_update_destroy_api_endpoint',
                      args=[self.associate.id]) + "?format=json"
        response = self.authorized_client.get(url,
                                              data=None,
                                              content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("Bart", str(response.data))
        self.assertIn("Mika", str(response.data))

    #-----------------------#
    # Delete API-endpoint #
    #-----------------------#

    @transaction.atomic
    def test_delete_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a DELETE request to the delete API-endpoint.
        """
        url = reverse('workery_associate_retrieve_update_destroy_api_endpoint',
                      args=[self.associate.id]) + "?format=json"
        response = self.unauthorized_client.delete(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        DELETE request to the delete API-endpoint.
        """
        # Add executive group so you can delete.
        self.user.groups.add(constants.EXECUTIVE_GROUP_ID)

        # Go ahead and delete.
        url = reverse('workery_associate_retrieve_update_destroy_api_endpoint',
                      args=[self.associate.id]) + "?format=json"
        response = self.authorized_client.delete(
            url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a DELETE request to the delete API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_associate_retrieve_update_destroy_api_endpoint',
                      args=[self.associate.id]) + "?format=json"
        response = self.authorized_client.delete(
            url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))
コード例 #27
0
class APIMeWithTenantSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Tenant Schema"""
        tenant.schema_name = 'galacticalliance'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks=True
        tenant.has_mentors=True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(id=constants.ENTREPRENEUR_GROUP_ID, name="Entreprenuer",),
            Group(id=constants.MENTOR_GROUP_ID, name="Mentor",),
            Group(id=constants.ADVISOR_GROUP_ID, name="Advisor",),
            Group(id=constants.ORGANIZATION_MANAGER_GROUP_ID, name="Org Manager",),
            Group(id=constants.ORGANIZATION_ADMIN_GROUP_ID, name="Org Admin",),
            Group(id=constants.CLIENT_MANAGER_GROUP_ID, name="Client Manager",),
            Group(id=constants.SYSTEM_ADMIN_GROUP_ID, name="System Admin",),
        ])
        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APIMeWithTenantSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant, HTTP_AUTHORIZATION='Token ' + token.key)
        self.authorized_client.login(
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD
        )
        self.tenant.owner = self.user
        self.tenant.save()

        # Above taken from:
        # http://www.django-rest-framework.org/api-guide/testing/#authenticating

    @transaction.atomic
    def tearDown(self):
        PostalAddress.objects.delete_all()
        ContactPoint.objects.delete_all()
        Intake.objects.delete_all()
        Me.objects.delete_all()
        items = User.objects.all()
        for item in items.all():
            item.delete()
        # super(APIMeWithTenantSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_list(self):
        response = self.unauthorized_client.get('/api/tenantme/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_authentication(self):
        response = self.authorized_client.get('/api/tenantme/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_post_with_anonymous_user(self):
        data = {
            'owner': self.user.id
        }
        response = self.unauthorized_client.post('/api/tenantme/', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_post_with_authenticated_owner(self):
        data = {
            'owner': self.user.id,
        }
        response = self.authorized_client.post(
            '/api/tenantme/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    @transaction.atomic
    def test_put(self):
        # Delete any previous data.
        items = Me.objects.delete_all()

        # Create a new object with our specific test data.
        Me.objects.create(
            id=1,
            owner=self.user,
        )

        # Run the test.
        data = {
            'id': 1,
            'owner': self.user.id
        }
        response = self.unauthorized_client.put('/api/tenantme/1/', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_put_with_authorization(self):
        # Create a new object with our specific test data.
        address = PostalAddress.objects.create(
            owner=self.user,
            name='User #' + str(self.user.id) + ' Address',
        )
        contact_point = ContactPoint.objects.create(
            owner=self.user,
            name='User #' + str(self.user.id) + ' Contact Point',
        )
        Me.objects.create(
            id=1,
            owner_id=self.user.id,
            address=address,
            contact_point=contact_point,
        )

        # Run the test.
        data = {
            'id': 1,
            'owner': self.user.id,
            'address': address.id,
            'contact_point': contact_point.id
        }
        response = self.authorized_client.put('/api/tenantme/1/', json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete(self):
        response = self.unauthorized_client.delete('/api/tenantme/1/')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_authentication_case_one(self):
        address = PostalAddress.objects.create(
            id=1,
            owner=self.user,
        )
        contact_point = ContactPoint.objects.create(
            id=1,
            owner=self.user,
        )
        me = Me.objects.create(
            id=666,
            owner=self.user,
        )
        Intake.objects.create(
            id=1,
            me=me,
        )
        response = self.authorized_client.delete('/api/tenantme/'+str(me.id)+'/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    @transaction.atomic
    def test_delete_with_authentication_case_two(self):
        me = Me.objects.create(
            id=666,
            owner=self.user,
        )
        response = self.authorized_client.delete('/api/tenantme/'+str(me.id)+'/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

    @transaction.atomic
    def test_delete_with_authentication_case_three(self):
        group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        self.user.groups.add(group)
        me = Me.objects.create(
            id=999,
            owner=self.user,
        )
        response = self.authorized_client.delete('/api/tenantme/'+str(me.id)+'/')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_admit_me_with_entrepreneur_user(self):
        # Setup our object.
        Me.objects.create(
            id=1,
            owner=self.user,
            is_in_intake=False,
        )

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantme/1/admit_me/',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        me = Me.objects.get(id=1)
        self.assertFalse(me.is_in_intake)

    @transaction.atomic
    def test_admit_me_with_org_manager_user(self):
        # Setup our object.
        Me.objects.create(
            id=1,
            owner=self.user,
            is_in_intake=False,
        )
        group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        self.user.groups.add(group)
        self.user.save()

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantme/1/admit_me/',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        me = Me.objects.get(id=1)
        self.assertTrue(me.is_in_intake)

    @transaction.atomic
    def test_expel_me_with_entrepreneur_user(self):
        # Setup our object.
        Me.objects.create(
            id=1,
            owner=self.user,
            is_in_intake=True,
        )

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantme/1/expel_me/',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        me = Me.objects.get(id=1)
        self.assertTrue(me.is_in_intake)

    @transaction.atomic
    def test_expel_me_with_org_manager_user(self):
        # Setup our object.
        Me.objects.create(
            id=1,
            owner=self.user,
            is_in_intake=True,
        )
        group = Group.objects.get(id=constants.ORGANIZATION_ADMIN_GROUP_ID)
        self.user.groups.add(group)
        self.user.save()

        # Run the test and verify.
        response = self.authorized_client.put(
            '/api/tenantme/1/expel_me/',
            json.dumps({}),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        me = Me.objects.get(id=1)
        self.assertFalse(me.is_in_intake)

    @transaction.atomic
    def test_unlock_with_success(self):
        # Delete any previous data.
        items = Me.objects.delete_all()

        # Create a new object with our specific test data.
        Me.objects.create(
            id=1,
            owner=self.user,
            is_locked=False,
        )

        # Run the test.
        data = {
            'id': 1,
            'owner': self.user.id,
            'password': TEST_USER_PASSWORD
        }
        response = self.authorized_client.put(
            '/api/tenantme/1/unlock_me/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_unlock_with_missing_password(self):
        # Delete any previous data.
        items = Me.objects.delete_all()

        # Create a new object with our specific test data.
        Me.objects.create(
            id=1,
            owner=self.user,
        )

        # Run the test.
        data = {
            'id': 1,
            'owner': self.user.id,
        }
        response = self.authorized_client.put(
            '/api/tenantme/1/unlock_me/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_unlock_with_wrong_password(self):
        # Delete any previous data.
        items = Me.objects.delete_all()

        # Create a new object with our specific test data.
        Me.objects.create(
            id=1,
            owner=self.user,
        )

        # Run the test.
        data = {
            'id': 1,
            'owner': self.user.id,
            'password': '******',
        }
        response = self.authorized_client.put(
            '/api/tenantme/1/unlock_me/',
            json.dumps(data),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
コード例 #28
0
class APIFunctionViewSetWithPublicSchemaTestCase(APITestCase, TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Public Schema"""
        tenant.schema_name = 'test'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])
        user = User.objects.create_user(  # Create our User.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English.
        super(APIFunctionViewSetWithPublicSchemaTestCase, self).setUp()

        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(
            self.tenant,
            HTTP_AUTHORIZATION='Token ' + token.key,
            format='json',
        )

    @transaction.atomic
    def tearDown(self):
        users = User.objects.all()
        for user in users.all():
            user.delete()
        tokens = Token.objects.all()
        super(APIFunctionViewSetWithPublicSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_api_function_is_email_unique_with_true(self):
        # Log in the the account.
        user = User.objects.get()
        token = Token.objects.get(user_id=user.id)

        # Begin this unit test.
        url = reverse('api_function_isemailunique')
        data = {'email': TEST_USER_EMAIL}
        response = self.authorized_client.post(url,
                                               json.dumps(data),
                                               HTTP_AUTHORIZATION='Token ' +
                                               token.key,
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn(b'is_unique', response.content)
        self.assertIn(b'false', response.content)

    @transaction.atomic
    def test_api_function_is_email_unique_with_false(self):
        # Log in the the account.
        user = User.objects.get()
        token = Token.objects.get(user_id=user.id)

        # Begin this unit test.
        url = reverse('api_function_isemailunique')
        data = {
            'email': '*****@*****.**',
        }
        response = self.authorized_client.post(url,
                                               json.dumps(data),
                                               HTTP_AUTHORIZATION='Token ' +
                                               token.key,
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn(b'is_unique', response.content)
        self.assertIn(b'true', response.content)

    @transaction.atomic
    def test_api_function_is_email_unique_with_400(self):
        # Log in the the account.
        user = User.objects.get()
        token = Token.objects.get(user_id=user.id)

        # Begin this unit test.
        url = reverse('api_function_isemailunique')
        data = {
            'password': '******',
        }
        response = self.authorized_client.post(url,
                                               json.dumps(data),
                                               HTTP_AUTHORIZATION='Token ' +
                                               token.key,
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertIn(b'email', response.content)
        self.assertIn(b'This field is required.', response.content)

    @transaction.atomic
    def test_api_function_is_email_unique_with_401(self):
        # Begin this unit test.
        url = reverse('api_function_isemailunique')
        data = {'email': TEST_USER_EMAIL}
        response = self.unauthorized_client.post(
            url,
            json.dumps(data),
            HTTP_AUTHORIZATION='Token 123',
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_api_function_is_organization_schema_name_unique(self):
        # Log in the the account.
        user = User.objects.get()
        token = Token.objects.get(user_id=user.id)

        # Begin this unit test.
        url = reverse('api_function_is_organization_schema_name_unique')
        data = {'name': 'test'}
        response = self.authorized_client.post(url,
                                               json.dumps(data),
                                               HTTP_AUTHORIZATION='Token ' +
                                               token.key,
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn(b'is_unique', response.content)
        self.assertIn(b'true', response.content)
コード例 #29
0
class TagListCreateAPIViewWithTenantTestCase(APITestCase, TenantTestCase):
    """
    Console:
    python manage.py test tenant_api.tests.test_tag_views
    """

    #------------------#
    # Setup Unit Tests #
    #------------------#

    def setup_tenant(tenant):
        """Tenant Schema"""
        tenant.schema_name = TEST_SCHEMA_NAME
        tenant.name = 'Over 55 (London) Inc.',
        tenant.alternate_name = "Over55",
        tenant.description = "Located at the Forks of the Thames in ...",
        tenant.address_country = "CA",
        tenant.address_locality = "London",
        tenant.address_region = "Ontario",
        tenant.post_office_box_number = "",  # Post Offic #
        tenant.postal_code = "N6H 1B4",
        tenant.street_address = "78 Riverside Drive",
        tenant.street_address_extra = "",  # Extra line.

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(TagListCreateAPIViewWithTenantTestCase, self).setUp()

        # Load up the dependat.
        call_command('init_app', verbosity=0)
        call_command('populate_tenant_content', TEST_SCHEMA_NAME, verbosity=0)
        call_command('populate_tenant_sample_db',
                     TEST_SCHEMA_NAME,
                     verbosity=0)

        # Get objects.
        self.customer = Customer.objects.get(owner__email='*****@*****.**')
        self.associate = Associate.objects.get(
            owner__email='*****@*****.**')

        # Get users.
        exec_user = SharedUser.objects.get(email='*****@*****.**')
        manager_user = SharedUser.objects.get(email='*****@*****.**')
        frontline_user = SharedUser.objects.get(email='*****@*****.**')
        associate_user = SharedUser.objects.get(email='*****@*****.**')
        customer_user = SharedUser.objects.get(email='*****@*****.**')

        # Get tokens.
        exec_token, exec_orig_iat = get_jwt_token_and_orig_iat(exec_user)
        manager_token, manager_orig_iat = get_jwt_token_and_orig_iat(
            manager_user)
        frontline_token, frontline_orig_iat = get_jwt_token_and_orig_iat(
            frontline_user)
        associate_token, associate_orig_iat = get_jwt_token_and_orig_iat(
            associate_user)
        customer_token, customer_orig_iat = get_jwt_token_and_orig_iat(
            customer_user)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.exec_client = TenantClient(
            self.tenant, HTTP_AUTHORIZATION='JWT {0}'.format(exec_token))
        self.exec_client.login(username='******',
                               password=TEST_USER_PASSWORD)
        self.manager_client = TenantClient(
            self.tenant, HTTP_AUTHORIZATION='JWT {0}'.format(manager_token))
        self.manager_client.login(username='******',
                                  password=TEST_USER_PASSWORD)
        self.staff_client = TenantClient(
            self.tenant, HTTP_AUTHORIZATION='JWT {0}'.format(manager_token))
        self.staff_client.login(username='******',
                                password=TEST_USER_PASSWORD)
        self.customer_client = TenantClient(
            self.tenant, HTTP_AUTHORIZATION='JWT {0}'.format(manager_token))
        self.customer_client.login(username='******',
                                   password=TEST_USER_PASSWORD)
        self.tag = Tag.objects.create(text="Some generic text")

    @transaction.atomic
    def tearDown(self):
        connection.set_schema(TEST_SCHEMA_NAME, True)  # Switch to Tenant.
        Tag.objects.delete_all()
        del self.unauthorized_client
        del self.exec_client
        del self.manager_client
        del self.staff_client
        del self.customer_client
        super(TagListCreateAPIViewWithTenantTestCase, self).tearDown()

    #-------------------#
    # List API-endpoint #
    #-------------------#

    @transaction.atomic
    def test_list_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a GET request to the LIST API-endpoint.
        """
        url = reverse('workery_tag_list_create_api_endpoint') + "?format=json"
        response = self.unauthorized_client.get(
            url, data=None, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        GET request to the list API-endpoint.
        """
        url = reverse('workery_tag_list_create_api_endpoint')
        url += "?format=json"

        # Executive
        response = self.exec_client.get(url,
                                        data=None,
                                        content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Manager
        response = self.manager_client.get(url,
                                           data=None,
                                           content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Staff
        response = self.staff_client.get(url,
                                         data=None,
                                         content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_list_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a GET request to the list API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_tag_list_create_api_endpoint')
        url += "?format=json"
        response = self.customer_client.get(url,
                                            data=None,
                                            content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    #---------------------#
    # Create API-endpoint #
    #---------------------#

    @transaction.atomic
    def test_create_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a POST request to the create API-endpoint.
        """
        url = reverse('workery_tag_list_create_api_endpoint') + "?format=json"
        response = self.unauthorized_client.post(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_create_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        POST request to the create API-endpoint.
        """
        url = reverse('workery_tag_list_create_api_endpoint')
        url += "?format=json"

        # Executive
        response = self.exec_client.post(url,
                                         data=json.dumps({
                                             'text':
                                             'generic text',
                                         }),
                                         content_type='application/json')
        self.assertIsNotNone(response)
        # print(response.content)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIn("generic text", str(response.data))

        # Manager
        response = self.manager_client.post(url,
                                            data=json.dumps({
                                                'text':
                                                'generic text #2',
                                            }),
                                            content_type='application/json')
        self.assertIsNotNone(response)
        # print(response.content)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIn("#2", str(response.data))

        # Staff
        response = self.staff_client.post(url,
                                          data=json.dumps({
                                              'text':
                                              'generic text #3',
                                          }),
                                          content_type='application/json')
        self.assertIsNotNone(response)
        # print(response)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIn("#3", str(response.data))

    @transaction.atomic
    def test_create_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a POST request to the list API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_tag_list_create_api_endpoint')
        url += "?format=json"
        response = self.customer_client.post(url,
                                             data=json.dumps({}),
                                             content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    #---------------------#
    # Update API-endpoint #
    #---------------------#

    @transaction.atomic
    def test_update_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a PUT request to the update API-endpoint.
        """
        url = reverse('workery_tag_retrieve_update_destroy_api_endpoint',
                      args=[self.tag.id]) + "?format=json"
        response = self.unauthorized_client.post(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_update_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        PUT request to the update API-endpoint.
        """
        url = reverse('workery_tag_retrieve_update_destroy_api_endpoint',
                      args=[self.tag.id]) + "?format=json"
        data = json.dumps({
            'text': 'generic text #1',
        })

        # Executive
        response = self.exec_client.put(url,
                                        data=data,
                                        content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("generic text #1", str(response.data))

        # Manager
        response = self.manager_client.put(url,
                                           data=data,
                                           content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("generic text #1", str(response.data))

        # Staff
        response = self.staff_client.put(url,
                                         data=data,
                                         content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("generic text #1", str(response.data))

    @transaction.atomic
    def test_update_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a PUT request to the update API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_tag_retrieve_update_destroy_api_endpoint',
                      args=[self.tag.id]) + "?format=json"
        data = json.dumps({
            'text': 'generic text',
        })
        response = self.customer_client.put(url,
                                            data=data,
                                            content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    #-----------------------#
    # Retrieve API-endpoint #
    #-----------------------#

    @transaction.atomic
    def test_retrieve_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a GET request to the retrieve API-endpoint.
        """
        url = reverse('workery_tag_retrieve_update_destroy_api_endpoint',
                      args=[self.tag.id]) + "?format=json"
        response = self.unauthorized_client.get(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_retrieve_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        GET request to the retrieve API-endpoint.
        """
        url = reverse('workery_tag_retrieve_update_destroy_api_endpoint',
                      args=[self.tag.id]) + "?format=json"

        response = self.exec_client.get(url,
                                        data=None,
                                        content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("generic text", str(response.data))

        response = self.manager_client.get(url,
                                           data=None,
                                           content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("generic text", str(response.data))

        response = self.staff_client.get(url,
                                         data=None,
                                         content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("generic text", str(response.data))

    @transaction.atomic
    def test_retrieve_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a GET request to the retrieve API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_tag_retrieve_update_destroy_api_endpoint',
                      args=[self.tag.id]) + "?format=json"
        response = self.exec_client.get(url,
                                        data=None,
                                        content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))

    #-----------------------#
    # Delete API-endpoint #
    #-----------------------#

    @transaction.atomic
    def test_delete_with_401_by_permissions(self):
        """
        Unit test will test anonymous make a DELETE request to the delete API-endpoint.
        """
        url = reverse('workery_tag_retrieve_update_destroy_api_endpoint',
                      args=[self.tag.id]) + "?format=json"
        response = self.unauthorized_client.delete(
            url, data={}, content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_delete_with_200_by_permissions(self):
        """
        Unit test will test authenticated user, who has permission, to make a
        DELETE request to the delete API-endpoint.
        """
        url = reverse('workery_tag_retrieve_update_destroy_api_endpoint',
                      args=[self.tag.id]) + "?format=json"
        response = self.exec_client.delete(url,
                                           data=None,
                                           content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_delete_with_403_by_permissions(self):
        """
        Unit test will test authenticated user, who does not have permission, to
        make a DELETE request to the delete API-endpoint.
        """
        Permission.objects.all().delete()
        url = reverse('workery_tag_retrieve_update_destroy_api_endpoint',
                      args=[self.tag.id]) + "?format=json"
        response = self.exec_client.delete(url,
                                           data=None,
                                           content_type='application/json')
        self.assertIsNotNone(response)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertIn(
            "You do not have permission to access this API-endpoint.",
            str(response.data))
コード例 #30
0
class APIPublicOrganizationWithPublicSchemaTestCase(APITestCase,
                                                    TenantTestCase):
    fixtures = []

    def setup_tenant(self, tenant):
        """Public Schema"""
        tenant.schema_name = 'test'
        tenant.name = "Galactic Alliance of Humankind"
        tenant.has_perks = True
        tenant.has_mentors = True
        tenant.how_discovered = "Command HQ"
        tenant.how_many_served = 1

    @classmethod
    def setUpTestData(cls):
        Group.objects.bulk_create([
            Group(
                id=constants.ENTREPRENEUR_GROUP_ID,
                name="Entreprenuer",
            ),
            Group(
                id=constants.MENTOR_GROUP_ID,
                name="Mentor",
            ),
            Group(
                id=constants.ADVISOR_GROUP_ID,
                name="Advisor",
            ),
            Group(
                id=constants.ORGANIZATION_MANAGER_GROUP_ID,
                name="Org Manager",
            ),
            Group(
                id=constants.ORGANIZATION_ADMIN_GROUP_ID,
                name="Org Admin",
            ),
            Group(
                id=constants.CLIENT_MANAGER_GROUP_ID,
                name="Client Manager",
            ),
            Group(
                id=constants.SYSTEM_ADMIN_GROUP_ID,
                name="System Admin",
            ),
        ])

        user = User.objects.create_user(  # Create our user.
            email=TEST_USER_EMAIL,
            username=TEST_USER_USERNAME,
            password=TEST_USER_PASSWORD)
        user.is_active = True
        user.save()

    @transaction.atomic
    def setUp(self):
        translation.activate('en')  # Set English
        super(APIPublicOrganizationWithPublicSchemaTestCase, self).setUp()

        # Initialize our test data.
        self.user = User.objects.get()
        token = Token.objects.get(user__username=TEST_USER_USERNAME)

        # Setup.
        self.unauthorized_client = TenantClient(self.tenant)
        self.authorized_client = TenantClient(self.tenant,
                                              HTTP_AUTHORIZATION='Token ' +
                                              token.key)
        self.authorized_client.login(username=TEST_USER_USERNAME,
                                     password=TEST_USER_PASSWORD)
        self.tenant.owner = self.user
        self.tenant.save()

    @transaction.atomic
    def tearDown(self):
        super(APIPublicOrganizationWithPublicSchemaTestCase, self).tearDown()

    @transaction.atomic
    def test_list(self):
        response = self.unauthorized_client.get(
            reverse('publicorganization-list'))
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_list_with_authentication(self):
        response = self.authorized_client.get('/api/publicorganization/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    @transaction.atomic
    def test_post(self):
        data = {
            'schema_name': 'galacticalliance',
            'name': 'Galactic Alliance of Humankind',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.unauthorized_client.post(
            '/api/publicorganization/',
            json.dumps(data),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    @transaction.atomic
    def test_post_with_upper_case_schema_name(self):
        data = {
            'schema_name': 'GalacticAlliance',
            'name': 'Galactic Alliance of Humankind',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.authorized_client.post('/api/publicorganization/',
                                               json.dumps(data),
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_post_with_non_alpha_schema_name(self):
        data = {
            'schema_name': 'ak47',
            'name': 'Galactic Alliance of Humankind',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.authorized_client.post('/api/publicorganization/',
                                               json.dumps(data),
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_post_with_special_characters_in_schema_name(self):
        data = {
            'schema_name': '*****@*****.**',
            'name': 'Galactic Alliance of Humankind',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.authorized_client.post('/api/publicorganization/',
                                               json.dumps(data),
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_post_with_whitespace_in_schema_name(self):
        data = {
            'schema_name': 'galactic alliance',
            'name': 'Galactic Alliance of Humankind',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.authorized_client.post('/api/publicorganization/',
                                               json.dumps(data),
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_post_with_reserved_word_in_schema_name(self):
        data = {
            'schema_name': 'api',
            'name': 'Galactic Alliance of Humankind',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.authorized_client.post('/api/publicorganization/',
                                               json.dumps(data),
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def test_post_with_banned_word_in_schema_name(self):
        # Create our BannedWord
        BannedWord.objects.create(
            text='hideauze',
            reason='They are the enemoy of humankind',
        )

        # Run our test and verify.
        data = {
            'schema_name': 'hideauze',
            'name': 'Galactic Alliance of Humankind',
            'description': 'Used for unit testing purposes.',
            'owner': self.user.id
        }
        response = self.authorized_client.post('/api/publicorganization/',
                                               json.dumps(data),
                                               content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)