fix error when run unittest case
[parser.git] / tosca2heat / tosca-parser / toscaparser / tests / test_toscatpl.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 os
14 import six
15
16 from toscaparser.common import exception
17 import toscaparser.elements.interfaces as ifaces
18 from toscaparser.elements.nodetype import NodeType
19 from toscaparser.functions import GetInput
20 from toscaparser.functions import GetProperty
21 from toscaparser.nodetemplate import NodeTemplate
22 from toscaparser.tests.base import TestCase
23 from toscaparser.tosca_template import ToscaTemplate
24 from toscaparser.utils.gettextutils import _
25 import toscaparser.utils.yamlparser
26
27
28 class ToscaTemplateTest(TestCase):
29
30     '''TOSCA template.'''
31     tosca_tpl = os.path.join(
32         os.path.dirname(os.path.abspath(__file__)),
33         "data/tosca_single_instance_wordpress.yaml")
34     tosca = ToscaTemplate(tosca_tpl)
35
36     tosca_elk_tpl = os.path.join(
37         os.path.dirname(os.path.abspath(__file__)),
38         "data/tosca_elk.yaml")
39
40     def test_version(self):
41         self.assertEqual(self.tosca.version, "tosca_simple_yaml_1_0")
42
43     def test_description(self):
44         expected_description = "TOSCA simple profile with wordpress, " \
45                                "web server and mysql on the same server."
46         self.assertEqual(self.tosca.description, expected_description)
47
48     def test_inputs(self):
49         self.assertEqual(
50             ['cpus', 'db_name', 'db_port',
51              'db_pwd', 'db_root_pwd', 'db_user'],
52             sorted([input.name for input in self.tosca.inputs]))
53
54         input_name = "db_port"
55         expected_description = "Port for the MySQL database."
56         for input in self.tosca.inputs:
57             if input.name == input_name:
58                 self.assertEqual(input.description, expected_description)
59
60     def test_node_tpls(self):
61         '''Test nodetemplate names.'''
62         self.assertEqual(
63             ['mysql_database', 'mysql_dbms', 'server',
64              'webserver', 'wordpress'],
65             sorted([tpl.name for tpl in self.tosca.nodetemplates]))
66
67         tpl_name = "mysql_database"
68         expected_type = "tosca.nodes.Database"
69         expected_properties = ['name', 'password', 'user']
70         expected_capabilities = ['database_endpoint', 'feature']
71         expected_requirements = [{'host': 'mysql_dbms'}]
72         ''' TODO: needs enhancement in tosca_elk.yaml..
73         expected_relationshp = ['tosca.relationships.HostedOn']
74         expected_host = ['mysql_dbms']
75         '''
76         expected_interface = [ifaces.LIFECYCLE_SHORTNAME]
77
78         for tpl in self.tosca.nodetemplates:
79             if tpl_name == tpl.name:
80                 '''Test node type.'''
81                 self.assertEqual(tpl.type, expected_type)
82
83                 '''Test properties.'''
84                 self.assertEqual(
85                     expected_properties,
86                     sorted(tpl.get_properties().keys()))
87
88                 '''Test capabilities.'''
89                 self.assertEqual(
90                     expected_capabilities,
91                     sorted(tpl.get_capabilities().keys()))
92
93                 '''Test requirements.'''
94                 self.assertEqual(
95                     expected_requirements, tpl.requirements)
96
97                 '''Test relationship.'''
98                 ''' needs enhancements in tosca_elk.yaml
99                 self.assertEqual(
100                     expected_relationshp,
101                     [x.type for x in tpl.relationships.keys()])
102                 self.assertEqual(
103                     expected_host,
104                     [y.name for y in tpl.relationships.values()])
105                 '''
106                 '''Test interfaces.'''
107                 self.assertEqual(
108                     expected_interface,
109                     [x.type for x in tpl.interfaces])
110
111             if tpl.name == 'server':
112                 '''Test property value'''
113                 props = tpl.get_properties()
114                 if props and 'mem_size' in props.keys():
115                     self.assertEqual(props['mem_size'].value, '4096 MB')
116                 '''Test capability'''
117                 caps = tpl.get_capabilities()
118                 self.assertIn('os', caps.keys())
119                 os_props_objs = None
120                 os_props = None
121                 os_type_prop = None
122                 if caps and 'os' in caps.keys():
123                     capability = caps['os']
124                     os_props_objs = capability.get_properties_objects()
125                     os_props = capability.get_properties()
126                     os_type_prop = capability.get_property_value('type')
127                     break
128                 self.assertEqual(
129                     ['Linux'],
130                     [p.value for p in os_props_objs if p.name == 'type'])
131                 self.assertEqual(
132                     'Linux',
133                     os_props['type'].value if 'type' in os_props else '')
134                 self.assertEqual('Linux', os_props['type'].value)
135                 self.assertEqual('Linux', os_type_prop)
136
137     def test_outputs(self):
138         self.assertEqual(
139             ['website_url'],
140             sorted([output.name for output in self.tosca.outputs]))
141
142     def test_interfaces(self):
143         wordpress_node = [
144             node for node in self.tosca.nodetemplates
145             if node.name == 'wordpress'][0]
146         interfaces = wordpress_node.interfaces
147         self.assertEqual(2, len(interfaces))
148         for interface in interfaces:
149             if interface.name == 'create':
150                 self.assertEqual(ifaces.LIFECYCLE_SHORTNAME,
151                                  interface.type)
152                 self.assertEqual('wordpress/wordpress_install.sh',
153                                  interface.implementation)
154                 self.assertIsNone(interface.inputs)
155             elif interface.name == 'configure':
156                 self.assertEqual(ifaces.LIFECYCLE_SHORTNAME,
157                                  interface.type)
158                 self.assertEqual('wordpress/wordpress_configure.sh',
159                                  interface.implementation)
160                 self.assertEqual(3, len(interface.inputs))
161                 TestCase.skip(self, 'bug #1440247')
162                 wp_db_port = interface.inputs['wp_db_port']
163                 self.assertTrue(isinstance(wp_db_port, GetProperty))
164                 self.assertEqual('get_property', wp_db_port.name)
165                 self.assertEqual(['SELF',
166                                   'database_endpoint',
167                                   'port'],
168                                  wp_db_port.args)
169                 result = wp_db_port.result()
170                 self.assertTrue(isinstance(result, GetInput))
171             else:
172                 raise AssertionError(
173                     'Unexpected interface: {0}'.format(interface.name))
174
175     def test_normative_type_by_short_name(self):
176         # test template with a short name Compute
177         template = os.path.join(
178             os.path.dirname(os.path.abspath(__file__)),
179             "data/test_tosca_normative_type_by_shortname.yaml")
180
181         tosca_tpl = ToscaTemplate(template)
182         expected_type = "tosca.nodes.Compute"
183         for tpl in tosca_tpl.nodetemplates:
184             self.assertEqual(tpl.type, expected_type)
185         for tpl in tosca_tpl.nodetemplates:
186             compute_type = NodeType(tpl.type)
187             self.assertEqual(
188                 sorted(['tosca.capabilities.Container',
189                         'tosca.capabilities.Node',
190                         'tosca.capabilities.OperatingSystem',
191                         'tosca.capabilities.network.Bindable',
192                         'tosca.capabilities.Scalable']),
193                 sorted([c.type
194                         for c in compute_type.get_capabilities_objects()]))
195
196     def test_template_with_no_inputs(self):
197         tosca_tpl = self._load_template('test_no_inputs_in_template.yaml')
198         self.assertEqual(0, len(tosca_tpl.inputs))
199
200     def test_template_with_no_outputs(self):
201         tosca_tpl = self._load_template('test_no_outputs_in_template.yaml')
202         self.assertEqual(0, len(tosca_tpl.outputs))
203
204     def test_relationship_interface(self):
205         template = ToscaTemplate(self.tosca_elk_tpl)
206         for node_tpl in template.nodetemplates:
207             if node_tpl.name == 'logstash':
208                 config_interface = 'Configure'
209                 artifact = 'logstash/configure_elasticsearch.py'
210                 relation = node_tpl.relationships
211                 for key in relation.keys():
212                     rel_tpl = relation.get(key).get_relationship_template()
213                     if rel_tpl:
214                         self.assertTrue(rel_tpl[0].is_derived_from(
215                             "tosca.relationships.Root"))
216                         interfaces = rel_tpl[0].interfaces
217                         for interface in interfaces:
218                             self.assertEqual(config_interface,
219                                              interface.type)
220                             self.assertEqual('pre_configure_source',
221                                              interface.name)
222                             self.assertEqual(artifact,
223                                              interface.implementation)
224
225     def test_relationship(self):
226         template = ToscaTemplate(self.tosca_elk_tpl)
227         for node_tpl in template.nodetemplates:
228             if node_tpl.name == 'paypal_pizzastore':
229                 expected_relationships = ['tosca.relationships.ConnectsTo',
230                                           'tosca.relationships.HostedOn']
231                 expected_hosts = ['tosca.nodes.Database',
232                                   'tosca.nodes.WebServer']
233                 self.assertEqual(len(node_tpl.relationships), 2)
234                 self.assertEqual(
235                     expected_relationships,
236                     sorted([k.type for k in node_tpl.relationships.keys()]))
237                 self.assertEqual(
238                     expected_hosts,
239                     sorted([v.type for v in node_tpl.relationships.values()]))
240
241     def test_template_macro(self):
242         template = ToscaTemplate(self.tosca_elk_tpl)
243         for node_tpl in template.nodetemplates:
244             if node_tpl.name == 'mongo_server':
245                 self.assertEqual(
246                     ['disk_size', 'mem_size', 'num_cpus'],
247                     sorted(node_tpl.get_capability('host').
248                            get_properties().keys()))
249
250     def test_template_requirements(self):
251         """Test different formats of requirements
252
253         The requirements can be defined in few different ways,
254         1. Requirement expressed as a capability with an implicit relationship.
255         2. Requirement expressed with explicit relationship.
256         3. Requirement expressed with a relationship template.
257         4. Requirement expressed via TOSCA types to provision a node
258            with explicit relationship.
259         5. Requirement expressed via TOSCA types with a filter.
260         """
261         tosca_tpl = os.path.join(
262             os.path.dirname(os.path.abspath(__file__)),
263             "data/test_requirements.yaml")
264         tosca = ToscaTemplate(tosca_tpl)
265         for node_tpl in tosca.nodetemplates:
266             if node_tpl.name == 'my_app':
267                 expected_relationship = [
268                     ('tosca.relationships.ConnectsTo', 'mysql_database'),
269                     ('tosca.relationships.HostedOn', 'my_webserver')]
270                 actual_relationship = sorted([
271                     (relation.type, node.name) for
272                     relation, node in node_tpl.relationships.items()])
273                 self.assertEqual(expected_relationship, actual_relationship)
274             if node_tpl.name == 'mysql_database':
275                     self.assertEqual(
276                         [('tosca.relationships.HostedOn', 'my_dbms')],
277                         [(relation.type, node.name) for
278                          relation,
279                          node in node_tpl.relationships.items()])
280             if node_tpl.name == 'my_server':
281                     self.assertEqual(
282                         [('tosca.relationships.AttachesTo', 'my_storage')],
283                         [(relation.type, node.name) for
284                          relation,
285                          node in node_tpl.relationships.items()])
286
287     def test_template_requirements_not_implemented(self):
288         # TODO(spzala): replace this test with new one once TOSCA types look up
289         # support is implemented.
290         """Requirements that yet need to be implemented
291
292         The following requirement formats are not yet implemented,
293         due to look up dependency:
294         1. Requirement expressed via TOSCA types to provision a node
295            with explicit relationship.
296         2. Requirement expressed via TOSCA types with a filter.
297         """
298         tpl_snippet_1 = '''
299         node_templates:
300           mysql_database:
301             type: tosca.nodes.Database
302             description: Requires a particular node type and relationship.
303                         To be full-filled via lookup into node repository.
304             requirements:
305               - req1:
306                   node: tosca.nodes.DBMS
307                   relationship: tosca.relationships.HostedOn
308         '''
309
310         tpl_snippet_2 = '''
311         node_templates:
312           my_webserver:
313             type: tosca.nodes.WebServer
314             description: Requires a particular node type with a filter.
315                          To be full-filled via lookup into node repository.
316             requirements:
317               - req1:
318                   node: tosca.nodes.Compute
319                   target_filter:
320                     properties:
321                       num_cpus: { in_range: [ 1, 4 ] }
322                       mem_size: { greater_or_equal: 2 }
323                     capabilities:
324                       - tosca.capabilities.OS:
325                           properties:
326                             architecture: x86_64
327                             type: linux
328         '''
329
330         tpl_snippet_3 = '''
331         node_templates:
332           my_webserver2:
333             type: tosca.nodes.WebServer
334             description: Requires a node type with a particular capability.
335                          To be full-filled via lookup into node repository.
336             requirements:
337               - req1:
338                   node: tosca.nodes.Compute
339                   relationship: tosca.relationships.HostedOn
340                   capability: tosca.capabilities.Container
341         '''
342         self._requirements_not_implemented(tpl_snippet_1, 'mysql_database')
343         self._requirements_not_implemented(tpl_snippet_2, 'my_webserver')
344         self._requirements_not_implemented(tpl_snippet_3, 'my_webserver2')
345
346     def _requirements_not_implemented(self, tpl_snippet, tpl_name):
347         nodetemplates = (toscaparser.utils.yamlparser.
348                          simple_parse(tpl_snippet))['node_templates']
349         self.assertRaises(
350             NotImplementedError,
351             lambda: NodeTemplate(tpl_name, nodetemplates).relationships)
352
353     # Test the following:
354     # 1. Custom node type derived from 'WebApplication' named 'TestApp'
355     #    with a custom Capability Type 'TestCapability'
356     # 2. Same as #1, but referencing a custom 'TestCapability' Capability Type
357     #    that is not defined
358     def test_custom_capability_type_definition(self):
359         tpl_snippet = '''
360         node_templates:
361           test_app:
362             type: tosca.nodes.WebApplication.TestApp
363             capabilities:
364               test_cap:
365                 properties:
366                   test: 1
367         '''
368         # custom node type definition with custom capability type definition
369         custom_def = '''
370         tosca.nodes.WebApplication.TestApp:
371           derived_from: tosca.nodes.WebApplication
372           capabilities:
373             test_cap:
374                type: tosca.capabilities.TestCapability
375         tosca.capabilities.TestCapability:
376           derived_from: tosca.capabilities.Root
377           properties:
378             test:
379               type: integer
380               required: false
381         '''
382         expected_capabilities = ['app_endpoint', 'feature', 'test_cap']
383         nodetemplates = (toscaparser.utils.yamlparser.
384                          simple_parse(tpl_snippet))['node_templates']
385         custom_def = (toscaparser.utils.yamlparser.
386                       simple_parse(custom_def))
387         name = list(nodetemplates.keys())[0]
388         tpl = NodeTemplate(name, nodetemplates, custom_def)
389         self.assertEqual(
390             expected_capabilities,
391             sorted(tpl.get_capabilities().keys()))
392
393         # custom definition without valid capability type definition
394         custom_def = '''
395         tosca.nodes.WebApplication.TestApp:
396           derived_from: tosca.nodes.WebApplication
397           capabilities:
398             test_cap:
399                type: tosca.capabilities.TestCapability
400         '''
401         custom_def = (toscaparser.utils.yamlparser.
402                       simple_parse(custom_def))
403         tpl = NodeTemplate(name, nodetemplates, custom_def)
404         err = self.assertRaises(
405             exception.InvalidTypeError,
406             lambda: NodeTemplate(name, nodetemplates,
407                                  custom_def).get_capabilities_objects())
408         self.assertEqual('Type "tosca.capabilities.TestCapability" is not '
409                          'a valid type.', six.text_type(err))
410
411     def test_local_template_with_local_relpath_import(self):
412         tosca_tpl = os.path.join(
413             os.path.dirname(os.path.abspath(__file__)),
414             "data/tosca_single_instance_wordpress.yaml")
415         tosca = ToscaTemplate(tosca_tpl)
416         self.assertTrue(tosca.topology_template.custom_defs)
417
418     def test_local_template_with_url_import(self):
419         tosca_tpl = os.path.join(
420             os.path.dirname(os.path.abspath(__file__)),
421             "data/tosca_single_instance_wordpress_with_url_import.yaml")
422         tosca = ToscaTemplate(tosca_tpl)
423         self.assertTrue(tosca.topology_template.custom_defs)
424
425     def test_url_template_with_local_relpath_import(self):
426         tosca_tpl = ('https://raw.githubusercontent.com/openstack/'
427                      'tosca-parser/master/toscaparser/tests/data/'
428                      'tosca_single_instance_wordpress.yaml')
429         tosca = ToscaTemplate(tosca_tpl, None, False)
430         self.assertTrue(tosca.topology_template.custom_defs)
431
432     def test_url_template_with_local_abspath_import(self):
433         tosca_tpl = ('https://raw.githubusercontent.com/openstack/'
434                      'tosca-parser/master/toscaparser/tests/data/'
435                      'tosca_single_instance_wordpress_with_local_abspath_'
436                      'import.yaml')
437         self.assertRaises(exception.ValidationError, ToscaTemplate, tosca_tpl,
438                           None, False)
439         err_msg = (_('Absolute file name "/tmp/tosca-parser/toscaparser/tests'
440                      '/data/custom_types/wordpress.yaml" cannot be used in a '
441                      'URL-based input template "%(tpl)s".')
442                    % {'tpl': tosca_tpl})
443         exception.ExceptionCollector.assertExceptionMessage(ImportError,
444                                                             err_msg)
445
446     def test_url_template_with_url_import(self):
447         tosca_tpl = ('https://raw.githubusercontent.com/openstack/'
448                      'tosca-parser/master/toscaparser/tests/data/'
449                      'tosca_single_instance_wordpress_with_url_import.yaml')
450         tosca = ToscaTemplate(tosca_tpl, None, False)
451         self.assertTrue(tosca.topology_template.custom_defs)
452
453     def test_csar_parsing_wordpress(self):
454         csar_archive = os.path.join(
455             os.path.dirname(os.path.abspath(__file__)),
456             'data/CSAR/csar_wordpress.zip')
457         self.assertTrue(ToscaTemplate(csar_archive))
458
459     def test_csar_parsing_elk_url_based(self):
460         csar_archive = ('https://github.com/openstack/tosca-parser/raw/master/'
461                         'toscaparser/tests/data/CSAR/csar_elk.zip')
462         self.assertTrue(ToscaTemplate(csar_archive, None, False))
463
464     def test_nested_imports_in_templates(self):
465         tosca_tpl = os.path.join(
466             os.path.dirname(os.path.abspath(__file__)),
467             "data/test_instance_nested_imports.yaml")
468         tosca = ToscaTemplate(tosca_tpl)
469         expected_custom_types = ['tosca.nodes.WebApplication.WordPress',
470                                  'test_namespace_prefix.Rsyslog',
471                                  'Test2ndRsyslogType',
472                                  'test_2nd_namespace_prefix.Rsyslog',
473                                  'tosca.nodes.SoftwareComponent.Logstash',
474                                  'tosca.nodes.SoftwareComponent.Rsyslog.'
475                                  'TestRsyslogType']
476         self.assertItemsEqual(tosca.topology_template.custom_defs.keys(),
477                               expected_custom_types)
478
479     def test_invalid_template_file(self):
480         template_file = 'invalid template file'
481         expected_msg = (_('"%s" is not a valid file.') % template_file)
482         self.assertRaises(
483             exception.ValidationError,
484             ToscaTemplate, template_file, None, False)
485         exception.ExceptionCollector.assertExceptionMessage(ValueError,
486                                                             expected_msg)
487
488     def test_multiple_validation_errors(self):
489         tosca_tpl = os.path.join(
490             os.path.dirname(os.path.abspath(__file__)),
491             "data/test_multiple_validation_errors.yaml")
492         self.assertRaises(exception.ValidationError, ToscaTemplate, tosca_tpl,
493                           None)
494         valid_versions = ', '.join(ToscaTemplate.VALID_TEMPLATE_VERSIONS)
495         err1_msg = (_('The template version "tosca_simple_yaml_1" is invalid. '
496                       'Valid versions are "%s".') % valid_versions)
497         exception.ExceptionCollector.assertExceptionMessage(
498             exception.InvalidTemplateVersion, err1_msg)
499
500         err2_msg = _('Import "custom_types/not_there.yaml" is not valid.')
501         exception.ExceptionCollector.assertExceptionMessage(
502             ImportError, err2_msg)
503
504         err3_msg = _('Type "tosca.nodes.WebApplication.WordPress" is not a '
505                      'valid type.')
506         exception.ExceptionCollector.assertExceptionMessage(
507             exception.InvalidTypeError, err3_msg)
508
509         err4_msg = _('Node template "wordpress" contains unknown field '
510                      '"requirement". Refer to the definition to verify valid '
511                      'values.')
512         exception.ExceptionCollector.assertExceptionMessage(
513             exception.UnknownFieldError, err4_msg)
514
515         err5_msg = _('\'Property "passwords" was not found in node template '
516                      '"mysql_database".\'')
517         exception.ExceptionCollector.assertExceptionMessage(
518             KeyError, err5_msg)
519
520         err6_msg = _('Template "mysql_dbms" is missing required field "type".')
521         exception.ExceptionCollector.assertExceptionMessage(
522             exception.MissingRequiredFieldError, err6_msg)
523
524         err7_msg = _('Node template "mysql_dbms" contains unknown field '
525                      '"type1". Refer to the definition to verify valid '
526                      'values.')
527         exception.ExceptionCollector.assertExceptionMessage(
528             exception.UnknownFieldError, err7_msg)
529
530         err8_msg = _('\'Node template "server1" was not found.\'')
531         exception.ExceptionCollector.assertExceptionMessage(
532             KeyError, err8_msg)
533
534         err9_msg = _('"relationship" used in template "webserver" is missing '
535                      'required field "type".')
536         exception.ExceptionCollector.assertExceptionMessage(
537             exception.MissingRequiredFieldError, err9_msg)
538
539     def test_invalid_section_names(self):
540         tosca_tpl = os.path.join(
541             os.path.dirname(os.path.abspath(__file__)),
542             "data/test_invalid_section_names.yaml")
543         self.assertRaises(exception.ValidationError, ToscaTemplate, tosca_tpl,
544                           None)
545         err1_msg = _('Template contains unknown field '
546                      '"tosca_definitions_versions". Refer to the definition '
547                      'to verify valid values.')
548         exception.ExceptionCollector.assertExceptionMessage(
549             exception.UnknownFieldError, err1_msg)
550
551         err2_msg = _('Template contains unknown field "descriptions". '
552                      'Refer to the definition to verify valid values.')
553         exception.ExceptionCollector.assertExceptionMessage(
554             exception.UnknownFieldError, err2_msg)
555
556         err3_msg = _('Template contains unknown field "import". Refer to '
557                      'the definition to verify valid values.')
558         exception.ExceptionCollector.assertExceptionMessage(
559             exception.UnknownFieldError, err3_msg)
560
561         err4_msg = _('Template contains unknown field "topology_templates". '
562                      'Refer to the definition to verify valid values.')
563         exception.ExceptionCollector.assertExceptionMessage(
564             exception.UnknownFieldError, err4_msg)
565
566     def test_csar_with_alternate_extenstion(self):
567         tosca_tpl = os.path.join(
568             os.path.dirname(os.path.abspath(__file__)),
569             "data/CSAR/csar_elk.csar")
570         tosca = ToscaTemplate(tosca_tpl)
571         self.assertTrue(tosca.topology_template.custom_defs)
572
573     def test_available_rel_tpls(self):
574         tosca_tpl = os.path.join(
575             os.path.dirname(os.path.abspath(__file__)),
576             "data/test_available_rel_tpls.yaml")
577         tosca = ToscaTemplate(tosca_tpl)
578         for node in tosca.nodetemplates:
579             for relationship, target in node.relationships.items():
580                 try:
581                     target.relationships
582                 except TypeError as error:
583                     self.fail(error)
584
585     def test_no_input(self):
586         self.assertRaises(exception.ValidationError, ToscaTemplate, None,
587                           None, False, None)
588         err_msg = (('No path or yaml_dict_tpl was provided. '
589                     'There is nothing to parse.'))
590         exception.ExceptionCollector.assertExceptionMessage(ValueError,
591                                                             err_msg)
592
593     def test_path_and_yaml_dict_tpl_input(self):
594         test_tpl = os.path.join(
595             os.path.dirname(os.path.abspath(__file__)),
596             "data/tosca_helloworld.yaml")
597
598         yaml_dict_tpl = toscaparser.utils.yamlparser.load_yaml(test_tpl)
599
600         tosca = ToscaTemplate(test_tpl, yaml_dict_tpl=yaml_dict_tpl)
601
602         self.assertEqual(tosca.version, "tosca_simple_yaml_1_0")
603
604     def test_yaml_dict_tpl_input(self):
605         test_tpl = os.path.join(
606             os.path.dirname(os.path.abspath(__file__)),
607             "data/tosca_helloworld.yaml")
608
609         yaml_dict_tpl = toscaparser.utils.yamlparser.load_yaml(test_tpl)
610
611         tosca = ToscaTemplate(yaml_dict_tpl=yaml_dict_tpl)
612
613         self.assertEqual(tosca.version, "tosca_simple_yaml_1_0")
614
615     def test_yaml_dict_tpl_with_params_and_url_import(self):
616         test_tpl = os.path.join(
617             os.path.dirname(os.path.abspath(__file__)),
618             "data/tosca_single_instance_wordpress_with_url_import.yaml")
619
620         yaml_dict_tpl = toscaparser.utils.yamlparser.load_yaml(test_tpl)
621
622         params = {'db_name': 'my_wordpress', 'db_user': 'my_db_user',
623                   'db_root_pwd': 'mypasswd'}
624
625         tosca = ToscaTemplate(parsed_params=params,
626                               yaml_dict_tpl=yaml_dict_tpl)
627
628         self.assertEqual(tosca.version, "tosca_simple_yaml_1_0")
629
630     def test_yaml_dict_tpl_with_rel_import(self):
631         test_tpl = os.path.join(
632             os.path.dirname(os.path.abspath(__file__)),
633             "data/tosca_single_instance_wordpress.yaml")
634
635         yaml_dict_tpl = toscaparser.utils.yamlparser.load_yaml(test_tpl)
636
637         self.assertRaises(exception.ValidationError, ToscaTemplate, None,
638                           None, False, yaml_dict_tpl)
639         err_msg = (_('Relative file name "custom_types/wordpress.yaml" '
640                      'cannot be used in a pre-parsed input template.'))
641         exception.ExceptionCollector.assertExceptionMessage(ImportError,
642                                                             err_msg)
643
644     def test_yaml_dict_tpl_with_fullpath_import(self):
645         test_tpl = os.path.join(
646             os.path.dirname(os.path.abspath(__file__)),
647             "data/tosca_single_instance_wordpress.yaml")
648
649         yaml_dict_tpl = toscaparser.utils.yamlparser.load_yaml(test_tpl)
650
651         yaml_dict_tpl['imports'] = [os.path.join(os.path.dirname(
652             os.path.abspath(__file__)), "data/custom_types/wordpress.yaml")]
653
654         params = {'db_name': 'my_wordpress', 'db_user': 'my_db_user',
655                   'db_root_pwd': 'mypasswd'}
656
657         tosca = ToscaTemplate(parsed_params=params,
658                               yaml_dict_tpl=yaml_dict_tpl)
659
660         self.assertEqual(tosca.version, "tosca_simple_yaml_1_0")
661
662     def test_policies_for_node_templates(self):
663         tosca_tpl = os.path.join(
664             os.path.dirname(os.path.abspath(__file__)),
665             "data/policies/tosca_policy_template.yaml")
666         tosca = ToscaTemplate(tosca_tpl)
667
668         for policy in tosca.topology_template.policies:
669             if policy.name == 'my_compute_placement_policy':
670                 self.assertEqual('tosca.policies.Placement', policy.type)
671                 self.assertEqual(['my_server_1', 'my_server_2'],
672                                  policy.targets)
673                 self.assertEqual('node_templates', policy.get_targets_type())
674                 for node in policy.targets_list:
675                     if node.name == 'my_server_1':
676                         '''Test property value'''
677                         props = node.get_properties()
678                         if props and 'mem_size' in props.keys():
679                             self.assertEqual(props['mem_size'].value,
680                                              '4096 MB')
681
682     def test_policies_for_groups(self):
683         tosca_tpl = os.path.join(
684             os.path.dirname(os.path.abspath(__file__)),
685             "data/policies/tosca_policy_template.yaml")
686         tosca = ToscaTemplate(tosca_tpl)
687
688         for policy in tosca.topology_template.policies:
689             if policy.name == 'my_groups_placement':
690                 self.assertEqual('mycompany.mytypes.myScalingPolicy',
691                                  policy.type)
692                 self.assertEqual(['webserver_group'], policy.targets)
693                 self.assertEqual('groups', policy.get_targets_type())
694                 group = policy.get_targets_list()[0]
695                 for node in group.get_member_nodes():
696                     if node.name == 'my_server_2':
697                         '''Test property value'''
698                         props = node.get_properties()
699                         if props and 'mem_size' in props.keys():
700                             self.assertEqual(props['mem_size'].value,
701                                              '4096 MB')
702
703     def test_node_filter(self):
704         tosca_tpl = os.path.join(
705             os.path.dirname(os.path.abspath(__file__)),
706             "data/test_node_filter.yaml")
707         ToscaTemplate(tosca_tpl)
708
709     def test_attributes_inheritance(self):
710         tosca_tpl = os.path.join(
711             os.path.dirname(os.path.abspath(__file__)),
712             "data/test_attributes_inheritance.yaml")
713         ToscaTemplate(tosca_tpl)
714
715     def test_repositories_definition(self):
716         tosca_tpl = os.path.join(
717             os.path.dirname(os.path.abspath(__file__)),
718             "data/test_repositories_definition.yaml")
719         ToscaTemplate(tosca_tpl)
720
721     def test_custom_caps_def(self):
722         tosca_tpl = os.path.join(
723             os.path.dirname(os.path.abspath(__file__)),
724             "data/test_custom_caps_def.yaml")
725         ToscaTemplate(tosca_tpl)
726
727     def test_custom_rel_with_script(self):
728         tosca_tpl = os.path.join(
729             os.path.dirname(os.path.abspath(__file__)),
730             "data/test_tosca_custom_rel_with_script.yaml")
731         tosca = ToscaTemplate(tosca_tpl)
732         rel = tosca.relationship_templates[0]
733         self.assertEqual(rel.type, "tosca.relationships.HostedOn")
734         self.assertTrue(rel.is_derived_from("tosca.relationships.Root"))
735         self.assertEqual(len(rel.interfaces), 1)
736         self.assertEqual(rel.interfaces[0].type, "Configure")