# Copyright (C) 2010  Internet Systems Consortium.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
# DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#
# Tests for the configuration manager run script
#

import unittest
import os
import sys
import bind10_config
from isc.testutils.parse_args import OptsError, TestOptParser

class MyConfigManager:
    def __init__(self, path, filename, session=None, rename_config_file=False):
        self._path = path
        self.read_config_called = False
        self.notify_boss_called = False
        self.run_called = False
        self.write_config_called = False
        self.rename_config_called = False
        self.running = True
        self.virtual_modules = []

    def read_config(self):
        self.read_config_called = True

    def notify_boss(self):
        self.notify_boss_called = True

    def run(self):
        self.run_called = True

    def write_config(self):
        self.write_config_called = True

    def rename_config_file(self, ofile, nfile):
        self.rename_config_called = True

    def set_virtual_module(self, spec, function):
        self.virtual_modules.append((spec, function))

class TestPlugins(unittest.TestCase):
    def test_load_plugins(self):
        """Test we can successfully find and load the mock plugin."""
        # Let it load the plugin
        b = __import__("b10-cfgmgr")
        # The parameters aren't important for this test
        cm = MyConfigManager(None, None)
        b.load_plugins(os.environ['TESTDATA_PATH'] + os.sep + 'plugins', cm)
        # Check exactly one plugin was loaded and the right data were fed into
        # the cm
        self.assertEqual(len(cm.virtual_modules), 1)
        (spec, check) = cm.virtual_modules[0]
        self.assertEqual(spec.get_module_name(), "mock_config_plugin")
        self.assertEqual(check(None), "Mock config plugin")

class TestConfigManagerStartup(unittest.TestCase):
    def test_cfgmgr(self):
        # some creative module use;
        # b10-cfgmgr has a hypen, so we use __import__
        # this also gives us the chance to override the imported
        # module ConfigManager in it.
        b = __import__("b10-cfgmgr")
        orig_load = b.load_plugins
        b.PLUGIN_PATHS = ["/plugin/path"]
        self.loaded_plugins = False
        def load_plugins(path, cm):
            # Check it's called with proper arguments
            self.assertEqual(path, "/plugin/path")
            self.assertTrue(isinstance(cm, MyConfigManager))
            self.loaded_plugins = True
        b.load_plugins = load_plugins
        b.ConfigManager = MyConfigManager

        b.main()
        b.load_plugins = orig_load

        self.assertTrue(b.cm.read_config_called)
        self.assertTrue(b.cm.notify_boss_called)
        self.assertTrue(b.cm.run_called)
        self.assertTrue(self.loaded_plugins)
        # if there are no changes, config is not written
        self.assertFalse(b.cm.write_config_called)
        self.assertFalse(b.cm.rename_config_called)

        self.assertTrue(b.cm.running)
        b.signal_handler(None, None)
        self.assertFalse(b.cm.running)

        # TODO: take value from the 'global config module'
        # (and rename the .in away from this file again)
        data_path = "@localstatedir@/@PACKAGE@".replace("${prefix}", "@prefix@")
        self.assertEqual(data_path, b.DATA_PATH)

        # remove the 'module' again, or later tests may fail
        # (if it is already present it won't be loaded again)
        sys.modules.pop("b10-cfgmgr")

    def test_cfgmgr_from_source(self):
        tmp_env_var = "/just/some/dir"
        env_var = None
        if "B10_FROM_SOURCE" in os.environ:
            env_var = os.environ["B10_FROM_SOURCE"]

        os.environ["B10_FROM_SOURCE"] = tmp_env_var
        bind10_config.reload()
        b = __import__("b10-cfgmgr", globals(), locals())
        b.PLUGIN_PATH = [] # It's enough to test plugins in one test
        b.ConfigManager = MyConfigManager
        self.assertEqual(tmp_env_var, b.DATA_PATH)

        if env_var != None:
            os.environ["B10_FROM_SOURCE"] = env_var
        bind10_config.reload()

        sys.modules.pop("b10-cfgmgr")

class TestParseArgs(unittest.TestCase):
    """
    Test for the parsing of command line arguments. We provide a different
    array to parse instead.
    """

    def test_defaults(self):
        """
        Test the default values when no options are provided.
        """
        # Pass it empty array, not our arguments
        b = __import__("b10-cfgmgr")
        parsed = b.parse_options([], TestOptParser)
        self.assertEqual(None, parsed.data_path)
        self.assertEqual(None, parsed.config_file)

    def test_wrong_args(self):
        """
        Test it fails when we pass invalid option.
        """
        b = __import__("b10-cfgmgr")
        self.assertRaises(OptsError, b.parse_options, ['--wrong-option'],
                          TestOptParser)

    def test_not_arg(self):
        """
        Test it fails when there's an argument that's not option
        (eg. without -- at the beginning).
        """
        b = __import__("b10-cfgmgr")
        self.assertRaises(OptsError, b.parse_options, ['not-option'],
                          TestOptParser)

    def test_datapath(self):
        """
        Test overwriting the data path.
        """
        b = __import__("b10-cfgmgr")
        parsed = b.parse_options(['--data-path=/path'], TestOptParser)
        self.assertEqual('/path', parsed.data_path)
        self.assertEqual(None, parsed.config_file)
        parsed = b.parse_options(['-p', '/path'], TestOptParser)
        self.assertEqual('/path', parsed.data_path)
        self.assertEqual(None, parsed.config_file)
        self.assertRaises(OptsError, b.parse_options, ['-p'], TestOptParser)
        self.assertRaises(OptsError, b.parse_options, ['--data-path'],
                          TestOptParser)

    def test_db_filename(self):
        """
        Test setting the configuration database file.
        """
        b = __import__("b10-cfgmgr")
        parsed = b.parse_options(['--config-filename=filename'],
                                 TestOptParser)
        self.assertEqual(None, parsed.data_path)
        self.assertEqual("filename", parsed.config_file)
        parsed = b.parse_options(['-c', 'filename'], TestOptParser)
        self.assertEqual(None, parsed.data_path)
        self.assertEqual("filename", parsed.config_file)
        self.assertRaises(OptsError, b.parse_options, ['-c'], TestOptParser)
        self.assertRaises(OptsError, b.parse_options, ['--config-filename'],
                          TestOptParser)

    def test_determine_path_and_file(self):
        b = __import__("b10-cfgmgr")
        self.assertEqual((b.DATA_PATH, b.DEFAULT_CONFIG_FILE),
                         b.determine_path_and_file(None, None))
        self.assertEqual(("/foo", b.DEFAULT_CONFIG_FILE),
                         b.determine_path_and_file("/foo", None))
        self.assertEqual((os.getcwd(), "file.config"),
                         b.determine_path_and_file(None, "file.config"))
        self.assertEqual(("/foo", "bar"),
                         b.determine_path_and_file("/foo", "bar"))

    def test_clear_config(self):
        b = __import__("b10-cfgmgr")
        parsed = b.parse_options([], TestOptParser)
        self.assertFalse(parsed.clear_config)
        parsed = b.parse_options(['--clear-config'], TestOptParser)
        self.assertTrue(parsed.clear_config)

if __name__ == '__main__':
    unittest.main()

