Synchronise the openstack bugs
[parser.git] / tosca2heat / heat-translator / translator / tests / test_shell.py
1 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
2 #    not use this file except in compliance with the License. You may obtain
3 #    a copy of the License at
4 #
5 #         http://www.apache.org/licenses/LICENSE-2.0
6 #
7 #    Unless required by applicable law or agreed to in writing, software
8 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 #    License for the specific language governing permissions and limitations
11 #    under the License.
12
13 import ast
14 import json
15 import os
16 import shutil
17 import tempfile
18
19 from mock import patch
20 from toscaparser.common import exception
21 from toscaparser.utils.gettextutils import _
22 import translator.shell as shell
23 from translator.tests.base import TestCase
24
25
26 class ShellTest(TestCase):
27     tosca_helloworld = os.path.join(
28         os.path.dirname(os.path.abspath(__file__)),
29         "data/tosca_helloworld.yaml")
30     template_file = '--template-file=' + tosca_helloworld
31     template_type = '--template-type=tosca'
32     template_validation = "--validate-only"
33     failure_msg = _('The program raised an exception unexpectedly.')
34
35     def test_invalid_file_value(self):
36         error = self.assertRaises(ValueError,
37                                   shell.main, ('--template-file=template.txt',
38                                                self.template_type))
39         err_msg = _('The path template.txt is not a valid file or URL.')
40         self.assertEqual(err_msg, str(error))
41
42     def test_invalid_type_value(self):
43         self.assertRaises(SystemExit, shell.main,
44                           (self.template_file, '--template-type=xyz'))
45
46     def test_invalid_parameters(self):
47         self.assertRaises(ValueError, shell.main,
48                           (self.template_file, self.template_type,
49                            '--parameters=key'))
50
51     def test_valid_template(self):
52         try:
53             shell.main([self.template_file, self.template_type])
54         except Exception:
55             self.fail(self.failure_msg)
56
57     def test_valid_template_without_type(self):
58         try:
59             shell.main([self.template_file])
60         except Exception:
61             self.fail(self.failure_msg)
62
63     def test_valid_template_with_parameters(self):
64         tosca_single_instance_wordpress = os.path.join(
65             os.path.dirname(os.path.abspath(__file__)),
66             "data/tosca_single_instance_wordpress.yaml")
67         parameters = '--parameters="cpus=2;db_name=wpdb;db_user=test;'\
68                      'db_port=2000;db_root_pwd=fun2test;db_pwd=fun2test"'
69         template = '--template-file=' + tosca_single_instance_wordpress
70         try:
71             shell.main([template, self.template_type, parameters])
72         except Exception:
73             self.fail(self.failure_msg)
74
75     def test_validate_only(self):
76         try:
77             shell.main([self.template_file, self.template_type,
78                         self.template_validation])
79         except Exception:
80             self.fail(self.failure_msg)
81
82         template = os.path.join(
83             os.path.dirname(os.path.abspath(__file__)),
84             "data/tosca_helloworld_invalid.yaml")
85         invalid_template = '--template-file=' + template
86         self.assertRaises(exception.ValidationError, shell.main,
87                           [invalid_template, self.template_type,
88                            self.template_validation])
89
90     def test_output_file(self):
91         temp_dir = tempfile.mkdtemp()
92         temp_file = "/test_translation_output.txt"
93         output_file = "--output-file=" + temp_dir + temp_file
94         try:
95             shell.main([self.template_file, self.template_type, output_file])
96         except Exception:
97             self.fail(self.failure_msg)
98         finally:
99             if temp_dir:
100                 shutil.rmtree(temp_dir)
101                 self.assertTrue(temp_dir is None or
102                                 not os.path.exists(temp_dir))
103
104     @patch('uuid.uuid4')
105     @patch('translator.common.utils.check_for_env_variables')
106     @patch('requests.post')
107     @patch('translator.common.utils.get_url_for')
108     @patch('translator.common.utils.get_token_id')
109     @patch('os.getenv')
110     @patch('translator.hot.tosca.tosca_compute.'
111            'ToscaCompute._create_nova_flavor_dict')
112     @patch('translator.hot.tosca.tosca_compute.'
113            'ToscaCompute._populate_image_dict')
114     def test_template_deploy_with_credentials(self, mock_populate_image_dict,
115                                               mock_flavor_dict,
116                                               mock_os_getenv,
117                                               mock_token,
118                                               mock_url, mock_post,
119                                               mock_env,
120                                               mock_uuid):
121         mock_uuid.return_value = 'abcXXX-abcXXX'
122         mock_env.return_value = True
123         mock_flavor_dict.return_value = {
124             'm1.medium': {'mem_size': 4096, 'disk_size': 40, 'num_cpus': 2}
125         }
126         mock_populate_image_dict.return_value = {
127             "rhel-6.5-test-image": {
128                 "version": "6.5",
129                 "architecture": "x86_64",
130                 "distribution": "RHEL",
131                 "type": "Linux"
132             }
133         }
134         mock_url.return_value = 'http://abc.com'
135         mock_token.return_value = 'mock_token'
136         mock_os_getenv.side_effect = ['demo', 'demo',
137                                       'demo', 'http://www.abc.com']
138         try:
139             data = {
140                 'stack_name': 'heat_abcXXX',
141                 'parameters': {},
142                 'template': {
143                     'outputs': {},
144                     'heat_template_version': '2013-05-23',
145                     'description': 'Template for deploying a single server '
146                                    'with predefined properties.\n',
147                     'parameters': {},
148                     'resources': {
149                         'my_server': {
150                             'type': 'OS::Nova::Server',
151                             'properties': {
152                                 'flavor': 'm1.medium',
153                                 'user_data_format': 'SOFTWARE_CONFIG',
154                                 'image': 'rhel-6.5-test-image'
155                             }
156                         }
157                     }
158                 }
159             }
160
161             mock_heat_res = {
162                 "stack": {
163                     "id": 1234
164                 }
165             }
166             headers = {
167                 'Content-Type': 'application/json',
168                 'X-Auth-Token': 'mock_token'
169             }
170
171             class mock_response(object):
172                 def __init__(self, status_code, _content):
173                     self.status_code = status_code
174                     self._content = _content
175
176             mock_response_obj = mock_response(201, json.dumps(mock_heat_res))
177             mock_post.return_value = mock_response_obj
178             shell.main([self.template_file, self.template_type,
179                         "--deploy"])
180             args, kwargs = mock_post.call_args
181             self.assertEqual(args[0], 'http://abc.com/stacks')
182             self.assertEqual(ast.literal_eval(kwargs['data']), data)
183             self.assertEqual(kwargs['headers'], headers)
184         except Exception:
185             self.fail(self.failure_msg)