test-module 5.06 KB
Newer Older
1
#!/usr/bin/env python
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
#

# this script is for testing modules without running through the
# entire guts of ansible, and is very helpful for when developing
# modules
#
# example:
26 27 28
#    test-module -m ../library/command -a "/bin/sleep 3"
#    test-module -m ../library/service -a "name=httpd ensure=restarted"
#    test-module -m ../library/service -a "name=httpd ensure=restarted" --debugger /usr/bin/pdb
29 30

import sys
31
import base64
32 33 34
import os
import subprocess
import traceback
35
import optparse
36 37
import ansible.utils as utils
import ansible.module_common as module_common
38
import ansible.constants as C
39 40 41 42 43 44

try:
    import json
except ImportError:
    import simplejson as json

45 46 47 48 49 50
def parse():
    """parse command line

    :return : (options, args)"""
    parser = optparse.OptionParser()

51
    parser.usage = "%prog -[options] (-h for help)"
52

53
    parser.add_option('-m', '--module-path', dest='module_path',
54
        help="REQUIRED: full path of module source to execute")
55
    parser.add_option('-a', '--args', dest='module_args', default="",
56
        help="module argument string")
57 58 59
    parser.add_option('-D', '--debugger', dest='debugger', 
        help="path to python debugger (e.g. /usr/bin/pdb)")
    options, args = parser.parse_args()
60
    if not options.module_path:
61 62 63 64 65
        parser.print_help()
        sys.exit(1)
    else:
        return options, args

66
def write_argsfile(argstring, json=False):
67
    """ Write args to a file for old-style module's use. """
68 69
    argspath = os.path.expanduser("~/.ansible_test_module_arguments")
    argsfile = open(argspath, 'w')
70 71 72
    if json:
        args = utils.parse_kv(argstring)
        argstring = utils.jsonify(args)
73 74 75 76
    argsfile.write(argstring)
    argsfile.close()
    return argspath

77 78 79
def boilerplate_module(modfile, args):
    """ simulate what ansible does with new style modules """

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    #module_fh = open(modfile)
    #module_data = module_fh.read()
    #module_fh.close()

    replacer = module_common.ModuleReplacer()

    #included_boilerplate = module_data.find(module_common.REPLACER) != -1 or module_data.find("import ansible.module_utils") != -1

    complex_args = {}
    inject = {}
    (module_data, module_style, shebang) = replacer.modify_module(
        modfile, 
        complex_args,
        args,
        inject 
    )
96

97 98 99 100 101 102 103
    modfile2_path = os.path.expanduser("~/.ansible_module_generated")
    print "* including generated source, if any, saving to: %s" % modfile2_path
    print "* this may offset any line numbers in tracebacks/debuggers!"
    modfile2 = open(modfile2_path, 'w')
    modfile2.write(module_data)
    modfile2.close()
    modfile = modfile2_path
104

105
    return (modfile2_path, module_style)
106

107 108
def runtest( modfile, argspath):
    """Test run a module, piping it's output for reporting."""
109

110
    os.system("chmod +x %s" % modfile)
111 112 113 114 115 116

    invoke = "%s" % (modfile)
    if argspath is not None:     
        invoke = "%s %s" % (modfile, argspath)

    cmd = subprocess.Popen(invoke, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
117 118 119 120 121 122 123 124 125 126 127 128 129 130
    (out, err) = cmd.communicate()

    try:
        print "***********************************"
        print "RAW OUTPUT"
        print out
        print err
        results = utils.parse_json(out)
    except:
        print "***********************************"
        print "INVALID OUTPUT FORMAT"
        print out
        traceback.print_exc()
        sys.exit(1)
131

132 133 134
    print "***********************************"
    print "PARSED OUTPUT"
    print utils.jsonify(results,format=True)
135

136 137 138
def rundebug(debugger, modfile, argspath):
    """Run interactively with console debugger."""

139 140 141 142
    if argspath is not None:
        subprocess.call("%s %s %s" % (debugger, modfile, argspath), shell=True)
    else:
        subprocess.call("%s %s" % (debugger, modfile), shell=True)
143

144
def main(): 
145

146
    options, args = parse()
147
    (modfile, module_style) = boilerplate_module(options.module_path, options.module_args)
148

149
    argspath=None
150 151
    if module_style != 'new':
        if module_style == 'non_native_want_json':
152
            argspath = write_argsfile(options.module_args, json=True)
153
        elif module_style == 'old':
154
            argspath = write_argsfile(options.module_args, json=False)
155 156
        else:
            raise Exception("internal error, unexpected module style: %s" % module_style)
157
    if options.debugger: 
158
        rundebug(options.debugger, modfile, argspath)
159
    else:
160
        runtest(modfile, argspath)
161
        
162 163
if __name__ == "__main__":
    main()
164