import json from django.contrib.auth.models import User from django.urls import reverse from figurines.models import Figurine from figurines.models import Set from rest_framework import status from rest_framework.test import APITestCase class SetTest(APITestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( 'admin', 'admin@localhost', 'admin') def test_create_set(self): """ Check we can create a set object. """ url = reverse('set-list') data = {'name': 'Skypanzers', 'shortname': 'SP'} self.client.force_authenticate(user=self.superuser) response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(Set.objects.count(), 1) self.assertEqual(Set.objects.get().name, 'Skypanzers') def test_sorted_set(self): """ Check that set list is sorted. """ Set.objects.create(name='Skypanzers') Set.objects.create(name='Liibo') Set.objects.create(name='Skypanzers2') Set.objects.create(name='Amimoche') url = reverse('set-list') self.client.force_authenticate(user=self.superuser) response = self.client.get(url, format='json') sorted_sets = list(Set.objects.all().order_by('name') .values_list('name', flat=True)) sets = [x.get('name') for x in json.loads(response.content)] self.assertEqual(sets, sorted_sets) class FigurineTest(APITestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( 'admin', 'admin@localhost', 'admin') def test_create_figurine(self): """ Check we can create a figurine object. """ # Figurine comes from a specific Set collection = Set.objects.create(name='Skypanzers') collection_url = reverse('set-detail', kwargs={'pk': collection.id}) url = reverse('figurine-list') data = { 'name': 'Posséïdon', 'collection': collection_url, } self.client.force_authenticate(user=self.superuser) response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(Figurine.objects.count(), 1) self.assertEqual(Figurine.objects.get().name, 'Posséïdon') self.assertEqual(Figurine.objects.get().collection_id, collection.id) def test_sorted_figurines(self): """ Check that figurine list is sorted. """ collection = Set.objects.create(name='Amimoche') Figurine.objects.create(name='Posséïdon', collection=collection) Figurine.objects.create(name='Veronica', collection=collection) Figurine.objects.create(name='Quintrépide', collection=collection) url = reverse('figurine-list') self.client.force_authenticate(user=self.superuser) response = self.client.get(url, format='json') sorted_figurines = list(Figurine.objects.all().order_by('name') .values_list('name', flat=True)) figurines = [x.get('name') for x in json.loads(response.content)] self.assertEqual(figurines, sorted_figurines)