# (c) cavaliba.com - tests CSV "Columns" export: schema/is_enabled opt-in, no id

from django.test import TestCase

import app_home.cache as cache
from app_data.data import Instance
from tests import helper


class TestCsvColumnsSchemaAndIsEnabled(TestCase):
    def setUp(self):
        cache.clear()
        helper.add_schema(
            classname="csvschematest",
            field_definition={
                "mystring": {"dataformat": "string", "displayname": "MyString"},
            },
        )
        helper.add_instance(
            classname="csvschematest",
            keyname="obj01",
            fields={"mystring": "hello"},
        )

    def _columns(self, fields=None):
        instance = Instance.from_keyname("csvschematest", "obj01")
        return instance.get_csv_columns(fields=fields)

    def _line(self, columns):
        instance = Instance.from_keyname("csvschematest", "obj01")
        return instance.get_csv_line(columns)

    def test_default_star_includes_schema_and_is_enabled(self):
        columns = self._columns(fields=None)
        self.assertIn("schema", columns)
        self.assertIn("is_enabled", columns)
        self.assertIn("keyname", columns)

    def test_schema_header_carries_classname_value(self):
        columns = self._columns(fields=None)
        line = self._line(columns)
        self.assertEqual(dict(zip(columns, line))["schema"], "csvschematest")

    def test_schema_excluded_by_explicit_blacklist(self):
        columns = self._columns(fields="!schema")
        self.assertNotIn("schema", columns)
        self.assertIn("keyname", columns)

    def test_is_enabled_excluded_by_explicit_blacklist(self):
        columns = self._columns(fields="!is_enabled")
        self.assertNotIn("is_enabled", columns)
        self.assertIn("keyname", columns)

    def test_narrow_whitelist_excludes_schema_and_is_enabled(self):
        columns = self._columns(fields="mystring")
        self.assertNotIn("schema", columns)
        self.assertNotIn("is_enabled", columns)
        self.assertIn("mystring", columns)
        self.assertIn("keyname", columns)

    def test_no_literal_classname_header(self):
        # the header is always "schema", never "classname"
        columns = self._columns(fields=None)
        self.assertNotIn("classname", columns)

    def test_id_never_present(self):
        for fields in (None, "*", "id", "!*"):
            columns = self._columns(fields=fields)
            self.assertNotIn("id", columns)
