"""This module contains the test case for the fields of the ``media`` app"""

from django.core.exceptions import ValidationError
from django.test.testcases import TestCase

from mtp.apps.common.tests.test_cases import WithMediaOnDisk

from .media_testapp.factories import ModelWithPdfFieldFactory


class MimeTypeRestrictedFileFieldTestCase(WithMediaOnDisk, TestCase):
    """Test for the ``MimeTypeRestrictedFileField`` field"""

    def test_clean_should_raise_if_invalid_mime_type(self):
        """Test that a file with an invalid mime type shouldn't be accepted"""

        instance = ModelWithPdfFieldFactory(file__filename='test.mov')

        # We expected a pdf, but get a movie instead
        with self.assertRaises(ValidationError) as error_context:
            instance.full_clean()

        self.assertEqual(
            error_context.exception.message_dict,
            {
                'file': [
                    'Unsupported file type. Please upload one of the following: application/pdf'
                ]
            }
        )

        # If we change the file to looks like a pdf, it should work
        instance = ModelWithPdfFieldFactory(file__filename='test.pdf')
        instance.full_clean()

    def test_clean_should_raise_if_max_size_greater_than_allowed(self):
        """Test that a file with a maximum size greater than the allowed one should raise"""

        instance = ModelWithPdfFieldFactory(
            file__filename='test.pdf',
            file__data=b'testwithmanycharacters'
        )

        # We expected a file with 4 bytes, but get one with 22
        with self.assertRaises(ValidationError) as error_context:
            instance.full_clean()

        self.assertEqual(
            error_context.exception.message_dict,
            {
                'file': [
                    'Please keep file size under 4\xa0bytes. Current size is 22\xa0bytes'
                ]
            }
        )

        # If we change the file to be be under the allowed size, it should work
        instance = ModelWithPdfFieldFactory(
            file__filename='test.pdf',
            file__data=b'test'
        )
        instance.full_clean()
