# Path: clearstack/answer_file.py
# class AnswerFile:
#     def generate(self, file, variables_cmd):
#         with open(file, "w") as f:
#             f.write("[general]\n\n")
#             for group in Controller.get().get_all_groups():
#                 for argument in group.get_all_arguments():
#                     f.write("# {0}\n".format(argument.description))
#                     value = variables_cmd.get(argument.conf_name,
#                                               argument.default_value)
#                     f.write("{0}={1}\n\n".format(argument.conf_name, value))
# 
#     def read(self, file, variables_cmd):
#         conf = Controller.get().CONF
#         config = configparser.RawConfigParser()
#         config.optionxform = str
#         if not os.path.isfile(file):
#             raise IOError("file {0} not found".format(file))
# 
#         """ Validate option in answer file"""
#         config.read(file)
#         if not config.has_section('general'):
#             raise KeyError("answer file {0} doesn't have general"
#                            " section".format(file))
#         conf_file = dict(config['general'])
#         conf_file.update(variables_cmd)  # override variables
#         conf.update(conf_file)
# 
#         try:
#             Controller.get().validate_groups(conf_file)
#         except Exception as e:
#             raise e
# 
#         all_args = Controller.get().get_all_arguments()
#         for non_supported in (set(conf_file) - set(all_args)):
#             LOG.warn("clearstack: variable {0} is not"
#                      " supported yet".format(non_supported))
# 
# Path: clearstack/argument.py
# class Argument(object):
#     def __init__(self, cmd_option, description,
#                  conf_name, default_value, validators=[],
#                  options=None):
#         self.cmd_option = cmd_option
#         self.description = description
#         self.conf_name = conf_name
#         self.default_value = default_value
#         self.validators = validators
#         self.option_list = options
# 
#     def validate(self, option):
#         for validator in self.validators:
#             try:
#                 validator(option)
#             except ValueError as e:
#                 raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
# 
# Path: clearstack/controller.py
# class Controller:
#     CONF = {}
#     _plugins = []
#     _groups = []
#     _sequences = []
# 
#     def add_sequence(self, desc, function, args=None):
#         self._sequences.append(Sequence(desc, function, args))
# 
#     def run_all_sequences(self):
#         for seq in self._sequences:
#             try:
#                 seq.run()
#             except Exception as e:
#                 raise e
# 
#     def add_plugin(self, plugin):
#         self._plugins.append(plugin)
# 
#     def get_all_plugins(self):
#         return self._plugins
# 
#     def add_group(self, name, args):
#         self._groups.append(Group(name, args))
# 
#     def get_all_groups(self):
#         return self._groups
# 
#     def get_all_arguments(self):
#         """Get a list of the configuration argument loaded"""
#         arguments = []
#         for group in self._groups:
#             arguments.extend([argument.conf_name
#                               for argument in group.get_all_arguments()])
#         return arguments
# 
#     def validate_groups(self, conf_values):
#         """ Load validation functions, in order to check
#         the values in the answer file """
#         arguments = {}
#         for group in self._groups:
#             for arg in group.get_all_arguments():
#                 try:
#                     arg.validate(conf_values[arg.conf_name])
#                 except Exception as e:
#                     raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
#         return arguments


import mock
import testtools
from clearstack.answer_file import AnswerFile
from clearstack.argument import Argument
from clearstack.controller import Controller
# See the License for the specific language governing permissions and
# limitations under the License.
#



conf = {'COMPONENT': [Argument('argument',
                               'description',
                               'CONFIG_ARGUMET',
                               'secure')]}

for group in conf:
    Controller.get().add_group(group, conf[group])


class AnswerFileTest(testtools.TestCase):
    def setUp(self):
        super(AnswerFileTest, self).setUp()

    def test_generate_file(self):
        m = mock.mock_open()
        filename = '/tmp/clearstack.answerfile'
        with mock.patch('clearstack.answer_file.open', m, create=True):
            AnswerFile.get().generate(filename, {})
        m.assert_called_once_with(filename, 'w')

    @mock.patch('os.path.isfile')
    def test_read_non_existing_file(self, mock_isfile):
        mock_isfile.side_effect = [False]
        filename = '/tmp/clearstack.answerfile'

# Path: clearstack/answer_file.py
# class AnswerFile:
#     def generate(self, file, variables_cmd):
#         with open(file, "w") as f:
#             f.write("[general]\n\n")
#             for group in Controller.get().get_all_groups():
#                 for argument in group.get_all_arguments():
#                     f.write("# {0}\n".format(argument.description))
#                     value = variables_cmd.get(argument.conf_name,
#                                               argument.default_value)
#                     f.write("{0}={1}\n\n".format(argument.conf_name, value))
# 
#     def read(self, file, variables_cmd):
#         conf = Controller.get().CONF
#         config = configparser.RawConfigParser()
#         config.optionxform = str
#         if not os.path.isfile(file):
#             raise IOError("file {0} not found".format(file))
# 
#         """ Validate option in answer file"""
#         config.read(file)
#         if not config.has_section('general'):
#             raise KeyError("answer file {0} doesn't have general"
#                            " section".format(file))
#         conf_file = dict(config['general'])
#         conf_file.update(variables_cmd)  # override variables
#         conf.update(conf_file)
# 
#         try:
#             Controller.get().validate_groups(conf_file)
#         except Exception as e:
#             raise e
# 
#         all_args = Controller.get().get_all_arguments()
#         for non_supported in (set(conf_file) - set(all_args)):
#             LOG.warn("clearstack: variable {0} is not"
#                      " supported yet".format(non_supported))
# 
# Path: clearstack/argument.py
# class Argument(object):
#     def __init__(self, cmd_option, description,
#                  conf_name, default_value, validators=[],
#                  options=None):
#         self.cmd_option = cmd_option
#         self.description = description
#         self.conf_name = conf_name
#         self.default_value = default_value
#         self.validators = validators
#         self.option_list = options
# 
#     def validate(self, option):
#         for validator in self.validators:
#             try:
#                 validator(option)
#             except ValueError as e:
#                 raise ValueError("{0}: {1}".format(self.conf_name, str(e)))
# 
# Path: clearstack/controller.py
# class Controller:
#     CONF = {}
#     _plugins = []
#     _groups = []
#     _sequences = []
# 
#     def add_sequence(self, desc, function, args=None):
#         self._sequences.append(Sequence(desc, function, args))
# 
#     def run_all_sequences(self):
#         for seq in self._sequences:
#             try:
#                 seq.run()
#             except Exception as e:
#                 raise e
# 
#     def add_plugin(self, plugin):
#         self._plugins.append(plugin)
# 
#     def get_all_plugins(self):
#         return self._plugins
# 
#     def add_group(self, name, args):
#         self._groups.append(Group(name, args))
# 
#     def get_all_groups(self):
#         return self._groups
# 
#     def get_all_arguments(self):
#         """Get a list of the configuration argument loaded"""
#         arguments = []
#         for group in self._groups:
#             arguments.extend([argument.conf_name
#                               for argument in group.get_all_arguments()])
#         return arguments
# 
#     def validate_groups(self, conf_values):
#         """ Load validation functions, in order to check
#         the values in the answer file """
#         arguments = {}
#         for group in self._groups:
#             for arg in group.get_all_arguments():
#                 try:
#                     arg.validate(conf_values[arg.conf_name])
#                 except Exception as e:
#                     raise Exception("{0}: {1}".format(arg.conf_name, str(e)))
#         return arguments


# Path: clearstack/tests/test_answer_file.py
import mock
import testtools
from clearstack.answer_file import AnswerFile
from clearstack.argument import Argument
from clearstack.controller import Controller

# See the License for the specific language governing permissions and
# limitations under the License.
#



conf = {'COMPONENT': [Argument('argument',
                               'description',
                               'CONFIG_ARGUMET',
                               'secure')]}

for group in conf:
    Controller.get().add_group(group, conf[group])


class AnswerFileTest(testtools.TestCase):
    def setUp(self):
        super(AnswerFileTest, self).setUp()

    def test_generate_file(self):
        m = mock.mock_open()
        filename = '/tmp/clearstack.answerfile'
        with mock.patch('clearstack.answer_file.open', m, create=True):
            AnswerFile.get().generate(filename, {})
        m.assert_called_once_with(filename, 'w')

    @mock.patch('os.path.isfile')
    def test_read_non_existing_file(self, mock_isfile):
        mock_isfile.side_effect = [False]
        filename = '/tmp/clearstack.answerfile'

        self.assertRaises(IOError, AnswerFile.get().read, filename, {})