Adds deployment via snapshot
[apex.git] / apex / tests / test_apex_common_utils.py
1 ##############################################################################
2 # Copyright (c) 2016 Dan Radez (Red Hat)
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 import ipaddress
11 import os
12 import shutil
13 import urllib.error
14
15 from apex.common import exceptions
16 from apex.common import utils
17 from apex.settings.network_settings import NetworkSettings
18 from apex.tests.constants import (
19     TEST_CONFIG_DIR,
20     TEST_PLAYBOOK_DIR)
21
22 from mock import patch, mock_open
23 from nose.tools import (
24     assert_equal,
25     assert_is_instance,
26     assert_not_is_instance,
27     assert_raises)
28
29 NET_SETS = os.path.join(TEST_CONFIG_DIR, 'network', 'network_settings.yaml')
30 a_mock_open = mock_open(read_data=None)
31
32
33 class TestCommonUtils:
34     @classmethod
35     def setup_class(cls):
36         """This method is run once for each class before any tests are run"""
37
38     @classmethod
39     def teardown_class(cls):
40         """This method is run once for each class _after_ all tests are run"""
41
42     def setup(self):
43         """This method is run once before _each_ test method is executed"""
44
45     def teardown(self):
46         """This method is run once after _each_ test method is executed"""
47
48     def test_str2bool(self):
49         assert_equal(utils.str2bool(True), True)
50         assert_equal(utils.str2bool(False), False)
51         assert_equal(utils.str2bool("True"), True)
52         assert_equal(utils.str2bool("YES"), True)
53
54     def test_parse_yaml(self):
55         assert_is_instance(utils.parse_yaml(NET_SETS), dict)
56
57     def test_dict_to_string(self):
58         net_settings = NetworkSettings(NET_SETS)
59         output = utils.dict_objects_to_str(net_settings)
60         assert_is_instance(output, dict)
61         for k, v in output.items():
62             assert_is_instance(k, str)
63             assert_not_is_instance(v, ipaddress.IPv4Address)
64
65     def test_run_ansible(self):
66         playbook = 'apex/tests/playbooks/test_playbook.yaml'
67         extra_vars = [{'testvar1': 'value1', 'testvar2': 'value2'}]
68         assert_equal(utils.run_ansible(None, os.path.join(playbook),
69                                        dry_run=True), None)
70         assert_equal(utils.run_ansible(extra_vars, os.path.join(playbook),
71                                        dry_run=True, host='1.1.1.1'), None)
72
73     def test_failed_run_ansible(self):
74         playbook = 'apex/tests/playbooks/test_failed_playbook.yaml'
75         assert_raises(Exception, utils.run_ansible, None,
76                       os.path.join(playbook), dry_run=True)
77
78     def test_fetch_upstream_and_unpack(self):
79         url = 'https://github.com/opnfv/apex/blob/master/'
80         utils.fetch_upstream_and_unpack('/tmp/fetch_test',
81                                         url, ['INFO'])
82         assert os.path.isfile('/tmp/fetch_test/INFO')
83         shutil.rmtree('/tmp/fetch_test')
84
85     def test_fetch_upstream_previous_file(self):
86         test_file = 'overcloud-full.tar.md5'
87         url = 'https://images.rdoproject.org/master/delorean/' \
88               'current-tripleo/stable/'
89         os.makedirs('/tmp/fetch_test', exist_ok=True)
90         open("/tmp/fetch_test/{}".format(test_file), 'w').close()
91         utils.fetch_upstream_and_unpack('/tmp/fetch_test',
92                                         url, [test_file])
93         assert os.path.isfile("/tmp/fetch_test/{}".format(test_file))
94         shutil.rmtree('/tmp/fetch_test')
95
96     def test_fetch_upstream_invalid_url(self):
97         url = 'http://notavalidsite.com/'
98         assert_raises(urllib.error.URLError,
99                       utils.fetch_upstream_and_unpack, '/tmp/fetch_test',
100                       url, ['INFO'])
101         shutil.rmtree('/tmp/fetch_test')
102
103     def test_fetch_upstream_and_unpack_tarball(self):
104         url = 'http://artifacts.opnfv.org/apex/tests/'
105         utils.fetch_upstream_and_unpack('/tmp/fetch_test',
106                                         url, ['dummy_test.tar'])
107         assert os.path.isfile('/tmp/fetch_test/test.txt')
108         shutil.rmtree('/tmp/fetch_test')
109
110     def test_nofetch_upstream_and_unpack(self):
111         test_file = 'overcloud-full.tar.md5'
112         url = 'https://images.rdoproject.org/master/delorean/' \
113               'current-tripleo/stable/'
114         os.makedirs('/tmp/fetch_test', exist_ok=True)
115         target = "/tmp/fetch_test/{}".format(test_file)
116         open(target, 'w').close()
117         target_mtime = os.path.getmtime(target)
118         utils.fetch_upstream_and_unpack('/tmp/fetch_test',
119                                         url, [test_file], fetch=False)
120         post_target_mtime = os.path.getmtime(target)
121         shutil.rmtree('/tmp/fetch_test')
122         assert_equal(target_mtime, post_target_mtime)
123
124     def test_nofetch_upstream_and_unpack_no_target(self):
125         test_file = 'overcloud-full.tar.md5'
126         url = 'https://images.rdoproject.org/master/delorean/' \
127               'current-tripleo/stable/'
128         utils.fetch_upstream_and_unpack('/tmp/fetch_test',
129                                         url, [test_file])
130         assert os.path.isfile("/tmp/fetch_test/{}".format(test_file))
131         shutil.rmtree('/tmp/fetch_test')
132
133     def test_open_webpage(self):
134         output = utils.open_webpage('http://opnfv.org')
135         assert output is not None
136
137     def test_open_invalid_webpage(self):
138         assert_raises(exceptions.FetchException, utils.open_webpage,
139                       'http://inv4lIdweb-page.com')
140
141     @patch('builtins.open', a_mock_open)
142     @patch('yaml.safe_dump')
143     @patch('yaml.safe_load')
144     def test_edit_tht_env(self, mock_yaml_load, mock_yaml_dump):
145         settings = {'SomeParameter': 'some_value'}
146         mock_yaml_load.return_value = {
147             'parameter_defaults': {'SomeParameter': 'dummy'}
148         }
149         utils.edit_tht_env('/dummy-environment.yaml', 'parameter_defaults',
150                            settings)
151         new_data = {'parameter_defaults': settings}
152         mock_yaml_dump.assert_called_once_with(new_data, a_mock_open(),
153                                                default_flow_style=False)
154
155     def test_unique(self):
156         dummy_list = [1, 2, 1, 3, 4, 5, 5]
157         assert_equal(utils.unique(dummy_list), [1, 2, 3, 4, 5])