class RestApiGetUserDatasTest(TestCase): fixtures = ['demo_dump.json'] ## Préparation du client de test def setUp(self): self.client = APIClient() user = User.objects.get(username='******') self.client.force_authenticate(user=user) ## Test d'une requete GET valide. Doit renvoyer un code 200 def test_get_user_datas(self): user_id = 3 response = self.client.get(reverse('backoffice:restapi-user-datas', kwargs={'user_id':user_id})) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, apiResponses['get_user_data']) ## Test d'une requete GET valide. Doit renvoyer un code 200 et une json vide car l'utilisateur ne possede pas de data associées def test_get_user_datas_empty(self): user_id = 4 response = self.client.get(reverse('backoffice:restapi-user-datas', kwargs={'user_id':user_id})) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, apiResponses['get_user_data_empty']) ## Test d'une requete GET invalide: user_id innexistant. Doit renvoyer un code 400 def test_get_user_datas_wrong_id(self): user_id = 420 response = self.client.get(reverse('backoffice:restapi-user-datas', kwargs={'user_id':user_id})) self.assertEqual(response.status_code, 400)
def test_release_list(self): """ Staff members will see all the releases, but regular users only see those associated to unrestricted collections""" client = APIClient() client.force_authenticate(user=self.staffuser) collections = "%s" % (self.coll1id, ) response = client.get("/api/hindustani/release", **{'HTTP_DUNYA_COLLECTION': collections}) data = response.data self.assertEqual(1, len(data["results"])) collections = "%s, %s, %s" % (self.coll1id, self.coll2id, self.coll3id) response = client.get("/api/hindustani/release", **{'HTTP_DUNYA_COLLECTION': collections}) data = response.data self.assertEqual(3, len(data["results"])) # A normal user passing a restricted collection will still only # get 1 release client.force_authenticate(user=self.normaluser) collections = "%s, %s" % (self.coll1id, self.coll2id) response = client.get("/api/hindustani/release", **{'HTTP_DUNYA_COLLECTION': collections}) data = response.data self.assertEqual(1, len(data["results"])) # A restricted user passing a restricted collection will still only # get 2 release client.force_authenticate(user=self.restricteduser) collections = "%s, %s, %s" % (self.coll1id, self.coll2id, self.coll3id) response = client.get("/api/hindustani/release", **{'HTTP_DUNYA_COLLECTION': collections}) data = response.data self.assertEqual(2, len(data["results"]))
class TestCharmessageDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. Therefore in setup some objects are created and received with different user accounts. """ def setUp(self): self.client = APIClient() config['general_system_enable_anonymous'] = True user = User.objects.get(pk=1) for index in range(10): ChatMessage.objects.create(user=user) @use_cache() def test_admin(self): """ Tests that only the following db queries are done: * 4 requests to get the session an the request user with its permissions, * 2 requests to get the list of all chatmessages, """ self.client.force_login(User.objects.get(pk=1)) with self.assertNumQueries(6): self.client.get(reverse('chatmessage-list'))
class RestApiGetSubjectConfigTest(TestCase): fixtures = ['demo_dump.json'] ## Préparation du client de test def setUp(self): self.client = APIClient() user = User.objects.get(username='******') self.client.force_authenticate(user=user) ## Test d'une requete GET valide. Doit renvoyer un code 200 def test_get_subject_config(self): class_id = 2 ref = 'maths' response = self.client.get(reverse('backoffice:restapi-subject-config', kwargs={'class_id':class_id,'ref':ref})) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, apiResponses['get_subject_config']) ## Test d'une requete GET invalide: utilisation d'un class_id invalide. Doit renvoyer un code 400 def test_get_subject_config_invalid_class_id(self): class_id = 420 ref = 'maths' response = self.client.get(reverse('backoffice:restapi-subject-config', kwargs={'class_id':class_id,'ref':ref})) self.assertEqual(response.status_code, 400) ## Test d'une requete GET invalide: utilisation d'une ref invalide. Doit renvoyer un code 400 def test_get_subject_config_invalid_ref(self): class_id = 2 ref = 'toto' response = self.client.get(reverse('backoffice:restapi-subject-config', kwargs={'class_id':class_id,'ref':ref})) self.assertEqual(response.status_code, 400)
def test_recording_list_collection(self): """ Staff members will see recordings from restricted collections in this list too """ client = APIClient() client.force_authenticate(user=self.staffuser) collections = self.coll1id response = client.get("/api/hindustani/recording", **{'HTTP_DUNYA_COLLECTION': collections}) data = response.data self.assertEqual(1, len(data["results"])) response = client.get("/api/hindustani/recording") data = response.data self.assertEqual(3, len(data["results"])) # A restricted user passing a restricted collection over the header parameter will # get 1 recording client.force_authenticate(user=self.staffuser) collections = self.coll3id response = client.get("/api/hindustani/recording", **{'HTTP_DUNYA_COLLECTION': collections}) data = response.data self.assertEqual(1, len(data["results"])) # A normal user passing a collection over the header parameter will still only # get 1 recording client.force_authenticate(user=self.normaluser) response = client.get("/api/hindustani/recording") data = response.data self.assertEqual(1, len(data["results"]))
def test_create_save_data_by_user(self): client = APIClient() client.force_authenticate(user=self.user2) response_create1 = client.post('/save-data/', data={ 'user': '******', 'game': '3', 'saved_file': 'file1.txt' }) # Access denied, can only create own response_create2 = client.post('/save-data/', data={ 'user': '******', 'game': '3', 'saved_file': 'file2.txt' }) response1 = client.get('/save-data/') response2 = client.get('/save-data/?game=3') self.assertEqual(response_create1.status_code, \ status.HTTP_403_FORBIDDEN) self.assertEqual(response_create2.status_code, \ status.HTTP_201_CREATED) self.assertEqual(response1.status_code, status.HTTP_200_OK) self.assertEqual(response1.status_code, status.HTTP_200_OK) self.assertEqual(len(response1.data), 1) self.assertEqual(len(response2.data), 1)
def test_read_save_data_by_user(self): client = APIClient() client.force_authenticate(user=self.user2) response_create = client.post('/save-data/', data={ 'user': '******', 'game': '3', 'saved_file': 'file2.txt' }) response1 = client.get('/save-data/') response2 = client.get('/save-data/1/') response3 = client.get('/save-data/?game=2') response4 = client.get('/save-data/?user=user1') response5 = client.get('/save-data/?user=user2') self.assertEqual(response_create.status_code, status.HTTP_201_CREATED) self.assertEqual(response1.status_code, status.HTTP_200_OK) self.assertEqual(response2.status_code, status.HTTP_404_NOT_FOUND) self.assertEqual(response3.status_code, status.HTTP_200_OK) self.assertEqual(response4.status_code, status.HTTP_200_OK) self.assertEqual(response5.status_code, status.HTTP_200_OK) self.assertEqual(len(response1.data), 1) self.assertEqual(len(response3.data), 0) self.assertEqual(len(response4.data), 0) self.assertEqual(len(response5.data), 1)
def test_read_game_session_by_user(self): client1 = APIClient() client1.force_authenticate(user=self.user1) client2 = APIClient() client2.force_authenticate(user=self.user2) # Joins game response_create1 = client1.post('/game-session/', data={ 'user': '******', 'game': self.game2.id }, format='json') response_create2 = client1.post('/game-session/', data={ 'user': '******', 'game': self.game1.id }, format='json') # Read Game Session response1 = client2.get('/game-session/') response2 = client2.get('/game-session/?game=1') response3 = client2.get('/game-session/?user=user1') response4 = client2.get('/game-session/?user=user2') response5 = client2.get('/game-session/1/') response6 = client2.get('/game-session/2/') self.assertEqual(response1.status_code, status.HTTP_200_OK) self.assertEqual(response2.status_code, status.HTTP_200_OK) self.assertEqual(response3.status_code, status.HTTP_200_OK) self.assertEqual(response4.status_code, status.HTTP_200_OK) self.assertEqual(response5.status_code, status.HTTP_404_NOT_FOUND) self.assertEqual(response6.status_code, status.HTTP_200_OK) self.assertEqual(len(response1.data), 1) self.assertEqual(len(response2.data), 1) self.assertEqual(len(response3.data), 0) self.assertEqual(len(response4.data), 1) self.assertEqual(response6.data['id'], 2)
def test_create_save_data_by_operator(self): client = APIClient() client.force_authenticate(user=self.user1) response_create1 = client.post('/save-data/', data={ 'user': '******', 'game': '3', 'saved_file': 'file1.txt' }) response_create2 = client.post('/save-data/', data={ 'user': '******', 'game': '3', 'saved_file': 'file2.txt' }) response1 = client.get('/save-data/') response2 = client.get('/save-data/?game=3') self.assertEqual(response_create1.status_code, \ status.HTTP_201_CREATED) self.assertEqual(response_create2.status_code, \ status.HTTP_201_CREATED) self.assertEqual(response1.status_code, status.HTTP_200_OK) self.assertEqual(response1.status_code, status.HTTP_200_OK) self.assertEqual(len(response1.data), 5) self.assertEqual(len(response2.data), 2)
class DropdownWithAuthTests(TestCase): """Tests correct dropdown behaviour with Auth views enabled.""" urls = "tests.browsable_api.auth_urls" def setUp(self): self.client = APIClient(enforce_csrf_checks=True) self.username = "******" self.email = "*****@*****.**" self.password = "******" self.user = User.objects.create_user(self.username, self.email, self.password) def tearDown(self): self.client.logout() def test_name_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get("/") self.assertContains(response, "john") def test_logout_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get("/") self.assertContains(response, ">Log out<") def test_login_shown_when_logged_out(self): response = self.client.get("/") self.assertContains(response, ">Log in<")
def test_buy_game_by_operator(self): client = APIClient() client.force_authenticate(user=self.user1) response_create1 = client.post('/game-ownership/', data={ 'user': self.user1.username, 'game': self.game1.id }, format='json') # Duplicate response_create2 = client.post('/game-ownership/', data={ 'user': self.user1.username, 'game': self.game3.id }, format='json') response_create3 = client.post('/game-ownership/', data={ 'user': self.user2.username, 'game': self.game3.id }, format='json') response1 = client.get('/game-ownership/') response2 = client.get('/game-ownership/?user=user1') response3 = client.get('/game-ownership/?user=user2') response4 = client.get('/game-ownership/?game=3') self.assertEqual(response_create1.status_code, \ status.HTTP_400_BAD_REQUEST) self.assertEqual(response_create2.status_code, \ status.HTTP_201_CREATED) self.assertEqual(response_create3.status_code, \ status.HTTP_201_CREATED) self.assertEqual(response1.status_code, status.HTTP_200_OK) self.assertEqual(response2.status_code, status.HTTP_200_OK) self.assertEqual(response3.status_code, status.HTTP_200_OK) self.assertEqual(response4.status_code, status.HTTP_200_OK) self.assertEqual(len(response1.data), 5) self.assertEqual(len(response2.data), 3) self.assertEqual(len(response3.data), 2) self.assertEqual(len(response4.data), 2)
def test_concert_list_collection(self): """ Staff members will see concerts from restricted collections in this list if they ask for them """ client = APIClient() client.force_authenticate(user=self.staffuser) collections = self.coll1id response = client.get("/api/carnatic/concert", **{'HTTP_DUNYA_COLLECTION': collections}) data = response.data self.assertEqual(1, len(data["results"])) collections = "%s, %s" % (self.coll1id, self.coll2id) response = client.get("/api/carnatic/concert", **{'HTTP_DUNYA_COLLECTION': collections}) data = response.data self.assertEqual(2, len(data["results"])) # A normal user passing a collection over header parameter will still only # get 1 concert client.force_authenticate(user=self.normaluser) collections = "%s, %s" % (self.coll1id, self.coll2id) response = client.get("/api/carnatic/concert", **{'HTTP_DUNYA_COLLECTION': collections}) data = response.data self.assertEqual(1, len(data["results"])) # A restricted user using will get the concert associated # with the restricted access collection client.force_authenticate(user=self.restricteduser) collections = "%s, %s, %s" % (self.coll1id, self.coll2id, self.coll3id) response = client.get("/api/carnatic/concert", **{'HTTP_DUNYA_COLLECTION': collections}) data = response.data self.assertEqual(2, len(data["results"]))
class XeroxViewTest(TestCase): def setUp(self): self.client = APIClient() self.sizes = ('q', 'n') self.urls = {} self.nurls = {} x_hash = XeroxMachine().add('http://www.google.com/google.jpg') no_hash = XeroxMachine().add('http://zarautz.xyz/open.jpg') for size in self.sizes: self.urls[size] = get_absolute_uri(reverse('image', args=(XeroxMachine.IMAGE_TYPE_IN_URL, x_hash, size))) self.nurls[size] = get_absolute_uri(reverse('image', args=(XeroxMachine.IMAGE_TYPE_IN_URL, no_hash, size))) def test_default_response(self): response = self.client.get(self.urls[self.sizes[0]]) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response['Content-Type'], 'image/jpeg') self.assertEqual(response['Cache-Control'], 'max-age=604800') def test_no_response(self): response = self.client.get(self.nurls[self.sizes[0]]) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_no_event_response(self): response = self.client.get(self.urls[self.sizes[0]].replace('/x/', '/e/')) # EventImage self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_no_place_response(self): response = self.client.get(self.urls[self.sizes[0]].replace('/x/', '/p/')) # PlaceImage self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_image_sizes(self): for size in self.sizes: image = Image.open(StringIO(self.client.get(self.urls[size]).content)) self.assertEqual(image.size[0], IMAGE_SIZES[size]['size'][0])
class TestViewSetUser(TransactionTestCase): fixtures = [ 'users.json', ] def setUp(self): super(TestViewSetUser, self).setUp() self.client = APIClient() def test_http_get(self): user = User.objects.get(pk=1) self.client.force_login(user) response = self.client.get('/0/sessions/') expected = json.loads(response.content) self.assertEquals(200, response.status_code) self.assertEquals(1, len(expected)) self.assertEquals(1, expected[0]['id']) self.client.logout() def test_http_get_not_logged_in(self): response = self.client.get('/0/sessions/') expected = json.loads(response.content) self.assertEquals(200, response.status_code) self.assertEquals(0, len(expected))
class TestDBQueries(TestCase): """ Tests that receiving elements only need the required db queries. Therefore in setup some objects are created and received with different user accounts. """ def setUp(self): self.client = APIClient() config["general_system_enable_anonymous"] = True for index in range(10): Mediafile.objects.create( title="some_file{}".format(index), mediafile=SimpleUploadedFile("some_file{}".format(index), b"some content."), ) def test_admin(self): """ Tests that only the following db queries are done: * 5 requests to get the session an the request user with its permissions and * 2 requests to get the list of all files. """ self.client.force_login(User.objects.get(pk=1)) with self.assertNumQueries(7): self.client.get(reverse("mediafile-list")) def test_anonymous(self): """ Tests that only the following db queries are done: * 2 requests to get the permission for anonymous (config and permissions) and * 2 requests to get the list of all projectors. """ with self.assertNumQueries(4): self.client.get(reverse("mediafile-list"))
def test_list_chapters(self, registered_users, books): user_bob = registered_users['bob'] books[0].owner = user_bob client = APIClient() client.force_authenticate(user=user_bob) response = client.get( reverse("v1:editor_chapter_list_create_api", kwargs={'pk': books[0].id}) ) # we got 200 OK assert response.status_code is status.HTTP_200_OK # we don't have chapters yet assert response.data['count'] is 0 # another book response = client.get( reverse("v1:editor_chapter_list_create_api", kwargs={'pk': books[1].id}) ) # we got 200 OK assert response.status_code is status.HTTP_200_OK # we don't have chapters yet assert response.data['count'] is 0
def test_detail(self): url = reverse('api-job-detail', kwargs={'pk': self.job1}) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['title'], 'job title 1') # unexisting or of someone else: 404 url = reverse('api-job-detail', kwargs={'pk': 0}) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # setting back the correct url url = reverse('api-job-detail', kwargs={'pk': self.job1}) client = APIClient() # another user SAME APP: OK user = User.objects.create(username='******', password='******', email="*****@*****.**") Membership.objects.create(user=user, account=self.account) token = Token.objects.get(user=user) token = 'Token ' + token.key + '/' + self.app.token client.credentials(HTTP_AUTHORIZATION=token) response = client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) # another user, another app: 404 token = Token.objects.get(user=self.user2) token = 'Token ' + token.key + '/' + self.app2.token client.credentials(HTTP_AUTHORIZATION=token) response = client.get(url, format='json') # this is not 403 beacuse the list is restricted by the app (see get_queryset) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
class RetrieveItem(TestCase): """ Tests retrieving items. """ def setUp(self): self.client = APIClient() config["general_system_enable_anonymous"] = True self.item = Topic.objects.create(title="test_title_Idais2pheepeiz5uph1c").agenda_item def test_normal_by_anonymous_without_perm_to_see_hidden_items(self): group = get_user_model().groups.field.related_model.objects.get(pk=1) # Group with pk 1 is for anonymous users. permission_string = "agenda.can_see_hidden_items" app_label, codename = permission_string.split(".") permission = group.permissions.get(content_type__app_label=app_label, codename=codename) group.permissions.remove(permission) self.item.type = Item.AGENDA_ITEM self.item.save() response = self.client.get(reverse("item-detail", args=[self.item.pk])) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_hidden_by_anonymous_without_perm_to_see_hidden_items(self): group = get_user_model().groups.field.related_model.objects.get(pk=1) # Group with pk 1 is for anonymous users. permission_string = "agenda.can_see_hidden_items" app_label, codename = permission_string.split(".") permission = group.permissions.get(content_type__app_label=app_label, codename=codename) group.permissions.remove(permission) response = self.client.get(reverse("item-detail", args=[self.item.pk])) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
class EndpointTest(APITestCase): def setUp(self): # Using the standard RequestFactory API to create a form POST request self.client = APIClient() self.session = "14-15" def test_root(self): """ Just for testing that things are OK """ response = self.client.get(reverse("api_root")) self.assertEqual(response.status_code, 200) # no key named 'error' self.assertNotIn("error", response.data.keys()) def test_search(self): """ Search all the things """ response = self.client.get(reverse("api_search", args=(self.session,)) + "?type=all&query=pura") # result is a list of entity types self.assertIsInstance(response.data, list) # there are 5 types of entities right now self.assertEqual(len(response.data), 5) def test_school_list(self): """ List of schools """ response = self.client.get(reverse("api_school_list", args=(self.session,)) + "?management=govt&area=urban") # no error self.assertNotIn("error", response.data.keys()) # there are more than 0 results self.assertNotEqual(response.data.get("count"), 0)
class ApiTests(APITestCase): def setUp(self): Instructional.objects.create(title="Example", body="text", source="http://www.google.com") self.instruct = Instructional.objects.last() self.api_root = '/api/' self.client = APIClient() user = User(username='******', is_active=True, is_superuser=True) user.set_password('1234') user.save() self.user = user def test_create_instructional(self): """ Ensure we can get a instructional object. """ self.client.login(username=self.user.username, password="******") response = self.client.get('/api/instructional/1/') self.assertEqual(response.data, {"id": 1, "title": "Example", "body": "text", "source": "http://www.google.com", "questions": []}) def test_create_questions(self): """ Ensure we can get a questions object. we didn't add questions to the instructional data so the reposnse will be not found """ self.client.login(username=self.user.username, password="******") response = self.client.get('/api/questions/1/') self.assertEqual(response.data, {u'detail': u'Not found.'})
class APITestCase(APITestCase): fixtures = ['user.json','robot.json'] def setUp(self): user = User.objects.get(username='******') self.client = APIClient() self.client.force_authenticate(user=user) def test_get_robots(self): """Ensure we can get a robot list in the full API""" url = reverse('robots_list') response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) def test_create_robot(self): """Ensure we can get a specific robot""" url = reverse('robots_list') data = {'username': '******','robot_path':'test'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['robot_path'], data['robot_path']) def test_delete_robot(self): url = reverse('robots_detail', kwargs={'pk':'1'}) response = self.client.delete(url, format='json') self.assertEqual(url,'/robots/1') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) def test_get_user(self): """Ensure we can get a single user in the full API""" url = reverse('users_list') response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK)
class VaultViewSetTest(TransactionTestCase): """ Test Vault viewset """ reset_sequences = True def setUp(self): self.client = APIClient() self.user = User.objects.create_user('hiren', '*****@*****.**', 'password') self.client.force_authenticate(user=self.user) self.tag = Tag.objects.create(name='tag object') vault = Vault.objects.create(site_url='http://xyz.com', username='******', email='*****@*****.**', password='******', note='note', tag=self.tag) def test_login_works(self): response = self.client.get('/api/vault/') self.assertEqual(response.status_code, 200) self.client.logout() response = self.client.get('/api/vault/') self.assertEqual(response.status_code, 403) def test_return_correct_item(self): # todo learn mockg response = self.client.get('/api/vault/1/') #self.assertEqual(response.json(), {'site_url': 'http://xyz.com', 'username': '******', # 'email': '*****@*****.**', 'password': '******', 'note': 'note', 'tag': self.tag}) def test_item_update_works(self): response = self.client.patch('/api/vault/1/', {'username': '******'}) #self.assertEqual(response.json(), {'site_url': 'http://xyz.com', 'username': '******', # 'email': '*****@*****.**', 'password': '******', 'note': 'note', 'tag': self.tag}) print(response.json())
class UserAPITests(TestCase): fixtures = ['frigg/builds/fixtures/users.json'] def setUp(self): self.client = APIClient() self.user = User.objects.first() def test_me_api_view_anonymous(self): response = self.client.get(reverse('api:user_me')) self.assertEqual(response.status_code, 200) data = response.json() self.assertTrue(data['is_anonymous'], 'User is not anonymous') self.assertFalse(data['is_staff'], 'Anonymous user is staff') def test_me_api_view(self): self.client.force_authenticate(user=self.user) response = self.client.get(reverse('api:user_me')) self.assertEqual(response.status_code, 200) data = response.json() self.assertFalse(data['is_anonymous'], 'User is anonymous') self.assertEqual(data['username'], 'dumbledore') self.assertEqual(data['email'], '*****@*****.**') self.assertTrue(data['is_staff'], 'Dumbledore is not staff') def test_me_api_view_not_staff(self): self.user.is_staff = False self.user.save() self.client.force_authenticate(user=self.user) response = self.client.get(reverse('api:user_me')) data = response.json() self.assertFalse(data['is_staff'], 'Dumbledore is staff')
class ChannelProgramsAPITestCase(APITestCase): @mock.patch("streams.tasks.manage_channel_proc.apply_async") def setUp(self, mock_manage_channel_proc): user, _ = User.objects.get_or_create( username="******", defaults={ "is_superuser": False, "is_staff": False, } ) Channel.objects.create( name="channel", enabled=True) self.client = APIClient() self.client.force_authenticate(user) def test_channel_programs(self): channel = Channel.objects.get(name="channel") response = self.client.get( "/api/channel/programs/{0}/".format(channel.pk)) self.assertEqual(response.status_code, 200) def test_channel_programs_not_exists(self): response = self.client.get( "/api/channel/programs/30000/") self.assertEqual(response.status_code, 404)
class TodoTest(TestCase): def setUp(self): self.username = '******' self.email = '*****@*****.**' self.password = '******' self.user = User.objects.create_user(self.username, self.email, self.password) self.user.save() self.client = APIClient() def test_get_empty_todo_list(self): token = Token.objects.create(user=self.user).key self.client.credentials(HTTP_AUTHORIZATION="Token " + token) request = self.client.get("/todos/", {}, format="json") self.assertEqual(request.status_code, status.HTTP_200_OK) def test_get_todo_list(self): todo = Todo.objects.create( title = "hacer tarea", body = "terminar modulo django", user = self.user, ) todo.save() token = Token.objects.create(user=self.user).key self.client.credentials(HTTP_AUTHORIZATION="Token " + token) request = self.client.get("/todos/", {}, format="json") self.assertEqual(request.status_code, status.HTTP_200_OK)
class DropdownWithAuthTests(TestCase): """Tests correct dropdown behaviour with Auth views enabled.""" def setUp(self): self.client = APIClient(enforce_csrf_checks=True) self.username = '******' self.email = '*****@*****.**' self.password = '******' self.user = User.objects.create_user( self.username, self.email, self.password ) def tearDown(self): self.client.logout() def test_name_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get('/') content = response.content.decode('utf8') assert 'john' in content def test_logout_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get('/') content = response.content.decode('utf8') assert '>Log out<' in content def test_login_shown_when_logged_out(self): response = self.client.get('/') content = response.content.decode('utf8') assert '>Log in<' in content
def test_site_activities_endpoint_returns_results_on_activities(self): """ Test site activities endpoint with empty db. """ reset_db() c = APIClient() u = create_user() c.login(username=u.username, password='******') data = { "title": "Test post title", "text": "Test post text", "tags": ['tag1', 'tag2'] } c.post('/api/posts', data, format='json') time.sleep(1) data['title'] = "Second test post title" c.post('/api/posts', data, format='json') expected = 2 request_url = '/api/siteactivities' response = c.get(request_url) self.assertEqual(response.status_code, status.HTTP_200_OK, 'Expected HTTP 200 got %s.' % response.status_code) content = json.loads(response.content) self.assertEquals(len(content), expected, 'Expected %s results, got %s' % (expected, len(content))) request_url = '/api/siteactivities/%s' % timezone.now().strftime('%s') response = c.get(request_url) expected = 1 self.assertEqual(response.status_code, status.HTTP_200_OK, 'Expected HTTP 200 got %s.' % response.status_code) content = json.loads(response.content) self.assertEquals(len(content), expected, 'Expected %s results, got %s' % (expected, len(content)))
def test_fetch_location(self): ''' get user's self location history ''' client = APIClient() client.login(username = "******", password = "******") response = client.get(reverse('location-list')) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 1) self.assertEqual(response.data[0]['lat'], 1.0) self.assertEqual(response.data[0]['lon'], 5.0) self.assertEqual(response.data[0]['prec'], 7.0) client.login(username = "******", password = "******") response = client.get(reverse('location-list')) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data),2) self.assertEqual(response.data[0]['lat'], 3.0) self.assertEqual(response.data[0]['lon'], 3.0) self.assertEqual(response.data[0]['prec'], 3.0) self.assertEqual(response.data[1]['lat'], 2.0) self.assertEqual(response.data[1]['lon'], 2.0) self.assertEqual(response.data[1]['prec'], 2.0)
class NoDropdownWithoutAuthTests(TestCase): """Tests correct dropdown behaviour with Auth views NOT enabled.""" urls = 'tests.browsable_api.no_auth_urls' def setUp(self): self.client = APIClient(enforce_csrf_checks=True) self.username = '******' self.email = '*****@*****.**' self.password = '******' self.user = User.objects.create_user(self.username, self.email, self.password) def tearDown(self): self.client.logout() def test_name_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get('/') self.assertContains(response, 'john') def test_dropdown_not_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get('/') self.assertNotContains(response, '<li class="dropdown">') def test_dropdown_not_shown_when_logged_out(self): response = self.client.get('/') self.assertNotContains(response, '<li class="dropdown">')
def test_paciente_search_api_view(self): newer_pac = models.Paciente.objects.create( cedula='13785815', nombres='Ithamar Alexander', apellidos='Torres Torres', fecha_nacimiento='1980-04-20' ) url = urlresolvers.reverse(paciente_urls.PACIENTE_SEARCH_API_URL_NAME) api_client = APIClient() self.assertTrue(api_client.login(username=self.LOGGED_USERNAME, password=self.LOGGED_PASSWORD)) response = api_client.get(url, format='json') serialized_data1 = serializers.PacienteSerializer(self.paciente).data serialized_data2 = serializers.PacienteSerializer(newer_pac).data self.assertIn(serialized_data1, response.data) self.assertIn(serialized_data2, response.data) # Test filtered results response = api_client.get(url + '?q=gustavo', format='json') self.assertIn(serialized_data1, response.data) self.assertNotIn(serialized_data2, response.data)
def test_company_list_unauthenticated(self): client = APIClient() response = client.get(self.api_path, content_type="application/json") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
class PublicUserApiTests(TestCase): def setUp(self): self.client = APIClient() def test_create_valid_user_success(self): payload = { 'email': '*****@*****.**', 'password': '******', 'name': 'Test Klemo' } res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**res.data) self.assertTrue(user.check_password(payload['password'])) self.assertNotIn('password', res.data) def test_user_exists(self): payload = {'email': '*****@*****.**', 'password': '******'} create_user(**payload) res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_password_too_short(self): payload = { 'email': '*****@*****.**', 'password': '******', 'name': 'Klement' } res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) user_exists = get_user_model().objects.filter( email=payload['email']).exists() self.assertFalse(user_exists) def test_create_token_for_user(self): payload = {'email': '*****@*****.**', 'password': '******'} create_user(**payload) res = self.client.post(TOKEN_URL, payload) self.assertIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_create_token_invalid_credentials(self): create_user(email='*****@*****.**', password='******') payload = {'email': '*****@*****.**', 'password': '******'} res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_no_user(self): payload = {'email': '*****@*****.**', 'password': '******'} res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_missing_field(self): res = self.client.post(TOKEN_URL, {'email': 'one', 'password': ''}) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_retrieve_user_unauthorized(self): res = self.client.get(ME_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
def test_sales_unit_api(admin_user): activate("en") get_default_shop() client = APIClient() client.force_authenticate(user=admin_user) sales_unit_data = { "translations": { "en": { "name": "Kilo", "symbol": "KG" } }, "decimals": 2 } response = client.post("/api/shuup/sales_unit/", content_type="application/json", data=json.dumps(sales_unit_data)) assert response.status_code == status.HTTP_201_CREATED sales_unit = SalesUnit.objects.first() assert sales_unit.name == sales_unit_data["translations"]["en"]["name"] assert sales_unit.symbol == sales_unit_data["translations"]["en"]["symbol"] assert sales_unit.decimals == sales_unit_data["decimals"] sales_unit_data["translations"]["en"]["name"] = "Pound" sales_unit_data["translations"]["en"]["symbol"] = "PD" sales_unit_data["decimals"] = 3 response = client.put("/api/shuup/sales_unit/%d/" % sales_unit.id, content_type="application/json", data=json.dumps(sales_unit_data)) assert response.status_code == status.HTTP_200_OK sales_unit = SalesUnit.objects.first() assert sales_unit.name == sales_unit_data["translations"]["en"]["name"] assert sales_unit.symbol == sales_unit_data["translations"]["en"]["symbol"] assert sales_unit.decimals == sales_unit_data["decimals"] response = client.get("/api/shuup/sales_unit/%d/" % sales_unit.id) assert response.status_code == status.HTTP_200_OK data = json.loads(response.content.decode("utf-8")) assert sales_unit.name == data["translations"]["en"]["name"] assert sales_unit.symbol == data["translations"]["en"]["symbol"] assert sales_unit.decimals == data["decimals"] response = client.get("/api/shuup/sales_unit/") assert response.status_code == status.HTTP_200_OK data = json.loads(response.content.decode("utf-8")) assert sales_unit.name == data[0]["translations"]["en"]["name"] assert sales_unit.symbol == data[0]["translations"]["en"]["symbol"] assert sales_unit.decimals == data[0]["decimals"] response = client.delete("/api/shuup/sales_unit/%d/" % sales_unit.id) assert response.status_code == status.HTTP_204_NO_CONTENT assert SalesUnit.objects.count() == 0 # create a product and relate it to a sales unit sales_unit = SalesUnit.objects.create(name="Kilo", symbol="KG") product = create_product("product with sales unit", sales_unit=sales_unit) # shouldn't be possible to delete a sales_unit with a related product response = client.delete("/api/shuup/sales_unit/%d/" % sales_unit.id) assert response.status_code == status.HTTP_400_BAD_REQUEST assert "This object can not be deleted because it is referenced by" in response.content.decode( "utf-8")
class PrivateUserFileApiTests(TestCase): """Test authenticated recipe API access""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**', 'testpass' ) self.client.force_authenticate(self.user) def test_retrieve_userfiles(self): """Test retrieving list of recipes""" sample_user_files(user=self.user) sample_user_files(user=self.user) res = self.client.get(USER_FILES_URL) userfiles = User_File.objects.all().order_by('-id') serializer = User_FileSerializer(userfiles, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) # there is an error of order of dict assertion error commented for the time being self.assertEqual(res.data, serializer.data) def test_userfiles_limited_to_user(self): """Test retrieving recipes for user""" user2 = get_user_model().objects.create_user( '*****@*****.**', 'pass' ) sample_user_files(user=user2) sample_user_files(user=self.user) res = self.client.get(USER_FILES_URL) userfiles = User_File.objects.filter(user=self.user) serializer = User_FileSerializer(userfiles, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data, serializer.data) def test_view_userfile_detail(self): """test viewing a user_file detail""" user_file = sample_user_files(user=self.user) user_file.tags.add(sample_tag(user=self.user)) user_file.file_types.add(sample_file_type(user=self.user)) url = detail_url(user_file.id) res = self.client.get(url) serializer = UserFileDetailSerializer(user_file) self.assertEqual(res.data, serializer.data) def test_create_basic_userfile(self): """test creating userfile""" payload = { 'title': 'ROOM' # 'created_on': '20/4/19' } res = self.client.post(USER_FILES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user_file = User_File.objects.get(id=res.data['id']) for key in payload.keys(): self.assertEqual(payload[key], getattr(user_file, key)) def test_create_userfile_with_tags(self): """test creating a userfile with tags""" tag1 = sample_tag(user=self.user, name='tag 1') tag2 = sample_tag(user=self.user, name='tag 2') payload = { 'title': 'test with two tags', 'tags': [tag1.id, tag2.id], # 'created_on' : '12/4/19' } res = self.client.post(USER_FILES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user_file = User_File.objects.get(id=res.data['id']) tags = user_file.tags.all() self.assertEqual(tags.count(), 2) self.assertIn(tag1, tags) self.assertIn(tag2, tags) def test_create_userfile_with_filetype(self): """test creating a userfile with tags""" file_type1 = sample_file_type(user=self.user, type='DWG') file_type2 = sample_file_type(user=self.user, type='DXF') payload = { 'title': 'HOTEL', 'file_types': [file_type1.id, file_type2.id], # 'created_on': '12/4/19' } res = self.client.post(USER_FILES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user_file = User_File.objects.get(id=res.data['id']) file_types = user_file.file_types.all() self.assertEqual(file_types.count(), 2) self.assertIn(file_type1, file_types) self.assertIn(file_type2, file_types) def test_partial_update_userfile(self): """test updating a recipe with patch""" user_file = sample_user_files(user=self.user) user_file.tags.add(sample_tag(user=self.user)) new_tag = sample_tag(user=self.user, name='room') payload = {'title': 'sample file changed', ' tags': [new_tag.id]} url = detail_url(user_file.id) self.client.patch(url, payload) user_file.refresh_from_db() self.assertEqual(user_file.title, payload['title']) tags = user_file.tags.all() self.assertEqual(len(tags), 1) self.assertIn(new_tag, tags) def test_full_update_userfile(self): """test updating a userfile with put""" user_file = sample_user_files(user=self.user) user_file.tags.add(sample_tag(user=self.user)) payload = { 'title': 'sample file changed' } url = detail_url(user_file.id) self.client.put(url, payload) user_file.refresh_from_db() self.assertEqual(user_file.title, payload['title']) tags = user_file.tags.all() self.assertEqual(len(tags), 0)
class UserFileUploadTests(TestCase): def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**', 'testpass' ) self.client.force_authenticate(self.user) self.user_file = sample_user_files(user=self.user) def tearDown(self): self.user_file.file.delete() def test_upload_file_to_userfile(self): """test uploading an file to userfiles""" url = userfile_upload_url(self.user_file.id) with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf: img = Image.new('RGB', (10, 10)) img.save(ntf, format='JPEG') ntf.seek(0) res = self.client.post(url, {'file': ntf}, format='multipart') self.user_file.refresh_from_db() self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertIn('file', res.data) self.assertTrue(os.path.exists(self.user_file.file.path)) def test_upload_file_bad_request(self): """test uploading an invalid file/image""" url = userfile_upload_url(self.user_file.id) res = self.client.post(url, {'file': 'notimage'}, format='multipart') self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_filter_userfile_by_tags(self): """test returning usefile with specific tags""" userfile1 = sample_user_files(user=self.user, title='room') userfile2 = sample_user_files(user=self.user, title='house') tag1 = sample_tag(user=self.user, name='my room') tag2 = sample_tag(user=self.user, name='my house') userfile1.tags.add(tag1) userfile2.tags.add(tag2) userfile3 = sample_user_files(user=self.user, title='bathroom') res = self.client.get( USER_FILES_URL, {'tags': '{},{}'.format(tag1.id, tag2.id)} ) serializer1 = User_FileSerializer(userfile1) serializer2 = User_FileSerializer(userfile2) serializer3 = User_FileSerializer(userfile3) self.assertIn(serializer1.data, res.data) self.assertIn(serializer2.data, res.data) self.assertNotIn(serializer3.data, res.data) def test_filter_userfile_by_filetype(self): """test returning usefile with specific tags""" userfile1 = sample_user_files(user=self.user, title='room1') userfile2 = sample_user_files(user=self.user, title='house1') file_type1 = sample_file_type(user=self.user, type='DWG') file_type2 = sample_file_type(user=self.user, type='DXF') userfile1.file_types.add(file_type1) userfile2.file_types.add(file_type2) userfile3 = sample_user_files(user=self.user, title='bathroom1') res = self.client.get( USER_FILES_URL, {'file_types': '{},{}'.format(file_type1.id, file_type2.id)} ) serializer1 = User_FileSerializer(userfile1) serializer2 = User_FileSerializer(userfile2) serializer3 = User_FileSerializer(userfile3) self.assertIn(serializer1.data, res.data) self.assertIn(serializer2.data, res.data) self.assertNotIn(serializer3.data, res.data)
class PublicUserApiTests(TestCase): """ Test the users API (public) """ def setUp(self): self.client = APIClient() def test_create_valid_user_success(self): """Test creating user with valid payload is successful""" payload = { 'email': '*****@*****.**', 'password': '******', 'name': 'Test name' } res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**res.data) self.assertTrue(user.check_password(payload['password'])) self.assertNotIn('password', res.data) def test_user_exists(self): """Test creating a user that already exists fails""" payload = { 'email': '*****@*****.**', 'password': '******', 'name': 'Test name' } create_user(**payload) res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_password_too_short(self): """Test that the password must be more than 5 characters""" payload = {'email': '*****@*****.**', 'password': '******'} res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) user_exists = get_user_model().objects.filter( email=payload['email'] ).exists() self.assertFalse(user_exists) def test_create_token_for_user(self): """Test that a token is created for the user""" payload = {'email': '*****@*****.**', 'password': '******'} create_user(**payload) res = self.client.post(TOKEN_URL, payload) self.assertIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_create_token_invalid_credentials(self): """Test that token is not created if invalid credentials are given""" create_user(email='*****@*****.**', password='******') payload = {'email': '*****@*****.**', 'password': '******'} res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_no_user(self): """Test that token is not created if user doesn't exist""" payload = {'email': '*****@*****.**', 'password': '******'} res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_missing_field(self): """Test that email and password are required""" res = self.client.post(TOKEN_URL, {'email': 'one', 'password': ''}) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_retrieve_user_unauthorized(self): """Test that authentication is required for users""" res = self.client.get(ME_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PublicUserApiTests(TestCase): """Test the users API (public)""" def setUp(self): self.client = APIClient() def test_create_valid_user_success(self): """Test creating using with a valid payload is successful""" payload = { 'email': '*****@*****.**', 'password': '******', 'name': 'name', } res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**res.data) self.assertTrue(user.check_password(payload['password'])) self.assertNotIn('password', res.data) def test_user_exists(self): """Test creating a user that already exists fails""" payload = {'email': '*****@*****.**', 'password': '******'} create_user(**payload) res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_password_too_short(self): """Test that password must be more than 5 characters""" payload = {'email': '*****@*****.**', 'password': '******'} res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) user_exists = get_user_model().objects.filter( email=payload['email']).exists() self.assertFalse(user_exists) def test_create_token_for_user(self): """Test that a token is created for a valid user""" payload = {'email': '*****@*****.**', 'password': '******'} create_user(**payload) resp = self.client.post(TOKEN_URL, payload) self.assertIn('token', resp.data) self.assertEqual(resp.status_code, status.HTTP_200_OK) def test_create_token_invalid_credentials(self): """Test that no token is created for an invalid user login""" create_user(email='*****@*****.**', password='******') payload = {'email': '*****@*****.**', 'password': '******'} resp = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', resp.data) self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_without_user(self): """Test that no token is created for an unexisting user""" payload = {'email': '*****@*****.**', 'password': '******'} resp = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', resp.data) self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_missing_password(self): """Test that no token is created when the password is empty""" payload = {'email': '*****@*****.**', 'password': ''} resp = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', resp.data) self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST) def test_retrieve_user_unauthorized(self): """Test that authentication required for users""" res = self.client.get(ME_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateIngredientsApiTests(TestCase): """Test the private ingredients API""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**', 'testpass', ) self.client.force_authenticate(self.user) def test_retrieve_ingredient_list(self): """Test retrieving a list of ingredients""" Ingredient.objects.create(user=self.user, name='Kale') Ingredient.objects.create(user=self.user, name='Salt') res = self.client.get(INGREDIENTS_URL) ingredients = Ingredient.objects.all().order_by('-name') serializer = IngredientSerializer(ingredients, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_ingredients_limited_to_user(self): """Test that ingredients for the authenticated user are returned""" user2 = get_user_model().objects.create_user( '*****@*****.**', 'testpass', ) Ingredient.objects.create(user=user2, name='Vinegar') ingredient = Ingredient.objects.create(user=self.user, name='Tumeric') res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data[0]['name'], ingredient.name) def test_create_ingredient_successful(self): """Test create a new ingredient""" payload = {'name': 'Cabbage'} self.client.post(INGREDIENTS_URL, payload) exists = Ingredient.objects.filter(user=self.user, name=payload['name']).exists() self.assertTrue(exists) def test_create_ingredient_invalid(self): """Test createing invalid ingredient fails""" payload = {'name': ''} res = self.client.post(INGREDIENTS_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_retrieve_ingredients_assigned_to_recipes(self): """retrieve ingredients that are assigned to some recipe""" ingredient1 = Ingredient.objects.create(user=self.user, name='Apples') ingredient2 = Ingredient.objects.create(user=self.user, name='Turkey') recipe = Recipe.objects.create(title='Apple crumble', time_minutes=5, price=10.00, user=self.user) recipe.ingredients.add(ingredient1) res = self.client.get(INGREDIENTS_URL, {'assigned_only': 1}) serializer1 = IngredientSerializer(ingredient1) serializer2 = IngredientSerializer(ingredient2) self.assertIn(serializer1.data, res.data)
class RecipeImageUploadTests(TestCase): def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**', 'testpass' ) self.client.force_authenticate(self.user) self.recipe = sample_recipe(user=self.user) # After the test run, tearDown is called def tearDown(self): # Delete image after test is done self.recipe.image.delete() def test_upload_image_to_recipe(self): """Test uploading an image to recipe""" url = image_upload_url(self.recipe.id) # Creates a named temporary file on the system at a random location # and write a image to that file and upload the file through API with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf: img = Image.new('RGB', (10, 10)) img.save(ntf, format='JPEG') # The way Python read file ntf.seek(0) # Defining 'multipart' to make form request, # a form consists of data by default, JSON res = self.client.post(url, {'image': ntf}, format='multipart') self.recipe.refresh_from_db() self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertIn('image', res.data) # print(self.recipe.image.path) # vol/web/media/uploads/recipe/840c61fa-62d4-4466-8903-46e7754e073c.jpg self.assertTrue(os.path.exists(self.recipe.image.path)) def test_upload_image_bad_request(self): """Test uploading an invalid image""" url = image_upload_url(self.recipe.id) res = self.client.post(url, {'image': 'notimage'}, format='multipart') self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_filter_recipes_by_tags(self): """Test returning recipes with specific tags""" recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry') recipe2 = sample_recipe(user=self.user, title='Aubergine with tahini') tag1 = sample_tag(user=self.user, name='Vegan') tag2 = sample_tag(user=self.user, name='Vegetarian') recipe1.tags.add(tag1) recipe2.tags.add(tag2) recipe3 = sample_recipe(user=self.user, title='Fish and chips') # pass a get parameter with tag we want to filter with res = self.client.get( RECIPES_URL, {'tags': '{},{}'.format(tag1.id, tag2.id)} ) serializer1 = RecipeSerializer(recipe1) serializer2 = RecipeSerializer(recipe2) serializer3 = RecipeSerializer(recipe3) self.assertIn(serializer1.data, res.data) self.assertIn(serializer2.data, res.data) self.assertNotIn(serializer3.data, res.data) def test_filter_recipes_by_ingredients(self): """Test returning recipes with specific ingredients""" recipe1 = sample_recipe(user=self.user, title='Posh beans on toast') recipe2 = sample_recipe(user=self.user, title='Chicken cacciatore') ingredient1 = sample_ingredient(user=self.user, name='Feta cheese') ingredient2 = sample_ingredient(user=self.user, name='Chicken') recipe1.ingredients.add(ingredient1) recipe2.ingredients.add(ingredient2) recipe3 = sample_recipe(user=self.user, title='Steak and mushrooms') res = self.client.get( RECIPES_URL, {'ingredients': '{},{}'.format(ingredient1.id, ingredient2.id)} ) serializer1 = RecipeSerializer(recipe1) serializer2 = RecipeSerializer(recipe2) serializer3 = RecipeSerializer(recipe3) self.assertIn(serializer1.data, res.data) self.assertIn(serializer2.data, res.data) self.assertNotIn(serializer3.data, res.data)
class JobAPITestCase(APITestCase): def setUp(self): self.job = JobFactory.create() token = Token.objects.get_or_create(user=self.job.author) self.client = APIClient(HTTP_AUTHORIZATION="Token " + token[0].key) self.api_path = f"/api/v1/companies/{self.job.company_id}/jobs/" def test_company_list_unauthenticated(self): client = APIClient() response = client.get(self.api_path, content_type="application/json") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_job_list_data_authenticated(self): response = self.client.get(f"{self.api_path}", content_type="application/json") self.assertEqual(response.status_code, 200) self.assertEqual(response.data[0]["title"], self.job.title) self.assertEqual(response.data[0]["description"], self.job.description) self.assertEqual(response.data[0]["category"]["id"], self.job.category.id) self.assertEqual(response.data[0]["state"], self.job.state) def test_delete_job_unauthenticated(self): client = APIClient() response = client.delete(self.api_path, content_type="application/json") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_delete_job_company_admin(self): response = self.client.delete(f"{self.api_path}{self.job.id}/", content_type="application/json") self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) def test_delete_job_normal_user(self): user = User.objects.create_user(username="******", email="*****@*****.**", password="******") token = Token.objects.get_or_create(user=user) user = APIClient(HTTP_AUTHORIZATION="Token " + token[0].key) response = user.delete(f"{self.api_path}", content_type="application/json") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_job_detail_retreive(self): response = self.client.get( "{}{}/".format(self.api_path, self.job.id), content_type="application/json", ) self.assertEqual(response.data["title"], self.job.title) self.assertEqual(response.data["description"], self.job.description) self.assertEqual(response.data["category"]["id"], self.job.category.id) self.assertEqual(response.data["state"], self.job.state) def test_job_detail_retreive_by_ananymous(self): client = APIClient() response = client.get( "{}{}/".format(self.api_path, self.job.id), content_type="application/json", ) self.assertEqual(response.status_code, 403) def test_job_create_by_admin(self): category = CategoryFactory.create() data = { "title": "title1", "description": "temp", "category": category.id, "company": self.job.company_id, "state": "DRAFT", "tags": ["tag1", "tag2"], } response = self.client.post( "{}".format(self.api_path), data=json.dumps(data), content_type="application/json", ) self.assertEqual(response.status_code, 201) self.assertEqual(response.data["title"], "title1") self.assertEqual(response.data["description"], "temp") self.assertEqual(response.data["category"], category.id) self.assertEqual(response.data["state"], "DRAFT") self.assertCountEqual(response.data["tags"], ["tag1", "tag2"]) def test_job_create_by_ananymous(self): data = { "title": "no title", "description": "no temp", "category": "", "company": "LOL", "author": self.job.author.id, "state": "DRAFT", "tags": ["tag1", "tag2"], } client = APIClient() response = client.post( "{}".format(self.api_path), data=json.dumps(data), content_type="application/json", ) self.assertEqual(response.status_code, 403) def test_job_update_by_admin(self): data = {"title": "updated title"} response = self.client.patch( f"{self.api_path}{self.job.id}/", data=json.dumps(data), content_type="application/json", ) self.assertEqual(response.status_code, 200) self.assertEqual(response.data["title"], data["title"]) def test_job_update_by_ananumous(self): data = {"title": "updated title"} client = APIClient() response = client.patch( f"{self.api_path}{self.job.id}/", data=json.dumps(data), content_type="application/json", ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_job_update_by_another_company_admin(self): admin = CompanyAdminFactory.create() token = Token.objects.get_or_create(user=admin) client = APIClient(HTTP_AUTHORIZATION="Token " + token[0].key) data = {"title": "updated title"} response = client.patch( f"{self.api_path}{self.job.id}/", data=json.dumps(data), content_type="application/json", ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_job_update_by_another_admin_same_company(self): admin_2 = CompanyAdminFactory() admin_2.company_id = self.job.company_id admin_2.save() token = Token.objects.get_or_create(user=admin_2) client = APIClient(HTTP_AUTHORIZATION="Token " + token[0].key) data = {"title": "updated title"} response = client.patch( f"{self.api_path}{self.job.id}/", data=json.dumps(data), content_type="application/json", ) self.assertEqual(response.status_code, 200) self.assertEqual(response.data["title"], data["title"]) def test_activate_state_admin(self): response = self.client.patch( f"{self.api_path}{self.job.id}/activate/", content_type="application/json", ) self.assertEqual(response.status_code, 200) self.assertEqual(response.data["message"], "Ok") def test_activate_state_ananymous(self): client = APIClient() response = client.patch( f"{self.api_path}{self.job.id}/activate/", content_type="application/json", ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_archive_state_admin(self): response = self.client.patch( f"{self.api_path}{self.job.id}/archive/", content_type="application/json", ) self.assertEqual(response.status_code, 200) self.assertEqual(response.data["message"], "Ok") def test_archive_state_ananymous(self): client = APIClient() response = client.patch( f"{self.api_path}{self.job.id}/archive/", content_type="application/json", ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_job_create_by_admin_with_no_title(self): category = CategoryFactory.create() data = { "description": "temp", "category": category.id, "company": self.job.company_id, "author": self.job.author.id, "state": "DRAFT", "tags": ["tag1", "tag2"], } response = self.client.post( "{}".format(self.api_path), data=json.dumps(data), content_type="application/json", ) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_list_with_DoesNotExist_company_id(self): response = self.client.get("/api/v1/companies/-1/jobs/", content_type="application/json") self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
class PrivateRecipeApiTests(TestCase): """Test authenticated recipe API access""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**', 'testpass') self.client.force_authenticate(self.user) def test_retrieve_recipes(self): """Test retrieving list of recipes""" sample_recipe(user=self.user) sample_recipe(user=self.user) res = self.client.get(RECIPES_URL) recipes = Recipe.objects.all().order_by('-id') serializer = RecipeSerializer(recipes, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) def test_recipes_limited_to_user(self): """Test retrieving recipes for user""" user2 = get_user_model().objects.create_user('*****@*****.**', 'pass') sample_recipe(user=user2) sample_recipe(user=self.user) res = self.client.get(RECIPES_URL) recipes = Recipe.objects.filter(user=self.user) serializer = RecipeSerializer(recipes, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data, serializer.data) def test_view_recipe_detail(self): """Test viewing a recipe detail""" recipe = sample_recipe(user=self.user) recipe.tags.add(sample_tag(user=self.user)) recipe.ingredients.add(sample_ingredient(user=self.user)) url = detail_url(recipe.id) res = self.client.get(url) serializer = RecipeDetailSerializer(recipe) self.assertEqual(res.data, serializer.data) def test_create_basic_recipe(self): """Test creating recipe""" payload = { 'title': 'Test recipe', 'time_minutes': 30, 'price': 10.00, } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data['id']) for key in payload.keys(): self.assertEqual(payload[key], getattr(recipe, key)) def test_create_recipe_with_tags(self): """Test creating a recipe with tags""" tag1 = sample_tag(user=self.user, name='Tag 1') tag2 = sample_tag(user=self.user, name='Tag 2') payload = { 'title': 'Test recipe with two tags', 'tags': [tag1.id, tag2.id], 'time_minutes': 30, 'price': 10.00 } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data['id']) tags = recipe.tags.all() self.assertEqual(tags.count(), 2) self.assertIn(tag1, tags) self.assertIn(tag2, tags) def test_create_recipe_with_ingredients(self): """Test creating recipe with ingredients""" ingredient1 = sample_ingredient(user=self.user, name='Ingredient 1') ingredient2 = sample_ingredient(user=self.user, name='Ingredient 2') payload = { 'title': 'Test recipe with ingredients', 'ingredients': [ingredient1.id, ingredient2.id], 'time_minutes': 45, 'price': 15.00 } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data['id']) ingredients = recipe.ingredients.all() self.assertEqual(ingredients.count(), 2) self.assertIn(ingredient1, ingredients) self.assertIn(ingredient2, ingredients) def test_partial_update_recipe(self): """Test updating a recipe with patch""" recipe = sample_recipe(user=self.user) recipe.tags.add(sample_tag(user=self.user)) new_tag = sample_tag(user=self.user, name='Curry') payload = {'title': 'Chicken tikka', 'tags': [new_tag.id]} url = detail_url(recipe.id) self.client.patch(url, payload) recipe.refresh_from_db() self.assertEqual(recipe.title, payload['title']) tags = recipe.tags.all() self.assertEqual(len(tags), 1) self.assertIn(new_tag, tags) def test_full_update_recipe(self): """Test updating a recipe with put""" recipe = sample_recipe(user=self.user) recipe.tags.add(sample_tag(user=self.user)) payload = { 'title': 'Spaghetti carbonara', 'time_minutes': 25, 'price': 5.00 } url = detail_url(recipe.id) self.client.put(url, payload) recipe.refresh_from_db() self.assertEqual(recipe.title, payload['title']) self.assertEqual(recipe.time_minutes, payload['time_minutes']) self.assertEqual(recipe.price, payload['price']) tags = recipe.tags.all() self.assertEqual(len(tags), 0)
class PrivateRecipeAPITests(TestCase): """Test authenticated recipe API access""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**', 'testpass' ) self.client.force_authenticate(self.user) def test_retrieve_recipes(self): """Test retrieving a list of recipes""" sample_recipe(user=self.user) sample_recipe(user=self.user) res = self.client.get(RECIPES_URL) recipes = Recipe.objects.all().order_by('-id') # want to return the data as a list, so manyTrue serializer = RecipeSerializer(recipes, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) def test_recipes_limited_to_user(self): """Test retrieving recipes for user""" user2 = get_user_model().objects.create_user( '*****@*****.**', 'password' ) sample_recipe(user=user2) sample_recipe(user=self.user) # return OrderedDict res = self.client.get(RECIPES_URL) # Retuen queryset recipes = Recipe.objects.filter(user=self.user) serializer = RecipeSerializer(recipes, many=True) # recipe API always return object in a list # even if there is only one recipe self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data, serializer.data) def test_view_recipe_detail(self): """Test viewing a recipe detail""" recipe = sample_recipe(user=self.user) recipe.tags.add(sample_tag(user=self.user)) recipe.ingredients.add(sample_ingredient(user=self.user)) url = detail_url(recipe.id) res = self.client.get(url) serializer = RecipeDetailSerializer(recipe) self.assertEqual(res.data, serializer.data) def test_create_basic_recipe(self): """Test creating recipe""" payload = { 'title': 'Test recipe', 'time_minutes': 30, 'price': 10.00, } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) # when we create an object using Django res framework, default behavior # is that it will return dictionary conatining the created object # res.deta['id'] get the if of the created object recipe = Recipe.objects.get(id=res.data['id']) # getattr allows to retrieve attributes using a variable. for key in payload.keys(): self.assertEqual(payload[key], getattr(recipe, key)) def test_create_recipe_with_tags(self): """Test creating a recipe with tags""" tag1 = sample_tag(user=self.user, name='Tag 1') tag2 = sample_tag(user=self.user, name='Tag 2') # pass tag id in a list payload = { 'title': 'Test recipe with two tags', 'tags': [tag1.id, tag2.id], 'time_minutes': 30, 'price': 10.00 } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data['id']) # Return all the tags assigned to our recipe as a queryset tags = recipe.tags.all() self.assertEqual(tags.count(), 2) # Check if the sample tags are same as the tags that are in queryset self.assertIn(tag1, tags) self.assertIn(tag2, tags) def test_create_recipe_with_ingredients(self): """Test creating recipe with ingredients""" ingredient1 = sample_ingredient(user=self.user, name='Ingredient 1') ingredient2 = sample_ingredient(user=self.user, name='Ingredient 2') payload = { 'title': 'Test recipe with ingredients', 'ingredients': [ingredient1.id, ingredient2.id], 'time_minutes': 45, 'price': 15.00 } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data['id']) ingredients = recipe.ingredients.all() self.assertEqual(ingredients.count(), 2) self.assertIn(ingredient1, ingredients) self.assertIn(ingredient2, ingredients) def test_partial_update_recipe(self): """Test updating a recipe with patch""" recipe = sample_recipe(user=self.user) recipe.tags.add(sample_tag(self.user)) new_tag = sample_tag(user=self.user, name='Curry') payload = {'title': 'Chicken tikka', 'tags': [new_tag.id]} # Use detail URL to update url = detail_url(recipe.id) self.client.patch(url, payload) # details of a created model instanc won't change unless reflesh recipe.refresh_from_db() self.assertEqual(recipe.title, payload['title']) tags = recipe.tags.all() self.assertEqual(len(tags), 1) # check if new tag in tags from database self.assertIn(new_tag, tags) def tast_full_update_recipe(self): """Test updating a recipe with put""" recipe = sample_recipe(user=self.user) recipe.tags.add(sample_tag(user=self.user)) payload = { 'title': 'Spagetti carbonara', 'time_minutes': 25, 'price': 5.00 } url = detail_url(recipe.id) self.client.put(url, payload) recipe.refresh_from_db() self.assertEqual(recipe.title, payload['title']) self.assertEqual(recipe.time_minutes, payload['time_minutes']) self.assertEqual(recipe.price, payload['price']) # By put request, if we don't update a field, it get removed # tag must be removed tags = recipe.tags.all() self.assertEqual(len(tags), 0)
class RecipeImageUploadAPITests(TestCase): def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( "*****@*****.**", "123456") self.client.force_authenticate(self.user) self.recipe = create_sample_recipe(user=self.user) def tearDown(self): self.recipe.image.delete() def test_upload_image_to_recipe(self): url = image_upload_url(self.recipe.id) with tempfile.NamedTemporaryFile(suffix=".jpg") as ntf: img = Image.new("RGB", (10, 10)) img.save(ntf, format="JPEG") ntf.seek(0) res = self.client.post(url, {"image": ntf}, format="multipart") self.recipe.refresh_from_db() self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertIn("image", res.data) self.assertTrue(os.path.exists(self.recipe.image.path)) def test_upload_invalid_image_bad_request(self): url = image_upload_url(self.recipe.id) res = self.client.post(url, {"image": "not a image"}, format="multipart") self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_filter_recipes_by_tags(self): recipe1 = create_sample_recipe(user=self.user, title="thai") recipe2 = create_sample_recipe(user=self.user, title="tahine") tag1 = create_sample_tag(user=self.user, name="Vegan") tag2 = create_sample_tag(user=self.user, name="Vegetarian") recipe1.tags.add(tag1) recipe2.tags.add(tag2) recipe3 = create_sample_recipe(user=self.user, title="fish and chips") res = self.client.get(RECIPE_URL, {"tags": f"{tag1.id},{tag2.id}"}) serializer1 = RecipeSerializer(recipe1) serializer2 = RecipeSerializer(recipe2) serializer3 = RecipeSerializer(recipe3) self.assertIn(serializer1.data, res.data) self.assertIn(serializer2.data, res.data) self.assertNotIn(serializer3.data, res.data) def test_filter_recipes_by_ingredients(self): recipe1 = create_sample_recipe(user=self.user, title="thai") recipe2 = create_sample_recipe(user=self.user, title="tahine") ing1 = create_sample_ingredient(user=self.user, name="Cucumber") ing2 = create_sample_ingredient(user=self.user, name="Red Beans") recipe1.ingredients.add(ing1) recipe2.ingredients.add(ing2) recipe3 = create_sample_recipe(user=self.user, title="fish and chips") res = self.client.get(RECIPE_URL, {"ingredients": f"{ing1.id},{ing2.id}"}) serializer1 = RecipeSerializer(recipe1) serializer2 = RecipeSerializer(recipe2) serializer3 = RecipeSerializer(recipe3) self.assertIn(serializer1.data, res.data) self.assertIn(serializer2.data, res.data) self.assertNotIn(serializer3.data, res.data)
class PublicUserApiTests(TestCase): """Test the users API (public)""" def setUp(self): self.client = APIClient() def test_create_valid_user_success(self): """Test creating user with valid payload is successful""" payload = { 'phone_number': '4086432477', 'password': '******', 'name': 'Test name', 'scores_initial': {}, 'scores_final': {}, 'first_name': '', 'last_name': '', 'age': '', 'zipcode': '', 'income': '', 'education': '', 'employment': '' } res = self.client.post(CREATE_USER_URL, payload, format='json') self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**res.data) self.assertTrue(user.check_password(payload['password'])) self.assertNotIn('password', res.data) def test_user_exists(self): """Test creating user that already exists fails""" payload = { 'phone_number': '4086432477', 'password': '******', } create_user(**payload) res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_password_too_short(self): """Test that the password must be more than 5 charachters""" payload = { 'phone_number': '4086432477', 'password': '******', } res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) user_exists = get_user_model().objects.filter( phone_number=payload['phone_number']).exists() self.assertFalse(user_exists) def test_create_token_for_user(self): """Test that a token is created for the user""" payload = { 'phone_number': '4086432477', 'password': '******', } create_user(**payload) res = self.client.post(TOKEN_URL, payload) self.assertIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_create_token_invalid_credentials(self): """Test that token is not created if invalid credentials are given""" create_user(phone_number='4086432477', password='******') payload = {'phone_number': '4086432477', 'password': '******'} res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_no_user(self): """Test that token is not created if user doesn't exist""" payload = {'phone_number': '4086432477', 'password': '******'} res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_missing_field(self): """Test that phone_number and password are required""" res = self.client.post(TOKEN_URL, { 'phone_number': 408, 'password': '' }) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_retrieve_user_unauthorized(self): """"Test that authentication is required for users""" res = self.client.get(ME_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class RecipeImageUploadTests(TestCase): def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**', 'testpass') self.client.force_authenticate(self.user) self.recipe = sample_recipe(user=self.user) def tearDown(self) -> None: """In contrast to setUp, this is run after running tests.""" # Keep our filesystem clean after running tests self.recipe.image.delete() def _test_upload_image_to_recipe(self): """Test uploading a valid image.""" url = image_upload_url(self.recipe.id) with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf: # Creates temp file we can write to, auto-deleted our with. # This is a 10 by 10 pixels black square test image. img = Image.new('RGB', (10, 10)) img.save(ntf, format='JPEG') ntf.seek(0) res = self.client.post(url, {'image': ntf}, format='multipart') self.recipe.refresh_from_db() self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertIn('image', res.data) self.assertTrue(os.path.exists(self.recipe.image.path)) def test_upload_image_bad_request(self): """Test uploading an invalid image.""" url = image_upload_url(self.recipe.id) res = self.client.post(url, {'image': 'not an image'}, format='multipart') self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_filter_recipes_by_tags(self): """Test returning recipes with specific tags.""" recipe_1 = sample_recipe(user=self.user, title='Thai vegetable curry') recipe_2 = sample_recipe(user=self.user, title='Aubergine with tahini') tag_1 = sample_tag(user=self.user, name='Vegan') tag_2 = sample_tag(user=self.user, name='Vegetarian') recipe_1.tags.add(tag_1) recipe_2.tags.add(tag_2) recipe_3 = sample_recipe(user=self.user, title='Fish and chips') # We'll develop API such that tag ids specified in get requests # will be used for filtering res = self.client.get(RECIPES_URL, {'tags': f'{tag_1.id}, {tag_2.id}'}) serializer_1 = RecipeSerializer(recipe_1) serializer_2 = RecipeSerializer(recipe_2) serializer_3 = RecipeSerializer(recipe_3) self.assertIn(serializer_1.data, res.data) self.assertIn(serializer_2.data, res.data) self.assertNotIn(serializer_3, res.data) def test_filter_recipe_by_ingredients(self): """Test returning recipes with specific ingredients.""" recipe_1 = sample_recipe(user=self.user, title='Posh beans on toast') recipe_2 = sample_recipe(user=self.user, title='Chicken cacciatore') ingredient_1 = sample_ingredient(user=self.user, name='Feta cheese') ingredient_2 = sample_ingredient(user=self.user, name='Chicken') recipe_1.ingredients.add(ingredient_1) recipe_2.ingredients.add(ingredient_2) recipe_3 = sample_recipe(user=self.user, title='Steak and mushrooms') res = self.client.get( RECIPES_URL, {'ingredients': f'{ingredient_1.id}, ' f'{ingredient_2.id}'}) serializer_1 = RecipeSerializer(recipe_1) serializer_2 = RecipeSerializer(recipe_2) serializer_3 = RecipeSerializer(recipe_3) self.assertIn(serializer_1.data, res.data) self.assertIn(serializer_2.data, res.data) self.assertNotIn(serializer_3.data, res.data)
class PrivateRecipeAPITests(TestCase): def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( "*****@*****.**", "123456") self.client.force_authenticate(self.user) def test_retrieving_recipes(self): create_sample_recipe(self.user) create_sample_recipe(self.user) res = self.client.get(RECIPE_URL) recipes = Recipe.objects.all().order_by("-id") serializer = RecipeSerializer(recipes, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) def test_recipes_limited_to_user(self): user2 = get_user_model().objects.create_user("*****@*****.**", "1234567") create_sample_recipe(self.user) create_sample_recipe(user2) res = self.client.get(RECIPE_URL) recipes = Recipe.objects.filter(user=self.user) serializer = RecipeSerializer(recipes, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data, serializer.data) def test_view_recipe_detail(self): recipe = create_sample_recipe(self.user) recipe.tags.add(create_sample_tag(user=self.user)) recipe.ingredients.add(create_sample_ingredient(user=self.user)) res = self.client.get(detail_url(recipe.id)) serializer = RecipeDetailSerializer(recipe) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) def test_create_basic_recipe(self): payload = { "title": "chocolate chessecake", "time_minutes": 30, "price": 5.50 } res = self.client.post(RECIPE_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data["id"]) for key in payload.keys(): if key == "price": self.assertEqual(float(res.data[key]), float(getattr(recipe, key))) else: self.assertEqual(res.data[key], getattr(recipe, key)) def test_create_recipe_with_tags(self): tag1 = create_sample_tag(user=self.user, name="Vegan") tag2 = create_sample_tag(user=self.user, name="Desert") payload = { "title": "Avocado Chessecake", "tags": [tag1.id, tag2.id], "time_minutes": 20, "price": 6.50, } res = self.client.post(RECIPE_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data["id"]) tags = recipe.tags.all() self.assertEqual(tags.count(), 2) self.assertIn(tag1, tags) self.assertIn(tag2, tags) def test_create_recipe_with_ingredients(self): ing1 = create_sample_ingredient(user=self.user, name="Onion") ing2 = create_sample_ingredient(user=self.user, name="Ginger") payload = { "title": "Same recipe", "ingredients": [ing1.id, ing2.id], "time_minutes": 20, "price": 7.50, "link": "https://recipes.com/recipe2", } res = self.client.post(RECIPE_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data["id"]) ingredients = recipe.ingredients.all() self.assertEqual(ingredients.count(), 2) self.assertIn(ing1, ingredients) self.assertIn(ing2, ingredients) def test_recipe_partial_update(self): """Test update recipe with PATCH""" recipe = create_sample_recipe(user=self.user, price=2) recipe.tags.add(create_sample_tag(user=self.user)) new_tag = create_sample_tag(user=self.user, name="Curry") payload = {"title": "Apple Pie", "tags": [new_tag.id]} self.client.patch(detail_url(recipe.id), payload) recipe.refresh_from_db() self.assertEqual(recipe.title, payload["title"]) tags = recipe.tags.all() self.assertEqual(len(tags), 1) self.assertIn(new_tag, tags) self.assertEqual(recipe.price, 2) def test_recipe_full_update(self): """Test update recipe with PUT""" recipe = create_sample_recipe(user=self.user) recipe.tags.add(create_sample_tag(user=self.user)) payload = {"title": "Apple Pie", "time_minutes": 25, "price": 20} self.client.put(detail_url(recipe.id), payload) recipe.refresh_from_db() tags = recipe.tags.all() self.assertEqual(recipe.title, payload["title"]) self.assertEqual(recipe.time_minutes, payload["time_minutes"]) self.assertEqual(recipe.price, payload["price"]) self.assertEqual(len(tags), 0)
class PrivateGoalsApiTests(TestCase): """Test the private goals API""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**', 'testpass') self.client.force_authenticate(self.user) def test_retrieve_goal_list(self): """Test retrieving a list of goals""" Goal.objects.create(title='Buying a house') Goal.objects.create(title='Being a billion dollars') res = self.client.get(GOAL_URL + '?page=1') goals = Goal.objects.all().order_by('title') p = Paginator(goals, 10) serializer = GoalSerializer(p.page(1), many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['results'], serializer.data) def test_retrieve_goal_list_page_2(self): """Test retrieving a list of goals""" Goal.objects.create(title='Buying a house') Goal.objects.create(title='Being a billionaire') res = self.client.get(GOAL_URL + '?page=2') goals = Goal.objects.all() p = Paginator(goals, 10) self.assertEqual(p.num_pages, 1) if p.num_pages > 1: serializer = GoalSerializer(p.page(2), many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['results'], serializer.data) else: self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_create_goal_successful(self): """Test create a new goal""" payload = { 'title': 'becoming famous', 'type': goals.Type.LONG_TERM, 'time': 2 } res = self.client.post(GOAL_URL, payload) exists = Goal.objects.filter(title=payload['title']).exists() self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertTrue(exists) def test_create_goal_invalid(self): """Test creating invalid goal fails""" payload = {'title': ''} res = self.client.post(GOAL_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_view_goal_detail(self): """Test viewing a goal detail""" goal = sample_goal(title="becoming famous") url = detail_url(goal.id) res = self.client.get(url) serializer = GoalSerializer(goal) self.assertEqual(res.data, serializer.data) def test_partial_update_recipe(self): """Test updating a recipe with patch""" goal = sample_goal(title='becoming a singer') payload = {'title': 'becoming a painter'} url = detail_url(goal.id) self.client.patch(url, payload) goal.refresh_from_db() self.assertEqual(goal.title, payload['title']) def test_full_update_recipe(self): """Test updating a recipe with put""" goal = sample_goal(title='becoming a singer') payload = { 'title': 'becoming a painter', 'type': goal.type, 'time': goal.time } url = detail_url(goal.id) res = self.client.put(url, payload) goal.refresh_from_db() self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(goal.title, payload['title']) def test_delete_goal_successful(self): """Test delete a new goal""" goal = sample_goal(title='becoming a singer') goal_id = goal.id url = detail_url(goal.id) self.client.delete(url) exists = Goal.objects.filter(id=goal_id).exists() self.assertFalse(exists)
class PrivateRecipeApiTests(TestCase): """Test authenticated recipe API access.""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**', 'testpass123') self.client.force_authenticate(self.user) def test_retrieve_recipes(self): """Test retrieving a list of recipes.""" sample_recipe(user=self.user) sample_recipe(user=self.user) res = self.client.get(RECIPES_URL) recipes = Recipe.objects.all().order_by('-id') serializer = RecipeSerializer(recipes, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) def test_recipes_limited_to_user(self): """Test retrieving for user only.""" user_2 = get_user_model().objects.create_user('*****@*****.**', 'pass123') sample_recipe(user=user_2) sample_recipe(user=self.user) res = self.client.get(RECIPES_URL) recipes = Recipe.objects.filter(user=self.user) serializer = RecipeSerializer(recipes, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data, serializer.data) def test_view_recipe_detail(self): """Test viewing a recipe detail.""" recipe = sample_recipe(user=self.user) # Link tag and ingredient to this recipe recipe.tags.add(sample_tag(user=self.user)) recipe.ingredients.add(sample_ingredient(user=self.user)) url = detail_url(recipe.id) res = self.client.get(url) serializer = RecipeDetailSerializer(recipe) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) def test_create_basic_recipe(self): """Test creating recipe.""" payload = { 'title': 'Chocolate cheesecake', 'time_minutes': 30, 'price': 5. } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) # When you create object, its returned in response data recipe = Recipe.objects.get(id=res.data['id']) for key in payload.keys(): self.assertEqual(payload[key], getattr(recipe, key)) def test_create_recipe_with_tag(self): """Test creating a recipe with tags.""" tag_1 = sample_tag(user=self.user, name='Vegan') tag_2 = sample_tag(user=self.user, name='Dessert') payload = { 'title': 'Avocado lime cheesecake', 'tags': [tag_1.id, tag_2.id], 'price': 20., 'time_minutes': 60 } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data['id']) tags = recipe.tags.all() self.assertEqual(tags.count(), 2) self.assertIn(tag_1, tags) self.assertIn(tag_2, tags) def test_create_recipe_with_ingredients(self): """Test creating recipe with ingredients.""" ingredient_1 = sample_ingredient(user=self.user, name='Prawns') ingredient_2 = sample_ingredient(user=self.user, name='Ginger') payload = { 'title': 'Thai prawn red curry', 'ingredients': [ingredient_1.id, ingredient_2.id], 'price': 7., 'time_minutes': 20 } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data['id']) ingredients = recipe.ingredients.all() self.assertEqual(ingredients.count(), 2) self.assertIn(ingredient_1, ingredients) self.assertIn(ingredient_2, ingredients) def test_partial_update_recipe(self): """Test updating a recipe with patch.""" recipe = sample_recipe(user=self.user) recipe.tags.add(sample_tag(user=self.user)) new_tag = sample_tag(user=self.user, name='Curry') # Payload for recipe with a new tag and new title payload = {'title': 'Chicken tikka', 'tags': [new_tag.id]} url = detail_url(recipe.id) self.client.patch(url, payload) # Refreshed details in db to commit changes recipe.refresh_from_db() self.assertEqual(recipe.title, payload['title']) tags = recipe.tags.all() self.assertEqual(len(tags), 1) self.assertIn(new_tag, tags) def test_full_update_recipe(self): """Test updating a recipe with put.""" # Put fully replaces object, also if not all fields in new payload # (i.e. fields not in payload are removed) recipe = sample_recipe(user=self.user) recipe.tags.add(sample_tag(user=self.user)) payload = { 'title': 'Spaghetti carbonara', 'time_minutes': 25, 'price': 5. } url = detail_url(recipe.id) self.client.put(url, payload) recipe.refresh_from_db() self.assertEqual(recipe.title, payload['title']) self.assertEqual(recipe.time_minutes, payload['time_minutes']) self.assertEqual(recipe.price, payload['price']) # Tag should be removed tags = recipe.tags.all() self.assertEqual(len(tags), 0)
class ViewsTestCase(APITestCase): def setUp(self): self.client = APIClient() self.user1 = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.user1_token = Token.objects.get(user__username=self.user1) self.desk_lamp = Relay.objects.create(name='desk lamp', device='lamp', status=False, owner=self.user1) def test_get_relays_list_without_token(self): url = reverse('api:relays') response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_get_relays_list_with_token(self): url = reverse('api:relays') self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.user1_token.key) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_post_relays_without_token(self): url = reverse('api:new_relay') response = self.client.post(url, {}, fromat='json') self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_post_successful_request(self): url = reverse('api:new_relay') self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.user1_token.key) self.new_relay = { 'name': 'post test', 'device': 'lamp', 'device': 'True', 'owner': self.user1 } response = self.client.post(url, self.new_relay, fromat='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_put_relay_without_token(self): url = reverse('api:relay', kwargs={'pk': self.desk_lamp.id}) response = self.client.put(url, {}, fromat='json') self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_put_successful_requests(self): url = reverse('api:relay', kwargs={'pk': self.desk_lamp.id}) self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.user1_token.key) self.updated_relay = { 'name': 'updated name', 'device': 'updated device', 'status': 'True', 'owner': self.user1 } response = self.client.put(url, self.updated_relay, fromat='json') self.assertEqual(response.status_code, status.HTTP_200_OK) def test_delete_without_token(self): url = reverse('api:relay', kwargs={'pk': self.desk_lamp.id}) response = self.client.delete(url, {}, fromat='json') self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_delete_successful_requests(self): url = reverse('api:relay', kwargs={'pk': self.desk_lamp.id}) self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.user1_token.key) response = self.client.delete(url, fromat='json') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
def test_user_invalid(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='Token ' + '') response = client.get("/api/users/") self.assertEqual(response.status_code, 404)
class PublicUserApiTest(TestCase): """Prueba de la API publica""" def setUp(self) -> None: self.client = APIClient() def test_create_valid_user_success(self): """Probar el envio correcto del usuario""" payload = { 'email': '*****@*****.**', 'password': '******', 'name': 'Test name' } res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**res.data) self.assertTrue(user.check_password(payload['password'])) self.assertNotIn('password', res.data) def test_user_exists(self): payload = { 'email': '*****@*****.**', 'password': '******' } create_user(**payload) res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_password_too_short(self): """Probando que la contraseña debe ser mayor que 5 caracteres""" payload = { 'email': '*****@*****.**', 'password': '******', 'name': 'Test name' } res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) user_exists = get_user_model().objects.filter( email=payload['email'] ).exists() self.assertFalse(user_exists) def test_create_token_for_user(self): """Probando que el token se crea para el usuario""" payload = { 'email': '*****@*****.**', 'password': '******', } create_user(**payload) res = self.client.post(TOKEN_URL, payload) self.assertIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_create_token_invalid_credentials(self): """Probando que el token no se cree con credenciales invalidas""" create_user(email='*****@*****.**', password='******') payload = { 'email': '*****@*****.**', 'password': '******', } res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_no_user(self): """Probando que no se genere un token con credenciales invalidas""" payload = { 'email': '*****@*****.**', 'password': '******', } res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_missing_field(self): """Probar que el usuario y contraseña son requeridos""" payload = { 'email': 'test', 'password': '', } res = self.client.post(TOKEN_URL, payload) self.assertNotIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_retrieve_user_unauthorized(self): """Probar que se requiere autenticación""" res = self.client.get(ME_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class QuestionCRUDViewsTest(TestCase): """Test for CRUD API view of question.""" def setUp(self): """Pre-populate test data.""" self.client = APIClient() user_data = { 'username': '******', 'email': '*****@*****.**', 'password': '******' } response = self.client.post('/user/signup', user_data, format='json') self.user = User.objects.get(username=user_data.get('username')) self.client.credentials(HTTP_AUTHORIZATION='JWT ' + response.data.get('token')) self.question = Question.objects.create(user=self.user, question='test question') self.first_answer = Answer.objects.create(question=self.question, answer='test first answer') self.second_answer = Answer.objects.create(question=self.question, answer='test second answer') self.url = f'/question/{self.question.id}/' self.bad_url = f'/question/999/' def tearDown(self): """Clean-up test data.""" del self.client del self.user del self.question del self.first_answer del self.second_answer def test_create_view(self): """Test create view for question.""" create_data = { 'question': 'test create question', 'answers': [{ 'answer': 'first answer' }, { 'answer': 'second answer' }] } # CREATED response = self.client.post('/question/', create_data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) created_question = Question.objects.get( id=int(response.data.get('id'))) self.assertIsNotNone(created_question) self.assertEqual(created_question.total_votes, 0) self.assertEqual( Answer.objects.filter(question=created_question).count(), 2) self.assertIsNotNone( Answer.objects.get(question=created_question, answer='first answer')) self.assertIsNotNone( Answer.objects.get(question=created_question, answer='second answer')) self.assertEqual(str(User.objects.get(username=self.user.username)), response.data.get('user')) response_json = json.dumps(response.data) self.assertIn(created_question.question, response_json) self.assertIn(str(created_question.total_votes), response_json) for ans in Answer.objects.filter(question=created_question): self.assertIn(ans.answer, response_json) self.assertIn(str(ans.votes_count), response_json) # BAD REQUESTS bad_data = { 'question': 'test question with same answers', 'answers': [{ 'answer': 'same answer' }, { 'answer': 'same answer' }] } response = self.client.post('/question/', bad_data, format='json') self.assertTrue(response.exception) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) bad_data.pop('answers') response = self.client.post('/question/', bad_data, format='json') self.assertTrue(response.exception) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_retrieve_view(self): """Test update view for question.""" response = self.client.get(self.url) self.assertEqual(response.status_code, status.HTTP_200_OK) response_json = json.dumps(response.data) self.assertIn(self.question.question, response_json) self.assertIn(str(self.question.total_votes), response_json) for ans in Answer.objects.filter(question=self.question): self.assertIn(str(ans.id), response_json) self.assertIn(ans.answer, response_json) self.assertIn(str(ans.votes_count), response_json) response = self.client.get(self.bad_url) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_delete_view(self): """Test delete view for question.""" response = self.client.delete(self.url) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) with self.assertRaises(Question.DoesNotExist): Question.objects.get(id=self.question.id) self.assertFalse( Answer.objects.filter(question=self.question).exists()) response = self.client.delete(self.bad_url) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_update_view(self): """Test update view for question.""" update_data = { 'question': 'test upd question', 'answers': [{ 'answer': 'first upd answer' }, { 'answer': 'second upd answer' }], } # UPDATED response = self.client.put(self.url, update_data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) upd_question = Question.objects.get(id=self.question.id) self.assertEqual(upd_question.question, update_data.get('question')) with self.assertRaises(Question.DoesNotExist): Question.objects.get(question=self.question.question) self.assertIsNotNone( Answer.objects.get(question=self.question.id, answer='first upd answer')) self.assertIsNotNone( Answer.objects.get(question=self.question.id, answer='second upd answer')) with self.assertRaises(Answer.DoesNotExist): Answer.objects.get(question=self.question.id, answer=self.first_answer.answer) Answer.objects.get(question=self.question.id, answer=self.second_answer.answer) response_json = json.dumps(response.data) self.assertIn(upd_question.question, response_json) self.assertIn(str(upd_question.total_votes), response_json) for ans in Answer.objects.filter(question=upd_question): self.assertIn(ans.answer, response_json) self.assertIn(str(ans.votes_count), response_json) # BAD REQUESTS bad_data = { 'question': 'test question with same answers', 'answers': [{ 'answer': 'same answer' }, { 'answer': 'same answer' }] } response = self.client.put(self.url, bad_data, format='json') self.assertTrue(response.exception) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) bad_data.pop('answers') response = self.client.put(self.url, bad_data, format='json') self.assertTrue(response.exception) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_auth_permission(self): """Test auth permission for update/destroy actions.""" unauth_client = APIClient() response = unauth_client.put(self.url, {}, format='json') self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) response = unauth_client.delete(self.url) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_object_level_permission(self): """Test object-level permission for update/delete views of question model.""" user = { 'username': '******', 'email': '*****@*****.**', 'password': '******' } response = self.client.post('/user/signup', user, format='json') bad_token = response.data.get('token') self.client.credentials(HTTP_AUTHORIZATION='JWT ' + bad_token) response = self.client.delete(self.url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) response = self.client.put(self.url, {}, format='json') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
class PrivateRecipeApiTest(TestCase): """Test authenticated recipe API access""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**', 'pass234' ) self.client.force_authenticate(self.user) def test_retrieve_recipes(self): """Test retrieving a list of recipes""" sample_recipe(user=self.user) sample_recipe(user=self.user) res = self.client.get(RECIPES_URL) recipes = Recipe.objects.all().order_by('-id') serializer = RecipeSerializer(recipes, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) def test_recipe_limited_to_user(self): """Test retiveing recipes for user""" user2 = get_user_model().objects.create_user( '*****@*****.**', 'passs12345' ) sample_recipe(user2) sample_recipe(self.user) res = self.client.get(RECIPES_URL) recipes = Recipe.objects.filter(user=self.user) serializer = RecipeSerializer(recipes, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data, serializer.data) def test_view_recipe_details(self): """Test viewing a recipe details""" recipe = sample_recipe(user=self.user) recipe.tags.add(sample_tag(user=self.user)) recipe.ingredients.add(sample_ingredient(user=self.user)) url = detail_url(recipe.id) res = self.client.get(url) serializer = RecipeDetailSerializer(recipe) self.assertEqual(res.data, serializer.data) def test_create_recipe(self): """Test creating recipe""" payload = { 'title': 'Chocolate cheesecake', 'time_minutes': 30, 'price': 5.00 } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data['id']) for key in payload.keys(): self.assertEqual(payload[key], getattr(recipe, key)) def test_create_recipe_with_tags(self): """Test creating a recipe with tags""" tag1 = sample_tag(user=self.user, name='Vegan') tag2 = sample_tag(user=self.user, name='Dessert') payload = { 'title': 'Avocado lime cheesecake', 'tags': [tag1.id, tag2.id], 'time_minutes': 60, 'price': 20 } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data['id']) tags = recipe.tags.all() self.assertEqual(tags.count(), 2) self.assertIn(tag1, tags) self.assertIn(tag2, tags) def test_create_recipe_with_ingredients(self): """Test creatig recipe with ingredients""" ingredient1 = sample_ingredient(user=self.user, name='Prawns') ingredient2 = sample_ingredient(user=self.user, name='Ginger') payload = { 'title': 'Thai prawn red curry', 'ingredients': [ingredient1.id, ingredient2.id], 'time_minutes': 20, 'price': 7.00 } res = self.client.post(RECIPES_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) recipe = Recipe.objects.get(id=res.data['id']) ingredients = recipe.ingredients.all() self.assertEqual(ingredients.count(), 2) self.assertIn(ingredient1, ingredients) self.assertIn(ingredient2, ingredients)
class RecipeImageUploadTests(TestCase): def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**' 'testpass') self.client.force_authenticate(self.user) self.recipe = sample_recipe(user=self.user) def tearDown(self): self.recipe.image.delete() def upload_image(self): """Test uploading an image to a recipe""" url = image_upload_url(self.recipe.id) with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf: # save an image to file img = Image.new('RGB', (32, 32)) img.save(ntf, format='JPEG') # go back to the beginning of the file ntf.seek(0) res = self.client.post(url, {'image': ntf}, format='multipart') self.recipe.refresh_from_db() self.assertEqual(res.state, status.HTTP_200_OK) self.assertIn('image', res.data) self.assertTrue(os.path.exists(self.recipe.image.path)) def upload_invalid_image(self): """Test uploading an invalid image""" url = image_upload_url(self.recipe.id) res = self.client.post(url, {'image': 'notimage'}, format='multipart') self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_filter_recipes_by_tags(self): """Test regurning recipes with specific tags""" recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry') recipe2 = sample_recipe(user=self.user, title='Carbonara pasta') tag1 = sample_tag(user=self.user, name='Vegan') tag2 = sample_tag(user=self.user, name='Italian') recipe1.tags.add(tag1) recipe2.tags.add(tag2) recipe3 = sample_recipe(user=self.user, title='Fish and chips') res = self.client.get(RECIPES_URL, {'tags': f'{tag1.id},{tag2.id}'}) ser1 = RecipeSerializer(recipe1) ser2 = RecipeSerializer(recipe2) ser3 = RecipeSerializer(recipe3) self.assertIn(ser1.data, res.data) self.assertIn(ser2.data, res.data) self.assertNotIn(ser3.data, res.data) def test_filter_recipes_by_ingredients(self): """Test returning recipes with specific ingredients""" recipe1 = sample_recipe(user=self.user, title='chili con carne') recipe2 = sample_recipe(user=self.user, title='chicken and pasta') recipe3 = sample_recipe(user=self.user, title='steak and mushrooms') ingred1 = sample_ingredient(user=self.user, name='chili') ingred2 = sample_ingredient(user=self.user, name='chicken') ingred3 = sample_ingredient(user=self.user, name='pasta') recipe1.ingredients.add(ingred1) recipe2.ingredients.add(ingred2) res = self.client.get(RECIPES_URL, {'ingredients': f'{ingred1.id},{ingred2.id}'}) serializer1 = RecipeSerializer(recipe1) serializer2 = RecipeSerializer(recipe2) serializer3 = RecipeSerializer(recipe3) self.assertIn(serializer1.data, res.data) self.assertIn(serializer2.data, res.data) self.assertNotIn(serializer3.data, res.data)
class RecipeImageUploadTests(TestCase): def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user('user', 'testpass') self.client.force_authenticate(self.user) self.recipe = sample_recipe(user=self.user) def tearDown(self): self.recipe.image.delete() def test_upload_image_to_recipe(self): """Test uploading an image to recipe""" url = image_upload_url(self.recipe.id) with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf: img = Image.new('RGB', (10, 10)) img.save(ntf, format='JPEG') ntf.seek(0) res = self.client.post(url, {'image': ntf}, format='multipart') self.recipe.refresh_from_db() self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertIn('image', res.data) self.assertTrue(os.path.exists(self.recipe.image.path)) def test_upload_image_bad_request(self): """Test uploading an invalid image""" url = image_upload_url(self.recipe.id) res = self.client.post(url, {'image': 'notimage'}, format='multipart') self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_filter_recipes_by_tags(self): """Test returning recipes with specific tags""" recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry') recipe2 = sample_recipe(user=self.user, title='Aubergine with tahini') tag1 = sample_tag(user=self.user, name='Vegan') tag2 = sample_tag(user=self.user, name='Vegetarian') recipe1.tags.add(tag1) recipe2.tags.add(tag2) recipe3 = sample_recipe(user=self.user, title='Fish and chips') res = self.client.get(RECIPES_URL, {'tags': '{},{}'.format(tag1.id, tag2.id)}) serializer1 = RecipeSerializer(recipe1) serializer2 = RecipeSerializer(recipe2) serializer3 = RecipeSerializer(recipe3) self.assertIn(serializer1.data, res.data) self.assertIn(serializer2.data, res.data) self.assertNotIn(serializer3.data, res.data) def test_filter_recipes_by_ingredients(self): """Test returning recipes with specific ingredients""" recipe1 = sample_recipe(user=self.user, title='Posh beans on toast') recipe2 = sample_recipe(user=self.user, title='Chicken cacciatore') ingredient1 = sample_ingredient(user=self.user, name='Feta cheese') ingredient2 = sample_ingredient(user=self.user, name='Chicken') recipe1.ingredients.add(ingredient1) recipe2.ingredients.add(ingredient2) recipe3 = sample_recipe(user=self.user, title='Steak and mushrooms') res = self.client.get( RECIPES_URL, {'ingredients': '{},{}'.format(ingredient1.id, ingredient2.id)}) serializer1 = RecipeSerializer(recipe1) serializer2 = RecipeSerializer(recipe2) serializer3 = RecipeSerializer(recipe3) self.assertIn(serializer1.data, res.data) self.assertIn(serializer2.data, res.data) self.assertNotIn(serializer3.data, res.data)
def test_group_category(self): client = APIClient() web_response = client.get(path=f"/api/statistics/groupCategory/248") self.assertEqual(200, web_response.status_code)
class PrivateGameApiTests(TestCase): def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( '*****@*****.**', 'testpass' ) self.client.force_authenticate(self.user) def test_retrieve_saved_games(self): """Test retrieving games saved by the user""" game1 = sample_game() game2 = sample_game(igdb_id=13, name='Fez') game3 = sample_game(igdb_id=14, name='Terraria') self.user.saved.add(game2) self.user.saved.add(game3) res = self.client.get(SAVED_URL) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) serializer3 = GameSerializer(game3) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertNotIn(serializer1.data, res.data['results']) self.assertIn(serializer2.data, res.data['results']) self.assertIn(serializer3.data, res.data['results']) def test_add_to_saved(self): """Test the game is added to the saved""" game = sample_game() res1 = self.client.post(reverse( 'gig:game-add-to-saved', args=[game.id] )) res2 = self.client.get(SAVED_URL) serializer = GameSerializer(game) self.assertEqual(res1.status_code, status.HTTP_200_OK) self.assertIn(serializer.data, res2.data['results']) def test_remove_from_saved(self): """Test the game is removed from the saved""" game = sample_game() self.user.saved.add(game) res1 = self.client.post(reverse( 'gig:game-remove-from-saved', args=[game.id] )) res2 = self.client.get(SAVED_URL) serializer = GameSerializer(game) self.assertEqual(res1.status_code, status.HTTP_200_OK) self.assertNotIn(serializer.data, res2.data['results']) def test_check_age(self): """Test check age for showing erotic games""" cache.clear() game1 = sample_game() game1.themes.add(Theme.objects.create(name='Horror')) game1.themes.add(Theme.objects.create(name='Erotic')) game2 = sample_game(igdb_id=5, name='Overwatch') game2.themes.add(Theme.objects.create(name='Comedy')) res = self.client.get( GAMES_URL, {'is_adult': 'n'} ) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertIn(serializer2.data, res.data['results']) self.assertNotIn(serializer1.data, res.data['results'])
class PrivateTestForIngredient(TestCase): """test privately Ingredient""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create(email="*****@*****.**", password="******") self.client.force_authenticate(self.user) def test_get_all_ingredient(self): """ test anthenticated user must get all of ingredient""" Ingredient.objects.create(name="dessert", user=self.user) Ingredient.objects.create( name="frouti", user=self.user, ) res = self.client.get(INGREDIENT_URL) ingredients = Ingredient.objects.all().order_by('-name') ingredient_srealizer = IngredientSerializer(ingredients, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, ingredient_srealizer.data) def test_ingredient_limited(self): """ingredient must show for own user""" user = get_user_model().objects.create(email="*****@*****.**", password="******") Ingredient.objects.create(name="desert", user=user) ingredient = Ingredient.objects.create(name="frouti", user=self.user) res = self.client.get(INGREDIENT_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data[0]['name'], ingredient.name) def test_create_ingredient_successful(self): """test create ingredient successfuly""" payload = {'name': 'test', 'user': self.user} res = self.client.post(INGREDIENT_URL, payload) exists = Ingredient.objects.filter(name=payload['name']).exists() self.assertTrue(exists) def test_create_ingredient_invalid(self): """test create ingredient with wrong value becomes fails""" payload = {'name': '', 'user': self.user} res = self.client.post(INGREDIENT_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_retrieve_ingredients_assigned_recipe(self): """test retrieving ingredients that assigned to specific recipe""" recipe = Recipe.objects.create(user=self.user, title='test', time_minutes=23, price=23) ingredient1 = Ingredient.objects.create(user=self.user, name="test") ingredient2 = Ingredient.objects.create(user=self.user, name='test2') recipe.ingredient.add(ingredient1) res = self.client.get(INGREDIENT_URL, {'assigned_only': 1}) serializer1 = IngredientSerializer(ingredient1) serializer2 = IngredientSerializer(ingredient2) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertIn(serializer1.data, res.data) self.assertNotIn(serializer2.data, res.data) def test_retrieving_ingredients_assigned_unique(self): """test filtering ingredients by assigned returns unique items""" ingredient1 = Ingredient.objects.create(user=self.user, name="test1") Ingredient.objects.create(user=self.user, name="test2") recipe1 = Recipe.objects.create(user=self.user, title="test1", time_minutes=2, price=23) recipe2 = Recipe.objects.create(user=self.user, title="test2", time_minutes=32, price=32) recipe1.ingredient.add(ingredient1) recipe2.ingredient.add(ingredient1) res = self.client.get(INGREDIENT_URL, {'assigned_only': 1}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1)
class AddressTestCase(TestCase): def setUp(self): logging.disable(logging.CRITICAL) self.token = TestHelpers.test_setup() self.client = APIClient() self.client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) self.items = AddressUtils.seeding(3) def test_list(self): resp = self.client.get('/api/v1/address/') self.assertEqual(resp.status_code, 200) resp = resp.json() self.assertEqual(resp['count'], 3) def test_detail(self): # Item not exist resp = self.client.get("/api/v1/address/{}".format(0)) self.assertEqual(resp.status_code, 404) # Item exist resp = self.client.get("/api/v1/address/{}".format(self.items[0].pk)) self.assertEqual(resp.status_code, 200) def test_create(self): # Add success item4 = AddressUtils.seeding(4, True, False) resp = self.client.post('/api/v1/address/', item4, format='json') self.assertEqual(resp.status_code, 200) self.assertEqual(Address.objects.count(), 4) def test_edit(self): item1 = AddressUtils.seeding(1, True, False) # Update not exist resp = self.client.put("/api/v1/address/{}".format(0), item1, format='json') self.assertEqual(resp.status_code, 404) # Update success resp = self.client.put("/api/v1/address/{}".format(self.items[0].pk), item1, format='json') self.assertEqual(resp.status_code, 200) def test_delete(self): # Remove not exist resp = self.client.delete("/api/v1/address/{}".format(0)) self.assertEqual(resp.status_code, 404) self.assertEqual(Address.objects.count(), 3) # Remove single success resp = self.client.delete("/api/v1/address/{}".format( self.items[0].pk)) self.assertEqual(resp.status_code, 204) self.assertEqual(Address.objects.count(), 2) # Remove list success resp = self.client.delete("/api/v1/address/?ids={}".format(','.join( [str(self.items[1].pk), str(self.items[2].pk)]))) self.assertEqual(resp.status_code, 204) self.assertEqual(Address.objects.count(), 0)
class GameApiTests(TestCase): """Test games API""" def setUp(self): self.client = APIClient() def test_retrieve_games(self): """Test retrieving a list of games""" game1 = sample_game() game2 = sample_game(name='Bioshock') cache.clear() res = self.client.get(GAMES_URL) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertIn(serializer1.data, res.data['results']) self.assertIn(serializer2.data, res.data['results']) def test_view_game_detail(self): """Test viewing a game detail""" game = sample_game() game.genres.add(sample_genre()) game.platforms.add(sample_platform()) game.developers.add(sample_developer()) game.publishers.add(sample_publisher()) url = detail_url(game.id) res = self.client.get(url) serializer = GameDetailSerializer(game) self.assertEqual(res.data, serializer.data) def test_filter_games_by_genres(self): """Test returning games with specific genres""" game1 = sample_game() game2 = sample_game(name='Dishonored') genre1 = sample_genre() genre2 = sample_genre(name='Simulator') game1.genres.add(genre1) game2.genres.add(genre2) game3 = sample_game(name='Watch Dogs') res = self.client.get( GAMES_URL, {'genres': f'{genre1.id},{genre2.id}'} ) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) serializer3 = GameSerializer(game3) self.assertIn(serializer1.data, res.data['results']) self.assertIn(serializer2.data, res.data['results']) self.assertNotIn(serializer3.data, res.data['results']) def test_filter_games_by_themes(self): """Test returning games with specific themes""" game1 = sample_game() game2 = sample_game(name='Dishonored') theme1 = sample_theme() theme2 = sample_theme(name='Sandbox') game1.themes.add(theme1) game2.themes.add(theme2) game3 = sample_game(name='Watch Dogs') res = self.client.get( GAMES_URL, {'themes': f'{theme1.id},{theme2.id}'} ) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) serializer3 = GameSerializer(game3) self.assertIn(serializer1.data, res.data['results']) self.assertIn(serializer2.data, res.data['results']) self.assertNotIn(serializer3.data, res.data['results']) def test_filter_games_by_platforms(self): """Test returning games with specific platforms""" game1 = sample_game() game2 = sample_game(name='Dishonored') platform1 = sample_platform() platform2 = sample_platform(name='PS4') game1.platforms.add(platform1) game2.platforms.add(platform2) game3 = sample_game(name='Watch Dogs') res = self.client.get( GAMES_URL, {'platforms': f'{platform1.id},{platform2.id}'} ) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) serializer3 = GameSerializer(game3) self.assertIn(serializer1.data, res.data['results']) self.assertIn(serializer2.data, res.data['results']) self.assertNotIn(serializer3.data, res.data['results']) def test_filter_games_by_developers(self): """Test returning games with specific developers""" game1 = sample_game() game2 = sample_game(name='Dishonored') developer1 = sample_developer() developer2 = sample_developer(name='Arkane Studios') game1.developers.add(developer1) game2.developers.add(developer2) game3 = sample_game(name='Watch Dogs') res = self.client.get( GAMES_URL, {'developers': f'{developer1.id},{developer2.id}'} ) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) serializer3 = GameSerializer(game3) self.assertIn(serializer1.data, res.data['results']) self.assertIn(serializer2.data, res.data['results']) self.assertNotIn(serializer3.data, res.data['results']) def test_filter_games_by_publishers(self): """Test returning games with specific publishers""" game1 = sample_game() game2 = sample_game(name='Dishonored') publisher1 = sample_publisher() publisher2 = sample_publisher(name='Bethesda Softworks') game1.publishers.add(publisher1) game2.publishers.add(publisher2) game3 = sample_game(name='Watch Dogs') res = self.client.get( GAMES_URL, {'publishers': f'{publisher1.id},{publisher2.id}'} ) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) serializer3 = GameSerializer(game3) self.assertIn(serializer1.data, res.data['results']) self.assertIn(serializer2.data, res.data['results']) self.assertNotIn(serializer3.data, res.data['results']) def test_filter_games_by_date(self): """Test filter games by date""" game1 = sample_game( first_release_date=datetime.datetime.fromtimestamp(1417943600) ) game2 = sample_game( first_release_date=datetime.datetime.fromtimestamp(1407995600) ) game3 = sample_game() date = datetime.datetime.fromtimestamp(1400000000) res = self.client.get( GAMES_URL, {'first_release_date__gte': date} ) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) serializer3 = GameSerializer(game3) self.assertIn(serializer1.data, res.data['results']) self.assertIn(serializer2.data, res.data['results']) self.assertNotIn(serializer3.data, res.data['results']) def test_filter_games_by_rating(self): """Test filter games by rating""" game1 = sample_game(rating=60) game2 = sample_game(rating=70) game3 = sample_game(rating=80) res = self.client.get( GAMES_URL, {'rating__gte': '70'} ) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) serializer3 = GameSerializer(game3) self.assertNotIn(serializer1.data, res.data['results']) self.assertIn(serializer2.data, res.data['results']) self.assertIn(serializer3.data, res.data['results']) def test_search_games_by_name(self): """Test search games by name""" game1 = sample_game(name='The Path') game2 = sample_game(name='Path of Exile') game3 = sample_game() res = self.client.get( GAMES_URL, {'search': 'path'} ) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) serializer3 = GameSerializer(game3) self.assertIn(serializer1.data, res.data['results']) self.assertIn(serializer2.data, res.data['results']) self.assertNotIn(serializer3.data, res.data['results']) def test_return_game_from_similar_games(self): """Test returning game by id in similar games""" game1 = sample_game(similar_games=[2, 3]) game2 = sample_game(id=2, name='Terraria') game3 = sample_game(id=3, name='Fez') similar_games = "," similar_games = similar_games.join(str(x) for x in game1.similar_games) res = self.client.get( GAMES_URL, {'ids': similar_games} ) serializer1 = GameSerializer(game1) serializer2 = GameSerializer(game2) serializer3 = GameSerializer(game3) self.assertIn(serializer2.data, res.data['results']) self.assertIn(serializer3.data, res.data['results']) self.assertNotIn(serializer1.data, res.data['results']) def test_saved_only_for_authenticated_users(self): """Test that authentication is required for saved""" res = self.client.get(SAVED_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) def test_add_to_saved_only_for_authenticated_users(self): """Test that authentication is required for adding to saved""" game = sample_game() res = self.client.post(reverse( 'gig:game-add-to-saved', args=[game.id] )) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) def test_remove_from_saved_only_for_authenticated_users(self): """Test that authentication is required for remove from saved""" game = sample_game() res = self.client.post(reverse( 'gig:game-remove-from-saved', args=[game.id] )) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)