Merge "The artifacttype's parent_type definition is error"
[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.assertEqual(
215                             rel_tpl[0].type, "tosca.relationships.ConnectsTo")
216                         self.assertTrue(rel_tpl[0].is_derived_from(
217                             "tosca.relationships.Root"))
218                         interfaces = rel_tpl[0].interfaces
219                         for interface in interfaces:
220                             self.assertEqual(config_interface,
221                                              interface.type)
222                             self.assertEqual('pre_configure_source',
223                                              interface.name)
224                             self.assertEqual(artifact,
225                                              interface.implementation)
226
227     def test_relationship(self):
228         template = ToscaTemplate(self.tosca_elk_tpl)
229         for node_tpl in template.nodetemplates:
230             if node_tpl.name == 'paypal_pizzastore':
231                 expected_relationships = ['tosca.relationships.ConnectsTo',
232                                           'tosca.relationships.HostedOn']
233                 expected_hosts = ['tosca.nodes.Database',
234                                   'tosca.nodes.WebServer']
235                 self.assertEqual(len(node_tpl.relationships), 2)
236                 self.assertEqual(
237                     expected_relationships,
238                     sorted([k.type for k in node_tpl.relationships.keys()]))
239                 self.assertEqual(
240                     expected_hosts,
241                     sorted([v.type for v in node_tpl.relationships.values()]))
242
243     def test_template_macro(self):
244         template = ToscaTemplate(self.tosca_elk_tpl)
245         for node_tpl in template.nodetemplates:
246             if node_tpl.name == 'mongo_server':
247                 self.assertEqual(
248                     ['disk_size', 'mem_size', 'num_cpus'],
249                     sorted(node_tpl.get_capability('host').
250                            get_properties().keys()))
251
252     def test_template_requirements(self):
253         """Test different formats of requirements
254
255         The requirements can be defined in few different ways,
256         1. Requirement expressed as a capability with an implicit relationship.
257         2. Requirement expressed with explicit relationship.
258         3. Requirement expressed with a relationship template.
259         4. Requirement expressed via TOSCA types to provision a node
260            with explicit relationship.
261         5. Requirement expressed via TOSCA types with a filter.
262         """
263         tosca_tpl = os.path.join(
264             os.path.dirname(os.path.abspath(__file__)),
265             "data/test_requirements.yaml")
266         tosca = ToscaTemplate(tosca_tpl)
267         for node_tpl in tosca.nodetemplates:
268             if node_tpl.name == 'my_app':
269                 expected_relationship = [
270                     ('tosca.relationships.ConnectsTo', 'mysql_database'),
271                     ('tosca.relationships.HostedOn', 'my_webserver')]
272                 actual_relationship = sorted([
273                     (relation.type, node.name) for
274                     relation, node in node_tpl.relationships.items()])
275                 self.assertEqual(expected_relationship, actual_relationship)
276             if node_tpl.name == 'mysql_database':
277                     self.assertEqual(
278                         [('tosca.relationships.HostedOn', 'my_dbms')],
279                         [(relation.type, node.name) for
280                          relation,
281                          node in node_tpl.relationships.items()])
282             if node_tpl.name == 'my_server':
283                     self.assertEqual(
284                         [('tosca.relationships.AttachesTo', 'my_storage')],
285                         [(relation.type, node.name) for
286                          relation,
287                          node in node_tpl.relationships.items()])
288
289     def test_template_requirements_not_implemented(self):
290         # TODO(spzala): replace this test with new one once TOSCA types look up
291         # support is implemented.
292         """Requirements that yet need to be implemented
293
294         The following requirement formats are not yet implemented,
295         due to look up dependency:
296         1. Requirement expressed via TOSCA types to provision a node
297            with explicit relationship.
298         2. Requirement expressed via TOSCA types with a filter.
299         """
300         tpl_snippet_1 = '''
301         node_templates:
302           mysql_database:
303             type: tosca.nodes.Database
304             description: Requires a particular node type and relationship.
305                         To be full-filled via lookup into node repository.
306             requirements:
307               - req1:
308                   node: tosca.nodes.DBMS
309                   relationship: tosca.relationships.HostedOn
310         '''
311
312         tpl_snippet_2 = '''
313         node_templates:
314           my_webserver:
315             type: tosca.nodes.WebServer
316             description: Requires a particular node type with a filter.
317                          To be full-filled via lookup into node repository.
318             requirements:
319               - req1:
320                   node: tosca.nodes.Compute
321                   target_filter:
322                     properties:
323                       num_cpus: { in_range: [ 1, 4 ] }
324                       mem_size: { greater_or_equal: 2 }
325                     capabilities:
326                       - tosca.capabilities.OS:
327                           properties:
328                             architecture: x86_64
329                             type: linux
330         '''
331
332         tpl_snippet_3 = '''
333         node_templates:
334           my_webserver2:
335             type: tosca.nodes.WebServer
336             description: Requires a node type with a particular capability.
337                          To be full-filled via lookup into node repository.
338             requirements:
339               - req1:
340                   node: tosca.nodes.Compute
341                   relationship: tosca.relationships.HostedOn
342                   capability: tosca.capabilities.Container
343         '''
344         self._requirements_not_implemented(tpl_snippet_1, 'mysql_database')
345         self._requirements_not_implemented(tpl_snippet_2, 'my_webserver')
346         self._requirements_not_implemented(tpl_snippet_3, 'my_webserver2')
347
348     def _requirements_not_implemented(self, tpl_snippet, tpl_name):
349         nodetemplates = (toscaparser.utils.yamlparser.
350                          simple_parse(tpl_snippet))['node_templates']
351         self.assertRaises(
352             NotImplementedError,
353             lambda: NodeTemplate(tpl_name, nodetemplates).relationships)
354
355     # Test the following:
356     # 1. Custom node type derived from 'WebApplication' named 'TestApp'
357     #    with a custom Capability Type 'TestCapability'
358     # 2. Same as #1, but referencing a custom 'TestCapability' Capability Type
359     #    that is not defined
360     def test_custom_capability_type_definition(self):
361         tpl_snippet = '''
362         node_templates:
363           test_app:
364             type: tosca.nodes.WebApplication.TestApp
365             capabilities:
366               test_cap:
367                 properties:
368                   test: 1
369         '''
370         # custom node type definition with custom capability type definition
371         custom_def = '''
372         tosca.nodes.WebApplication.TestApp:
373           derived_from: tosca.nodes.WebApplication
374           capabilities:
375             test_cap:
376                type: tosca.capabilities.TestCapability
377         tosca.capabilities.TestCapability:
378           derived_from: tosca.capabilities.Root
379           properties:
380             test:
381               type: integer
382               required: false
383         '''
384         expected_capabilities = ['app_endpoint', 'feature', 'test_cap']
385         nodetemplates = (toscaparser.utils.yamlparser.
386                          simple_parse(tpl_snippet))['node_templates']
387         custom_def = (toscaparser.utils.yamlparser.
388                       simple_parse(custom_def))
389         name = list(nodetemplates.keys())[0]
390         tpl = NodeTemplate(name, nodetemplates, custom_def)
391         self.assertEqual(
392             expected_capabilities,
393             sorted(tpl.get_capabilities().keys()))
394
395         # custom definition without valid capability type definition
396         custom_def = '''
397         tosca.nodes.WebApplication.TestApp:
398           derived_from: tosca.nodes.WebApplication
399           capabilities:
400             test_cap:
401                type: tosca.capabilities.TestCapability
402         '''
403         custom_def = (toscaparser.utils.yamlparser.
404                       simple_parse(custom_def))
405         tpl = NodeTemplate(name, nodetemplates, custom_def)
406         err = self.assertRaises(
407             exception.InvalidTypeError,
408             lambda: NodeTemplate(name, nodetemplates,
409                                  custom_def).get_capabilities_objects())
410         self.assertEqual('Type "tosca.capabilities.TestCapability" is not '
411                          'a valid type.', six.text_type(err))
412
413     def test_local_template_with_local_relpath_import(self):
414         tosca_tpl = os.path.join(
415             os.path.dirname(os.path.abspath(__file__)),
416             "data/tosca_single_instance_wordpress.yaml")
417         tosca = ToscaTemplate(tosca_tpl)
418         self.assertTrue(tosca.topology_template.custom_defs)
419
420     def test_local_template_with_url_import(self):
421         tosca_tpl = os.path.join(
422             os.path.dirname(os.path.abspath(__file__)),
423             "data/tosca_single_instance_wordpress_with_url_import.yaml")
424         tosca = ToscaTemplate(tosca_tpl)
425         self.assertTrue(tosca.topology_template.custom_defs)
426
427     def test_url_template_with_local_relpath_import(self):
428         tosca_tpl = ('https://raw.githubusercontent.com/openstack/'
429                      'tosca-parser/master/toscaparser/tests/data/'
430                      'tosca_single_instance_wordpress.yaml')
431         tosca = ToscaTemplate(tosca_tpl, None, False)
432         self.assertTrue(tosca.topology_template.custom_defs)
433
434     def test_url_template_with_local_abspath_import(self):
435         tosca_tpl = ('https://raw.githubusercontent.com/openstack/'
436                      'tosca-parser/master/toscaparser/tests/data/'
437                      'tosca_single_instance_wordpress_with_local_abspath_'
438                      'import.yaml')
439         self.assertRaises(exception.ValidationError, ToscaTemplate, tosca_tpl,
440                           None, False)
441         err_msg = (_('Absolute file name "/tmp/tosca-parser/toscaparser/tests'
442                      '/data/custom_types/wordpress.yaml" cannot be used in a '
443                      'URL-based input template "%(tpl)s".')
444                    % {'tpl': tosca_tpl})
445         exception.ExceptionCollector.assertExceptionMessage(ImportError,
446                                                             err_msg)
447
448     def test_url_template_with_url_import(self):
449         tosca_tpl = ('https://raw.githubusercontent.com/openstack/'
450                      'tosca-parser/master/toscaparser/tests/data/'
451                      'tosca_single_instance_wordpress_with_url_import.yaml')
452         tosca = ToscaTemplate(tosca_tpl, None, False)
453         self.assertTrue(tosca.topology_template.custom_defs)
454
455     def test_csar_parsing_wordpress(self):
456         csar_archive = os.path.join(
457             os.path.dirname(os.path.abspath(__file__)),
458             'data/CSAR/csar_wordpress.zip')
459         self.assertTrue(ToscaTemplate(csar_archive))
460
461     def test_csar_parsing_elk_url_based(self):
462         csar_archive = ('https://github.com/openstack/tosca-parser/raw/master/'
463                         'toscaparser/tests/data/CSAR/csar_elk.zip')
464         self.assertTrue(ToscaTemplate(csar_archive, None, False))
465
466     def test_nested_imports_in_templates(self):
467         tosca_tpl = os.path.join(
468             os.path.dirname(os.path.abspath(__file__)),
469             "data/test_instance_nested_imports.yaml")
470         tosca = ToscaTemplate(tosca_tpl)
471         expected_custom_types = ['tosca.nodes.WebApplication.WordPress',
472                                  'test_namespace_prefix.Rsyslog',
473                                  'Test2ndRsyslogType',
474                                  'test_2nd_namespace_prefix.Rsyslog',
475                                  'tosca.nodes.SoftwareComponent.Logstash',
476                                  'tosca.nodes.SoftwareComponent.Rsyslog.'
477                                  'TestRsyslogType']
478         self.assertItemsEqual(tosca.topology_template.custom_defs.keys(),
479                               expected_custom_types)
480
481     def test_invalid_template_file(self):
482         template_file = 'invalid template file'
483         expected_msg = (_('"%s" is not a valid file.') % template_file)
484         self.assertRaises(
485             exception.ValidationError,
486             ToscaTemplate, template_file, None, False)
487         exception.ExceptionCollector.assertExceptionMessage(ValueError,
488                                                             expected_msg)
489
490     def test_multiple_validation_errors(self):
491         tosca_tpl = os.path.join(
492             os.path.dirname(os.path.abspath(__file__)),
493             "data/test_multiple_validation_errors.yaml")
494         self.assertRaises(exception.ValidationError, ToscaTemplate, tosca_tpl,
495                           None)
496         valid_versions = ', '.join(ToscaTemplate.VALID_TEMPLATE_VERSIONS)
497         err1_msg = (_('The template version "tosca_simple_yaml_1" is invalid. '
498                       'Valid versions are "%s".') % valid_versions)
499         exception.ExceptionCollector.assertExceptionMessage(
500             exception.InvalidTemplateVersion, err1_msg)
501
502         err2_msg = _('Import "custom_types/not_there.yaml" is not valid.')
503         exception.ExceptionCollector.assertExceptionMessage(
504             ImportError, err2_msg)
505
506         err3_msg = _('Type "tosca.nodes.WebApplication.WordPress" is not a '
507                      'valid type.')
508         exception.ExceptionCollector.assertExceptionMessage(
509             exception.InvalidTypeError, err3_msg)
510
511         err4_msg = _('Node template "wordpress" contains unknown field '
512                      '"requirement". Refer to the definition to verify valid '
513                      'values.')
514         exception.ExceptionCollector.assertExceptionMessage(
515             exception.UnknownFieldError, err4_msg)
516
517         err5_msg = _('\'Property "passwords" was not found in node template '
518                      '"mysql_database".\'')
519         exception.ExceptionCollector.assertExceptionMessage(
520             KeyError, err5_msg)
521
522         err6_msg = _('Template "mysql_dbms" is missing required field "type".')
523         exception.ExceptionCollector.assertExceptionMessage(
524             exception.MissingRequiredFieldError, err6_msg)
525
526         err7_msg = _('Node template "mysql_dbms" contains unknown field '
527                      '"type1". Refer to the definition to verify valid '
528                      'values.')
529         exception.ExceptionCollector.assertExceptionMessage(
530             exception.UnknownFieldError, err7_msg)
531
532         err8_msg = _('\'Node template "server1" was not found.\'')
533         exception.ExceptionCollector.assertExceptionMessage(
534             KeyError, err8_msg)
535
536         err9_msg = _('"relationship" used in template "webserver" is missing '
537                      'required field "type".')
538         exception.ExceptionCollector.assertExceptionMessage(
539             exception.MissingRequiredFieldError, err9_msg)
540
541     def test_invalid_section_names(self):
542         tosca_tpl = os.path.join(
543             os.path.dirname(os.path.abspath(__file__)),
544             "data/test_invalid_section_names.yaml")
545         self.assertRaises(exception.ValidationError, ToscaTemplate, tosca_tpl,
546                           None)
547         err1_msg = _('Template contains unknown field '
548                      '"tosca_definitions_versions". Refer to the definition '
549                      'to verify valid values.')
550         exception.ExceptionCollector.assertExceptionMessage(
551             exception.UnknownFieldError, err1_msg)
552
553         err2_msg = _('Template contains unknown field "descriptions". '
554                      'Refer to the definition to verify valid values.')
555         exception.ExceptionCollector.assertExceptionMessage(
556             exception.UnknownFieldError, err2_msg)
557
558         err3_msg = _('Template contains unknown field "import". Refer to '
559                      'the definition to verify valid values.')
560         exception.ExceptionCollector.assertExceptionMessage(
561             exception.UnknownFieldError, err3_msg)
562
563         err4_msg = _('Template contains unknown field "topology_templates". '
564                      'Refer to the definition to verify valid values.')
565         exception.ExceptionCollector.assertExceptionMessage(
566             exception.UnknownFieldError, err4_msg)
567
568     def test_csar_with_alternate_extenstion(self):
569         tosca_tpl = os.path.join(
570             os.path.dirname(os.path.abspath(__file__)),
571             "data/CSAR/csar_elk.csar")
572         tosca = ToscaTemplate(tosca_tpl)
573         self.assertTrue(tosca.topology_template.custom_defs)
574
575     def test_available_rel_tpls(self):
576         tosca_tpl = os.path.join(
577             os.path.dirname(os.path.abspath(__file__)),
578             "data/test_available_rel_tpls.yaml")
579         tosca = ToscaTemplate(tosca_tpl)
580         for node in tosca.nodetemplates:
581             for relationship, target in node.relationships.items():
582                 try:
583                     target.relationships
584                 except TypeError as error:
585                     self.fail(error)
586
587     def test_no_input(self):
588         self.assertRaises(exception.ValidationError, ToscaTemplate, None,
589                           None, False, None)
590         err_msg = (('No path or yaml_dict_tpl was provided. '
591                     'There is nothing to parse.'))
592         exception.ExceptionCollector.assertExceptionMessage(ValueError,
593                                                             err_msg)
594
595     def test_path_and_yaml_dict_tpl_input(self):
596         test_tpl = os.path.join(
597             os.path.dirname(os.path.abspath(__file__)),
598             "data/tosca_helloworld.yaml")
599
600         yaml_dict_tpl = toscaparser.utils.yamlparser.load_yaml(test_tpl)
601
602         tosca = ToscaTemplate(test_tpl, yaml_dict_tpl=yaml_dict_tpl)
603
604         self.assertEqual(tosca.version, "tosca_simple_yaml_1_0")
605
606     def test_yaml_dict_tpl_input(self):
607         test_tpl = os.path.join(
608             os.path.dirname(os.path.abspath(__file__)),
609             "data/tosca_helloworld.yaml")
610
611         yaml_dict_tpl = toscaparser.utils.yamlparser.load_yaml(test_tpl)
612
613         tosca = ToscaTemplate(yaml_dict_tpl=yaml_dict_tpl)
614
615         self.assertEqual(tosca.version, "tosca_simple_yaml_1_0")
616
617     def test_yaml_dict_tpl_with_params_and_url_import(self):
618         test_tpl = os.path.join(
619             os.path.dirname(os.path.abspath(__file__)),
620             "data/tosca_single_instance_wordpress_with_url_import.yaml")
621
622         yaml_dict_tpl = toscaparser.utils.yamlparser.load_yaml(test_tpl)
623
624         params = {'db_name': 'my_wordpress', 'db_user': 'my_db_user',
625                   'db_root_pwd': 'mypasswd'}
626
627         tosca = ToscaTemplate(parsed_params=params,
628                               yaml_dict_tpl=yaml_dict_tpl)
629
630         self.assertEqual(tosca.version, "tosca_simple_yaml_1_0")
631
632     def test_yaml_dict_tpl_with_rel_import(self):
633         test_tpl = os.path.join(
634             os.path.dirname(os.path.abspath(__file__)),
635             "data/tosca_single_instance_wordpress.yaml")
636
637         yaml_dict_tpl = toscaparser.utils.yamlparser.load_yaml(test_tpl)
638
639         self.assertRaises(exception.ValidationError, ToscaTemplate, None,
640                           None, False, yaml_dict_tpl)
641         err_msg = (_('Relative file name "custom_types/wordpress.yaml" '
642                      'cannot be used in a pre-parsed input template.'))
643         exception.ExceptionCollector.assertExceptionMessage(ImportError,
644                                                             err_msg)
645
646     def test_yaml_dict_tpl_with_fullpath_import(self):
647         test_tpl = os.path.join(
648             os.path.dirname(os.path.abspath(__file__)),
649             "data/tosca_single_instance_wordpress.yaml")
650
651         yaml_dict_tpl = toscaparser.utils.yamlparser.load_yaml(test_tpl)
652
653         yaml_dict_tpl['imports'] = [os.path.join(os.path.dirname(
654             os.path.abspath(__file__)), "data/custom_types/wordpress.yaml")]
655
656         params = {'db_name': 'my_wordpress', 'db_user': 'my_db_user',
657                   'db_root_pwd': 'mypasswd'}
658
659         tosca = ToscaTemplate(parsed_params=params,
660                               yaml_dict_tpl=yaml_dict_tpl)
661
662         self.assertEqual(tosca.version, "tosca_simple_yaml_1_0")
663
664     def test_policies_for_node_templates(self):
665         tosca_tpl = os.path.join(
666             os.path.dirname(os.path.abspath(__file__)),
667             "data/policies/tosca_policy_template.yaml")
668         tosca = ToscaTemplate(tosca_tpl)
669
670         for policy in tosca.topology_template.policies:
671             if policy.name == 'my_compute_placement_policy':
672                 self.assertEqual('tosca.policies.Placement', policy.type)
673                 self.assertEqual(['my_server_1', 'my_server_2'],
674                                  policy.targets)
675                 self.assertEqual('node_templates', policy.get_targets_type())
676                 for node in policy.targets_list:
677                     if node.name == 'my_server_1':
678                         '''Test property value'''
679                         props = node.get_properties()
680                         if props and 'mem_size' in props.keys():
681                             self.assertEqual(props['mem_size'].value,
682                                              '4096 MB')
683
684     def test_policies_for_groups(self):
685         tosca_tpl = os.path.join(
686             os.path.dirname(os.path.abspath(__file__)),
687             "data/policies/tosca_policy_template.yaml")
688         tosca = ToscaTemplate(tosca_tpl)
689
690         for policy in tosca.topology_template.policies:
691             if policy.name == 'my_groups_placement':
692                 self.assertEqual('mycompany.mytypes.myScalingPolicy',
693                                  policy.type)
694                 self.assertEqual(['webserver_group'], policy.targets)
695                 self.assertEqual('groups', policy.get_targets_type())
696                 group = policy.get_targets_list()[0]
697                 for node in group.get_member_nodes():
698                     if node.name == 'my_server_2':
699                         '''Test property value'''
700                         props = node.get_properties()
701                         if props and 'mem_size' in props.keys():
702                             self.assertEqual(props['mem_size'].value,
703                                              '4096 MB')
704
705     def test_node_filter(self):
706         tosca_tpl = os.path.join(
707             os.path.dirname(os.path.abspath(__file__)),
708             "data/test_node_filter.yaml")
709         ToscaTemplate(tosca_tpl)
710
711     def test_attributes_inheritance(self):
712         tosca_tpl = os.path.join(
713             os.path.dirname(os.path.abspath(__file__)),
714             "data/test_attributes_inheritance.yaml")
715         ToscaTemplate(tosca_tpl)
716
717     def test_repositories_definition(self):
718         tosca_tpl = os.path.join(
719             os.path.dirname(os.path.abspath(__file__)),
720             "data/test_repositories_definition.yaml")
721         ToscaTemplate(tosca_tpl)
722
723     def test_custom_caps_def(self):
724         tosca_tpl = os.path.join(
725             os.path.dirname(os.path.abspath(__file__)),
726             "data/test_custom_caps_def.yaml")
727         ToscaTemplate(tosca_tpl)
728
729     def test_custom_rel_with_script(self):
730         tosca_tpl = os.path.join(
731             os.path.dirname(os.path.abspath(__file__)),
732             "data/test_tosca_custom_rel_with_script.yaml")
733         tosca = ToscaTemplate(tosca_tpl)
734         rel = tosca.relationship_templates[0]
735         self.assertEqual(rel.type, "tosca.relationships.HostedOn")
736         self.assertTrue(rel.is_derived_from("tosca.relationships.Root"))
737         self.assertEqual(len(rel.interfaces), 1)
738         self.assertEqual(rel.interfaces[0].type, "Configure")