Пример #1
0
class RoleEndpointTest(TestCase):
	def setUp(self):
		self.client = APIClient()

		self.user = User.objects.create_user("Foo", "Bar", "*****@*****.**", "123456")
		self.dev_user = User.objects.create_user("Foo", "Bar1", "*****@*****.**", "123456")

		self.application = Application(
                    name="Test Application",
                    user=self.dev_user,
                    client_type=Application.CLIENT_PUBLIC,
                    authorization_grant_type=Application.GRANT_PASSWORD,
                )
		self.application.save()

		self.token = AccessToken(
					token="ABC123",
					user=self.user,
					expires=datetime.datetime.now() + datetime.timedelta(days=1),
					scope='read write',
					application=self.application
				)
		self.token.save()

		self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token.token)

	def tearDown(self):
		self.application.delete()
		self.token.delete()
		self.user.delete()
		self.dev_user.delete()
Пример #2
0
class AccessTokenTest(TestCaseUtils, TestCase):
	def setUp(self):
		self.client = APIClient()

		self.user = User.objects.create_user("Foo", "Bar", "*****@*****.**", "123456")
		self.user.is_active = True
		self.user.save()
		self.dev_user = User.objects.create_user("Foo", "Bar1", "*****@*****.**", "123456")

		settings._SCOPES = ['read', 'write']
		settings._DEFAULT_SCOPES = ['read', 'write']

		self.application = Application(
                    name="Test Application",
                    user=self.dev_user,
                    client_type=Application.CLIENT_PUBLIC,
                    authorization_grant_type=Application.GRANT_PASSWORD,
                )
		self.application.save()

	def tearDown(self):
		self.application.delete()
		self.user.delete()
		self.dev_user.delete()

	def test_get_token(self):
	    """
	    Request an access token using Resource Owner Password Flow
	    """
	    token_request_data = {
		    'grant_type': 'password',
		    'username': '******',
		    'password': '******'
	    }

	    auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)

	    response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
	    content = json.loads(response.content.decode("utf-8"))
	    self.assertTrue('access_token' in content)
	    self.assertTrue('refresh_token' in content)
Пример #3
0
class ClientCredentialTest(TestCaseUtils, TestCase):
	def setUp(self):
		self.client = APIClient()

		self.test_user = User.objects.create_user("Edwin", "J", "*****@*****.**", "123456")

		self.application = Application(
			name="Test Application Client Credentials",
			redirect_uris="http://127.0.0.1:8000/api/",
			user=self.test_user,
			client_type=Application.CLIENT_PUBLIC,
			authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS,
			)
		self.application.save()

	def tearDown(self):
		self.test_user.delete()
		self.application.delete()

	def test_client_credentials_access_allowed(self):
		token_request_data = {'grant_type': 'client_credentials'}
		
		auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)

		response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
		self.assertEqual(response.status_code, 200)

		content = json.loads(response.content.decode("utf-8"))

		self.assertTrue('access_token' in content)
		access_token = content['access_token']

	def test_client_credentials_access_not_allowed(self):
		token_request_data = {'grant_type': 'client_credentials'}

		response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data)
		self.assertEqual(response.status_code, 401)

		content = json.loads(response.content.decode("utf-8"))
		self.assertTrue('invalid_client', content['error'])
Пример #4
0
class PostsTest(APITestCase):
    create_post_data = dict()
    update_post_data = dict()

    def setUp(self):
        self.client = APIClient()
        self.test_user = User.objects.create_user(
            first_name='test',
            last_name='user',
            username='******',
            email='*****@*****.**',
            password='******',
        )
        self.application = Application(
            name="Test Application",
            redirect_uris="http://*****:*****@tag('posts')
    def test_posts(self):
        tok = AccessToken.objects.create(user=self.test_user,
                                         token='1234567890',
                                         application=self.application,
                                         scope='read write',
                                         expires=timezone.now() +
                                         datetime.timedelta(days=1))
        auth_headers = {
            'HTTP_AUTHORIZATION': 'Bearer ' + tok.token,
        }
        make_writer_response = self.client.post(
            reverse('users:test_make_writer',
                    kwargs={'username': self.test_user.username}),
            **auth_headers)
        self.assertEquals(make_writer_response.status_code, status.HTTP_200_OK)
        with open(
                os.path.join(os.path.dirname(__file__),
                             'test_images/create_post.png'),
                'rb') as create_post_image:
            self.create_post_data = {
                'post_heading': 'This is a test heading',
                'post_heading_image': create_post_image,
                'post_body': 'This is a test body.',
                'read_duration': '1',
                'tag': 'UX',
            }
            create_post_response = self.client.post(
                reverse('posts:create_post'),
                data=self.create_post_data,
                **auth_headers)
            self.assertEquals(create_post_response.status_code,
                              status.HTTP_200_OK)
        tag_posts_response = self.client.get(
            reverse('posts:view_tag_posts', kwargs={'tag_name': 'UX'}),
            **auth_headers)
        self.assertEquals(tag_posts_response.status_code, status.HTTP_200_OK)
        with open(
                os.path.join(os.path.dirname(__file__),
                             'test_images/update_post.png'),
                'rb') as update_post_image:
            self.update_post_data = {
                'post_heading': 'This is an update of test heading',
                'post_heading_image': update_post_image,
                'post_body': 'This is an update of test body.',
                'read_duration': '1.5',
                'tag': 'Machine learning',
            }
            update_post_response = self.client.post(reverse(
                'posts:update_post',
                kwargs={'slug': tag_posts_response.json()[0]['slug']}),
                                                    data=self.update_post_data,
                                                    **auth_headers)
            self.assertEquals(update_post_response.status_code,
                              status.HTTP_200_OK)
        os.remove(settings.BASE_DIR + tag_posts_response.json()[0]
                  ['post_heading_image'].replace(settings.DOMAIN_URL, ''))
        delete_post_response = self.client.post(
            reverse('posts:delete_post',
                    kwargs={'slug': tag_posts_response.json()[0]['slug']}),
            **auth_headers)
        self.assertEquals(delete_post_response.status_code, status.HTTP_200_OK)

    @tag('ratings')
    def test_ratings(self):
        tok = AccessToken.objects.create(user=self.test_user,
                                         token='1234567890',
                                         application=self.application,
                                         scope='read write',
                                         expires=timezone.now() +
                                         datetime.timedelta(days=1))
        auth_headers = {
            'HTTP_AUTHORIZATION': 'Bearer ' + tok.token,
        }
        make_writer_response = self.client.post(
            reverse('users:test_make_writer',
                    kwargs={'username': self.test_user.username}),
            **auth_headers)
        self.assertEquals(make_writer_response.status_code, status.HTTP_200_OK)
        with open(
                os.path.join(os.path.dirname(__file__),
                             'test_images/create_post.png'),
                'rb') as create_post_image:
            self.create_post_data = {
                'post_heading': 'This is a test heading',
                'post_heading_image': create_post_image,
                'post_body': 'This is a test body.',
                'read_duration': '1',
                'tag': 'UX',
            }
            create_post_response = self.client.post(
                reverse('posts:create_post'),
                data=self.create_post_data,
                **auth_headers)
            self.assertEquals(create_post_response.status_code,
                              status.HTTP_200_OK)
        tag_posts_response = self.client.get(
            reverse('posts:view_tag_posts', kwargs={'tag_name': 'UX'}),
            **auth_headers)
        self.assertEquals(tag_posts_response.status_code, status.HTTP_200_OK)
        view_post_response = self.client.get(
            reverse(
                'posts:view_post',
                kwargs={
                    'username':
                    tag_posts_response.json()[0]['post_author']['username'],
                    'slug':
                    tag_posts_response.json()[0]['slug']
                }), **auth_headers)
        self.assertEquals(view_post_response.status_code, status.HTTP_200_OK)
        like_post_response = self.client.post(reverse(
            'posts:rate_post',
            kwargs={'slug': tag_posts_response.json()[0]['slug']}),
                                              data={'rating': 1},
                                              **auth_headers)
        self.assertEquals(like_post_response.status_code, status.HTTP_200_OK)
        rated_posts_response = self.client.get(
            reverse('posts:view_rated_posts'), **auth_headers)
        self.assertEquals(rated_posts_response.status_code, status.HTTP_200_OK)
        dislike_post_response = self.client.post(reverse(
            'posts:rate_post',
            kwargs={'slug': tag_posts_response.json()[0]['slug']}),
                                                 data={'rating': 0},
                                                 **auth_headers)
        self.assertEquals(dislike_post_response.status_code,
                          status.HTTP_200_OK)
        os.remove(settings.BASE_DIR + tag_posts_response.json()[0]
                  ['post_heading_image'].replace(settings.DOMAIN_URL, ''))
        delete_post_response = self.client.post(
            reverse('posts:delete_post',
                    kwargs={'slug': tag_posts_response.json()[0]['slug']}),
            **auth_headers)
        self.assertEquals(delete_post_response.status_code, status.HTTP_200_OK)

    @tag('comments')
    def test_comments(self):
        tok = AccessToken.objects.create(user=self.test_user,
                                         token='1234567890',
                                         application=self.application,
                                         scope='read write',
                                         expires=timezone.now() +
                                         datetime.timedelta(days=1))
        auth_headers = {
            'HTTP_AUTHORIZATION': 'Bearer ' + tok.token,
        }
        make_writer_response = self.client.post(
            reverse('users:test_make_writer',
                    kwargs={'username': self.test_user.username}),
            **auth_headers)
        self.assertEquals(make_writer_response.status_code, status.HTTP_200_OK)
        with open(
                os.path.join(os.path.dirname(__file__),
                             'test_images/create_post.png'),
                'rb') as create_post_image:
            self.create_post_data = {
                'post_heading': 'This is a test heading',
                'post_heading_image': create_post_image,
                'post_body': 'This is a test body.',
                'read_duration': '1',
                'tag': 'UX',
            }
            create_post_response = self.client.post(
                reverse('posts:create_post'),
                data=self.create_post_data,
                **auth_headers)
            self.assertEquals(create_post_response.status_code,
                              status.HTTP_200_OK)
        tag_posts_response = self.client.get(
            reverse('posts:view_tag_posts', kwargs={'tag_name': 'UX'}),
            **auth_headers)
        self.assertEquals(tag_posts_response.status_code, status.HTTP_200_OK)
        create_comment_response = self.client.post(
            reverse('posts:create_comment',
                    kwargs={'slug': tag_posts_response.json()[0]['slug']}),
            data={'comment': 'This is a test comment.'},
            **auth_headers)
        self.assertEquals(create_comment_response.status_code,
                          status.HTTP_200_OK)
        view_post_comments_response = self.client.get(
            reverse('posts:view_comments',
                    kwargs={'slug': tag_posts_response.json()[0]['slug']}),
            **auth_headers)
        self.assertEquals(view_post_comments_response.status_code,
                          status.HTTP_200_OK)
        update_post_comment_response = self.client.post(
            reverse('posts:update_comment',
                    kwargs={
                        'resource_key':
                        view_post_comments_response.json()[0]['resource_key']
                    }),
            data={'comment': 'This is an updated test comment.'},
            **auth_headers)
        self.assertEquals(update_post_comment_response.status_code,
                          status.HTTP_200_OK)
        delete_post_comment_response = self.client.post(
            reverse('posts:delete_comment',
                    kwargs={
                        'resource_key':
                        view_post_comments_response.json()[0]['resource_key']
                    }), **auth_headers)
        self.assertEquals(delete_post_comment_response.status_code,
                          status.HTTP_200_OK)
        os.remove(settings.BASE_DIR + tag_posts_response.json()[0]
                  ['post_heading_image'].replace(settings.DOMAIN_URL, ''))
        delete_post_response = self.client.post(
            reverse('posts:delete_post',
                    kwargs={'slug': tag_posts_response.json()[0]['slug']}),
            **auth_headers)
        self.assertEquals(delete_post_response.status_code, status.HTTP_200_OK)

    @tag('replies')
    def test_replies(self):
        tok = AccessToken.objects.create(user=self.test_user,
                                         token='1234567890',
                                         application=self.application,
                                         scope='read write',
                                         expires=timezone.now() +
                                         datetime.timedelta(days=1))
        auth_headers = {
            'HTTP_AUTHORIZATION': 'Bearer ' + tok.token,
        }
        make_writer_response = self.client.post(
            reverse('users:test_make_writer',
                    kwargs={'username': self.test_user.username}),
            **auth_headers)
        self.assertEquals(make_writer_response.status_code, status.HTTP_200_OK)
        with open(
                os.path.join(os.path.dirname(__file__),
                             'test_images/create_post.png'),
                'rb') as create_post_image:
            self.create_post_data = {
                'post_heading': 'This is a test heading',
                'post_heading_image': create_post_image,
                'post_body': 'This is a test body.',
                'read_duration': '1',
                'tag': 'UX',
            }
            create_post_response = self.client.post(
                reverse('posts:create_post'),
                data=self.create_post_data,
                **auth_headers)
            self.assertEquals(create_post_response.status_code,
                              status.HTTP_200_OK)
        tag_posts_response = self.client.get(
            reverse('posts:view_tag_posts', kwargs={'tag_name': 'UX'}),
            **auth_headers)
        self.assertEquals(tag_posts_response.status_code, status.HTTP_200_OK)
        create_comment_response = self.client.post(
            reverse('posts:create_comment',
                    kwargs={'slug': tag_posts_response.json()[0]['slug']}),
            data={'comment': 'This is a test comment.'},
            **auth_headers)
        self.assertEquals(create_comment_response.status_code,
                          status.HTTP_200_OK)
        view_post_comments_response = self.client.get(
            reverse('posts:view_comments',
                    kwargs={'slug': tag_posts_response.json()[0]['slug']}),
            **auth_headers)
        self.assertEquals(view_post_comments_response.status_code,
                          status.HTTP_200_OK)
        create_reply_response = self.client.post(
            reverse('posts:create_reply',
                    kwargs={
                        'resource_key':
                        view_post_comments_response.json()[0]['resource_key']
                    }),
            data={'reply': 'This is a test reply.'},
            **auth_headers)
        self.assertEquals(create_reply_response.status_code,
                          status.HTTP_200_OK)
        view_post_replies_response = self.client.get(
            reverse('posts:view_replies',
                    kwargs={
                        'resource_key':
                        view_post_comments_response.json()[0]['resource_key']
                    }), **auth_headers)
        self.assertEquals(view_post_replies_response.status_code,
                          status.HTTP_200_OK)
        update_reply_response = self.client.post(
            reverse('posts:update_reply',
                    kwargs={
                        'resource_key':
                        view_post_replies_response.json()[0]['resource_key']
                    }),
            data={'reply': 'This is an updated test reply.'},
            **auth_headers)
        self.assertEquals(update_reply_response.status_code,
                          status.HTTP_200_OK)
        delete_reply_response = self.client.post(
            reverse('posts:delete_reply',
                    kwargs={
                        'resource_key':
                        view_post_replies_response.json()[0]['resource_key']
                    }), **auth_headers)
        self.assertEquals(delete_reply_response.status_code,
                          status.HTTP_200_OK)
        os.remove(settings.BASE_DIR + tag_posts_response.json()[0]
                  ['post_heading_image'].replace(settings.DOMAIN_URL, ''))
        delete_post_response = self.client.post(
            reverse('posts:delete_post',
                    kwargs={'slug': tag_posts_response.json()[0]['slug']}),
            **auth_headers)
        self.assertEquals(delete_post_response.status_code, status.HTTP_200_OK)

    @tag('bookmarks')
    def test_bookmarks(self):
        tok = AccessToken.objects.create(user=self.test_user,
                                         token='1234567890',
                                         application=self.application,
                                         scope='read write',
                                         expires=timezone.now() +
                                         datetime.timedelta(days=1))
        auth_headers = {
            'HTTP_AUTHORIZATION': 'Bearer ' + tok.token,
        }
        make_writer_response = self.client.post(
            reverse('users:test_make_writer',
                    kwargs={'username': self.test_user.username}),
            **auth_headers)
        self.assertEquals(make_writer_response.status_code, status.HTTP_200_OK)
        with open(
                os.path.join(os.path.dirname(__file__),
                             'test_images/create_post.png'),
                'rb') as create_post_image:
            self.create_post_data = {
                'post_heading': 'This is a test heading',
                'post_heading_image': create_post_image,
                'post_body': 'This is a test body.',
                'read_duration': '1',
                'tag': 'UX',
            }
            create_post_response = self.client.post(
                reverse('posts:create_post'),
                data=self.create_post_data,
                **auth_headers)
            self.assertEquals(create_post_response.status_code,
                              status.HTTP_200_OK)
        tag_posts_response = self.client.get(
            reverse('posts:view_tag_posts', kwargs={'tag_name': 'UX'}),
            **auth_headers)
        self.assertEquals(tag_posts_response.status_code, status.HTTP_200_OK)
        create_bookmark_response = self.client.post(
            reverse('posts:create_bookmark',
                    kwargs={'slug': tag_posts_response.json()[0]['slug']}),
            **auth_headers)
        self.assertEquals(create_bookmark_response.status_code,
                          status.HTTP_200_OK)
        view_bookmarks_response = self.client.get(
            reverse('posts:view_bookmarks'), **auth_headers)
        self.assertEquals(view_bookmarks_response.status_code,
                          status.HTTP_200_OK)
        delete_bookmark_response = self.client.post(
            reverse('posts:delete_bookmark',
                    kwargs={
                        'resource_key':
                        view_bookmarks_response.json()[0]['resource_key']
                    }), **auth_headers)
        self.assertEquals(delete_bookmark_response.status_code,
                          status.HTTP_200_OK)
        os.remove(settings.BASE_DIR + tag_posts_response.json()[0]
                  ['post_heading_image'].replace(settings.DOMAIN_URL, ''))
        delete_post_response = self.client.post(
            reverse('posts:delete_post',
                    kwargs={'slug': tag_posts_response.json()[0]['slug']}),
            **auth_headers)
        self.assertEquals(delete_post_response.status_code, status.HTTP_200_OK)
Пример #5
0
class AccountEndpointTest(TestCaseUtils, TestCase):
	def setUp(self):
		self.client = APIClient()

		self.user = User.objects.create_user("Foo", "Bar", "*****@*****.**", "123456")
		self.user.is_active = True
		self.user.save()
		self.dev_user = User.objects.create_user("Foo", "Bar1", "*****@*****.**", "123456")
		self.dev_user.is_active = True
		self.dev_user.save()

		self.application = Application(
                    name="Test Application",
                    user=self.dev_user,
                    client_type=Application.CLIENT_PUBLIC,
                    authorization_grant_type=Application.GRANT_PASSWORD,
                )
		self.application.save()

		token_request_data = {
			'grant_type': 'password',
			'username': '******',
			'password': '******'
		}

		auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)

		response = self.client.post(reverse('oauth2_provider:token'), data=token_request_data, **auth_headers)
		content = json.loads(response.content.decode("utf-8"))

		self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + content['access_token'])

	def tearDown(self):
		self.application.delete()
		self.user.delete()
		self.dev_user.delete()

	def test_add_new_account(self):
	    """
	    test get user information
	    """
	    response = self.client.post('/api/v1/account/', {
												    		'name': 'Test Business',
												    		'user': self.user.id,
												    		'metadata': "{'address': '24 JUMP STREET'}"
												    	})
	    self.assertEqual(response.status_code, 201)

	    content = json.loads(response.content.decode("utf-8"))
	    self.assertTrue('name' in content)
	    self.assertTrue('metadata' in content)
	    self.assertTrue('user' in content)

	def test_get_business_account_user(self):
		"""
		it should returns account info after created via POST
		"""
		response = self.client.post('/api/v1/account/', json.dumps({
    														'name': 'Test Business',
    														'user': self.user.id,
    														'metadata': {'address': '24 JUMP STREET'}
    		}))

		self.assertEqual(response.status_code, 201)

		response = self.client.get('/api/v1/users/get_user/')
		self.assertEqual(response.status_code, 200)

		content = json.loads(response.content.decode("utf-8"))
		self.assertTrue('user' in content)
		self.assertTrue('first_name' in content['user'])
		self.assertTrue('last_name' in content['user'])
		self.assertTrue('address' in content['user'])
		self.assertTrue('account' in content['user'])

		# check if account information exists
		self.assertTrue('name' in content['user']['account'])
		self.assertTrue('metadata' in content['user']['account'])

	def test_get_business_account_user(self):
		response = self.client.get('/api/v1/users/get_user/')
		self.assertEqual(response.status_code, 200)

		content = json.loads(response.content.decode("utf-8"))
		self.assertTrue('user' in content)
		self.assertTrue('first_name' in content['user'])
		self.assertTrue('last_name' in content['user'])
		self.assertTrue('address' in content['user'])
		self.assertTrue('account' in content['user'])

		self.assertEqual({}, content['user']['account'])

	def test_update_business_account(self):
		response = self.client.post('/api/v1/account/', {
    														'name': 'Test Business',
    														'user': self.user.id,
    														'metadata': "{'address': '24 JUMP STREET'}"
    		})

		self.assertEqual(response.status_code, 201)
		content = json.loads(response.content.decode("utf-8"))

		response = self.client.put('/api/v1/account/' + str(content['id']) + '/', {
    														'name': 'Test Business 1',
    														'user': self.user.id,
    														'metadata': "{'address': '24 JUMP STREET'}"
    		})

		self.assertEqual(response.status_code, 200)
		content = json.loads(response.content.decode("utf-8"))
		self.assertEqual(content['name'], 'Test Business 1')

	def test_delete_business_account(self):
		response = self.client.post('/api/v1/account/', {
    														'name': 'Test Business',
    														'user': self.user.id,
    														'metadata': "{'address': '24 JUMP STREET'}"
    		})

		self.assertEqual(response.status_code, 201)
		content = json.loads(response.content.decode("utf-8"))

		response = self.client.delete('/api/v1/account/' + str(content['id']) + '/')
		self.assertTrue(Account.objects.filter().count() == 0)

	def test_add_business_account_failed(self):
		self.client.credentials()

		response = self.client.post('/api/v1/account/', {
    														'name': 'Test Business',
    														'user': self.user.id,
    														'metadata': "{'address': '24 JUMP STREET'}"
    		})
		self.assertEqual(response.status_code, 401)

	def test_update_business_account_failed(self):
		response = self.client.post('/api/v1/account/', {
    														'name': 'Test Business',
    														'user': self.user.id,
    														'metadata': "{'address': '24 JUMP STREET'}"
    		})
		self.assertEqual(response.status_code, 201)
		content = json.loads(response.content.decode("utf-8"))

		self.client.credentials()

		response = self.client.put('/api/v1/account/' + str(content['id']) + '/', {
    														'name': 'Test Business 1',
    														'user': self.user.id,
    														'metadata': "{'address': '24 JUMP STREET'}"
    		})

		self.assertEqual(response.status_code, 401)
		content = json.loads(response.content.decode("utf-8"))
		self.assertTrue(content['detail'], 'Authentication credentials were not provided.')