import os
from pathlib import Path

from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy

from core.validators import ValidateFileExtension

import pytest

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
file_json = os.path.join(BASE_DIR, "tests", "test_data/file.json")
file_zip = os.path.join(BASE_DIR, "tests", "test_data/file.zip")
file_without_extension = os.path.join(BASE_DIR, "tests", "test_data/file")


class TestExtensionValidator:

    @pytest.mark.unit
    def test_raise_error_if_extension_incorrect(self):
        """
            The test fails if the validator did not raise a ValidationError with invalid file
        """

        validator = ValidateFileExtension(allowed_extensions=['.zip'])
        ext = Path(file_json).suffix.lower()
        try:
            validator(open(file_json, 'rb'))
        except ValidationError as e:
            assert str(e.message) == gettext_lazy(
                "File extension '{extension}' is not allowed. Allowed extensions are: '{allowed_extensions}'.").format(
                extension=ext, allowed_extensions=', '.join(validator.allowed_extensions))
        else:
            assert False, 'Validator not working'

    @pytest.mark.unit
    def test_works_with_several_extensions(self):
        """
            The test fails if the validator raise a ValidationError with correct file
        """
        validator = ValidateFileExtension(allowed_extensions=['.zip', '.json'])
        try:
            validator(open(file_zip, 'rb'))
        except ValidationError:
            assert False, 'Validator not working'
        else:
            assert True

    @pytest.mark.unit
    def test_works_with_files_without_extension(self):
        """
            The test fails if the validator did not raise a ValidationError with file without extension
        """
        validator = ValidateFileExtension(allowed_extensions=['.zip', '.json'])
        try:
            validator(open(file_without_extension, 'rb'))
        except ValidationError:
            assert True
        else:
            assert False, 'Validator not working'
