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

# (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 39 40 41 42 43

try:
    import json
except ImportError:
    import simplejson as json

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

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

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

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

65 66
def write_argsfile(argstring):
    """ Write args to a file for old-style module's use. """
67 68 69 70 71 72
    argspath = os.path.expanduser("~/.ansible_test_module_arguments")
    argsfile = open(argspath, 'w')
    argsfile.write(argstring)
    argsfile.close()
    return argspath

73 74 75
def boilerplate_module(modfile, args):
    """ simulate what ansible does with new style modules """

76 77 78 79 80 81 82
    module_fh = open(modfile)
    module_data = module_fh.read()
    included_boilerplate = module_data.find(module_common.REPLACER) != -1
    module_fh.close()

    if included_boilerplate:
        module_data = module_data.replace(module_common.REPLACER, module_common.MODULE_COMMON)
83 84 85
        encoded_args = base64.b64encode(args)
        module_data = module_data.replace(module_common.REPLACER_ARGS, encoded_args)

86 87 88 89 90 91 92
        modfile2_path = os.path.expanduser("~/.ansible_module_generated")
        print "* including generated source, if any, saving to: %s" % modfile2_path
        print "* this will offset any line numbers in tracebacks/debuggers!"
        modfile2 = open(modfile2_path, 'w')
        modfile2.write(module_data)
        modfile2.close()
        modfile = modfile2_path
93
        return (modfile2_path, included_boilerplate)
94 95
    else:
        print "* module boilerplate substitution not requested in module, line numbers will be unaltered"
96
        return (modfile, included_boilerplate)
97

98 99
def runtest( modfile, argspath):
    """Test run a module, piping it's output for reporting."""
100

101
    os.system("chmod +x %s" % modfile)
102 103 104 105 106 107

    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)
108 109 110 111 112 113 114 115 116 117 118 119 120 121
    (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)
122

123 124 125
    print "***********************************"
    print "PARSED OUTPUT"
    print utils.jsonify(results,format=True)
126

127 128 129
def rundebug(debugger, modfile, argspath):
    """Run interactively with console debugger."""

130 131 132 133
    if argspath is not None:
        subprocess.call("%s %s %s" % (debugger, modfile, argspath), shell=True)
    else:
        subprocess.call("%s %s" % (debugger, modfile), shell=True)
134

135
def main(): 
136

137 138 139 140 141
    options, args = parse()
    (modfile, is_new_style) = boilerplate_module(options.module_path, options.module_args)
    argspath=None
    if not is_new_style:
        argspath = write_argsfile(options.module_args)
142
    if options.debugger: 
143
        rundebug(options.debugger, modfile, argspath)
144
    else:
145
        runtest(modfile, argspath)
146 147 148
	
if __name__ == "__main__":
    main()
149

150