def load(self, data, file_name='<string>', show_content=True): ''' Creates a python datastructure from the given data, which can be either a JSON or YAML string. ''' new_data = None try: # we first try to load this data as JSON new_data = json.loads(data) except: # must not be JSON, let the rest try if isinstance(data, AnsibleUnicode): # The PyYAML's libyaml bindings use PyUnicode_CheckExact so # they are unable to cope with our subclass. # Unwrap and re-wrap the unicode so we can keep track of line # numbers in_data = text_type(data) else: in_data = data try: new_data = self._safe_load(in_data, file_name=file_name) except YAMLError as yaml_exc: self._handle_error(yaml_exc, file_name, show_content) if isinstance(data, AnsibleUnicode): new_data = AnsibleUnicode(new_data) new_data.ansible_pos = data.ansible_pos return new_data
def load(self, data, file_name='<string>', show_content=True): ''' Creates a python datastructure from the given data, which can be either a JSON or YAML string. ''' try: # we first try to load this data as JSON return json.loads(data) except: # if loading JSON failed for any reason, we go ahead # and try to parse it as YAML instead if isinstance(data, AnsibleUnicode): # The PyYAML's libyaml bindings use PyUnicode_CheckExact so # they are unable to cope with our subclass. # Unwrap and re-wrap the unicode so we can keep track of line # numbers new_data = unicode(data) else: new_data = data try: new_data = self._safe_load(new_data, file_name=file_name) except YAMLError as yaml_exc: self._handle_error(yaml_exc, file_name, show_content) if isinstance(data, AnsibleUnicode): new_data = AnsibleUnicode(new_data) new_data.ansible_pos = data.ansible_pos return new_data
def construct_yaml_str(self, node): # Override the default string handling function # to always return unicode objects value = self.construct_scalar(node) ret = AnsibleUnicode(value) ret.ansible_pos = self._node_position_info(node) return ret
def raw_triage(self, key_string, item, patterns): # process dict values if isinstance(item, AnsibleMapping): return AnsibleMapping( dict((key, self.raw_triage('.'.join([key_string, key]), value, patterns)) for key, value in item.iteritems())) # process list values elif isinstance(item, AnsibleSequence): return AnsibleSequence([ self.raw_triage('.'.join([key_string, str(i)]), value, patterns) for i, value in enumerate(item) ]) # wrap values if they match raw_vars pattern elif isinstance(item, AnsibleUnicode): match = next( (pattern for pattern in patterns if re.match(pattern, key_string)), None) return AnsibleUnicode(''.join( ['{% raw %}', item, '{% endraw %}'])) if not item.startswith( ('{% raw', '{%raw')) and match else item
def from_yaml(data, file_name='<string>', show_content=True, vault_secrets=None): ''' Creates a python datastructure from the given data, which can be either a JSON or YAML string. ''' new_data = None if isinstance(data, AnsibleUnicode): # The PyYAML's libyaml bindings use PyUnicode_CheckExact so # they are unable to cope with our subclass. # Unwrap and re-wrap the unicode so we can keep track of line # numbers # Note: Cannot use to_text() because AnsibleUnicode is a subclass of the text_type. # Should not have to worry about tracebacks because python's text constructors (unicode() on # python2 and str() on python3) can handle a subtype of themselves. in_data = text_type(data) else: in_data = data try: # we first try to load this data as JSON. Fixes issues with extra vars json strings not # being parsed correctly by the yaml parser new_data = json.loads(in_data) except Exception: # must not be JSON, let the rest try try: new_data = _safe_load(in_data, file_name=file_name, vault_secrets=vault_secrets) except YAMLError as yaml_exc: _handle_error(yaml_exc, file_name, show_content) if isinstance(data, AnsibleUnicode): new_data = AnsibleUnicode(new_data) new_data.ansible_pos = data.ansible_pos return new_data
def load(self, data, file_name='<string>', show_content=True): ''' Creates a python datastructure from the given data, which can be either a JSON or YAML string. ''' # YAML parser will take JSON as it is a subset. if isinstance(data, AnsibleUnicode): # The PyYAML's libyaml bindings use PyUnicode_CheckExact so # they are unable to cope with our subclass. # Unwrap and re-wrap the unicode so we can keep track of line # numbers in_data = text_type(data) else: in_data = data try: new_data = self._safe_load(in_data, file_name=file_name) except YAMLError as yaml_exc: self._handle_error(yaml_exc, file_name, show_content) if isinstance(data, AnsibleUnicode): new_data = AnsibleUnicode(new_data) new_data.ansible_pos = data.ansible_pos return new_data
def _do_assert(self, condition, category="", fill_result=True): ''' perform a single assert and fill the result ''' cond = Conditional(loader=self._loader) cond.when = [AnsibleUnicode(condition)] test_result = cond.evaluate_conditional(templar=self._templar, all_vars=self._task_vars) if fill_result and not test_result: self._result['failed'] = True self._result['evaluated_to'] = False if 'assertion' not in self._result.keys(): self._result['assertion'] = [] self._result['assertion'].append('{0}> {1}'.format( category, condition)) self._result['msg'] = self._params['fail_msg'] return test_result
def test_task_executor_execute(self): fake_loader = DictDataLoader({}) mock_host = MagicMock() mock_task = MagicMock() mock_task.args = dict() mock_task.retries = 0 mock_task.delay = -1 mock_task.register = 'foo' mock_task.until = None mock_task.changed_when = None mock_task.failed_when = None mock_task.post_validate.return_value = None # mock_task.async cannot be left unset, because on Python 3 MagicMock() # > 0 raises a TypeError There are two reasons for using the value 1 # here: on Python 2 comparing MagicMock() > 0 returns True, and the # other reason is that if I specify 0 here, the test fails. ;) mock_task. async = 1 mock_task.poll = 0 mock_play_context = MagicMock() mock_play_context.post_validate.return_value = None mock_play_context.update_vars.return_value = None mock_connection = MagicMock() mock_connection.set_host_overrides.return_value = None mock_connection._connect.return_value = None mock_action = MagicMock() mock_queue = MagicMock() shared_loader = None new_stdin = None job_vars = dict(omit="XXXXXXXXXXXXXXXXXXX") te = TaskExecutor( host=mock_host, task=mock_task, job_vars=job_vars, play_context=mock_play_context, new_stdin=new_stdin, loader=fake_loader, shared_loader_obj=shared_loader, rslt_q=mock_queue, ) te._get_connection = MagicMock(return_value=mock_connection) te._get_action_handler = MagicMock(return_value=mock_action) mock_action.run.return_value = dict(ansible_facts=dict()) res = te._execute() mock_task.changed_when = MagicMock( return_value=AnsibleUnicode("1 == 1")) res = te._execute() mock_task.changed_when = None mock_task.failed_when = MagicMock( return_value=AnsibleUnicode("1 == 1")) res = te._execute() mock_task.failed_when = None mock_task.evaluate_conditional.return_value = False res = te._execute() mock_task.evaluate_conditional.return_value = True mock_task.args = dict(_raw_params='foo.yml', a='foo', b='bar') mock_task.action = 'include' res = te._execute()