# (c) cavaliba.com - tests / views_importer - prefill on parse failure

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, override_settings
from django.urls import reverse

import app_home.cache as cache
from tests import helper


@override_settings(CAVALIBA_AUTH_MODE="unittest")
class ViewImporterPrefillTest(TestCase):
    """On a parse failure, the view re-renders with the bound ImportForm, so
    every field except the file input keeps the value the user submitted."""

    def setUp(self):
        cache.clear()
        helper.add_admin_user(login="unittest")
        helper.add_pipeline_noop()

    def test_pipeline_selection_survives_a_parse_error(self):
        # "café" encoded as iso-8859-1 is not valid ascii - decoding it with
        # encoding="ascii" raises UnicodeDecodeError inside load_file_csv().
        content = "keyname,mystring\nrow1,café\n".encode("iso-8859-1")
        data = {
            "file": SimpleUploadedFile("data.csv", content, content_type="text/csv"),
            "pipeline": "pipeline_noop",
            "encoding": "ascii",
            "separator": ",",
            "split_multivalue": "on",
            "submit": "verify",
        }
        response = self.client.post(reverse("app_data:data_import"), data)

        self.assertEqual(response.status_code, 200)
        rendered = [str(m) for m in response.context["messages"]]
        self.assertTrue(any("Import failed" in m for m in rendered))
        self.assertIn('value="pipeline_noop" selected', response.content.decode())
