# (c) cavaliba.com


from io import StringIO

from django.core.management import call_command
from django.test import TestCase

import app_home.cache as cache
from tests import helper


class CommandTest(TestCase):
    def setUp(self):
        cache.clear()
        helper.add_schema(classname="test1")
        helper.add_instance(classname="test1", keyname="test1-01")

    def test_check_command(self):

        output = StringIO()
        StringIO()
        call_command("check", verbosity=2, stdout=output)
        assert "System check identified no issues" in output.getvalue()

    def test_version_command(self):
        output = StringIO()
        StringIO()
        call_command("cavaliba", "version", verbosity=2, stdout=output)
        assert "." in output.getvalue()
        self.assertTrue(len(output.getvalue()) > 5)

    def test_start_command(self):
        output = StringIO()
        StringIO()
        call_command("cavaliba", "start", verbosity=2, stdout=output)
        assert "start done" in output.getvalue()

    def test_schema_command(self):
        output = StringIO()
        StringIO()
        call_command("cavaliba", "schema", verbosity=2, stdout=output)
        assert "IAM" in output.getvalue()

    def test_get_command(self):
        output = StringIO()
        StringIO()
        call_command("cavaliba", "get", "--schema", "test1", "--yaml", verbosity=2, stdout=output)
        assert "keyname: test1-01" in output.getvalue()

    def test_conf_command(self):

        output = StringIO()
        StringIO()
        call_command("cavaliba", "conf", verbosity=2, stdout=output)
        assert "GLOBAL_APPNAME" in output.getvalue()

    def test_log_command(self):
        output = StringIO()
        StringIO()
        call_command("cavaliba", "log", verbosity=2, stdout=output)
        assert "entries" in output.getvalue()

    def test_log_purge_command(self):

        output = StringIO()
        StringIO()
        call_command("cavaliba", "log", "--log_purge", verbosity=2, stdout=output)
        assert "log done" in output.getvalue()

    def test_load_command_unknown(self):

        output = StringIO()
        err = StringIO()
        call_command("cavaliba", "load", "unknown_file", verbosity=2, stdout=output, stderr=err)
        assert "load done" in output.getvalue()
        assert "SKIP - Unknown filename" in err.getvalue()
