"""This module contains tests about the ``translation.utils`` module."""

import tempfile
from unittest import skipIf, TestCase as UnitTestCase

import polib
from django.core.management.utils import find_command

from . import constants
from ..exceptions import PoFileCheckError
from ..utils import check_po_file


@skipIf(find_command('msgfmt') is None, "GNU gettext tools 0.15 or newer are not installed.")
class POFileCheckTestCase(UnitTestCase):
    """Test validation of a ``PO`` file.

    Notes
    -----
    This class is based on ``unittest.TestCase`` as it's not at all related to ``django``.

    """

    def test_file_without_errors(self):
        """Test that doing a check on a PO file without errors doesn't raise."""

        # An example po with a lot of different cases
        po_content = constants.CORRECT_POFILE

        with tempfile.NamedTemporaryFile(suffix='.po') as tmp_file:
            tmp_file.write(po_content)
            tmp_file.flush()

            po_file = polib.pofile(tmp_file.name)
            check_po_file(po_file)

    maxDiff = None

    def test_file_with_errors(self):
        """Test that doing a check on a PO file with errors raise an exception."""

        # An example po with a lot of different cases, and some errors
        po_content = bytes(r"""
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-10-16 12:32+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: \n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: mtp/templates/pinax/notifications/user_welcome/subject.txt:5
msgid "Welcome to the Magency digital training platform."
msgstr "Benvenuto nella piattaforma di formazione digitale."

#: mtp/apps/accounts/admin.py:86
msgid "Account data"
msgstr ""

#, fuzzy
#: mtp/templates/cms/translation/dashboard.html:42
msgid "Add"
msgstr "Aggiungi"

#: mtp/apps/common/client_mail_templates.py:21
#, python-format
msgid "[%(training_name)s] Your new training content is online."
msgstr "[%(training-name)s] Il tuo contenuto di formazione e on line."

#: mtp/templates/cms/workshops/workshopstep_sort.html:6
msgid ""
"\n"
"        Sort the steps of the quiz \"workshop_title\"\n"
"    "
msgstr ""
"\n"
"        Ordina i passi del quiz \"titolo_workshop\"\n"
"    "

#: mtp/apps/likes/models.py:79
#, python-format
msgid "%s like %s"
msgstr "% like %s"

#: mtp/templates/cms/surveys/question_form.html:88
#, python-format
msgid "Edit the question \"%(question_title)s\" of the pool \"%(pool_name)s\""
msgstr "Modifica la domanda \"%(question_title)s\" del gruppo \"%(pool_name)s\""

#: mtp/custom/nissan/templates/cms/assessments/lesson_references_import.html:5
msgid ""
"\n"
"        Import lesson references from the SABA LMS\n"
"    "
msgstr ""
"Carica i riferimenti della lezione dal portale della formazione SABA\n"

#: mtp/templates/cms/trainings/training_confirm_delete.html:12
#, python-format
msgid "Are you sure you want to delete the training \"%(training_name)s\"?"
msgstr "Sei sicuro di voler cancellare la formazione \"%(training_name)s\"?"

#: mtp/templates/cms/assessments/competency_form.html:8
#, python-format
msgid "New competency for \"%(job_profile_name)s\""
msgstr "Nuova competenza per \"%/job_profile_name)s\""

#: mtp/apps/accounts/admin.py:96
#~ msgid "MTP Profile data"
#~ msgstr "Dati profilo MTP"
        """, 'utf-8')

        with tempfile.NamedTemporaryFile(suffix='.po') as tmp_file:
            tmp_file.write(po_content)
            tmp_file.flush()

            po_file = polib.pofile(tmp_file.name)
            with self.assertRaises(PoFileCheckError) as raise_context:
                check_po_file(po_file, max_passes=2)

            expected_errors = [
                (
                    35,
                    "[%(training_name)s] Your new training content is online.",
                    "a format specification for argument 'training-name', as in 'msgstr', doesn't "
                    "exist in 'msgid'"
                ),
                (
                    50,
                    "%s like %s",
                    "format specifications in 'msgid' and 'msgstr' for argument 1 are not the same"
                ),
                (
                    60,
                    "\n        Import lesson references from the SABA LMS\n    ",
                    "'msgid' and 'msgstr' entries do not both begin with '\\n'"
                ),
                (
                    73,
                    "New competency for \"%(job_profile_name)s\"",
                    "'msgstr' is not a valid Python format string, unlike 'msgid'. Reason: In the "
                    "directive number 1, the character '/' is not a valid conversion specifier."
                ),
            ]

            errors = [
                (
                    entry.linenum if entry else None,
                    entry.msgid if entry else None,
                    error_msg
                ) for entry, error_msg in raise_context.exception.errors
            ]

            self.assertListEqual(errors, expected_errors)
