diff options
Diffstat (limited to 'utils/test')
| -rw-r--r-- | utils/test/cli_installer_tests.py | 246 | ||||
| -rw-r--r-- | utils/test/fixture.py | 27 | ||||
| -rw-r--r-- | utils/test/oo_config_tests.py | 81 | ||||
| -rw-r--r-- | utils/test/openshift_ansible_tests.py | 71 | ||||
| -rw-r--r-- | utils/test/test_utils.py | 99 | 
5 files changed, 395 insertions, 129 deletions
diff --git a/utils/test/cli_installer_tests.py b/utils/test/cli_installer_tests.py index 6d9d443ff..0cb37eaff 100644 --- a/utils/test/cli_installer_tests.py +++ b/utils/test/cli_installer_tests.py @@ -4,7 +4,8 @@  import copy  import os -import ConfigParser + +from six.moves import configparser  import ooinstall.cli_installer as cli @@ -408,7 +409,7 @@ class UnattendedCliTests(OOCliFixture):          result = self.runner.invoke(cli.cli, self.cli_args)          if result.exception is None or result.exit_code != 1: -            print "Exit code: %s" % result.exit_code +            print("Exit code: %s" % result.exit_code)              self.fail("Unexpected CLI return")      # unattended with config file and all installed hosts (with --force) @@ -523,7 +524,7 @@ class UnattendedCliTests(OOCliFixture):          self.assert_result(result, 0)          # Check the inventory file looks as we would expect: -        inventory = ConfigParser.ConfigParser(allow_no_value=True) +        inventory = configparser.ConfigParser(allow_no_value=True)          inventory.read(os.path.join(self.work_dir, 'hosts'))          self.assertEquals('root',              inventory.get('OSEv3:vars', 'ansible_ssh_user')) @@ -566,7 +567,7 @@ class UnattendedCliTests(OOCliFixture):          self.assertEquals('3.3', written_config['variant_version'])          # Make sure the correct value was passed to ansible: -        inventory = ConfigParser.ConfigParser(allow_no_value=True) +        inventory = configparser.ConfigParser(allow_no_value=True)          inventory.read(os.path.join(self.work_dir, 'hosts'))          self.assertEquals('openshift-enterprise',              inventory.get('OSEv3:vars', 'deployment_type')) @@ -594,87 +595,101 @@ class UnattendedCliTests(OOCliFixture):          # and written to disk:          self.assertEquals('3.3', written_config['variant_version']) -        inventory = ConfigParser.ConfigParser(allow_no_value=True) +        inventory = configparser.ConfigParser(allow_no_value=True)          inventory.read(os.path.join(self.work_dir, 'hosts'))          self.assertEquals('openshift-enterprise',              inventory.get('OSEv3:vars', 'deployment_type')) -    @patch('ooinstall.openshift_ansible.run_ansible') -    @patch('ooinstall.openshift_ansible.load_system_facts') -    def test_no_ansible_config_specified(self, load_facts_mock, run_ansible_mock): -        load_facts_mock.return_value = (MOCK_FACTS, 0) -        run_ansible_mock.return_value = 0 - -        config = SAMPLE_CONFIG % 'openshift-enterprise' - -        self._ansible_config_test(load_facts_mock, run_ansible_mock, -            config, None, None) - -    @patch('ooinstall.openshift_ansible.run_ansible') -    @patch('ooinstall.openshift_ansible.load_system_facts') -    def test_ansible_config_specified_cli(self, load_facts_mock, run_ansible_mock): -        load_facts_mock.return_value = (MOCK_FACTS, 0) -        run_ansible_mock.return_value = 0 - -        config = SAMPLE_CONFIG % 'openshift-enterprise' -        ansible_config = os.path.join(self.work_dir, 'ansible.cfg') - -        self._ansible_config_test(load_facts_mock, run_ansible_mock, -            config, ansible_config, ansible_config) - -    @patch('ooinstall.openshift_ansible.run_ansible') -    @patch('ooinstall.openshift_ansible.load_system_facts') -    def test_ansible_config_specified_in_installer_config(self, -        load_facts_mock, run_ansible_mock): - -        load_facts_mock.return_value = (MOCK_FACTS, 0) -        run_ansible_mock.return_value = 0 - -        ansible_config = os.path.join(self.work_dir, 'ansible.cfg') -        config = SAMPLE_CONFIG % 'openshift-enterprise' -        config = "%s\nansible_config: %s" % (config, ansible_config) -        self._ansible_config_test(load_facts_mock, run_ansible_mock, -            config, None, ansible_config) - -    #pylint: disable=too-many-arguments -    # This method allows for drastically simpler tests to write, and the args -    # are all useful. -    def _ansible_config_test(self, load_facts_mock, run_ansible_mock, -        installer_config, ansible_config_cli=None, expected_result=None): -        """ -        Utility method for testing the ways you can specify the ansible config. -        """ - -        load_facts_mock.return_value = (MOCK_FACTS, 0) -        run_ansible_mock.return_value = 0 - -        config_file = self.write_config(os.path.join(self.work_dir, -            'ooinstall.conf'), installer_config) - -        self.cli_args.extend(["-c", config_file]) -        if ansible_config_cli: -            self.cli_args.extend(["--ansible-config", ansible_config_cli]) -        self.cli_args.append("install") -        result = self.runner.invoke(cli.cli, self.cli_args) -        self.assert_result(result, 0) - -        # Test the env vars for facts playbook: -        facts_env_vars = load_facts_mock.call_args[0][2] -        if expected_result: -            self.assertEquals(expected_result, facts_env_vars['ANSIBLE_CONFIG']) -        else: -            # If user running test has rpm installed, this might be set to default: -            self.assertTrue('ANSIBLE_CONFIG' not in facts_env_vars or -                facts_env_vars['ANSIBLE_CONFIG'] == cli.DEFAULT_ANSIBLE_CONFIG) - -        # Test the env vars for main playbook: -        env_vars = run_ansible_mock.call_args[0][2] -        if expected_result: -            self.assertEquals(expected_result, env_vars['ANSIBLE_CONFIG']) -        else: -            # If user running test has rpm installed, this might be set to default: -            self.assertTrue('ANSIBLE_CONFIG' not in env_vars or -                env_vars['ANSIBLE_CONFIG'] == cli.DEFAULT_ANSIBLE_CONFIG) +    # 2016-09-26 - tbielawa - COMMENTING OUT these tests FOR NOW while +    # we wait to see if anyone notices that we took away their ability +    # to set the ansible_config parameter in the command line options +    # and in the installer config file. +    # +    # We have removed the ability to set the ansible config file +    # manually so that our new quieter output mode is the default and +    # only output mode. +    # +    # RE: https://trello.com/c/DSwwizwP - atomic-openshift-install +    # should only output relevant information. + +    # @patch('ooinstall.openshift_ansible.run_ansible') +    # @patch('ooinstall.openshift_ansible.load_system_facts') +    # def test_no_ansible_config_specified(self, load_facts_mock, run_ansible_mock): +    #     load_facts_mock.return_value = (MOCK_FACTS, 0) +    #     run_ansible_mock.return_value = 0 + +    #     config = SAMPLE_CONFIG % 'openshift-enterprise' + +    #     self._ansible_config_test(load_facts_mock, run_ansible_mock, +    #         config, None, None) + +    # @patch('ooinstall.openshift_ansible.run_ansible') +    # @patch('ooinstall.openshift_ansible.load_system_facts') +    # def test_ansible_config_specified_cli(self, load_facts_mock, run_ansible_mock): +    #     load_facts_mock.return_value = (MOCK_FACTS, 0) +    #     run_ansible_mock.return_value = 0 + +    #     config = SAMPLE_CONFIG % 'openshift-enterprise' +    #     ansible_config = os.path.join(self.work_dir, 'ansible.cfg') + +    #     self._ansible_config_test(load_facts_mock, run_ansible_mock, +    #         config, ansible_config, ansible_config) + +    # @patch('ooinstall.openshift_ansible.run_ansible') +    # @patch('ooinstall.openshift_ansible.load_system_facts') +    # def test_ansible_config_specified_in_installer_config(self, +    #     load_facts_mock, run_ansible_mock): + +    #     load_facts_mock.return_value = (MOCK_FACTS, 0) +    #     run_ansible_mock.return_value = 0 + +    #     ansible_config = os.path.join(self.work_dir, 'ansible.cfg') +    #     config = SAMPLE_CONFIG % 'openshift-enterprise' +    #     config = "%s\nansible_config: %s" % (config, ansible_config) +    #     self._ansible_config_test(load_facts_mock, run_ansible_mock, +    #         config, None, ansible_config) + +    # #pylint: disable=too-many-arguments +    # # This method allows for drastically simpler tests to write, and the args +    # # are all useful. +    # def _ansible_config_test(self, load_facts_mock, run_ansible_mock, +    #     installer_config, ansible_config_cli=None, expected_result=None): +    #     """ +    #     Utility method for testing the ways you can specify the ansible config. +    #     """ + +    #     load_facts_mock.return_value = (MOCK_FACTS, 0) +    #     run_ansible_mock.return_value = 0 + +    #     config_file = self.write_config(os.path.join(self.work_dir, +    #         'ooinstall.conf'), installer_config) + +    #     self.cli_args.extend(["-c", config_file]) +    #     if ansible_config_cli: +    #         self.cli_args.extend(["--ansible-config", ansible_config_cli]) +    #     self.cli_args.append("install") +    #     result = self.runner.invoke(cli.cli, self.cli_args) +    #     self.assert_result(result, 0) + +    #     # Test the env vars for facts playbook: +    #     facts_env_vars = load_facts_mock.call_args[0][2] +    #     if expected_result: +    #         self.assertEquals(expected_result, facts_env_vars['ANSIBLE_CONFIG']) +    #     else: +    #         # If user running test has rpm installed, this might be set to default: +    #         self.assertTrue('ANSIBLE_CONFIG' not in facts_env_vars or +    #             facts_env_vars['ANSIBLE_CONFIG'] == cli.DEFAULT_ANSIBLE_CONFIG) + +    #     # Test the env vars for main playbook: +    #     env_vars = run_ansible_mock.call_args[0][2] +    #     if expected_result: +    #         self.assertEquals(expected_result, env_vars['ANSIBLE_CONFIG']) +    #     else: +    #         # If user running test has rpm installed, this might be set to default: +    #         # +    #         # By default we will use the quiet config +    #         self.assertTrue('ANSIBLE_CONFIG' not in env_vars or +    #             env_vars['ANSIBLE_CONFIG'] == cli.QUIET_ANSIBLE_CONFIG)      # unattended with bad config file and no installed hosts (without --force)      @patch('ooinstall.openshift_ansible.run_main_playbook') @@ -816,7 +831,7 @@ class AttendedCliTests(OOCliFixture):          written_config = read_yaml(self.config_file)          self._verify_config_hosts(written_config, 4) -        inventory = ConfigParser.ConfigParser(allow_no_value=True) +        inventory = configparser.ConfigParser(allow_no_value=True)          inventory.read(os.path.join(self.work_dir, 'hosts'))          self.assert_inventory_host_var(inventory, 'nodes', '10.0.0.1',                                   'openshift_schedulable=False') @@ -828,7 +843,7 @@ class AttendedCliTests(OOCliFixture):      # interactive with config file and some installed some uninstalled hosts      @patch('ooinstall.openshift_ansible.run_main_playbook')      @patch('ooinstall.openshift_ansible.load_system_facts') -    def test_add_nodes(self, load_facts_mock, run_playbook_mock): +    def test_scaleup_hint(self, load_facts_mock, run_playbook_mock):          # Modify the mock facts to return a version indicating OpenShift          # is already installed on our master, and the first node. @@ -852,13 +867,12 @@ class AttendedCliTests(OOCliFixture):          result = self.runner.invoke(cli.cli,                                      self.cli_args,                                      input=cli_input) -        self.assert_result(result, 0) -        self._verify_load_facts(load_facts_mock) -        self._verify_run_playbook(run_playbook_mock, 3, 2) +        # This is testing the install workflow so we want to make sure we +        # exit with the appropriate hint. +        self.assertTrue('scaleup' in result.output) +        self.assert_result(result, 1) -        written_config = read_yaml(self.config_file) -        self._verify_config_hosts(written_config, 3)      @patch('ooinstall.openshift_ansible.run_main_playbook')      @patch('ooinstall.openshift_ansible.load_system_facts') @@ -883,30 +897,30 @@ class AttendedCliTests(OOCliFixture):          written_config = read_yaml(config_file)          self._verify_config_hosts(written_config, 3) -    #interactive with config file and all installed hosts -    @patch('ooinstall.openshift_ansible.run_main_playbook') -    @patch('ooinstall.openshift_ansible.load_system_facts') -    def test_get_hosts_to_run_on(self, load_facts_mock, run_playbook_mock): -        mock_facts = copy.deepcopy(MOCK_FACTS) -        mock_facts['10.0.0.1']['common']['version'] = "3.0.0" -        mock_facts['10.0.0.2']['common']['version'] = "3.0.0" - -        cli_input = build_input(hosts=[ -            ('10.0.0.1', True, False), -            ], -                                      add_nodes=[('10.0.0.2', False, False)], -                                      ssh_user='root', -                                      variant_num=1, -                                      schedulable_masters_ok=True, -                                      confirm_facts='y', -                                      storage='10.0.0.1',) - -        self._verify_get_hosts_to_run_on(mock_facts, load_facts_mock, -                                         run_playbook_mock, -                                         cli_input, -                                         exp_hosts_len=2, -                                         exp_hosts_to_run_on_len=2, -                                         force=False) +#    #interactive with config file and all installed hosts +#    @patch('ooinstall.openshift_ansible.run_main_playbook') +#    @patch('ooinstall.openshift_ansible.load_system_facts') +#    def test_get_hosts_to_run_on(self, load_facts_mock, run_playbook_mock): +#        mock_facts = copy.deepcopy(MOCK_FACTS) +#        mock_facts['10.0.0.1']['common']['version'] = "3.0.0" +#        mock_facts['10.0.0.2']['common']['version'] = "3.0.0" +# +#        cli_input = build_input(hosts=[ +#            ('10.0.0.1', True, False), +#            ], +#                                      add_nodes=[('10.0.0.2', False, False)], +#                                      ssh_user='root', +#                                      variant_num=1, +#                                      schedulable_masters_ok=True, +#                                      confirm_facts='y', +#                                      storage='10.0.0.1',) +# +#        self._verify_get_hosts_to_run_on(mock_facts, load_facts_mock, +#                                         run_playbook_mock, +#                                         cli_input, +#                                         exp_hosts_len=2, +#                                         exp_hosts_to_run_on_len=2, +#                                         force=False)      #interactive multimaster: one more node than master      @patch('ooinstall.openshift_ansible.run_main_playbook') @@ -936,7 +950,7 @@ class AttendedCliTests(OOCliFixture):          written_config = read_yaml(self.config_file)          self._verify_config_hosts(written_config, 6) -        inventory = ConfigParser.ConfigParser(allow_no_value=True) +        inventory = configparser.ConfigParser(allow_no_value=True)          inventory.read(os.path.join(self.work_dir, 'hosts'))          self.assert_inventory_host_var(inventory, 'nodes', '10.0.0.1',                                         'openshift_schedulable=False') @@ -977,7 +991,7 @@ class AttendedCliTests(OOCliFixture):          written_config = read_yaml(self.config_file)          self._verify_config_hosts(written_config, 5) -        inventory = ConfigParser.ConfigParser(allow_no_value=True) +        inventory = configparser.ConfigParser(allow_no_value=True)          inventory.read(os.path.join(self.work_dir, 'hosts'))          self.assert_inventory_host_var(inventory, 'nodes', '10.0.0.1',                                         'openshift_schedulable=True') @@ -1069,7 +1083,7 @@ class AttendedCliTests(OOCliFixture):          written_config = read_yaml(self.config_file)          self._verify_config_hosts(written_config, 1) -        inventory = ConfigParser.ConfigParser(allow_no_value=True) +        inventory = configparser.ConfigParser(allow_no_value=True)          inventory.read(os.path.join(self.work_dir, 'hosts'))          self.assert_inventory_host_var(inventory, 'nodes', '10.0.0.1',                                         'openshift_schedulable=True') @@ -1103,7 +1117,7 @@ class AttendedCliTests(OOCliFixture):          written_config = read_yaml(self.config_file)          self._verify_config_hosts(written_config, 4) -        inventory = ConfigParser.ConfigParser(allow_no_value=True) +        inventory = configparser.ConfigParser(allow_no_value=True)          inventory.read(os.path.join(self.work_dir, 'hosts'))          self.assert_inventory_host_var(inventory, 'nodes', '10.0.0.1',                                   'openshift_schedulable=False') diff --git a/utils/test/fixture.py b/utils/test/fixture.py index a883e5c56..5200d275d 100644 --- a/utils/test/fixture.py +++ b/utils/test/fixture.py @@ -65,13 +65,13 @@ class OOCliFixture(OOInstallFixture):      def assert_result(self, result, exit_code):          if result.exit_code != exit_code: -            print "Unexpected result from CLI execution" -            print "Exit code: %s" % result.exit_code -            print "Exception: %s" % result.exception -            print result.exc_info +            print("Unexpected result from CLI execution") +            print("Exit code: %s" % result.exit_code) +            print("Exception: %s" % result.exception) +            print(result.exc_info)              import traceback              traceback.print_exception(*result.exc_info) -            print "Output:\n%s" % result.output +            print("Output:\n%s" % result.output)              self.fail("Exception during CLI execution")      def _verify_load_facts(self, load_facts_mock): @@ -138,8 +138,8 @@ class OOCliFixture(OOInstallFixture):              written_config = read_yaml(config_file)              self._verify_config_hosts(written_config, exp_hosts_len) -        if "Uninstalled" in result.output: -            # verify we exited on seeing uninstalled hosts +        if "If you want to force reinstall" in result.output: +            # verify we exited on seeing installed hosts              self.assertEqual(result.exit_code, 1)          else:              self.assert_result(result, 0) @@ -156,7 +156,7 @@ class OOCliFixture(OOInstallFixture):  #pylint: disable=too-many-arguments,too-many-branches,too-many-statements  def build_input(ssh_user=None, hosts=None, variant_num=None,                  add_nodes=None, confirm_facts=None, schedulable_masters_ok=None, -                master_lb=None, storage=None): +                master_lb=('', False), storage=None):      """      Build an input string simulating a user entering values in an interactive      attended install. @@ -204,11 +204,11 @@ def build_input(ssh_user=None, hosts=None, variant_num=None,              i += 1      # You can pass a single master_lb or a list if you intend for one to get rejected: -    if master_lb: -        if isinstance(master_lb[0], list) or isinstance(master_lb[0], tuple): -            inputs.extend(master_lb[0]) -        else: -            inputs.append(master_lb[0]) +    if isinstance(master_lb[0], list) or isinstance(master_lb[0], tuple): +        inputs.extend(master_lb[0]) +    else: +        inputs.append(master_lb[0]) +    if master_lb[0]:          inputs.append('y' if master_lb[1] else 'n')      if storage: @@ -248,6 +248,7 @@ def build_input(ssh_user=None, hosts=None, variant_num=None,      inputs.extend([          confirm_facts,          'y',  # lets do this +        'y',      ])      return '\n'.join(inputs) diff --git a/utils/test/oo_config_tests.py b/utils/test/oo_config_tests.py index b5068cc14..2b4fce512 100644 --- a/utils/test/oo_config_tests.py +++ b/utils/test/oo_config_tests.py @@ -8,7 +8,10 @@ import tempfile  import shutil  import yaml +from six.moves import cStringIO +  from ooinstall.oo_config import OOConfig, Host, OOConfigInvalidHostError +import ooinstall.openshift_ansible  SAMPLE_CONFIG = """  variant: openshift-enterprise @@ -224,3 +227,81 @@ class HostTests(OOInstallFixture):              'public_hostname': 'a.example.com',          }          self.assertRaises(OOConfigInvalidHostError, Host, **yaml_props) + +    def test_inventory_file_quotes_node_labels(self): +        """Verify a host entry wraps openshift_node_labels value in double quotes""" +        yaml_props = { +            'ip': '192.168.0.1', +            'hostname': 'a.example.com', +            'connect_to': 'a-private.example.com', +            'public_ip': '192.168.0.1', +            'public_hostname': 'a.example.com', +            'new_host': True, +            'roles': ['node'], +            'node_labels': { +                'region': 'infra' +            }, + +        } + +        new_node = Host(**yaml_props) +        inventory = cStringIO() +        # This is what the 'write_host' function generates. write_host +        # has no return value, it just writes directly to the file +        # 'inventory' which in this test-case is a StringIO object +        ooinstall.openshift_ansible.write_host( +            new_node, +            'node', +            inventory, +            schedulable=True) +        # read the value of what was written to the inventory "file" +        legacy_inventory_line = inventory.getvalue() + +        # Given the `yaml_props` above we should see a line like this: +        #     openshift_node_labels="{'region': 'infra'}" +        node_labels_expected = '''openshift_node_labels="{'region': 'infra'}"'''  # Quotes around the hash +        node_labels_bad = '''openshift_node_labels={'region': 'infra'}'''  # No quotes around the hash + +        # The good line is present in the written inventory line +        self.assertIn(node_labels_expected, legacy_inventory_line) +        # An unquoted version is not present +        self.assertNotIn(node_labels_bad, legacy_inventory_line) + + +    # def test_new_write_inventory_same_as_legacy(self): +    #     """Verify the original write_host function produces the same output as the new method""" +    #     yaml_props = { +    #         'ip': '192.168.0.1', +    #         'hostname': 'a.example.com', +    #         'connect_to': 'a-private.example.com', +    #         'public_ip': '192.168.0.1', +    #         'public_hostname': 'a.example.com', +    #         'new_host': True, +    #         'roles': ['node'], +    #         'other_variables': { +    #             'zzz': 'last', +    #             'foo': 'bar', +    #             'aaa': 'first', +    #         }, +    #     } + +    #     new_node = Host(**yaml_props) +    #     inventory = cStringIO() + +    #     # This is what the original 'write_host' function will +    #     # generate. write_host has no return value, it just writes +    #     # directly to the file 'inventory' which in this test-case is +    #     # a StringIO object +    #     ooinstall.openshift_ansible.write_host( +    #         new_node, +    #         'node', +    #         inventory, +    #         schedulable=True) +    #     legacy_inventory_line = inventory.getvalue() + +    #     # This is what the new method in the Host class generates +    #     new_inventory_line = new_node.inventory_string('node', schedulable=True) + +    #     self.assertEqual( +    #         legacy_inventory_line, +    #         new_inventory_line) diff --git a/utils/test/openshift_ansible_tests.py b/utils/test/openshift_ansible_tests.py new file mode 100644 index 000000000..5847fe37b --- /dev/null +++ b/utils/test/openshift_ansible_tests.py @@ -0,0 +1,71 @@ +import os +import unittest +import tempfile +import shutil +import yaml + +from six.moves import configparser + +from ooinstall import openshift_ansible +from ooinstall.oo_config import Host, OOConfig + + +BASE_CONFIG = """ +--- +variant: openshift-enterprise +variant_version: 3.3 +version: v2 +deployment: +    ansible_ssh_user: cloud-user +    hosts: [] +    roles: +        master: +        node: +""" + + +class TestOpenShiftAnsible(unittest.TestCase): + +    def setUp(self): +        self.tempfiles = [] +        self.work_dir = tempfile.mkdtemp(prefix='openshift_ansible_tests') +        self.configfile = os.path.join(self.work_dir, 'ooinstall.config') +        with open(self.configfile, 'w') as config_file: +            config_file.write(BASE_CONFIG) +        self.inventory = os.path.join(self.work_dir, 'hosts') +        config = OOConfig(self.configfile) +        config.settings['ansible_inventory_path'] = self.inventory +        openshift_ansible.set_config(config) + +    def tearDown(self): +        shutil.rmtree(self.work_dir) + +    def generate_hosts(self, num_hosts, name_prefix, roles=None, new_host=False): +        hosts = [] +        for num in range(1, num_hosts + 1): +            hosts.append(Host(connect_to=name_prefix + str(num), +                              roles=roles, new_host=new_host)) +        return hosts + +    def test_generate_inventory_new_nodes(self): +        hosts = self.generate_hosts(1, 'master', roles=(['master', 'etcd'])) +        hosts.extend(self.generate_hosts(1, 'node', roles=['node'])) +        hosts.extend(self.generate_hosts(1, 'new_node', roles=['node'], new_host=True)) +        openshift_ansible.generate_inventory(hosts) +        inventory = configparser.ConfigParser(allow_no_value=True) +        inventory.read(self.inventory) +        self.assertTrue(inventory.has_section('new_nodes')) +        self.assertTrue(inventory.has_option('new_nodes', 'new_node1')) + +    def test_write_inventory_vars_role_vars(self): +        with open(self.inventory, 'w') as inv: +            openshift_ansible.CFG.deployment.roles['master'].variables={'color': 'blue'} +            openshift_ansible.CFG.deployment.roles['node'].variables={'color': 'green'} +            openshift_ansible.write_inventory_vars(inv, None) + +        inventory = configparser.ConfigParser(allow_no_value=True) +        inventory.read(self.inventory) +        self.assertTrue(inventory.has_section('masters:vars')) +        self.assertEquals('blue', inventory.get('masters:vars', 'color')) +        self.assertTrue(inventory.has_section('nodes:vars')) +        self.assertEquals('green', inventory.get('nodes:vars', 'color')) diff --git a/utils/test/test_utils.py b/utils/test/test_utils.py new file mode 100644 index 000000000..cbce64f7e --- /dev/null +++ b/utils/test/test_utils.py @@ -0,0 +1,99 @@ +""" +Unittests for ooinstall utils. +""" + +import six +import unittest +import logging +import sys +import copy +from ooinstall.utils import debug_env, is_valid_hostname +import mock + + +class TestUtils(unittest.TestCase): +    """ +    Parent unittest TestCase. +    """ + +    def setUp(self): +        self.debug_all_params = { +            'OPENSHIFT_FOO': 'bar', +            'ANSIBLE_FOO': 'bar', +            'OO_FOO': 'bar' +        } + +        self.expected = [ +            mock.call('ANSIBLE_FOO: bar'), +            mock.call('OPENSHIFT_FOO: bar'), +            mock.call('OO_FOO: bar'), +        ] + + +    ###################################################################### +    # Validate ooinstall.utils.debug_env functionality + +    def test_utils_debug_env_all_debugged(self): +        """Verify debug_env debugs specific env variables""" + +        with mock.patch('ooinstall.utils.installer_log') as _il: +            debug_env(self.debug_all_params) + +            # Debug was called for each item we expect +            self.assertEqual( +                len(self.debug_all_params), +                _il.debug.call_count) + +            # Each item we expect was logged +            six.assertCountEqual( +                self, +                self.expected, +                _il.debug.call_args_list) + +    def test_utils_debug_env_some_debugged(self): +        """Verify debug_env skips non-wanted env variables""" +        debug_some_params = copy.deepcopy(self.debug_all_params) +        # This will not be logged by debug_env +        debug_some_params['MG_FRBBR'] = "SKIPPED" + +        with mock.patch('ooinstall.utils.installer_log') as _il: +            debug_env(debug_some_params) + +            # The actual number of debug calls was less than the +            # number of items passed to debug_env +            self.assertLess( +                _il.debug.call_count, +                len(debug_some_params)) + +            six.assertCountEqual( +                self, +                self.expected, +                _il.debug.call_args_list) + +    ###################################################################### +    def test_utils_is_valid_hostname_invalid(self): +        """Verify is_valid_hostname can detect None or too-long hostnames""" +        # A hostname that's empty, None, or more than 255 chars is invalid +        empty_hostname = '' +        res = is_valid_hostname(empty_hostname) +        self.assertFalse(res) + +        none_hostname = None +        res = is_valid_hostname(none_hostname) +        self.assertFalse(res) + +        too_long_hostname = "a" * 256 +        res = is_valid_hostname(too_long_hostname) +        self.assertFalse(res) + +    def test_utils_is_valid_hostname_ends_with_dot(self): +        """Verify is_valid_hostname can parse hostnames with trailing periods""" +        hostname = "foo.example.com." +        res = is_valid_hostname(hostname) +        self.assertTrue(res) + +    def test_utils_is_valid_hostname_normal_hostname(self): +        """Verify is_valid_hostname can parse regular hostnames""" +        hostname = "foo.example.com" +        res = is_valid_hostname(hostname) +        self.assertTrue(res)  | 
