<reponame>hiway/zentropi20<gh_stars>0
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User

from .models import Frame
from rest_framework.test import APIClient
from rest_framework import status


class ModelTestCase(TestCase):

    def setUp(self):
        user = User.objects.create(username="tester")  # ADD THIS LINE
        self.frame_name = "hello, world!"
        self.frame = Frame(name=self.frame_name, owner=user)

    def test_model_can_create_a_frame(self):
        old_count = Frame.objects.count()
        self.frame.save()
        new_count = Frame.objects.count()
        self.assertNotEqual(old_count, new_count)


class ViewTestCase(TestCase):

    def setUp(self):
        user = User.objects.create(username="tester")
        self.client = APIClient()
        self.client.force_authenticate(user=user)
        self.frame_data = {'name': 'test a frame', 'owner': user.id}
        self.response = self.client.post(
            reverse('create'),
            self.frame_data,
            format="json")

    def test_authorization_is_enforced(self):
        """Test that the api has user authorization."""
        new_client = APIClient()
        res = new_client.get(reverse('details',
                    kwargs={'pk': 1}), kwargs={'pk': 1}, format="json")
        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_api_can_create_a_frame(self):
        self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

    def test_api_can_get_a_frame(self):
        """Test the api can get a given frame."""
        frame = Frame.objects.get()
        response = self.client.get(
            reverse('details',
                    kwargs={'pk': frame.id}), format="json")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertContains(response, frame)

    def test_api_can_update_frame(self):
        """Test the api can update a given frame."""
        frame = Frame.objects.get()
        change_frame = {'name': 'new'}
        res = self.client.put(
            reverse('details', kwargs={'pk': frame.id}),
            change_frame, format='json'
        )
        self.assertEqual(res.status_code, status.HTTP_200_OK)

    def test_api_can_delete_frame(self):
        """Test the api can delete a frame."""
        frame = Frame.objects.get()
        response = self.client.delete(
            reverse('details', kwargs={'pk': frame.id}),
            format='json',
            follow=True)

        self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT)
