Support python3 uploaded to pypi websit
[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
14 import json
15 import mock
16 import os
17 import shutil
18 import tempfile
19
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         shell.main([self.template_file, self.template_type])
53
54     def test_valid_template_without_type(self):
55         try:
56             shell.main([self.template_file])
57         except Exception:
58             self.fail(self.failure_msg)
59
60     def test_valid_template_with_parameters(self):
61         tosca_single_instance_wordpress = os.path.join(
62             os.path.dirname(os.path.abspath(__file__)),
63             "data/tosca_single_instance_wordpress.yaml")
64         parameters = '--parameters="cpus=2;db_name=wpdb;db_user=test;'\
65                      'db_port=2000;db_root_pwd=fun2test;db_pwd=fun2test"'
66         template = '--template-file=' + tosca_single_instance_wordpress
67         try:
68             shell.main([template, self.template_type, parameters])
69         except Exception:
70             self.fail(self.failure_msg)
71
72     def test_validate_only(self):
73         try:
74             shell.main([self.template_file, self.template_type,
75                         self.template_validation])
76         except Exception:
77             self.fail(self.failure_msg)
78
79         template = os.path.join(
80             os.path.dirname(os.path.abspath(__file__)),
81             "data/tosca_helloworld_invalid.yaml")
82         invalid_template = '--template-file=' + template
83         self.assertRaises(exception.ValidationError, shell.main,
84                           [invalid_template, self.template_type,
85                            self.template_validation])
86
87     def test_output_file(self):
88         temp_dir = tempfile.mkdtemp()
89         temp_file = "/test_translation_output.txt"
90         output_file = "--output-file=" + temp_dir + temp_file
91         try:
92             shell.main([self.template_file, self.template_type, output_file])
93         except Exception:
94             self.fail(self.failure_msg)
95         finally:
96             if temp_dir:
97                 shutil.rmtree(temp_dir)
98                 self.assertTrue(temp_dir is None or
99                                 not os.path.exists(temp_dir))
100
101     @mock.patch('uuid.uuid4')
102     @mock.patch.object(shell.TranslatorShell, '_create_stack')
103     @mock.patch('keystoneauth1.loading.load_auth_from_argparse_arguments')
104     @mock.patch('keystoneauth1.loading.load_session_from_argparse_arguments')
105     @mock.patch('translator.common.flavors.get_flavors')
106     @mock.patch('translator.common.images.get_images')
107     def test_template_deploy(self, mock_populate_image_dict,
108                              mock_flavor_dict,
109                              mock_keystone_session,
110                              mock_keystone_auth,
111                              mock_client,
112                              mock_uuid):
113         mock_uuid.return_value = 'abcXXX-abcXXX'
114         mock_flavor_dict.return_value = {
115             'm1.medium': {'mem_size': 4096, 'disk_size': 40, 'num_cpus': 2}
116         }
117         mock_populate_image_dict.return_value = {
118             "rhel-6.5-test-image": {
119                 "version": "6.5",
120                 "architecture": "x86_64",
121                 "distribution": "RHEL",
122                 "type": "Linux"
123             }
124         }
125
126         try:
127             data = {
128                 'outputs': {},
129                 'heat_template_version': '2013-05-23',
130                 'description': 'Template for deploying a single server '
131                                'with predefined properties.\n',
132                 'parameters': {},
133                 'resources': {
134                     'my_server': {
135                         'type': 'OS::Nova::Server',
136                         'properties': {
137                             'flavor': 'm1.medium',
138                             'user_data_format': 'SOFTWARE_CONFIG',
139                             'software_config_transport': 'POLL_SERVER_HEAT',
140                             'image': 'rhel-6.5-test-image'
141                         }
142                     }
143                 }
144             }
145
146             mock_heat_res = {
147                 "stacks": [
148                     {
149                         "id": "d648ad27-fb9c-44d1-b293-646ea6c4f8da",
150                         "stack_status": "CREATE_IN_PROGRESS",
151                     }
152                 ]
153             }
154
155             class mock_response(object):
156                 def __init__(self, status_code, _content):
157                     self.status_code = status_code
158                     self._content = _content
159
160             mock_response_obj = mock_response(201, json.dumps(mock_heat_res))
161             mock_client.return_value = mock_response_obj
162             shell.main([self.template_file, self.template_type, "--deploy"])
163             args, kwargs = mock_client.call_args
164             self.assertEqual(kwargs["stack_name"],
165                              'heat_tosca_helloworld_abcXXX')
166             self.assertEqual(kwargs["template"], data)
167         except Exception as e:
168             self.fail(e)