1# Copyright (c) 2017 Ansible Project 2# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) 3from __future__ import (absolute_import, division, print_function) 4__metaclass__ = type 5 6 7import os 8import json 9import shutil 10import tempfile 11 12import pytest 13 14from units.compat.mock import patch, MagicMock 15from ansible.modules import async_wrapper 16 17from pprint import pprint 18 19 20class TestAsyncWrapper: 21 22 def test_run_module(self, monkeypatch): 23 24 def mock_get_interpreter(module_path): 25 return ['/usr/bin/python'] 26 27 module_result = {'rc': 0} 28 module_lines = [ 29 '#!/usr/bin/python', 30 'import sys', 31 'sys.stderr.write("stderr stuff")', 32 "print('%s')" % json.dumps(module_result) 33 ] 34 module_data = '\n'.join(module_lines) + '\n' 35 module_data = module_data.encode('utf-8') 36 37 workdir = tempfile.mkdtemp() 38 fh, fn = tempfile.mkstemp(dir=workdir) 39 40 with open(fn, 'wb') as f: 41 f.write(module_data) 42 43 command = fn 44 jobid = 0 45 jobpath = os.path.join(os.path.dirname(command), 'job') 46 47 monkeypatch.setattr(async_wrapper, '_get_interpreter', mock_get_interpreter) 48 49 res = async_wrapper._run_module(command, jobid, jobpath) 50 51 with open(os.path.join(workdir, 'job'), 'r') as f: 52 jres = json.loads(f.read()) 53 54 shutil.rmtree(workdir) 55 56 assert jres.get('rc') == 0 57 assert jres.get('stderr') == 'stderr stuff' 58