"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: michel.peltriaux@sgdnord.rlp.de
Created on: 09.12.21

"""
import mimetypes

from django.core.files.uploadedfile import InMemoryUploadedFile

from konova.models import AbstractDocument
from konova.tests.test_views import BaseTestCase


class TestCaseDocuments(BaseTestCase):
    """
    Tests for the Documents functionalities
    """

    @classmethod
    def setUpTestData(cls):
        """ Creates a test file in memory for using in further tests

        Returns:

        """
        super().setUpTestData()
        cls.max_file_size = AbstractDocument._maximum_file_size * pow(1000, 2)
        cls.test_file = InMemoryUploadedFile(
            charset="utf-8",
            name="test_file",
            size=cls.max_file_size,
            file=None,
            content_type=None,
            field_name=None
        )

    def test_allowed_mime_types(self):
        """ Unit test for mime type validity checker

        Checks that only as acceptable configured mime types of an AbstractDocument object will pass the
        validity check.

        Returns:

        """
        accepted_mime_types = []
        for file_ending, mime_type in mimetypes.types_map.items():
            self.test_file.content_type = mime_type
            valid = AbstractDocument.is_mime_type_valid(self.test_file)
            if valid:
                accepted_mime_types.append(mime_type)
        accepted_mime_types = set(accepted_mime_types)

        self.assertEqual(accepted_mime_types, AbstractDocument._valid_mime_types)

    def test_max_file_size(self):
        """ Unit test for maximum file size validity checker

        Returns:

        """
        # Test for exact maximum size
        self.assertTrue(AbstractDocument.is_file_size_valid(self.test_file))

        # Test for lower than maximum size
        self.test_file.size = self.max_file_size - 1
        self.assertTrue(AbstractDocument.is_file_size_valid(self.test_file))

        # Test for larger than maximum size
        self.test_file.size = self.max_file_size + 1
        self.assertFalse(AbstractDocument.is_file_size_valid(self.test_file))
