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