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