test/: PEP8 compliancy (#24803)

* test/: PEP8 compliancy

- Make PEP8 compliant

* Python3 chokes on casting int to bytes (#24952)

But if we tell the formatter that the var is a number, it works
This commit is contained in:
Dag Wieers 2017-05-30 19:05:19 +02:00 committed by John R Barker
parent 31c59ad5f9
commit 4efec414e7
110 changed files with 1702 additions and 1547 deletions

View file

@ -49,7 +49,7 @@ setup(
# Ansible will also make use of a system copy of python-six and # Ansible will also make use of a system copy of python-six and
# python-selectors2 if installed but use a Bundled copy if it's not. # python-selectors2 if installed but use a Bundled copy if it's not.
install_requires=install_requirements, install_requires=install_requirements,
package_dir={ '': 'lib' }, package_dir={'': 'lib'},
packages=find_packages('lib'), packages=find_packages('lib'),
package_data={ package_data={
'': [ '': [

View file

@ -1 +0,0 @@

View file

@ -4,15 +4,16 @@ Find and delete AWS resources matching the provided --match string. Unless
Please use caution, you can easily delete you're *ENTIRE* EC2 infrastructure. Please use caution, you can easily delete you're *ENTIRE* EC2 infrastructure.
''' '''
import boto
import boto.ec2.elb
import optparse
import os import os
import os.path
import re import re
import sys import sys
import boto
import optparse
import yaml
import os.path
import boto.ec2.elb
import time import time
import yaml
def delete_aws_resources(get_func, attr, opts): def delete_aws_resources(get_func, attr, opts):
for item in get_func(): for item in get_func():
@ -20,6 +21,7 @@ def delete_aws_resources(get_func, attr, opts):
if re.search(opts.match_re, val): if re.search(opts.match_re, val):
prompt_and_delete(item, "Delete matching %s? [y/n]: " % (item,), opts.assumeyes) prompt_and_delete(item, "Delete matching %s? [y/n]: " % (item,), opts.assumeyes)
def delete_autoscaling_group(get_func, attr, opts): def delete_autoscaling_group(get_func, attr, opts):
assumeyes = opts.assumeyes assumeyes = opts.assumeyes
group_name = None group_name = None
@ -49,7 +51,8 @@ def delete_autoscaling_group(get_func, attr, opts):
group.delete() group.delete()
while len(asg.get_all_groups(names=[group_name])): while len(asg.get_all_groups(names=[group_name])):
time.sleep(5) time.sleep(5)
print ("Terminated ASG: %s" % group_name) print("Terminated ASG: %s" % group_name)
def delete_aws_eips(get_func, attr, opts): def delete_aws_eips(get_func, attr, opts):
@ -65,22 +68,25 @@ def delete_aws_eips(get_func, attr, opts):
if val in eip_log: if val in eip_log:
prompt_and_delete(item, "Delete matching %s? [y/n]: " % (item,), opts.assumeyes) prompt_and_delete(item, "Delete matching %s? [y/n]: " % (item,), opts.assumeyes)
def delete_aws_instances(reservation, opts): def delete_aws_instances(reservation, opts):
for list in reservation: for list in reservation:
for item in list.instances: for item in list.instances:
prompt_and_delete(item, "Delete matching %s? [y/n]: " % (item,), opts.assumeyes) prompt_and_delete(item, "Delete matching %s? [y/n]: " % (item,), opts.assumeyes)
def prompt_and_delete(item, prompt, assumeyes): def prompt_and_delete(item, prompt, assumeyes):
if not assumeyes: if not assumeyes:
assumeyes = raw_input(prompt).lower() == 'y' assumeyes = raw_input(prompt).lower() == 'y'
assert hasattr(item, 'delete') or hasattr(item, 'terminate') , "Class <%s> has no delete or terminate attribute" % item.__class__ assert hasattr(item, 'delete') or hasattr(item, 'terminate'), "Class <%s> has no delete or terminate attribute" % item.__class__
if assumeyes: if assumeyes:
if hasattr(item, 'delete'): if hasattr(item, 'delete'):
item.delete() item.delete()
print ("Deleted %s" % item) print("Deleted %s" % item)
if hasattr(item, 'terminate'): if hasattr(item, 'terminate'):
item.terminate() item.terminate()
print ("Terminated %s" % item) print("Terminated %s" % item)
def parse_args(): def parse_args():
# Load details from credentials.yml # Load details from credentials.yml
@ -94,45 +100,61 @@ def parse_args():
if default_aws_secret_key is None: if default_aws_secret_key is None:
default_aws_secret_key = credentials['ec2_secret_key'] default_aws_secret_key = credentials['ec2_secret_key']
parser = optparse.OptionParser(usage="%s [options]" % (sys.argv[0],), parser = optparse.OptionParser(
description=__doc__) usage="%s [options]" % (sys.argv[0], ),
parser.add_option("--access", description=__doc__
)
parser.add_option(
"--access",
action="store", dest="ec2_access_key", action="store", dest="ec2_access_key",
default=default_aws_access_key, default=default_aws_access_key,
help="Amazon ec2 access id. Can use EC2_ACCESS_KEY environment variable, or a values from credentials.yml.") help="Amazon ec2 access id. Can use EC2_ACCESS_KEY environment variable, or a values from credentials.yml."
parser.add_option("--secret", )
parser.add_option(
"--secret",
action="store", dest="ec2_secret_key", action="store", dest="ec2_secret_key",
default=default_aws_secret_key, default=default_aws_secret_key,
help="Amazon ec2 secret key. Can use EC2_SECRET_KEY environment variable, or a values from credentials.yml.") help="Amazon ec2 secret key. Can use EC2_SECRET_KEY environment variable, or a values from credentials.yml."
parser.add_option("--eip-log", )
parser.add_option(
"--eip-log",
action="store", dest="eip_log", action="store", dest="eip_log",
default = None, default=None,
help = "Path to log of EIPs created during test.") help="Path to log of EIPs created during test."
parser.add_option("--integration-config", )
parser.add_option(
"--integration-config",
action="store", dest="int_config", action="store", dest="int_config",
default = "integration_config.yml", default="integration_config.yml",
help = "path to integration config") help="path to integration config"
parser.add_option("--credentials", "-c", )
parser.add_option(
"--credentials", "-c",
action="store", dest="credential_file", action="store", dest="credential_file",
default="credentials.yml", default="credentials.yml",
help="YAML file to read cloud credentials (default: %default)") help="YAML file to read cloud credentials (default: %default)"
parser.add_option("--yes", "-y", )
parser.add_option(
"--yes", "-y",
action="store_true", dest="assumeyes", action="store_true", dest="assumeyes",
default=False, default=False,
help="Don't prompt for confirmation") help="Don't prompt for confirmation"
parser.add_option("--match", )
parser.add_option(
"--match",
action="store", dest="match_re", action="store", dest="match_re",
default="^ansible-testing-", default="^ansible-testing-",
help="Regular expression used to find AWS resources (default: %default)") help="Regular expression used to find AWS resources (default: %default)"
)
(opts, args) = parser.parse_args() (opts, args) = parser.parse_args()
for required in ['ec2_access_key', 'ec2_secret_key']: for required in ['ec2_access_key', 'ec2_secret_key']:
if getattr(opts, required) is None: if getattr(opts, required) is None:
parser.error("Missing required parameter: --%s" % required) parser.error("Missing required parameter: --%s" % required)
return (opts, args) return (opts, args)
if __name__ == '__main__': if __name__ == '__main__':
(opts, args) = parse_args() (opts, args) = parse_args()
@ -140,7 +162,7 @@ if __name__ == '__main__':
int_config = yaml.load(open(opts.int_config).read()) int_config = yaml.load(open(opts.int_config).read())
if not opts.eip_log: if not opts.eip_log:
output_dir = os.path.expanduser(int_config["output_dir"]) output_dir = os.path.expanduser(int_config["output_dir"])
opts.eip_log = output_dir + '/' + opts.match_re.replace('^','') + '-eip_integration_tests.log' opts.eip_log = output_dir + '/' + opts.match_re.replace('^', '') + '-eip_integration_tests.log'
# Connect to AWS # Connect to AWS
aws = boto.connect_ec2(aws_access_key_id=opts.ec2_access_key, aws = boto.connect_ec2(aws_access_key_id=opts.ec2_access_key,
@ -172,7 +194,7 @@ if __name__ == '__main__':
delete_aws_eips(aws.get_all_addresses, 'public_ip', opts) delete_aws_eips(aws.get_all_addresses, 'public_ip', opts)
# Delete temporary instances # Delete temporary instances
filters = {"tag:Name":opts.match_re.replace('^',''), "instance-state-name": ['running', 'pending', 'stopped' ]} filters = {"tag:Name": opts.match_re.replace('^', ''), "instance-state-name": ['running', 'pending', 'stopped']}
delete_aws_instances(aws.get_all_instances(filters=filters), opts) delete_aws_instances(aws.get_all_instances(filters=filters), opts)
except KeyboardInterrupt as e: except KeyboardInterrupt as e:

View file

@ -4,21 +4,25 @@ Find and delete GCE resources matching the provided --match string. Unless
Please use caution, you can easily delete your *ENTIRE* GCE infrastructure. Please use caution, you can easily delete your *ENTIRE* GCE infrastructure.
''' '''
import optparse
import os import os
import re import re
import sys import sys
import optparse
import yaml import yaml
try: try:
from libcloud.compute.types import Provider from libcloud.common.google import (
GoogleBaseError,
QuotaExceededError,
ResourceExistsError,
ResourceInUseError,
ResourceNotFoundError,
)
from libcloud.compute.providers import get_driver from libcloud.compute.providers import get_driver
from libcloud.common.google import GoogleBaseError, QuotaExceededError, \ from libcloud.compute.types import Provider
ResourceExistsError, ResourceInUseError, ResourceNotFoundError
_ = Provider.GCE _ = Provider.GCE
except ImportError: except ImportError:
print("failed=True " + \ print("failed=True msg='libcloud with GCE support (0.13.3+) required for this module'")
"msg='libcloud with GCE support (0.13.3+) required for this module'")
sys.exit(1) sys.exit(1)
import gce_credentials import gce_credentials
@ -30,26 +34,34 @@ def delete_gce_resources(get_func, attr, opts):
if re.search(opts.match_re, val, re.IGNORECASE): if re.search(opts.match_re, val, re.IGNORECASE):
prompt_and_delete(item, "Delete matching %s? [y/n]: " % (item,), opts.assumeyes) prompt_and_delete(item, "Delete matching %s? [y/n]: " % (item,), opts.assumeyes)
def prompt_and_delete(item, prompt, assumeyes): def prompt_and_delete(item, prompt, assumeyes):
if not assumeyes: if not assumeyes:
assumeyes = raw_input(prompt).lower() == 'y' assumeyes = raw_input(prompt).lower() == 'y'
assert hasattr(item, 'destroy'), "Class <%s> has no delete attribute" % item.__class__ assert hasattr(item, 'destroy'), "Class <%s> has no delete attribute" % item.__class__
if assumeyes: if assumeyes:
item.destroy() item.destroy()
print ("Deleted %s" % item) print("Deleted %s" % item)
def parse_args(): def parse_args():
parser = optparse.OptionParser(usage="%s [options]" % (sys.argv[0],), parser = optparse.OptionParser(
description=__doc__) usage="%s [options]" % sys.argv[0],
description=__doc__
)
gce_credentials.add_credentials_options(parser) gce_credentials.add_credentials_options(parser)
parser.add_option("--yes", "-y", parser.add_option(
"--yes", "-y",
action="store_true", dest="assumeyes", action="store_true", dest="assumeyes",
default=False, default=False,
help="Don't prompt for confirmation") help="Don't prompt for confirmation"
parser.add_option("--match", )
parser.add_option(
"--match",
action="store", dest="match_re", action="store", dest="match_re",
default="^ansible-testing-", default="^ansible-testing-",
help="Regular expression used to find GCE resources (default: %default)") help="Regular expression used to find GCE resources (default: %default)"
)
(opts, args) = parser.parse_args() (opts, args) = parser.parse_args()
gce_credentials.check_required(opts, parser) gce_credentials.check_required(opts, parser)
@ -65,6 +77,7 @@ if __name__ == '__main__':
try: try:
# Delete matching instances # Delete matching instances
delete_gce_resources(gce.list_nodes, 'name', opts) delete_gce_resources(gce.list_nodes, 'name', opts)
# Delete matching snapshots # Delete matching snapshots
def get_snapshots(): def get_snapshots():
for volume in gce.list_volumes(): for volume in gce.list_volumes():

View file

@ -59,15 +59,15 @@ def prompt_and_delete(item, prompt, assumeyes):
if assumeyes: if assumeyes:
if hasattr(item, 'delete'): if hasattr(item, 'delete'):
item.delete() item.delete()
print ("Deleted %s" % item) print("Deleted %s" % item)
if hasattr(item, 'terminate'): if hasattr(item, 'terminate'):
item.terminate() item.terminate()
print ("Terminated %s" % item) print("Terminated %s" % item)
def delete_rax(args): def delete_rax(args):
"""Function for deleting CloudServers""" """Function for deleting CloudServers"""
print ("--- Cleaning CloudServers matching '%s'" % args.match_re) print("--- Cleaning CloudServers matching '%s'" % args.match_re)
search_opts = dict(name='^%s' % args.match_re) search_opts = dict(name='^%s' % args.match_re)
for region in pyrax.identity.services.compute.regions: for region in pyrax.identity.services.compute.regions:
cs = pyrax.connect_to_cloudservers(region=region) cs = pyrax.connect_to_cloudservers(region=region)
@ -80,7 +80,7 @@ def delete_rax(args):
def delete_rax_clb(args): def delete_rax_clb(args):
"""Function for deleting Cloud Load Balancers""" """Function for deleting Cloud Load Balancers"""
print ("--- Cleaning Cloud Load Balancers matching '%s'" % args.match_re) print("--- Cleaning Cloud Load Balancers matching '%s'" % args.match_re)
for region in pyrax.identity.services.load_balancer.regions: for region in pyrax.identity.services.load_balancer.regions:
clb = pyrax.connect_to_cloud_loadbalancers(region=region) clb = pyrax.connect_to_cloud_loadbalancers(region=region)
for lb in rax_list_iterator(clb): for lb in rax_list_iterator(clb):
@ -92,7 +92,7 @@ def delete_rax_clb(args):
def delete_rax_keypair(args): def delete_rax_keypair(args):
"""Function for deleting Rackspace Key pairs""" """Function for deleting Rackspace Key pairs"""
print ("--- Cleaning Key Pairs matching '%s'" % args.match_re) print("--- Cleaning Key Pairs matching '%s'" % args.match_re)
for region in pyrax.identity.services.compute.regions: for region in pyrax.identity.services.compute.regions:
cs = pyrax.connect_to_cloudservers(region=region) cs = pyrax.connect_to_cloudservers(region=region)
for keypair in cs.keypairs.list(): for keypair in cs.keypairs.list():
@ -104,7 +104,7 @@ def delete_rax_keypair(args):
def delete_rax_network(args): def delete_rax_network(args):
"""Function for deleting Cloud Networks""" """Function for deleting Cloud Networks"""
print ("--- Cleaning Cloud Networks matching '%s'" % args.match_re) print("--- Cleaning Cloud Networks matching '%s'" % args.match_re)
for region in pyrax.identity.services.network.regions: for region in pyrax.identity.services.network.regions:
cnw = pyrax.connect_to_cloud_networks(region=region) cnw = pyrax.connect_to_cloud_networks(region=region)
for network in cnw.list(): for network in cnw.list():
@ -116,7 +116,7 @@ def delete_rax_network(args):
def delete_rax_cbs(args): def delete_rax_cbs(args):
"""Function for deleting Cloud Networks""" """Function for deleting Cloud Networks"""
print ("--- Cleaning Cloud Block Storage matching '%s'" % args.match_re) print("--- Cleaning Cloud Block Storage matching '%s'" % args.match_re)
for region in pyrax.identity.services.network.regions: for region in pyrax.identity.services.network.regions:
cbs = pyrax.connect_to_cloud_blockstorage(region=region) cbs = pyrax.connect_to_cloud_blockstorage(region=region)
for volume in cbs.list(): for volume in cbs.list():
@ -128,7 +128,7 @@ def delete_rax_cbs(args):
def delete_rax_cdb(args): def delete_rax_cdb(args):
"""Function for deleting Cloud Databases""" """Function for deleting Cloud Databases"""
print ("--- Cleaning Cloud Databases matching '%s'" % args.match_re) print("--- Cleaning Cloud Databases matching '%s'" % args.match_re)
for region in pyrax.identity.services.database.regions: for region in pyrax.identity.services.database.regions:
cdb = pyrax.connect_to_cloud_databases(region=region) cdb = pyrax.connect_to_cloud_databases(region=region)
for db in rax_list_iterator(cdb): for db in rax_list_iterator(cdb):
@ -146,7 +146,7 @@ def _force_delete_rax_scaling_group(manager):
def delete_rax_scaling_group(args): def delete_rax_scaling_group(args):
"""Function for deleting Autoscale Groups""" """Function for deleting Autoscale Groups"""
print ("--- Cleaning Autoscale Groups matching '%s'" % args.match_re) print("--- Cleaning Autoscale Groups matching '%s'" % args.match_re)
for region in pyrax.identity.services.autoscale.regions: for region in pyrax.identity.services.autoscale.regions:
asg = pyrax.connect_to_autoscale(region=region) asg = pyrax.connect_to_autoscale(region=region)
for group in rax_list_iterator(asg): for group in rax_list_iterator(asg):
@ -170,11 +170,11 @@ def main():
try: try:
func(args) func(args)
except Exception as e: except Exception as e:
print ("---- %s failed (%s)" % (func.__name__, e.message)) print("---- %s failed (%s)" % (func.__name__, e.message))
if __name__ == '__main__': if __name__ == '__main__':
try: try:
main() main()
except KeyboardInterrupt: except KeyboardInterrupt:
print ('\nExiting...') print('\nExiting...')

View file

@ -8,8 +8,7 @@ try:
from libcloud.compute.providers import get_driver from libcloud.compute.providers import get_driver
_ = Provider.GCE _ = Provider.GCE
except ImportError: except ImportError:
print("failed=True " + \ print("failed=True msg='libcloud with GCE support (0.13.3+) required for this module'")
"msg='libcloud with GCE support (0.13.3+) required for this module'")
sys.exit(1) sys.exit(1)

View file

@ -7,19 +7,22 @@ ${prefix}-snapshot. prefix will be forced to lowercase, to ensure the names are
legal GCE resource names. legal GCE resource names.
''' '''
import sys
import optparse
import gce_credentials import gce_credentials
import optparse
import sys
def parse_args(): def parse_args():
parser = optparse.OptionParser( parser = optparse.OptionParser(
usage="%s [options] <prefix>" % (sys.argv[0],), description=__doc__) usage="%s [options] <prefix>" % (sys.argv[0],), description=__doc__
)
gce_credentials.add_credentials_options(parser) gce_credentials.add_credentials_options(parser)
parser.add_option("--prefix", parser.add_option(
action="store", dest="prefix", "--prefix",
help="String used to prefix GCE resource names (default: %default)") action="store",
dest="prefix",
help="String used to prefix GCE resource names (default: %default)"
)
(opts, args) = parser.parse_args() (opts, args) = parser.parse_args()
gce_credentials.check_required(opts, parser) gce_credentials.check_required(opts, parser)
@ -27,6 +30,7 @@ def parse_args():
parser.error("Missing required argument: name prefix") parser.error("Missing required argument: name prefix")
return (opts, args) return (opts, args)
if __name__ == '__main__': if __name__ == '__main__':
(opts, args) = parse_args() (opts, args) = parse_args()
@ -34,9 +38,8 @@ if __name__ == '__main__':
prefix = args[0].lower() prefix = args[0].lower()
try: try:
base_volume = gce.create_volume( base_volume = gce.create_volume(
size=10, name=prefix+'-base', location='us-central1-a') size=10, name=prefix + '-base', location='us-central1-a')
gce.create_volume_snapshot(base_volume, name=prefix+'-snapshot') gce.create_volume_snapshot(base_volume, name=prefix + '-snapshot')
gce.create_volume( gce.create_volume(size=10, name=prefix + '-extra', location='us-central1-a')
size=10, name=prefix+'-extra', location='us-central1-a')
except KeyboardInterrupt as e: except KeyboardInterrupt as e:
print("\nExiting on user command.") print("\nExiting on user command.")

View file

@ -1,7 +1,9 @@
import sys
import json import json
import sys
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
def main(): def main():
if "--interactive" in sys.argv: if "--interactive" in sys.argv:
import ansible.module_utils.basic import ansible.module_utils.basic
@ -11,8 +13,9 @@ def main():
) )
)) ))
module = AnsibleModule(argument_spec = dict( module = AnsibleModule(
fail_mode = dict(type='list', default=['success']) argument_spec=dict(
fail_mode=dict(type='list', default=['success'])
) )
) )

View file

@ -14,4 +14,3 @@ if __name__ == '__main__':
mimetypes.add_type('application/json', '.json') mimetypes.add_type('application/json', '.json')
import SimpleHTTPServer import SimpleHTTPServer
SimpleHTTPServer.test() SimpleHTTPServer.test()

View file

@ -81,6 +81,7 @@ class Role(object):
for dep in self.dependencies: for dep in self.dependencies:
f.write('- { role: %s }\n' % dep) f.write('- { role: %s }\n' % dep)
class DynamicInventory(object): class DynamicInventory(object):
BASESCRIPT = '''#!/usr/bin/python BASESCRIPT = '''#!/usr/bin/python
import json import json
@ -140,13 +141,12 @@ print(json.dumps(data, indent=2, sort_keys=True))
'hosts': [xhost], 'hosts': [xhost],
} }
def write_script(self): def write_script(self):
fdir = os.path.join(TESTDIR, 'inventory') fdir = os.path.join(TESTDIR, 'inventory')
if not os.path.isdir(fdir): if not os.path.isdir(fdir):
os.makedirs(fdir) os.makedirs(fdir)
fpath = os.path.join(fdir, 'hosts') fpath = os.path.join(fdir, 'hosts')
#fpath = os.path.join(TESTDIR, 'inventory') # fpath = os.path.join(TESTDIR, 'inventory')
self.fpath = fpath self.fpath = fpath
data = json.dumps(self.inventory) data = json.dumps(self.inventory)
@ -414,22 +414,22 @@ def main():
features = [ features = [
'extra_vars', 'extra_vars',
'include_params', 'include_params',
#'role_params', # FIXME: we don't yet validate tasks within a role # 'role_params', # FIXME: we don't yet validate tasks within a role
'set_fact', 'set_fact',
#'registered_vars', # FIXME: hard to simulate # 'registered_vars', # FIXME: hard to simulate
'include_vars', 'include_vars',
#'role_dep_params', # 'role_dep_params',
'task_vars', 'task_vars',
'block_vars', 'block_vars',
'role_var', 'role_var',
'vars_file', 'vars_file',
'play_var', 'play_var',
#'host_facts', # FIXME: hard to simulate # 'host_facts', # FIXME: hard to simulate
'pb_host_vars_file', 'pb_host_vars_file',
'ini_host_vars_file', 'ini_host_vars_file',
'ini_host', 'ini_host',
'pb_group_vars_file_child', 'pb_group_vars_file_child',
#'ini_group_vars_file_child', #FIXME: this contradicts documented precedence pb group vars files should override inventory ones # 'ini_group_vars_file_child', #FIXME: this contradicts documented precedence pb group vars files should override inventory ones
'pb_group_vars_file_parent', 'pb_group_vars_file_parent',
'ini_group_vars_file_parent', 'ini_group_vars_file_parent',
'pb_group_vars_file_all', 'pb_group_vars_file_all',
@ -489,7 +489,7 @@ def main():
dinv = options.use_dynamic_inventory dinv = options.use_dynamic_inventory
if dinv: if dinv:
# some features are specific to ini, so swap those # some features are specific to ini, so swap those
for idx,x in enumerate(features): for (idx, x) in enumerate(features):
if x.startswith('ini_') and 'vars_file' not in x: if x.startswith('ini_') and 'vars_file' not in x:
features[idx] = x.replace('ini_', 'script_') features[idx] = x.replace('ini_', 'script_')

View file

@ -821,110 +821,3 @@ lib/ansible/utils/path.py
lib/ansible/utils/ssh_functions.py lib/ansible/utils/ssh_functions.py
lib/ansible/utils/vars.py lib/ansible/utils/vars.py
lib/ansible/vars/manager.py lib/ansible/vars/manager.py
setup.py
test/integration/cleanup_azure.py
test/integration/cleanup_ec2.py
test/integration/cleanup_gce.py
test/integration/cleanup_rax.py
test/integration/gce_credentials.py
test/integration/setup_gce.py
test/integration/targets/async/library/async_test.py
test/integration/targets/uri/files/testserver.py
test/sanity/code-smell/ansible-var-precedence-check.py
test/units/cli/test_galaxy.py
test/units/contrib/inventory/test_vmware_inventory.py
test/units/errors/test_errors.py
test/units/executor/module_common/test_recursive_finder.py
test/units/executor/test_play_iterator.py
test/units/executor/test_playbook_executor.py
test/units/executor/test_task_executor.py
test/units/executor/test_task_result.py
test/units/inventory/test_inventory.py
test/units/mock/generator.py
test/units/mock/loader.py
test/units/module_utils/basic/test__log_invocation.py
test/units/module_utils/basic/test_deprecate_warn.py
test/units/module_utils/basic/test_exit_json.py
test/units/module_utils/basic/test_heuristic_log_sanitize.py
test/units/module_utils/basic/test_log.py
test/units/module_utils/basic/test_no_log.py
test/units/module_utils/basic/test_run_command.py
test/units/module_utils/basic/test_safe_eval.py
test/units/module_utils/basic/test_set_mode_if_different.py
test/units/module_utils/ec2/test_aws.py
test/units/module_utils/json_utils/test_filter_non_json_lines.py
test/units/module_utils/test_basic.py
test/units/module_utils/test_distribution_version.py
test/units/module_utils/test_facts.py
test/units/module_utils/test_postgresql.py
test/units/module_utils/test_text.py
test/units/modules/cloud/amazon/test_ec2_vpc_nat_gateway.py
test/units/modules/cloud/amazon/test_lambda.py
test/units/modules/cloud/amazon/test_s3.py
test/units/modules/cloud/docker/test_docker.py
test/units/modules/cloud/google/test_gce_tag.py
test/units/modules/cloud/openstack/test_os_server.py
test/units/modules/network/cumulus/test_nclu.py
test/units/modules/network/eos/eos_module.py
test/units/modules/network/eos/test_eos_command.py
test/units/modules/network/eos/test_eos_config.py
test/units/modules/network/eos/test_eos_system.py
test/units/modules/network/eos/test_eos_user.py
test/units/modules/network/ios/ios_module.py
test/units/modules/network/ios/test_ios_banner.py
test/units/modules/network/ios/test_ios_command.py
test/units/modules/network/ios/test_ios_config.py
test/units/modules/network/ios/test_ios_system.py
test/units/modules/network/ios/test_ios_template.py
test/units/modules/network/ios/test_ios_vrf.py
test/units/modules/network/iosxr/iosxr_module.py
test/units/modules/network/iosxr/test_iosxr_config.py
test/units/modules/network/iosxr/test_iosxr_facts.py
test/units/modules/network/iosxr/test_iosxr_system.py
test/units/modules/network/nxos/nxos_module.py
test/units/modules/network/nxos/test_nxos_command.py
test/units/modules/network/nxos/test_nxos_config.py
test/units/modules/network/nxos/test_nxos_evpn_global.py
test/units/modules/network/nxos/test_nxos_system.py
test/units/modules/network/vyos/test_vyos_command.py
test/units/modules/network/vyos/vyos_module.py
test/units/modules/packaging/os/test_apt.py
test/units/parsing/test_dataloader.py
test/units/parsing/test_mod_args.py
test/units/parsing/utils/test_addresses.py
test/units/parsing/utils/test_jsonify.py
test/units/parsing/vault/test_vault.py
test/units/parsing/vault/test_vault_editor.py
test/units/parsing/yaml/test_dumper.py
test/units/parsing/yaml/test_loader.py
test/units/parsing/yaml/test_objects.py
test/units/playbook/role/test_role.py
test/units/playbook/test_attribute.py
test/units/playbook/test_base.py
test/units/playbook/test_block.py
test/units/playbook/test_conditional.py
test/units/playbook/test_helpers.py
test/units/playbook/test_play_context.py
test/units/playbook/test_playbook.py
test/units/playbook/test_taggable.py
test/units/playbook/test_task.py
test/units/plugins/action/test_action.py
test/units/plugins/action/test_raw.py
test/units/plugins/action/test_synchronize.py
test/units/plugins/connection/test_connection.py
test/units/plugins/connection/test_netconf.py
test/units/plugins/connection/test_network_cli.py
test/units/plugins/connection/test_ssh.py
test/units/plugins/lookup/test_ini.py
test/units/plugins/lookup/test_password.py
test/units/plugins/strategy/test_strategy_base.py
test/units/plugins/test_plugins.py
test/units/template/test_safe_eval.py
test/units/template/test_templar.py
test/units/template/test_template_utilities.py
test/units/template/test_vars.py
test/units/test_constants.py
test/units/utils/test_helpers.py
test/units/utils/test_shlex.py
test/units/utils/test_vars.py
test/units/vars/test_variable_manager.py

View file

@ -19,20 +19,19 @@
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
import ansible
import os import os
import shutil import shutil
import tarfile import tarfile
import tempfile import tempfile
import yaml import yaml
from ansible.cli.galaxy import GalaxyCLI
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import call, patch from ansible.compat.tests.mock import call, patch
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.module_utils.six import PY3 from ansible.module_utils.six import PY3
import ansible
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.cli.galaxy import GalaxyCLI
class TestGalaxy(unittest.TestCase): class TestGalaxy(unittest.TestCase):
@classmethod @classmethod
@ -101,7 +100,7 @@ class TestGalaxy(unittest.TestCase):
gc = GalaxyCLI(args=self.default_args) gc = GalaxyCLI(args=self.default_args)
role_info = {'name': 'some_role_name'} role_info = {'name': 'some_role_name'}
display_result = gc._display_role_info(role_info) display_result = gc._display_role_info(role_info)
self.assertTrue(display_result.find('some_role_name') >-1) self.assertTrue(display_result.find('some_role_name') > -1)
def test_display_galaxy_info(self): def test_display_galaxy_info(self):
gc = GalaxyCLI(args=self.default_args) gc = GalaxyCLI(args=self.default_args)
@ -330,7 +329,7 @@ class ValidRoleTests(object):
self.assertTrue(os.path.isdir(os.path.join(self.role_dir, d)), msg="Expected role subdirectory {0} doesn't exist".format(d)) self.assertTrue(os.path.isdir(os.path.join(self.role_dir, d)), msg="Expected role subdirectory {0} doesn't exist".format(d))
def test_travis_yml(self): def test_travis_yml(self):
with open(os.path.join(self.role_dir,'.travis.yml'), 'r') as f: with open(os.path.join(self.role_dir, '.travis.yml'), 'r') as f:
contents = f.read() contents = f.read()
with open(os.path.join(self.role_skeleton_path, '.travis.yml'), 'r') as f: with open(os.path.join(self.role_skeleton_path, '.travis.yml'), 'r') as f:
@ -378,7 +377,7 @@ class TestGalaxyInitContainerEnabled(unittest.TestCase, ValidRoleTests):
def test_metadata_container_tag(self): def test_metadata_container_tag(self):
with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf: with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:
metadata = yaml.safe_load(mf) metadata = yaml.safe_load(mf)
self.assertIn('container', metadata.get('galaxy_info', dict()).get('galaxy_tags',[]), msg='container tag not set in role metadata') self.assertIn('container', metadata.get('galaxy_info', dict()).get('galaxy_tags', []), msg='container tag not set in role metadata')
def test_metadata_contents(self): def test_metadata_contents(self):
with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf: with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:

View file

@ -10,8 +10,6 @@ except ImportError:
from nose.plugins.skip import SkipTest from nose.plugins.skip import SkipTest
raise SkipTest("test_vmware_inventory.py requires the python module 'vmware_inventory'") raise SkipTest("test_vmware_inventory.py requires the python module 'vmware_inventory'")
# contrib's dirstruct doesn't contain __init__.py files # contrib's dirstruct doesn't contain __init__.py files
checkout_path = os.path.dirname(__file__) checkout_path = os.path.dirname(__file__)
checkout_path = checkout_path.replace('/test/units/contrib/inventory', '') checkout_path = checkout_path.replace('/test/units/contrib/inventory', '')
@ -21,14 +19,18 @@ sys.path.append(os.path.abspath(inventory_dir))
# cleanup so that nose's path is not polluted with other inv scripts # cleanup so that nose's path is not polluted with other inv scripts
sys.path.remove(os.path.abspath(inventory_dir)) sys.path.remove(os.path.abspath(inventory_dir))
BASICINVENTORY = {
'all': {
'hosts': ['foo', 'bar']
BASICINVENTORY = {'all': {'hosts': ['foo', 'bar']}, },
'_meta': { 'hostvars': { 'foo': {'hostname': 'foo'}, '_meta': {
'bar': {'hostname': 'bar'}} 'hostvars': {
'foo': {'hostname': 'foo'},
'bar': {'hostname': 'bar'}
} }
} }
}
class FakeArgs(object): class FakeArgs(object):
debug = False debug = False
@ -37,6 +39,7 @@ class FakeArgs(object):
host = False host = False
list = True list = True
class TestVMWareInventory(unittest.TestCase): class TestVMWareInventory(unittest.TestCase):
def test_host_info_returns_single_host(self): def test_host_info_returns_single_host(self):
@ -61,7 +64,7 @@ class TestVMWareInventory(unittest.TestCase):
except: except:
pass pass
assert serializable assert serializable
#import epdb; epdb.st() # import epdb; epdb.st()
def test_show_list_returns_serializable_data(self): def test_show_list_returns_serializable_data(self):
fakeargs = FakeArgs() fakeargs = FakeArgs()
@ -78,7 +81,7 @@ class TestVMWareInventory(unittest.TestCase):
except: except:
pass pass
assert serializable assert serializable
#import epdb; epdb.st() # import epdb; epdb.st()
def test_show_list_returns_all_data(self): def test_show_list_returns_all_data(self):
fakeargs = FakeArgs() fakeargs = FakeArgs()
@ -105,7 +108,7 @@ class TestVMWareInventory(unittest.TestCase):
except: except:
pass pass
assert serializable assert serializable
#import epdb; epdb.st() # import epdb; epdb.st()
def test_show_host_returns_just_host(self): def test_show_host_returns_just_host(self):
fakeargs = FakeArgs() fakeargs = FakeArgs()
@ -117,5 +120,5 @@ class TestVMWareInventory(unittest.TestCase):
showdata = vmw.show() showdata = vmw.show()
expected = BASICINVENTORY['_meta']['hostvars']['foo'] expected = BASICINVENTORY['_meta']['hostvars']['foo']
expected = json.dumps(expected, indent=2) expected = json.dumps(expected, indent=2)
#import epdb; epdb.st() # import epdb; epdb.st()
assert showdata == expected assert showdata == expected

View file

@ -19,13 +19,12 @@
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
from ansible.compat.tests import unittest
from ansible.parsing.yaml.objects import AnsibleBaseYAMLObject from ansible.compat.tests import BUILTINS, unittest
from ansible.errors import AnsibleError
from ansible.compat.tests import BUILTINS
from ansible.compat.tests.mock import mock_open, patch from ansible.compat.tests.mock import mock_open, patch
from ansible.errors import AnsibleError
from ansible.parsing.yaml.objects import AnsibleBaseYAMLObject
class TestErrors(unittest.TestCase): class TestErrors(unittest.TestCase):

View file

@ -20,13 +20,13 @@ from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
import imp import imp
import pytest
import zipfile import zipfile
from collections import namedtuple from collections import namedtuple
from functools import partial from functools import partial
from io import BytesIO, StringIO from io import BytesIO, StringIO
import pytest
import ansible.errors import ansible.errors
from ansible.executor.module_common import recursive_finder from ansible.executor.module_common import recursive_finder
@ -42,12 +42,12 @@ def finder_containers():
FinderContainers = namedtuple('FinderContainers', ['py_module_names', 'py_module_cache', 'zf']) FinderContainers = namedtuple('FinderContainers', ['py_module_names', 'py_module_cache', 'zf'])
py_module_names = set() py_module_names = set()
#py_module_cache = {('__init__',): b''} # py_module_cache = {('__init__',): b''}
py_module_cache = {} py_module_cache = {}
zipoutput = BytesIO() zipoutput = BytesIO()
zf = zipfile.ZipFile(zipoutput, mode='w', compression=zipfile.ZIP_STORED) zf = zipfile.ZipFile(zipoutput, mode='w', compression=zipfile.ZIP_STORED)
#zf.writestr('ansible/__init__.py', b'') # zf.writestr('ansible/__init__.py', b'')
return FinderContainers(py_module_names, py_module_cache, zf) return FinderContainers(py_module_names, py_module_cache, zf)
@ -79,7 +79,7 @@ class TestRecursiveFinder(object):
else: else:
module_utils_data = StringIO(u'# License\ndef do_something():\n pass\n') module_utils_data = StringIO(u'# License\ndef do_something():\n pass\n')
mocker.patch('imp.find_module', side_effect=partial(find_package_foo, module_utils_data)) mocker.patch('imp.find_module', side_effect=partial(find_package_foo, module_utils_data))
mocker.patch('ansible.executor.module_common._slurp', side_effect= lambda x: b'# License\ndef do_something():\n pass\n') mocker.patch('ansible.executor.module_common._slurp', side_effect=lambda x: b'# License\ndef do_something():\n pass\n')
name = 'ping' name = 'ping'
data = b'#!/usr/bin/python\nfrom ansible.module_utils import foo' data = b'#!/usr/bin/python\nfrom ansible.module_utils import foo'

View file

@ -57,10 +57,9 @@ class TestPlayIterator(unittest.TestCase):
new_hs = hs.copy() new_hs = hs.copy()
@patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop)
def test_play_iterator(self): def test_play_iterator(self):
#import epdb; epdb.st() # import epdb; epdb.st()
fake_loader = DictDataLoader({ fake_loader = DictDataLoader({
"test_play.yml": """ "test_play.yml": """
- hosts: all - hosts: all
@ -191,11 +190,11 @@ class TestPlayIterator(unittest.TestCase):
self.assertEqual(task.name, "role always task") self.assertEqual(task.name, "role always task")
self.assertIsNotNone(task._role) self.assertIsNotNone(task._role)
# role include task # role include task
#(host_state, task) = itr.get_next_task_for_host(hosts[0]) # (host_state, task) = itr.get_next_task_for_host(hosts[0])
#self.assertIsNotNone(task) # self.assertIsNotNone(task)
#self.assertEqual(task.action, 'debug') # self.assertEqual(task.action, 'debug')
#self.assertEqual(task.name, "role included task") # self.assertEqual(task.name, "role included task")
#self.assertIsNotNone(task._role) # self.assertIsNotNone(task._role)
# role task after include # role task after include
(host_state, task) = itr.get_next_task_for_host(hosts[0]) (host_state, task) = itr.get_next_task_for_host(hosts[0])
self.assertIsNotNone(task) self.assertIsNotNone(task)
@ -427,7 +426,7 @@ class TestPlayIterator(unittest.TestCase):
) )
# test the high-level add_tasks() method # test the high-level add_tasks() method
s = HostState(blocks=[0,1,2]) s = HostState(blocks=[0, 1, 2])
itr._insert_tasks_into_state = MagicMock(return_value=s) itr._insert_tasks_into_state = MagicMock(return_value=s)
itr.add_tasks(hosts[0], [MagicMock(), MagicMock(), MagicMock()]) itr.add_tasks(hosts[0], [MagicMock(), MagicMock(), MagicMock()])
self.assertEqual(itr._host_states[hosts[0].name], s) self.assertEqual(itr._host_states[hosts[0].name], s)

View file

@ -21,13 +21,13 @@ __metaclass__ = type
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import MagicMock from ansible.compat.tests.mock import MagicMock
from ansible.executor.playbook_executor import PlaybookExecutor from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.playbook import Playbook from ansible.playbook import Playbook
from ansible.template import Templar from ansible.template import Templar
from units.mock.loader import DictDataLoader from units.mock.loader import DictDataLoader
class TestPlaybookExecutor(unittest.TestCase): class TestPlaybookExecutor(unittest.TestCase):
def setUp(self): def setUp(self):
@ -96,46 +96,55 @@ class TestPlaybookExecutor(unittest.TestCase):
playbook = Playbook.load(pbe._playbooks[0], variable_manager=mock_var_manager, loader=fake_loader) playbook = Playbook.load(pbe._playbooks[0], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0] play = playbook.get_plays()[0]
play.post_validate(templar) play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0','host1','host2','host3','host4','host5','host6','host7','host8','host9'] mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
self.assertEqual(pbe._get_serialized_batches(play), [['host0','host1','host2','host3','host4','host5','host6','host7','host8','host9']]) self.assertEqual(pbe._get_serialized_batches(play), [['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']])
playbook = Playbook.load(pbe._playbooks[1], variable_manager=mock_var_manager, loader=fake_loader) playbook = Playbook.load(pbe._playbooks[1], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0] play = playbook.get_plays()[0]
play.post_validate(templar) play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0','host1','host2','host3','host4','host5','host6','host7','host8','host9'] mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
self.assertEqual(pbe._get_serialized_batches(play), [['host0','host1'],['host2','host3'],['host4','host5'],['host6','host7'],['host8','host9']]) self.assertEqual(
pbe._get_serialized_batches(play),
[['host0', 'host1'], ['host2', 'host3'], ['host4', 'host5'], ['host6', 'host7'], ['host8', 'host9']]
)
playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader) playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0] play = playbook.get_plays()[0]
play.post_validate(templar) play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0','host1','host2','host3','host4','host5','host6','host7','host8','host9'] mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
self.assertEqual(pbe._get_serialized_batches(play), [['host0','host1'],['host2','host3'],['host4','host5'],['host6','host7'],['host8','host9']]) self.assertEqual(
pbe._get_serialized_batches(play),
[['host0', 'host1'], ['host2', 'host3'], ['host4', 'host5'], ['host6', 'host7'], ['host8', 'host9']]
)
playbook = Playbook.load(pbe._playbooks[3], variable_manager=mock_var_manager, loader=fake_loader) playbook = Playbook.load(pbe._playbooks[3], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0] play = playbook.get_plays()[0]
play.post_validate(templar) play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0','host1','host2','host3','host4','host5','host6','host7','host8','host9'] mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
self.assertEqual(pbe._get_serialized_batches(play), [['host0'],['host1','host2'],['host3','host4','host5'],['host6','host7','host8'],['host9']]) self.assertEqual(
pbe._get_serialized_batches(play),
[['host0'], ['host1', 'host2'], ['host3', 'host4', 'host5'], ['host6', 'host7', 'host8'], ['host9']]
)
playbook = Playbook.load(pbe._playbooks[4], variable_manager=mock_var_manager, loader=fake_loader) playbook = Playbook.load(pbe._playbooks[4], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0] play = playbook.get_plays()[0]
play.post_validate(templar) play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0','host1','host2','host3','host4','host5','host6','host7','host8','host9'] mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
self.assertEqual(pbe._get_serialized_batches(play), [['host0'],['host1','host2'],['host3','host4','host5','host6','host7','host8','host9']]) self.assertEqual(pbe._get_serialized_batches(play), [['host0'], ['host1', 'host2'], ['host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']])
# Test when serial percent is under 1.0 # Test when serial percent is under 1.0
playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader) playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0] play = playbook.get_plays()[0]
play.post_validate(templar) play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0','host1','host2'] mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2']
self.assertEqual(pbe._get_serialized_batches(play), [['host0'],['host1'],['host2']]) self.assertEqual(pbe._get_serialized_batches(play), [['host0'], ['host1'], ['host2']])
# Test when there is a remainder for serial as a percent # Test when there is a remainder for serial as a percent
playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader) playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0] play = playbook.get_plays()[0]
play.post_validate(templar) play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0','host1','host2','host3','host4','host5','host6','host7','host8','host9','host10'] mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9', 'host10']
self.assertEqual( self.assertEqual(
pbe._get_serialized_batches(play), pbe._get_serialized_batches(play),
[['host0','host1'],['host2','host3'],['host4','host5'],['host6','host7'],['host8','host9'],['host10']] [['host0', 'host1'], ['host2', 'host3'], ['host4', 'host5'], ['host6', 'host7'], ['host8', 'host9'], ['host10']]
) )

View file

@ -21,7 +21,6 @@ __metaclass__ = type
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock from ansible.compat.tests.mock import patch, MagicMock
from ansible.errors import AnsibleError, AnsibleParserError from ansible.errors import AnsibleError, AnsibleParserError
from ansible.executor.task_executor import TaskExecutor from ansible.executor.task_executor import TaskExecutor
from ansible.playbook.play_context import PlayContext from ansible.playbook.play_context import PlayContext
@ -30,6 +29,7 @@ from ansible.parsing.yaml.objects import AnsibleUnicode
from units.mock.loader import DictDataLoader from units.mock.loader import DictDataLoader
class TestTaskExecutor(unittest.TestCase): class TestTaskExecutor(unittest.TestCase):
def setUp(self): def setUp(self):
@ -48,14 +48,14 @@ class TestTaskExecutor(unittest.TestCase):
job_vars = dict() job_vars = dict()
mock_queue = MagicMock() mock_queue = MagicMock()
te = TaskExecutor( te = TaskExecutor(
host = mock_host, host=mock_host,
task = mock_task, task=mock_task,
job_vars = job_vars, job_vars=job_vars,
play_context = mock_play_context, play_context=mock_play_context,
new_stdin = new_stdin, new_stdin=new_stdin,
loader = fake_loader, loader=fake_loader,
shared_loader_obj = mock_shared_loader, shared_loader_obj=mock_shared_loader,
rslt_q = mock_queue, rslt_q=mock_queue,
) )
def test_task_executor_run(self): def test_task_executor_run(self):
@ -75,14 +75,14 @@ class TestTaskExecutor(unittest.TestCase):
job_vars = dict() job_vars = dict()
te = TaskExecutor( te = TaskExecutor(
host = mock_host, host=mock_host,
task = mock_task, task=mock_task,
job_vars = job_vars, job_vars=job_vars,
play_context = mock_play_context, play_context=mock_play_context,
new_stdin = new_stdin, new_stdin=new_stdin,
loader = fake_loader, loader=fake_loader,
shared_loader_obj = mock_shared_loader, shared_loader_obj=mock_shared_loader,
rslt_q = mock_queue, rslt_q=mock_queue,
) )
te._get_loop_items = MagicMock(return_value=None) te._get_loop_items = MagicMock(return_value=None)
@ -92,7 +92,7 @@ class TestTaskExecutor(unittest.TestCase):
te._get_loop_items = MagicMock(return_value=[]) te._get_loop_items = MagicMock(return_value=[])
res = te.run() res = te.run()
te._get_loop_items = MagicMock(return_value=['a','b','c']) te._get_loop_items = MagicMock(return_value=['a', 'b', 'c'])
te._run_loop = MagicMock(return_value=[dict(item='a', changed=True), dict(item='b', failed=True), dict(item='c')]) te._run_loop = MagicMock(return_value=[dict(item='a', changed=True), dict(item='b', failed=True), dict(item='c')])
res = te.run() res = te.run()
@ -119,14 +119,14 @@ class TestTaskExecutor(unittest.TestCase):
mock_queue = MagicMock() mock_queue = MagicMock()
te = TaskExecutor( te = TaskExecutor(
host = mock_host, host=mock_host,
task = mock_task, task=mock_task,
job_vars = job_vars, job_vars=job_vars,
play_context = mock_play_context, play_context=mock_play_context,
new_stdin = new_stdin, new_stdin=new_stdin,
loader = fake_loader, loader=fake_loader,
shared_loader_obj = mock_shared_loader, shared_loader_obj=mock_shared_loader,
rslt_q = mock_queue, rslt_q=mock_queue,
) )
items = te._get_loop_items() items = te._get_loop_items()
@ -155,14 +155,14 @@ class TestTaskExecutor(unittest.TestCase):
job_vars = dict() job_vars = dict()
te = TaskExecutor( te = TaskExecutor(
host = mock_host, host=mock_host,
task = mock_task, task=mock_task,
job_vars = job_vars, job_vars=job_vars,
play_context = mock_play_context, play_context=mock_play_context,
new_stdin = new_stdin, new_stdin=new_stdin,
loader = fake_loader, loader=fake_loader,
shared_loader_obj = mock_shared_loader, shared_loader_obj=mock_shared_loader,
rslt_q = mock_queue, rslt_q=mock_queue,
) )
def _execute(variables): def _execute(variables):
@ -201,51 +201,49 @@ class TestTaskExecutor(unittest.TestCase):
job_vars = dict(pkg_mgr='yum') job_vars = dict(pkg_mgr='yum')
te = TaskExecutor( te = TaskExecutor(
host = mock_host, host=mock_host,
task = mock_task, task=mock_task,
job_vars = job_vars, job_vars=job_vars,
play_context = mock_play_context, play_context=mock_play_context,
new_stdin = new_stdin, new_stdin=new_stdin,
loader = fake_loader, loader=fake_loader,
shared_loader_obj = mock_shared_loader, shared_loader_obj=mock_shared_loader,
rslt_q = mock_queue, rslt_q=mock_queue,
) )
#
# No replacement # No replacement
#
mock_task.action = 'yum' mock_task.action = 'yum'
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
self.assertEqual(new_items, ['a', 'b', 'c']) self.assertEqual(new_items, ['a', 'b', 'c'])
self.assertIsInstance(mock_task.args, MagicMock) self.assertIsInstance(mock_task.args, MagicMock)
mock_task.action = 'foo' mock_task.action = 'foo'
mock_task.args={'name': '{{item}}'} mock_task.args = {'name': '{{item}}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
self.assertEqual(new_items, ['a', 'b', 'c']) self.assertEqual(new_items, ['a', 'b', 'c'])
self.assertEqual(mock_task.args, {'name': '{{item}}'}) self.assertEqual(mock_task.args, {'name': '{{item}}'})
mock_task.action = 'yum' mock_task.action = 'yum'
mock_task.args={'name': 'static'} mock_task.args = {'name': 'static'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
self.assertEqual(new_items, ['a', 'b', 'c']) self.assertEqual(new_items, ['a', 'b', 'c'])
self.assertEqual(mock_task.args, {'name': 'static'}) self.assertEqual(mock_task.args, {'name': 'static'})
mock_task.action = 'yum' mock_task.action = 'yum'
mock_task.args={'name': '{{pkg_mgr}}'} mock_task.args = {'name': '{{pkg_mgr}}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
self.assertEqual(new_items, ['a', 'b', 'c']) self.assertEqual(new_items, ['a', 'b', 'c'])
self.assertEqual(mock_task.args, {'name': '{{pkg_mgr}}'}) self.assertEqual(mock_task.args, {'name': '{{pkg_mgr}}'})
mock_task.action = '{{unknown}}' mock_task.action = '{{unknown}}'
mock_task.args={'name': '{{item}}'} mock_task.args = {'name': '{{item}}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
self.assertEqual(new_items, ['a', 'b', 'c']) self.assertEqual(new_items, ['a', 'b', 'c'])
self.assertEqual(mock_task.args, {'name': '{{item}}'}) self.assertEqual(mock_task.args, {'name': '{{item}}'})
# Could do something like this to recover from bad deps in a package # Could do something like this to recover from bad deps in a package
job_vars = dict(pkg_mgr='yum', packages=['a', 'b']) job_vars = dict(pkg_mgr='yum', packages=['a', 'b'])
items = [ 'absent', 'latest' ] items = ['absent', 'latest']
mock_task.action = 'yum' mock_task.action = 'yum'
mock_task.args = {'name': '{{ packages }}', 'state': '{{ item }}'} mock_task.args = {'name': '{{ packages }}', 'state': '{{ item }}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
@ -261,7 +259,7 @@ class TestTaskExecutor(unittest.TestCase):
# an error later. If so, we can throw it now instead. # an error later. If so, we can throw it now instead.
# Squashing in this case would not be intuitive as the user is being # Squashing in this case would not be intuitive as the user is being
# explicit in using each list entry as a key. # explicit in using each list entry as a key.
job_vars = dict(pkg_mgr='yum', packages={ "a": "foo", "b": "bar", "foo": "baz", "bar": "quux" }) job_vars = dict(pkg_mgr='yum', packages={"a": "foo", "b": "bar", "foo": "baz", "bar": "quux"})
items = [['a', 'b'], ['foo', 'bar']] items = [['a', 'b'], ['foo', 'bar']]
mock_task.action = 'yum' mock_task.action = 'yum'
mock_task.args = {'name': '{{ packages[item] }}'} mock_task.args = {'name': '{{ packages[item] }}'}
@ -269,21 +267,19 @@ class TestTaskExecutor(unittest.TestCase):
self.assertEqual(new_items, items) self.assertEqual(new_items, items)
self.assertEqual(mock_task.args, {'name': '{{ packages[item] }}'}) self.assertEqual(mock_task.args, {'name': '{{ packages[item] }}'})
#
# Replaces # Replaces
#
items = ['a', 'b', 'c'] items = ['a', 'b', 'c']
mock_task.action = 'yum' mock_task.action = 'yum'
mock_task.args={'name': '{{item}}'} mock_task.args = {'name': '{{item}}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
self.assertEqual(new_items, [['a','c']])
self.assertEqual(mock_task.args, {'name': ['a','c']})
mock_task.action = '{{pkg_mgr}}'
mock_task.args={'name': '{{item}}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
self.assertEqual(new_items, [['a', 'c']]) self.assertEqual(new_items, [['a', 'c']])
self.assertEqual(mock_task.args, {'name': ['a','c']}) self.assertEqual(mock_task.args, {'name': ['a', 'c']})
mock_task.action = '{{pkg_mgr}}'
mock_task.args = {'name': '{{item}}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
self.assertEqual(new_items, [['a', 'c']])
self.assertEqual(mock_task.args, {'name': ['a', 'c']})
# New loop_var # New loop_var
mock_task.action = 'yum' mock_task.action = 'yum'
@ -292,7 +288,7 @@ class TestTaskExecutor(unittest.TestCase):
loop_var = 'a_loop_var_item' loop_var = 'a_loop_var_item'
new_items = te._squash_items(items=items, loop_var='a_loop_var_item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='a_loop_var_item', variables=job_vars)
self.assertEqual(new_items, [['a', 'c']]) self.assertEqual(new_items, [['a', 'c']])
self.assertEqual(mock_task.args, {'name': ['a','c']}) self.assertEqual(mock_task.args, {'name': ['a', 'c']})
loop_var = 'item' loop_var = 'item'
# #
@ -307,8 +303,8 @@ class TestTaskExecutor(unittest.TestCase):
mock_task.action = 'yum' mock_task.action = 'yum'
mock_task.args = {'name': '{{ item }}'} mock_task.args = {'name': '{{ item }}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
#self.assertEqual(new_items, [['a', 'b', 'foo', 'bar']]) # self.assertEqual(new_items, [['a', 'b', 'foo', 'bar']])
#self.assertEqual(mock_task.args, {'name': ['a', 'b', 'foo', 'bar']}) # self.assertEqual(mock_task.args, {'name': ['a', 'b', 'foo', 'bar']})
self.assertEqual(new_items, items) self.assertEqual(new_items, items)
self.assertEqual(mock_task.args, {'name': '{{ item }}'}) self.assertEqual(mock_task.args, {'name': '{{ item }}'})
@ -317,8 +313,8 @@ class TestTaskExecutor(unittest.TestCase):
mock_task.action = 'yum' mock_task.action = 'yum'
mock_task.args = {'name': '{{ packages[item] }}'} mock_task.args = {'name': '{{ packages[item] }}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
#self.assertEqual(new_items, [['foo', 'baz']]) # self.assertEqual(new_items, [['foo', 'baz']])
#self.assertEqual(mock_task.args, {'name': ['foo', 'baz']}) # self.assertEqual(mock_task.args, {'name': ['foo', 'baz']})
self.assertEqual(new_items, items) self.assertEqual(new_items, items)
self.assertEqual(mock_task.args, {'name': '{{ packages[item] }}'}) self.assertEqual(mock_task.args, {'name': '{{ packages[item] }}'})
@ -328,35 +324,38 @@ class TestTaskExecutor(unittest.TestCase):
mock_task.action = 'yum' mock_task.action = 'yum'
mock_task.args = {'name': '{{ item["package"] }}'} mock_task.args = {'name': '{{ item["package"] }}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
#self.assertEqual(new_items, [['foo', 'bar']]) # self.assertEqual(new_items, [['foo', 'bar']])
#self.assertEqual(mock_task.args, {'name': ['foo', 'bar']}) # self.assertEqual(mock_task.args, {'name': ['foo', 'bar']})
self.assertEqual(new_items, items) self.assertEqual(new_items, items)
self.assertEqual(mock_task.args, {'name': '{{ item["package"] }}'}) self.assertEqual(mock_task.args, {'name': '{{ item["package"] }}'})
items = [dict(name='a', state='present'), items = [
dict(name='a', state='present'),
dict(name='b', state='present'), dict(name='b', state='present'),
dict(name='c', state='present')] dict(name='c', state='present'),
]
mock_task.action = 'yum' mock_task.action = 'yum'
mock_task.args={'name': '{{item.name}}', 'state': '{{item.state}}'} mock_task.args = {'name': '{{item.name}}', 'state': '{{item.state}}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
#self.assertEqual(new_items, [dict(name=['a', 'b', 'c'], state='present')]) # self.assertEqual(new_items, [dict(name=['a', 'b', 'c'], state='present')])
#self.assertEqual(mock_task.args, {'name': ['a', 'b', 'c'], 'state': 'present'}) # self.assertEqual(mock_task.args, {'name': ['a', 'b', 'c'], 'state': 'present'})
self.assertEqual(new_items, items) self.assertEqual(new_items, items)
self.assertEqual(mock_task.args, {'name': '{{item.name}}', 'state': '{{item.state}}'}) self.assertEqual(mock_task.args, {'name': '{{item.name}}', 'state': '{{item.state}}'})
items = [dict(name='a', state='present'), items = [
dict(name='a', state='present'),
dict(name='b', state='present'), dict(name='b', state='present'),
dict(name='c', state='absent')] dict(name='c', state='absent'),
]
mock_task.action = 'yum' mock_task.action = 'yum'
mock_task.args={'name': '{{item.name}}', 'state': '{{item.state}}'} mock_task.args = {'name': '{{item.name}}', 'state': '{{item.state}}'}
new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) new_items = te._squash_items(items=items, loop_var='item', variables=job_vars)
#self.assertEqual(new_items, [dict(name=['a', 'b'], state='present'), # self.assertEqual(new_items, [dict(name=['a', 'b'], state='present'),
# dict(name='c', state='absent')]) # dict(name='c', state='absent')])
#self.assertEqual(mock_task.args, {'name': '{{item.name}}', 'state': '{{item.state}}'}) # self.assertEqual(mock_task.args, {'name': '{{item.name}}', 'state': '{{item.state}}'})
self.assertEqual(new_items, items) self.assertEqual(new_items, items)
self.assertEqual(mock_task.args, {'name': '{{item.name}}', 'state': '{{item.state}}'}) self.assertEqual(mock_task.args, {'name': '{{item.name}}', 'state': '{{item.state}}'})
def test_task_executor_execute(self): def test_task_executor_execute(self):
fake_loader = DictDataLoader({}) fake_loader = DictDataLoader({})
@ -394,14 +393,14 @@ class TestTaskExecutor(unittest.TestCase):
job_vars = dict(omit="XXXXXXXXXXXXXXXXXXX") job_vars = dict(omit="XXXXXXXXXXXXXXXXXXX")
te = TaskExecutor( te = TaskExecutor(
host = mock_host, host=mock_host,
task = mock_task, task=mock_task,
job_vars = job_vars, job_vars=job_vars,
play_context = mock_play_context, play_context=mock_play_context,
new_stdin = new_stdin, new_stdin=new_stdin,
loader = fake_loader, loader=fake_loader,
shared_loader_obj = shared_loader, shared_loader_obj=shared_loader,
rslt_q = mock_queue, rslt_q=mock_queue,
) )
te._get_connection = MagicMock(return_value=mock_connection) te._get_connection = MagicMock(return_value=mock_connection)
@ -449,14 +448,14 @@ class TestTaskExecutor(unittest.TestCase):
job_vars = dict(omit="XXXXXXXXXXXXXXXXXXX") job_vars = dict(omit="XXXXXXXXXXXXXXXXXXX")
te = TaskExecutor( te = TaskExecutor(
host = mock_host, host=mock_host,
task = mock_task, task=mock_task,
job_vars = job_vars, job_vars=job_vars,
play_context = mock_play_context, play_context=mock_play_context,
new_stdin = new_stdin, new_stdin=new_stdin,
loader = fake_loader, loader=fake_loader,
shared_loader_obj = shared_loader, shared_loader_obj=shared_loader,
rslt_q = mock_queue, rslt_q=mock_queue,
) )
te._connection = MagicMock() te._connection = MagicMock()
@ -485,4 +484,3 @@ class TestTaskExecutor(unittest.TestCase):
mock_templar = MagicMock() mock_templar = MagicMock()
res = te._poll_async_result(result=dict(ansible_job_id=1), templar=mock_templar) res = te._poll_async_result(result=dict(ansible_job_id=1), templar=mock_templar)
self.assertEqual(res, dict(finished=1)) self.assertEqual(res, dict(finished=1))

View file

@ -24,6 +24,7 @@ from ansible.compat.tests.mock import patch, MagicMock
from ansible.executor.task_result import TaskResult from ansible.executor.task_result import TaskResult
class TestTaskResult(unittest.TestCase): class TestTaskResult(unittest.TestCase):
def test_task_result_basic(self): def test_task_result_basic(self):
mock_host = MagicMock() mock_host = MagicMock()

View file

@ -29,6 +29,7 @@ from ansible.vars.manager import VariableManager
from units.mock.loader import DictDataLoader from units.mock.loader import DictDataLoader
class TestInventory(unittest.TestCase): class TestInventory(unittest.TestCase):
patterns = { patterns = {
@ -38,7 +39,7 @@ class TestInventory(unittest.TestCase):
' a,b ,c[1:2] ': ['a', 'b', 'c[1:2]'], ' a,b ,c[1:2] ': ['a', 'b', 'c[1:2]'],
'9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9'], '9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9'],
'9a01:7f8:191:7701::9,9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9'], '9a01:7f8:191:7701::9,9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9'],
'9a01:7f8:191:7701::9,9a01:7f8:191:7701::9,foo': ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9','foo'], '9a01:7f8:191:7701::9,9a01:7f8:191:7701::9,foo': ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9', 'foo'],
'foo[1:2]': ['foo[1:2]'], 'foo[1:2]': ['foo[1:2]'],
'a::b': ['a::b'], 'a::b': ['a::b'],
'a:b': ['a', 'b'], 'a:b': ['a', 'b'],
@ -51,7 +52,7 @@ class TestInventory(unittest.TestCase):
[['a', 'b'], ['a', 'b']], [['a', 'b'], ['a', 'b']],
[['a, b'], ['a', 'b']], [['a, b'], ['a', 'b']],
[['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9,foo'], [['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9,foo'],
['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9','foo']] ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9', 'foo']]
] ]
# pattern_string: [ ('base_pattern', (a,b)), ['x','y','z'] ] # pattern_string: [ ('base_pattern', (a,b)), ['x','y','z'] ]
@ -59,7 +60,7 @@ class TestInventory(unittest.TestCase):
# when applied to string.ascii_letters. # when applied to string.ascii_letters.
subscripts = { subscripts = {
'a': [('a',None), list(string.ascii_letters)], 'a': [('a', None), list(string.ascii_letters)],
'a[0]': [('a', (0, None)), ['a']], 'a[0]': [('a', (0, None)), ['a']],
'a[1]': [('a', (1, None)), ['b']], 'a[1]': [('a', (1, None)), ['b']],
'a[2:3]': [('a', (2, 3)), ['c', 'd']], 'a[2:3]': [('a', (2, 3)), ['c', 'd']],
@ -143,7 +144,7 @@ class InventoryDefaultGroup(unittest.TestCase):
def _get_inventory(self, inventory_content): def _get_inventory(self, inventory_content):
fake_loader = DictDataLoader({ __file__: inventory_content}) fake_loader = DictDataLoader({__file__: inventory_content})
return InventoryManager(loader=fake_loader, sources=[__file__]) return InventoryManager(loader=fake_loader, sources=[__file__])

View file

@ -21,6 +21,7 @@ __metaclass__ = type
from collections import Mapping from collections import Mapping
def make_method(func, args, kwargs): def make_method(func, args, kwargs):
def test_method(self): def test_method(self):

View file

@ -20,8 +20,8 @@
from __future__ import (absolute_import, division) from __future__ import (absolute_import, division)
__metaclass__ = type __metaclass__ = type
import sys
import json import json
import sys
from units.mock.procenv import swap_stdin_and_argv from units.mock.procenv import swap_stdin_and_argv
@ -31,23 +31,21 @@ from ansible.compat.tests.mock import MagicMock
class TestModuleUtilsBasic(unittest.TestCase): class TestModuleUtilsBasic(unittest.TestCase):
def test_module_utils_basic__log_invocation(self): def test_module_utils_basic__log_invocation(self):
with swap_stdin_and_argv(stdin_data=json.dumps( with swap_stdin_and_argv(stdin_data=json.dumps(dict(
dict( ANSIBLE_MODULE_ARGS=dict(foo=False, bar=[1, 2, 3], bam="bam", baz=u'baz')),
ANSIBLE_MODULE_ARGS=dict( )):
foo=False, bar=[1,2,3], bam="bam", baz=u'baz'),
))):
from ansible.module_utils import basic from ansible.module_utils import basic
# test basic log invocation # test basic log invocation
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec=dict( argument_spec=dict(
foo = dict(default=True, type='bool'), foo=dict(default=True, type='bool'),
bar = dict(default=[], type='list'), bar=dict(default=[], type='list'),
bam = dict(default="bam"), bam=dict(default="bam"),
baz = dict(default=u"baz"), baz=dict(default=u"baz"),
password = dict(default=True), password=dict(default=True),
no_log = dict(default="you shouldn't see me", no_log=True), no_log=dict(default="you shouldn't see me", no_log=True),
), ),
) )
@ -73,7 +71,8 @@ class TestModuleUtilsBasic(unittest.TestCase):
self.assertIn(' password=NOT_LOGGING_PASSWORD', message) self.assertIn(' password=NOT_LOGGING_PASSWORD', message)
kwargs = am.log.call_args[1] kwargs = am.log.call_args[1]
self.assertEqual(kwargs, self.assertEqual(
kwargs,
dict(log_args={ dict(log_args={
'foo': 'False', 'foo': 'False',
'bar': '[1, 2, 3]', 'bar': '[1, 2, 3]',

View file

@ -34,7 +34,7 @@ class TestAnsibleModuleWarnDeprecate(unittest.TestCase):
ansible.module_utils.basic._ANSIBLE_ARGS = None ansible.module_utils.basic._ANSIBLE_ARGS = None
am = ansible.module_utils.basic.AnsibleModule( am = ansible.module_utils.basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
am._name = 'unittest' am._name = 'unittest'
@ -51,7 +51,7 @@ class TestAnsibleModuleWarnDeprecate(unittest.TestCase):
ansible.module_utils.basic._ANSIBLE_ARGS = None ansible.module_utils.basic._ANSIBLE_ARGS = None
am = ansible.module_utils.basic.AnsibleModule( am = ansible.module_utils.basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
am._name = 'unittest' am._name = 'unittest'
@ -76,7 +76,7 @@ class TestAnsibleModuleWarnDeprecate(unittest.TestCase):
ansible.module_utils.basic._ANSIBLE_ARGS = None ansible.module_utils.basic._ANSIBLE_ARGS = None
am = ansible.module_utils.basic.AnsibleModule( am = ansible.module_utils.basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
am._name = 'unittest' am._name = 'unittest'

View file

@ -25,13 +25,13 @@ import json
import sys import sys
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from units.mock.procenv import swap_stdin_and_argv, swap_stdout
from ansible.module_utils import basic from ansible.module_utils import basic
from units.mock.procenv import swap_stdin_and_argv, swap_stdout
empty_invocation = {u'module_args': {}} empty_invocation = {u'module_args': {}}
class TestAnsibleModuleExitJson(unittest.TestCase): class TestAnsibleModuleExitJson(unittest.TestCase):
def setUp(self): def setUp(self):
args = json.dumps(dict(ANSIBLE_MODULE_ARGS={})) args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
@ -89,24 +89,28 @@ class TestAnsibleModuleExitJson(unittest.TestCase):
return_val = json.loads(self.fake_stream.getvalue()) return_val = json.loads(self.fake_stream.getvalue())
self.assertEquals(return_val, dict(changed=True, msg='success', invocation=empty_invocation)) self.assertEquals(return_val, dict(changed=True, msg='success', invocation=empty_invocation))
class TestAnsibleModuleExitValuesRemoved(unittest.TestCase): class TestAnsibleModuleExitValuesRemoved(unittest.TestCase):
OMIT = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER' OMIT = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
dataset = ( dataset = (
(dict(username='person', password='$ecret k3y'), (
dict(username='person', password='$ecret k3y'),
dict(one=1, pwd='$ecret k3y', url='https://username:password12345@foo.com/login/', dict(one=1, pwd='$ecret k3y', url='https://username:password12345@foo.com/login/',
not_secret='following the leader', msg='here'), not_secret='following the leader', msg='here'),
dict(one=1, pwd=OMIT, url='https://username:password12345@foo.com/login/', dict(one=1, pwd=OMIT, url='https://username:password12345@foo.com/login/',
not_secret='following the leader', changed=False, msg='here', not_secret='following the leader', changed=False, msg='here',
invocation=dict(module_args=dict(password=OMIT, token=None, username='person'))), invocation=dict(module_args=dict(password=OMIT, token=None, username='person'))),
), ),
(dict(username='person', password='password12345'), (
dict(username='person', password='password12345'),
dict(one=1, pwd='$ecret k3y', url='https://username:password12345@foo.com/login/', dict(one=1, pwd='$ecret k3y', url='https://username:password12345@foo.com/login/',
not_secret='following the leader', msg='here'), not_secret='following the leader', msg='here'),
dict(one=1, pwd='$ecret k3y', url='https://username:********@foo.com/login/', dict(one=1, pwd='$ecret k3y', url='https://username:********@foo.com/login/',
not_secret='following the leader', changed=False, msg='here', not_secret='following the leader', changed=False, msg='here',
invocation=dict(module_args=dict(password=OMIT, token=None, username='person'))), invocation=dict(module_args=dict(password=OMIT, token=None, username='person'))),
), ),
(dict(username='person', password='$ecret k3y'), (
dict(username='person', password='$ecret k3y'),
dict(one=1, pwd='$ecret k3y', url='https://username:$ecret k3y@foo.com/login/', dict(one=1, pwd='$ecret k3y', url='https://username:$ecret k3y@foo.com/login/',
not_secret='following the leader', msg='here'), not_secret='following the leader', msg='here'),
dict(one=1, pwd=OMIT, url='https://username:********@foo.com/login/', dict(one=1, pwd=OMIT, url='https://username:********@foo.com/login/',
@ -125,7 +129,7 @@ class TestAnsibleModuleExitValuesRemoved(unittest.TestCase):
with swap_stdout(): with swap_stdout():
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
module = basic.AnsibleModule( module = basic.AnsibleModule(
argument_spec = dict( argument_spec=dict(
username=dict(), username=dict(),
password=dict(no_log=True), password=dict(no_log=True),
token=dict(no_log=True), token=dict(no_log=True),
@ -147,7 +151,7 @@ class TestAnsibleModuleExitValuesRemoved(unittest.TestCase):
with swap_stdout(): with swap_stdout():
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
module = basic.AnsibleModule( module = basic.AnsibleModule(
argument_spec = dict( argument_spec=dict(
username=dict(), username=dict(),
password=dict(no_log=True), password=dict(no_log=True),
token=dict(no_log=True), token=dict(no_log=True),

View file

@ -25,9 +25,9 @@ import syslog
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock from ansible.compat.tests.mock import patch, MagicMock
from ansible.module_utils.basic import heuristic_log_sanitize from ansible.module_utils.basic import heuristic_log_sanitize
class TestHeuristicLogSanitize(unittest.TestCase): class TestHeuristicLogSanitize(unittest.TestCase):
def setUp(self): def setUp(self):
self.URL_SECRET = 'http://username:pas:word@foo.com/data' self.URL_SECRET = 'http://username:pas:word@foo.com/data'
@ -39,13 +39,16 @@ class TestHeuristicLogSanitize(unittest.TestCase):
def _gen_data(self, records, per_rec, top_level, secret_text): def _gen_data(self, records, per_rec, top_level, secret_text):
hostvars = {'hostvars': {}} hostvars = {'hostvars': {}}
for i in range(1, records, 1): for i in range(1, records, 1):
host_facts = {'host%s' % i: host_facts = {
{'pstack': 'host%s' % i: {
{'running': '875.1', 'pstack': {
'running': '875.1',
'symlinked': '880.0', 'symlinked': '880.0',
'tars': [], 'tars': [],
'versions': ['885.0']}, 'versions': ['885.0']
}} },
}
}
if per_rec: if per_rec:
host_facts['host%s' % i]['secret'] = secret_text host_facts['host%s' % i]['secret'] = secret_text
hostvars['hostvars'].update(host_facts) hostvars['hostvars'].update(host_facts)

View file

@ -51,7 +51,7 @@ class TestAnsibleModuleSysLogSmokeTest(unittest.TestCase):
ansible.module_utils.basic._ANSIBLE_ARGS = None ansible.module_utils.basic._ANSIBLE_ARGS = None
self.am = ansible.module_utils.basic.AnsibleModule( self.am = ansible.module_utils.basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
self.am._name = 'unittest' self.am._name = 'unittest'
@ -89,7 +89,7 @@ class TestAnsibleModuleJournaldSmokeTest(unittest.TestCase):
ansible.module_utils.basic._ANSIBLE_ARGS = None ansible.module_utils.basic._ANSIBLE_ARGS = None
self.am = ansible.module_utils.basic.AnsibleModule( self.am = ansible.module_utils.basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
self.am._name = 'unittest' self.am._name = 'unittest'
@ -138,7 +138,7 @@ class TestAnsibleModuleLogSyslog(unittest.TestCase):
ansible.module_utils.basic._ANSIBLE_ARGS = None ansible.module_utils.basic._ANSIBLE_ARGS = None
self.am = ansible.module_utils.basic.AnsibleModule( self.am = ansible.module_utils.basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
self.am._name = 'unittest' self.am._name = 'unittest'
@ -200,7 +200,7 @@ class TestAnsibleModuleLogJournal(unittest.TestCase):
ansible.module_utils.basic._ANSIBLE_ARGS = None ansible.module_utils.basic._ANSIBLE_ARGS = None
self.am = ansible.module_utils.basic.AnsibleModule( self.am = ansible.module_utils.basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
self.am._name = 'unittest' self.am._name = 'unittest'
@ -270,4 +270,3 @@ class TestAnsibleModuleLogJournal(unittest.TestCase):
# We added this journal field # We added this journal field
self.assertIn('TEST', mock_func.call_args[1]) self.assertIn('TEST', mock_func.call_args[1])
self.assertIn('log unittest', mock_func.call_args[1]['TEST']) self.assertIn('log unittest', mock_func.call_args[1]['TEST'])

View file

@ -42,10 +42,21 @@ class TestReturnValues(unittest.TestCase):
(['1', '2', '3'], frozenset(['1', '2', '3'])), (['1', '2', '3'], frozenset(['1', '2', '3'])),
(('1', '2', '3'), frozenset(['1', '2', '3'])), (('1', '2', '3'), frozenset(['1', '2', '3'])),
({'one': 1, 'two': 'dos'}, frozenset(['1', 'dos'])), ({'one': 1, 'two': 'dos'}, frozenset(['1', 'dos'])),
({'one': 1, 'two': 'dos', (
'three': ['amigos', 'musketeers', None, {
{'ping': 'pong', 'base': ('balls', 'raquets')}]}, 'one': 1,
frozenset(['1', 'dos', 'amigos', 'musketeers', 'pong', 'balls', 'raquets'])), 'two': 'dos',
'three': [
'amigos', 'musketeers', None, {
'ping': 'pong',
'base': (
'balls', 'raquets'
)
}
]
},
frozenset(['1', 'dos', 'amigos', 'musketeers', 'pong', 'balls', 'raquets'])
),
(u'Toshio くらとみ', frozenset(['Toshio くらとみ'])), (u'Toshio くらとみ', frozenset(['Toshio くらとみ'])),
('Toshio くらとみ', frozenset(['Toshio くらとみ'])), ('Toshio くらとみ', frozenset(['Toshio くらとみ'])),
) )
@ -67,13 +78,22 @@ class TestRemoveValues(unittest.TestCase):
(1.0, frozenset(['4321'])), (1.0, frozenset(['4321'])),
(['string', 'strang', 'strung'], frozenset(['nope'])), (['string', 'strang', 'strung'], frozenset(['nope'])),
({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['nope'])), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['nope'])),
({'one': 1, 'two': 'dos', (
'three': ['amigos', 'musketeers', None, {
{'ping': 'pong', 'base': ['balls', 'raquets']}]}, 'one': 1,
frozenset(['nope'])), 'two': 'dos',
'three': [
'amigos', 'musketeers', None, {
'ping': 'pong', 'base': ['balls', 'raquets']
}
]
},
frozenset(['nope'])
),
('Toshio くら', frozenset(['とみ'])), ('Toshio くら', frozenset(['とみ'])),
(u'Toshio くら', frozenset(['とみ'])), (u'Toshio くら', frozenset(['とみ'])),
) )
dataset_remove = ( dataset_remove = (
('string', frozenset(['string']), OMIT), ('string', frozenset(['string']), OMIT),
(1234, frozenset(['1234']), OMIT), (1234, frozenset(['1234']), OMIT),
@ -84,20 +104,40 @@ class TestRemoveValues(unittest.TestCase):
(('string', 'strang', 'strung'), frozenset(['string', 'strung']), [OMIT, 'strang', OMIT]), (('string', 'strang', 'strung'), frozenset(['string', 'strung']), [OMIT, 'strang', OMIT]),
((1234567890, 345678, 987654321), frozenset(['1234567890']), [OMIT, 345678, 987654321]), ((1234567890, 345678, 987654321), frozenset(['1234567890']), [OMIT, 345678, 987654321]),
((1234567890, 345678, 987654321), frozenset(['345678']), [OMIT, OMIT, 987654321]), ((1234567890, 345678, 987654321), frozenset(['345678']), [OMIT, OMIT, 987654321]),
({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key']), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key']), {'one': 1, 'two': 'dos', 'secret': OMIT}),
{'one': 1, 'two': 'dos', 'secret': OMIT}), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key', 'dos', '1']), {'one': OMIT, 'two': OMIT, 'secret': OMIT}),
({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key', 'dos', '1']), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key', 'dos', '1']), {'one': OMIT, 'two': OMIT, 'secret': OMIT}),
{'one': OMIT, 'two': OMIT, 'secret': OMIT}), (
({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key', 'dos', '1']), {
{'one': OMIT, 'two': OMIT, 'secret': OMIT}), 'one': 1,
({'one': 1, 'two': 'dos', 'three': ['amigos', 'musketeers', None, 'two': 'dos',
{'ping': 'pong', 'base': ['balls', 'raquets']}]}, 'three': [
'amigos', 'musketeers', None, {
'ping': 'pong', 'base': [
'balls', 'raquets'
]
}
]
},
frozenset(['balls', 'base', 'pong', 'amigos']), frozenset(['balls', 'base', 'pong', 'amigos']),
{'one': 1, 'two': 'dos', 'three': [OMIT, 'musketeers', {
None, {'ping': OMIT, 'base': [OMIT, 'raquets']}]}), 'one': 1,
('This sentence has an enigma wrapped in a mystery inside of a secret. - mr mystery', 'two': 'dos',
'three': [
OMIT, 'musketeers', None, {
'ping': OMIT,
'base': [
OMIT, 'raquets'
]
}
]
}
),
(
'This sentence has an enigma wrapped in a mystery inside of a secret. - mr mystery',
frozenset(['enigma', 'mystery', 'secret']), frozenset(['enigma', 'mystery', 'secret']),
'This sentence has an ******** wrapped in a ******** inside of a ********. - mr ********'), 'This sentence has an ******** wrapped in a ******** inside of a ********. - mr ********'
),
('Toshio くらとみ', frozenset(['くらとみ']), 'Toshio ********'), ('Toshio くらとみ', frozenset(['くらとみ']), 'Toshio ********'),
(u'Toshio くらとみ', frozenset(['くらとみ']), u'Toshio ********'), (u'Toshio くらとみ', frozenset(['くらとみ']), u'Toshio ********'),
) )
@ -112,5 +152,3 @@ class TestRemoveValues(unittest.TestCase):
def test_unknown_type(self): def test_unknown_type(self):
self.assertRaises(TypeError, remove_values, object(), frozenset()) self.assertRaises(TypeError, remove_values, object(), frozenset())

View file

@ -27,13 +27,13 @@ from io import BytesIO, StringIO
import pytest import pytest
from ansible.module_utils.six import PY3
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import call, MagicMock, Mock, patch, sentinel from ansible.compat.tests.mock import call, MagicMock, Mock, patch, sentinel
from ansible.module_utils.six import PY3
import ansible.module_utils.basic
from units.mock.procenv import swap_stdin_and_argv from units.mock.procenv import swap_stdin_and_argv
import ansible.module_utils.basic
class OpenBytesIO(BytesIO): class OpenBytesIO(BytesIO):
"""BytesIO with dummy close() method """BytesIO with dummy close() method
@ -207,4 +207,3 @@ class TestAnsibleModuleRunCommand(unittest.TestCase):
else: else:
self.assertEqual(stdout.decode('utf-8'), u'Žarn§') self.assertEqual(stdout.decode('utf-8'), u'Žarn§')
self.assertEqual(stderr.decode('utf-8'), u'لرئيسية') self.assertEqual(stderr.decode('utf-8'), u'لرئيسية')

View file

@ -36,12 +36,12 @@ VALID_STRINGS = (
[("True", True)], [("True", True)],
[("False", False)], [("False", False)],
[("{}", {})], [("{}", {})],
) )
# Passing things that aren't strings should just return the object # Passing things that aren't strings should just return the object
NONSTRINGS = ( NONSTRINGS = (
[({'a':1}, {'a':1})], [({'a': 1}, {'a': 1})],
) )
# These strings are not basic types. For security, these should not be # These strings are not basic types. For security, these should not be
# executed. We return the same string and get an exception for some # executed. We return the same string and get an exception for some
@ -50,25 +50,29 @@ INVALID_STRINGS = (
[("a.foo()", "a.foo()", None)], [("a.foo()", "a.foo()", None)],
[("import foo", "import foo", None)], [("import foo", "import foo", None)],
[("__import__('foo')", "__import__('foo')", ValueError)], [("__import__('foo')", "__import__('foo')", ValueError)],
) )
def _check_simple_types(self, code, expected): def _check_simple_types(self, code, expected):
# test some basic usage for various types # test some basic usage for various types
self.assertEqual(self.am.safe_eval(code), expected) self.assertEqual(self.am.safe_eval(code), expected)
def _check_simple_types_with_exceptions(self, code, expected): def _check_simple_types_with_exceptions(self, code, expected):
# Test simple types with exceptions requested # Test simple types with exceptions requested
self.assertEqual(self.am.safe_eval(code, include_exceptions=True), (expected, None)) self.assertEqual(self.am.safe_eval(code, include_exceptions=True), (expected, None))
def _check_invalid_strings(self, code, expected): def _check_invalid_strings(self, code, expected):
self.assertEqual(self.am.safe_eval(code), expected) self.assertEqual(self.am.safe_eval(code), expected)
def _check_invalid_strings_with_exceptions(self, code, expected, exception): def _check_invalid_strings_with_exceptions(self, code, expected, exception):
res = self.am.safe_eval("a=1", include_exceptions=True) res = self.am.safe_eval("a=1", include_exceptions=True)
self.assertEqual(res[0], "a=1") self.assertEqual(res[0], "a=1")
self.assertEqual(type(res[1]), SyntaxError) self.assertEqual(type(res[1]), SyntaxError)
@add_method(_check_simple_types, *VALID_STRINGS) @add_method(_check_simple_types, *VALID_STRINGS)
@add_method(_check_simple_types, *NONSTRINGS) @add_method(_check_simple_types, *NONSTRINGS)
@add_method(_check_simple_types_with_exceptions, *VALID_STRINGS) @add_method(_check_simple_types_with_exceptions, *VALID_STRINGS)

View file

@ -35,6 +35,7 @@ from ansible.module_utils import known_hosts
from units.mock.procenv import ModuleTestCase from units.mock.procenv import ModuleTestCase
from units.mock.generator import add_method from units.mock.generator import add_method
class TestSetModeIfDifferentBase(ModuleTestCase): class TestSetModeIfDifferentBase(ModuleTestCase):
def setUp(self): def setUp(self):
@ -49,7 +50,7 @@ class TestSetModeIfDifferentBase(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
self.am = basic.AnsibleModule( self.am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
def tearDown(self): def tearDown(self):
@ -60,8 +61,10 @@ class TestSetModeIfDifferentBase(ModuleTestCase):
def _check_no_mode_given_returns_previous_changes(self, previous_changes=True): def _check_no_mode_given_returns_previous_changes(self, previous_changes=True):
with patch('os.lstat', side_effect=[self.mock_stat1]): with patch('os.lstat', side_effect=[self.mock_stat1]):
self.assertEqual(self.am.set_mode_if_different('/path/to/file', None, previous_changes), previous_changes) self.assertEqual(self.am.set_mode_if_different('/path/to/file', None, previous_changes), previous_changes)
def _check_mode_changed_to_0660(self, mode): def _check_mode_changed_to_0660(self, mode):
# Note: This is for checking that all the different ways of specifying # Note: This is for checking that all the different ways of specifying
# 0660 mode work. It cannot be used to check that setting a mode that is # 0660 mode work. It cannot be used to check that setting a mode that is
@ -71,6 +74,7 @@ def _check_mode_changed_to_0660(self, mode):
self.assertEqual(self.am.set_mode_if_different('/path/to/file', mode, False), True) self.assertEqual(self.am.set_mode_if_different('/path/to/file', mode, False), True)
m_lchmod.assert_called_with(b'/path/to/file', 0o660) m_lchmod.assert_called_with(b'/path/to/file', 0o660)
def _check_mode_unchanged_when_already_0660(self, mode): def _check_mode_unchanged_when_already_0660(self, mode):
# Note: This is for checking that all the different ways of specifying # Note: This is for checking that all the different ways of specifying
# 0660 mode work. It cannot be used to check that setting a mode that is # 0660 mode work. It cannot be used to check that setting a mode that is
@ -83,18 +87,12 @@ SYNONYMS_0660 = (
[[0o660]], [[0o660]],
[['0o660']], [['0o660']],
[['660']], [['660']],
) )
@add_method(_check_no_mode_given_returns_previous_changes,
[dict(previous_changes=True)], @add_method(_check_no_mode_given_returns_previous_changes, [dict(previous_changes=True)], [dict(previous_changes=False)], )
[dict(previous_changes=False)], @add_method(_check_mode_changed_to_0660, *SYNONYMS_0660)
) @add_method(_check_mode_unchanged_when_already_0660, *SYNONYMS_0660)
@add_method(_check_mode_changed_to_0660,
*SYNONYMS_0660
)
@add_method(_check_mode_unchanged_when_already_0660,
*SYNONYMS_0660
)
class TestSetModeIfDifferent(TestSetModeIfDifferentBase): class TestSetModeIfDifferent(TestSetModeIfDifferentBase):
def test_module_utils_basic_ansible_module_set_mode_if_different(self): def test_module_utils_basic_ansible_module_set_mode_if_different(self):
with patch('os.lstat') as m: with patch('os.lstat') as m:
@ -105,6 +103,7 @@ class TestSetModeIfDifferent(TestSetModeIfDifferentBase):
self.am.set_mode_if_different('/path/to/file', 'o+w,g+w,a-r', False) self.am.set_mode_if_different('/path/to/file', 'o+w,g+w,a-r', False)
original_hasattr = hasattr original_hasattr = hasattr
def _hasattr(obj, name): def _hasattr(obj, name):
if obj == os and name == 'lchmod': if obj == os and name == 'lchmod':
return False return False
@ -131,16 +130,10 @@ def _check_knows_to_change_to_0660_in_check_mode(self, mode):
with patch('os.lstat', side_effect=[self.mock_stat1, self.mock_stat2, self.mock_stat2]) as m_lstat: with patch('os.lstat', side_effect=[self.mock_stat1, self.mock_stat2, self.mock_stat2]) as m_lstat:
self.assertEqual(self.am.set_mode_if_different('/path/to/file', mode, False), True) self.assertEqual(self.am.set_mode_if_different('/path/to/file', mode, False), True)
@add_method(_check_no_mode_given_returns_previous_changes,
[dict(previous_changes=True)], @add_method(_check_no_mode_given_returns_previous_changes, [dict(previous_changes=True)], [dict(previous_changes=False)],)
[dict(previous_changes=False)], @add_method(_check_knows_to_change_to_0660_in_check_mode, *SYNONYMS_0660)
) @add_method(_check_mode_unchanged_when_already_0660, *SYNONYMS_0660)
@add_method(_check_knows_to_change_to_0660_in_check_mode,
*SYNONYMS_0660
)
@add_method(_check_mode_unchanged_when_already_0660,
*SYNONYMS_0660
)
class TestSetModeIfDifferentWithCheckMode(TestSetModeIfDifferentBase): class TestSetModeIfDifferentWithCheckMode(TestSetModeIfDifferentBase):
def setUp(self): def setUp(self):
super(TestSetModeIfDifferentWithCheckMode, self).setUp() super(TestSetModeIfDifferentWithCheckMode, self).setUp()

View file

@ -69,7 +69,7 @@ class RetryTestCase(unittest.TestCase):
self.counter += 1 self.counter += 1
raise botocore.exceptions.ClientError(err_msg, 'toooo fast!!') raise botocore.exceptions.ClientError(err_msg, 'toooo fast!!')
#with self.assertRaises(botocore.exceptions.ClientError): # with self.assertRaises(botocore.exceptions.ClientError):
try: try:
fail() fail()
except Exception as e: except Exception as e:
@ -85,7 +85,7 @@ class RetryTestCase(unittest.TestCase):
self.counter += 1 self.counter += 1
raise botocore.exceptions.ClientError(err_msg, 'unexpected error') raise botocore.exceptions.ClientError(err_msg, 'unexpected error')
#with self.assertRaises(botocore.exceptions.ClientError): # with self.assertRaises(botocore.exceptions.ClientError):
try: try:
raise_unexpected_error() raise_unexpected_error()
except Exception as e: except Exception as e:

View file

@ -22,11 +22,12 @@ __metaclass__ = type
import json import json
from ansible.compat.tests import unittest
from nose.tools import eq_, raises from nose.tools import eq_, raises
from ansible.compat.tests import unittest
from ansible.module_utils.json_utils import _filter_non_json_lines from ansible.module_utils.json_utils import _filter_non_json_lines
class TestAnsibleModuleExitJson(unittest.TestCase): class TestAnsibleModuleExitJson(unittest.TestCase):
single_line_json_dict = u"""{"key": "value", "olá": "mundo"}""" single_line_json_dict = u"""{"key": "value", "olá": "mundo"}"""
single_line_json_array = u"""["a","b","c"]""" single_line_json_array = u"""["a","b","c"]"""
@ -38,10 +39,12 @@ class TestAnsibleModuleExitJson(unittest.TestCase):
"b", "b",
"c"]""" "c"]"""
all_inputs = [single_line_json_dict, all_inputs = [
single_line_json_dict,
single_line_json_array, single_line_json_array,
multi_line_json_dict, multi_line_json_dict,
multi_line_json_array] multi_line_json_array
]
junk = [u"single line of junk", u"line 1/2 of junk\nline 2/2 of junk"] junk = [u"single line of junk", u"line 1/2 of junk\nline 2/2 of junk"]
@ -82,7 +85,8 @@ class TestAnsibleModuleExitJson(unittest.TestCase):
def test_unparsable_filter_non_json_lines(self): def test_unparsable_filter_non_json_lines(self):
for i in self.unparsable_cases: for i in self.unparsable_cases:
self.assertRaises(ValueError, self.assertRaises(
ValueError,
lambda data: _filter_non_json_lines(data), lambda data: _filter_non_json_lines(data),
data=i data=i
) )

View file

@ -35,6 +35,7 @@ from ansible.module_utils.six.moves import builtins
realimport = builtins.__import__ realimport = builtins.__import__
class TestModuleUtilsBasic(ModuleTestCase): class TestModuleUtilsBasic(ModuleTestCase):
def clear_modules(self, mods): def clear_modules(self, mods):
@ -95,8 +96,8 @@ class TestModuleUtilsBasic(ModuleTestCase):
mod = builtins.__import__('ansible.module_utils.basic') mod = builtins.__import__('ansible.module_utils.basic')
# FIXME: doesn't work yet # FIXME: doesn't work yet
#@patch.object(builtins, 'bytes') # @patch.object(builtins, 'bytes')
#def test_module_utils_basic_bytes(self, mock_bytes): # def test_module_utils_basic_bytes(self, mock_bytes):
# mock_bytes.side_effect = NameError() # mock_bytes.side_effect = NameError()
# from ansible.module_utils import basic # from ansible.module_utils import basic
@ -118,12 +119,12 @@ class TestModuleUtilsBasic(ModuleTestCase):
self.assertEqual(mod.module_utils.basic.literal_eval("'1'"), "1") self.assertEqual(mod.module_utils.basic.literal_eval("'1'"), "1")
self.assertEqual(mod.module_utils.basic.literal_eval("1"), 1) self.assertEqual(mod.module_utils.basic.literal_eval("1"), 1)
self.assertEqual(mod.module_utils.basic.literal_eval("-1"), -1) self.assertEqual(mod.module_utils.basic.literal_eval("-1"), -1)
self.assertEqual(mod.module_utils.basic.literal_eval("(1,2,3)"), (1,2,3)) self.assertEqual(mod.module_utils.basic.literal_eval("(1,2,3)"), (1, 2, 3))
self.assertEqual(mod.module_utils.basic.literal_eval("[1]"), [1]) self.assertEqual(mod.module_utils.basic.literal_eval("[1]"), [1])
self.assertEqual(mod.module_utils.basic.literal_eval("True"), True) self.assertEqual(mod.module_utils.basic.literal_eval("True"), True)
self.assertEqual(mod.module_utils.basic.literal_eval("False"), False) self.assertEqual(mod.module_utils.basic.literal_eval("False"), False)
self.assertEqual(mod.module_utils.basic.literal_eval("None"), None) self.assertEqual(mod.module_utils.basic.literal_eval("None"), None)
#self.assertEqual(mod.module_utils.basic.literal_eval('{"a": 1}'), dict(a=1)) # self.assertEqual(mod.module_utils.basic.literal_eval('{"a": 1}'), dict(a=1))
self.assertRaises(ValueError, mod.module_utils.basic.literal_eval, "asdfasdfasdf") self.assertRaises(ValueError, mod.module_utils.basic.literal_eval, "asdfasdfasdf")
@patch.object(builtins, '__import__') @patch.object(builtins, '__import__')
@ -162,13 +163,13 @@ class TestModuleUtilsBasic(ModuleTestCase):
self.assertEqual(get_distribution(), "Foo") self.assertEqual(get_distribution(), "Foo")
with patch('os.path.isfile', return_value=True): with patch('os.path.isfile', return_value=True):
with patch('platform.linux_distribution', side_effect=[("AmazonFooBar",)]): with patch('platform.linux_distribution', side_effect=[("AmazonFooBar", )]):
self.assertEqual(get_distribution(), "Amazonfoobar") self.assertEqual(get_distribution(), "Amazonfoobar")
with patch('platform.linux_distribution', side_effect=(("",), ("AmazonFooBam",))): with patch('platform.linux_distribution', side_effect=(("", ), ("AmazonFooBam",))):
self.assertEqual(get_distribution(), "Amazon") self.assertEqual(get_distribution(), "Amazon")
with patch('platform.linux_distribution', side_effect=[("",),("",)]): with patch('platform.linux_distribution', side_effect=[("", ), ("", )]):
self.assertEqual(get_distribution(), "OtherLinux") self.assertEqual(get_distribution(), "OtherLinux")
def _dist(distname='', version='', id='', supported_dists=(), full_distribution_name=1): def _dist(distname='', version='', id='', supported_dists=(), full_distribution_name=1):
@ -241,11 +242,11 @@ class TestModuleUtilsBasic(ModuleTestCase):
from ansible.module_utils.basic import json_dict_unicode_to_bytes, json_dict_bytes_to_unicode from ansible.module_utils.basic import json_dict_unicode_to_bytes, json_dict_bytes_to_unicode
test_data = dict( test_data = dict(
item1 = u"Fóo", item1=u"Fóo",
item2 = [u"Bár", u"Bam"], item2=[u"Bár", u"Bam"],
item3 = dict(sub1=u"Súb"), item3=dict(sub1=u"Súb"),
item4 = (u"föo", u"bär", u"©"), item4=(u"föo", u"bär", u"©"),
item5 = 42, item5=42,
) )
res = json_dict_unicode_to_bytes(test_data) res = json_dict_unicode_to_bytes(test_data)
res2 = json_dict_bytes_to_unicode(res) res2 = json_dict_bytes_to_unicode(res)
@ -265,10 +266,10 @@ class TestModuleUtilsBasic(ModuleTestCase):
) )
arg_spec = dict( arg_spec = dict(
foo = dict(required=True), foo=dict(required=True),
bar = dict(), bar=dict(),
bam = dict(), bam=dict(),
baz = dict(), baz=dict(),
) )
mut_ex = (('bar', 'bam'),) mut_ex = (('bar', 'bam'),)
req_to = (('bam', 'baz'),) req_to = (('bam', 'baz'),)
@ -279,9 +280,9 @@ class TestModuleUtilsBasic(ModuleTestCase):
with swap_stdin_and_argv(stdin_data=args): with swap_stdin_and_argv(stdin_data=args):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = arg_spec, argument_spec=arg_spec,
mutually_exclusive = mut_ex, mutually_exclusive=mut_ex,
required_together = req_to, required_together=req_to,
no_log=True, no_log=True,
check_invalid_arguments=False, check_invalid_arguments=False,
add_file_common_args=True, add_file_common_args=True,
@ -298,9 +299,9 @@ class TestModuleUtilsBasic(ModuleTestCase):
self.assertRaises( self.assertRaises(
SystemExit, SystemExit,
basic.AnsibleModule, basic.AnsibleModule,
argument_spec = arg_spec, argument_spec=arg_spec,
mutually_exclusive = mut_ex, mutually_exclusive=mut_ex,
required_together = req_to, required_together=req_to,
no_log=True, no_log=True,
check_invalid_arguments=False, check_invalid_arguments=False,
add_file_common_args=True, add_file_common_args=True,
@ -308,16 +309,16 @@ class TestModuleUtilsBasic(ModuleTestCase):
) )
# fail because of mutually exclusive parameters # fail because of mutually exclusive parameters
args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"foo":"hello", "bar": "bad", "bam": "bad"})) args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"foo": "hello", "bar": "bad", "bam": "bad"}))
with swap_stdin_and_argv(stdin_data=args): with swap_stdin_and_argv(stdin_data=args):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
self.assertRaises( self.assertRaises(
SystemExit, SystemExit,
basic.AnsibleModule, basic.AnsibleModule,
argument_spec = arg_spec, argument_spec=arg_spec,
mutually_exclusive = mut_ex, mutually_exclusive=mut_ex,
required_together = req_to, required_together=req_to,
no_log=True, no_log=True,
check_invalid_arguments=False, check_invalid_arguments=False,
add_file_common_args=True, add_file_common_args=True,
@ -332,9 +333,9 @@ class TestModuleUtilsBasic(ModuleTestCase):
self.assertRaises( self.assertRaises(
SystemExit, SystemExit,
basic.AnsibleModule, basic.AnsibleModule,
argument_spec = arg_spec, argument_spec=arg_spec,
mutually_exclusive = mut_ex, mutually_exclusive=mut_ex,
required_together = req_to, required_together=req_to,
no_log=True, no_log=True,
check_invalid_arguments=False, check_invalid_arguments=False,
add_file_common_args=True, add_file_common_args=True,
@ -345,11 +346,11 @@ class TestModuleUtilsBasic(ModuleTestCase):
from ansible.module_utils import basic from ansible.module_utils import basic
arg_spec = dict( arg_spec = dict(
foo = dict(type='float'), foo=dict(type='float'),
foo2 = dict(type='float'), foo2=dict(type='float'),
foo3 = dict(type='float'), foo3=dict(type='float'),
bar = dict(type='int'), bar=dict(type='int'),
bar2 = dict(type='int'), bar2=dict(type='int'),
) )
# should test ok # should test ok
@ -364,7 +365,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
with swap_stdin_and_argv(stdin_data=args): with swap_stdin_and_argv(stdin_data=args):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = arg_spec, argument_spec=arg_spec,
no_log=True, no_log=True,
check_invalid_arguments=False, check_invalid_arguments=False,
add_file_common_args=True, add_file_common_args=True,
@ -379,7 +380,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
self.assertRaises( self.assertRaises(
SystemExit, SystemExit,
basic.AnsibleModule, basic.AnsibleModule,
argument_spec = arg_spec, argument_spec=arg_spec,
no_log=True, no_log=True,
check_invalid_arguments=False, check_invalid_arguments=False,
add_file_common_args=True, add_file_common_args=True,
@ -391,7 +392,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
am.selinux_mls_enabled = MagicMock() am.selinux_mls_enabled = MagicMock()
@ -404,25 +405,25 @@ class TestModuleUtilsBasic(ModuleTestCase):
self.assertEqual(res, dict()) self.assertEqual(res, dict())
base_params = dict( base_params = dict(
path = '/path/to/file', path='/path/to/file',
mode = 0o600, mode=0o600,
owner = 'root', owner='root',
group = 'root', group='root',
seuser = '_default', seuser='_default',
serole = '_default', serole='_default',
setype = '_default', setype='_default',
selevel = '_default', selevel='_default',
) )
extended_params = base_params.copy() extended_params = base_params.copy()
extended_params.update(dict( extended_params.update(dict(
follow = True, follow=True,
foo = 'bar', foo='bar',
)) ))
final_params = base_params.copy() final_params = base_params.copy()
final_params.update(dict( final_params.update(dict(
path = '/path/to/real_file', path='/path/to/real_file',
secontext=['unconfined_u', 'object_r', 'default_t', 's0'], secontext=['unconfined_u', 'object_r', 'default_t', 's0'],
attributes=None, attributes=None,
)) ))
@ -441,7 +442,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
basic.HAVE_SELINUX = False basic.HAVE_SELINUX = False
@ -461,7 +462,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
am.selinux_mls_enabled = MagicMock() am.selinux_mls_enabled = MagicMock()
@ -475,7 +476,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
# we first test the cases where the python selinux lib is # we first test the cases where the python selinux lib is
@ -486,7 +487,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
am.get_bin_path = MagicMock() am.get_bin_path = MagicMock()
am.get_bin_path.return_value = '/path/to/selinuxenabled' am.get_bin_path.return_value = '/path/to/selinuxenabled'
am.run_command = MagicMock() am.run_command = MagicMock()
am.run_command.return_value=(0, '', '') am.run_command.return_value = (0, '', '')
self.assertRaises(SystemExit, am.selinux_enabled) self.assertRaises(SystemExit, am.selinux_enabled)
am.get_bin_path.return_value = None am.get_bin_path.return_value = None
self.assertEqual(am.selinux_enabled(), False) self.assertEqual(am.selinux_enabled(), False)
@ -507,7 +508,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
am.selinux_initial_context = MagicMock(return_value=[None, None, None, None]) am.selinux_initial_context = MagicMock(return_value=[None, None, None, None])
@ -543,7 +544,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
am.selinux_initial_context = MagicMock(return_value=[None, None, None, None]) am.selinux_initial_context = MagicMock(return_value=[None, None, None, None])
@ -588,7 +589,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
with swap_stdin_and_argv(stdin_data=args): with swap_stdin_and_argv(stdin_data=args):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
def _mock_find_mount_point(path): def _mock_find_mount_point(path):
@ -628,7 +629,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
mock_stat = MagicMock() mock_stat = MagicMock()
@ -643,7 +644,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
def _mock_ismount(path): def _mock_ismount(path):
@ -669,7 +670,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
basic.HAVE_SELINUX = False basic.HAVE_SELINUX = False
@ -714,7 +715,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
self.assertEqual(am.set_owner_if_different('/path/to/file', None, True), True) self.assertEqual(am.set_owner_if_different('/path/to/file', None, True), True)
@ -753,7 +754,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
self.assertEqual(am.set_group_if_different('/path/to/file', None, True), True) self.assertEqual(am.set_group_if_different('/path/to/file', None, True), True)
@ -824,7 +825,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
environ = dict() environ = dict()
@ -885,7 +886,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
stat1.st_mode = 0o0644 stat1.st_mode = 0o0644
stat1.st_uid = 0 stat1.st_uid = 0
stat1.st_gid = 0 stat1.st_gid = 0
_os_stat.side_effect = [stat1,] _os_stat.side_effect = [stat1, ]
am.selinux_enabled.return_value = False am.selinux_enabled.return_value = False
_os_chmod.reset_mock() _os_chmod.reset_mock()
_os_chown.reset_mock() _os_chown.reset_mock()
@ -904,7 +905,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
stat1.st_mode = 0o0644 stat1.st_mode = 0o0644
stat1.st_uid = 0 stat1.st_uid = 0
stat1.st_gid = 0 stat1.st_gid = 0
_os_stat.side_effect = [stat1,] _os_stat.side_effect = [stat1, ]
mock_context = MagicMock() mock_context = MagicMock()
am.selinux_context.return_value = mock_context am.selinux_context.return_value = mock_context
am.selinux_enabled.return_value = True am.selinux_enabled.return_value = True
@ -1000,7 +1001,7 @@ class TestModuleUtilsBasic(ModuleTestCase):
basic._ANSIBLE_ARGS = None basic._ANSIBLE_ARGS = None
am = basic.AnsibleModule( am = basic.AnsibleModule(
argument_spec = dict(), argument_spec=dict(),
) )
mock_stat = MagicMock() mock_stat = MagicMock()

View file

@ -44,10 +44,12 @@ TESTSETS = [
], ],
"input": { "input": {
"/etc/redhat-release": "CentOS Linux release 7.2.1511 (Core) \n", "/etc/redhat-release": "CentOS Linux release 7.2.1511 (Core) \n",
"/etc/os-release": ("NAME=\"CentOS Linux\"\nVERSION=\"7 (Core)\"\nID=\"centos\"\nID_LIKE=\"rhel fedora\"\nVERSION_ID=\"7\"\n" "/etc/os-release": (
"NAME=\"CentOS Linux\"\nVERSION=\"7 (Core)\"\nID=\"centos\"\nID_LIKE=\"rhel fedora\"\nVERSION_ID=\"7\"\n"
"PRETTY_NAME=\"CentOS Linux 7 (Core)\"\nANSI_COLOR=\"0;31\"\nCPE_NAME=\"cpe:/o:centos:centos:7\"\n" "PRETTY_NAME=\"CentOS Linux 7 (Core)\"\nANSI_COLOR=\"0;31\"\nCPE_NAME=\"cpe:/o:centos:centos:7\"\n"
"HOME_URL=\"https://www.centos.org/\"\nBUG_REPORT_URL=\"https://bugs.centos.org/\"\n\nCENTOS_MANTISBT_PROJECT=\"CentOS-7\"\n" "HOME_URL=\"https://www.centos.org/\"\nBUG_REPORT_URL=\"https://bugs.centos.org/\"\n\nCENTOS_MANTISBT_PROJECT=\"CentOS-7\"\n"
"CENTOS_MANTISBT_PROJECT_VERSION=\"7\"\nREDHAT_SUPPORT_PRODUCT=\"centos\"\nREDHAT_SUPPORT_PRODUCT_VERSION=\"7\"\n\n"), "CENTOS_MANTISBT_PROJECT_VERSION=\"7\"\nREDHAT_SUPPORT_PRODUCT=\"centos\"\nREDHAT_SUPPORT_PRODUCT_VERSION=\"7\"\n\n"
),
"/etc/system-release": "CentOS Linux release 7.2.1511 (Core) \n" "/etc/system-release": "CentOS Linux release 7.2.1511 (Core) \n"
}, },
"name": "CentOS 7.2.1511", "name": "CentOS 7.2.1511",
@ -56,7 +58,7 @@ TESTSETS = [
"distribution": "CentOS", "distribution": "CentOS",
"distribution_major_version": "7", "distribution_major_version": "7",
"os_family": "RedHat", "os_family": "RedHat",
"distribution_version": "7.2.1511" "distribution_version": "7.2.1511",
} }
}, },
{ {
@ -68,8 +70,10 @@ TESTSETS = [
], ],
"input": { "input": {
"/etc/redhat-release": "CentOS release 6.7 (Final)\n", "/etc/redhat-release": "CentOS release 6.7 (Final)\n",
"/etc/lsb-release": ("LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:" "/etc/lsb-release": (
"printing-4.0-amd64:printing-4.0-noarch\n"), "LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:"
"printing-4.0-amd64:printing-4.0-noarch\n"
),
"/etc/system-release": "CentOS release 6.7 (Final)\n" "/etc/system-release": "CentOS release 6.7 (Final)\n"
}, },
"result": { "result": {
@ -89,12 +93,14 @@ TESTSETS = [
], ],
"input": { "input": {
"/etc/redhat-release": "Red Hat Enterprise Linux Server release 7.2 (Maipo)\n", "/etc/redhat-release": "Red Hat Enterprise Linux Server release 7.2 (Maipo)\n",
"/etc/os-release": ("NAME=\"Red Hat Enterprise Linux Server\"\nVERSION=\"7.2 (Maipo)\"\nID=\"rhel\"\nID_LIKE=\"fedora\"\nVERSION_ID=\"7.2\"\n" "/etc/os-release": (
"NAME=\"Red Hat Enterprise Linux Server\"\nVERSION=\"7.2 (Maipo)\"\nID=\"rhel\"\nID_LIKE=\"fedora\"\nVERSION_ID=\"7.2\"\n"
"PRETTY_NAME=\"Red Hat Enterprise Linux Server 7.2 (Maipo)\"\nANSI_COLOR=\"0;31\"\n" "PRETTY_NAME=\"Red Hat Enterprise Linux Server 7.2 (Maipo)\"\nANSI_COLOR=\"0;31\"\n"
"CPE_NAME=\"cpe:/o:redhat:enterprise_linux:7.2:GA:server\"\nHOME_URL=\"https://www.redhat.com/\"\n" "CPE_NAME=\"cpe:/o:redhat:enterprise_linux:7.2:GA:server\"\nHOME_URL=\"https://www.redhat.com/\"\n"
"BUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\n\nREDHAT_BUGZILLA_PRODUCT=\"Red Hat Enterprise Linux 7\"\n" "BUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\n\nREDHAT_BUGZILLA_PRODUCT=\"Red Hat Enterprise Linux 7\"\n"
"REDHAT_BUGZILLA_PRODUCT_VERSION=7.2\nREDHAT_SUPPORT_PRODUCT=\"Red Hat Enterprise Linux\"\n" "REDHAT_BUGZILLA_PRODUCT_VERSION=7.2\nREDHAT_SUPPORT_PRODUCT=\"Red Hat Enterprise Linux\"\n"
"REDHAT_SUPPORT_PRODUCT_VERSION=\"7.2\"\n"), "REDHAT_SUPPORT_PRODUCT_VERSION=\"7.2\"\n"
),
"/etc/system-release": "Red Hat Enterprise Linux Server release 7.2 (Maipo)\n" "/etc/system-release": "Red Hat Enterprise Linux Server release 7.2 (Maipo)\n"
}, },
"result": { "result": {
@ -114,8 +120,10 @@ TESTSETS = [
], ],
"input": { "input": {
"/etc/redhat-release": "Red Hat Enterprise Linux Server release 6.7 (Santiago)\n", "/etc/redhat-release": "Red Hat Enterprise Linux Server release 6.7 (Santiago)\n",
"/etc/lsb-release": ("LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:" "/etc/lsb-release": (
"printing-4.0-amd64:printing-4.0-noarch\n"), "LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:"
"printing-4.0-amd64:printing-4.0-noarch\n"
),
"/etc/system-release": "Red Hat Enterprise Linux Server release 6.7 (Santiago)\n" "/etc/system-release": "Red Hat Enterprise Linux Server release 6.7 (Santiago)\n"
}, },
"result": { "result": {
@ -135,7 +143,8 @@ TESTSETS = [
], ],
"input": { "input": {
"/etc/redhat-release": "Virtuozzo Linux release 7.3\n", "/etc/redhat-release": "Virtuozzo Linux release 7.3\n",
"/etc/os-release": ("NAME=\"Virtuozzo\"\n" "/etc/os-release": (
"NAME=\"Virtuozzo\"\n"
"VERSION=\"7.0.3\"\n" "VERSION=\"7.0.3\"\n"
"ID=\"virtuozzo\"\n" "ID=\"virtuozzo\"\n"
"ID_LIKE=\"rhel fedora\"\n" "ID_LIKE=\"rhel fedora\"\n"
@ -144,7 +153,8 @@ TESTSETS = [
"ANSI_COLOR=\"0;31\"\n" "ANSI_COLOR=\"0;31\"\n"
"CPE_NAME=\"cpe:/o:virtuozzoproject:vz:7\"\n" "CPE_NAME=\"cpe:/o:virtuozzoproject:vz:7\"\n"
"HOME_URL=\"http://www.virtuozzo.com\"\n" "HOME_URL=\"http://www.virtuozzo.com\"\n"
"BUG_REPORT_URL=\"https://bugs.openvz.org/\"\n"), "BUG_REPORT_URL=\"https://bugs.openvz.org/\"\n"
),
"/etc/system-release": "Virtuozzo release 7.0.3 (640)\n" "/etc/system-release": "Virtuozzo release 7.0.3 (640)\n"
}, },
"result": { "result": {
@ -156,10 +166,9 @@ TESTSETS = [
} }
}, },
{ {
"name" : "openSUSE Leap 42.1", "name": "openSUSE Leap 42.1",
"input": { "input": {
"/etc/os-release": "/etc/os-release": """
"""
NAME="openSUSE Leap" NAME="openSUSE Leap"
VERSION="42.1" VERSION="42.1"
VERSION_ID="42.1" VERSION_ID="42.1"
@ -170,16 +179,16 @@ CPE_NAME="cpe:/o:opensuse:opensuse:42.1"
BUG_REPORT_URL="https://bugs.opensuse.org" BUG_REPORT_URL="https://bugs.opensuse.org"
HOME_URL="https://opensuse.org/" HOME_URL="https://opensuse.org/"
ID_LIKE="suse" ID_LIKE="suse"
""", """,
"/etc/SuSE-release":""" "/etc/SuSE-release": """
openSUSE 42.1 (x86_64) openSUSE 42.1 (x86_64)
VERSION = 42.1 VERSION = 42.1
CODENAME = Malachite CODENAME = Malachite
# /etc/SuSE-release is deprecated and will be removed in the future, use /etc/os-release instead # /etc/SuSE-release is deprecated and will be removed in the future, use /etc/os-release instead
""" """
}, },
"platform.dist": ['SuSE', '42.1', 'x86_64'], "platform.dist": ['SuSE', '42.1', 'x86_64'],
"result":{ "result": {
"distribution": "openSUSE Leap", "distribution": "openSUSE Leap",
"distribution_major_version": "42", "distribution_major_version": "42",
"distribution_release": "1", "distribution_release": "1",
@ -189,7 +198,8 @@ CODENAME = Malachite
}, },
{ {
'name': 'openSUSE 13.2', 'name': 'openSUSE 13.2',
'input': {'/etc/SuSE-release': """openSUSE 13.2 (x86_64) 'input': {
'/etc/SuSE-release': """openSUSE 13.2 (x86_64)
VERSION = 13.2 VERSION = 13.2
CODENAME = Harlequin CODENAME = Harlequin
# /etc/SuSE-release is deprecated and will be removed in the future, use /etc/os-release instead # /etc/SuSE-release is deprecated and will be removed in the future, use /etc/os-release instead
@ -204,13 +214,16 @@ CPE_NAME="cpe:/o:opensuse:opensuse:13.2"
BUG_REPORT_URL="https://bugs.opensuse.org" BUG_REPORT_URL="https://bugs.opensuse.org"
HOME_URL="https://opensuse.org/" HOME_URL="https://opensuse.org/"
ID_LIKE="suse" ID_LIKE="suse"
"""}, """
},
'platform.dist': ('SuSE', '13.2', 'x86_64'), 'platform.dist': ('SuSE', '13.2', 'x86_64'),
'result': {'distribution': u'openSUSE', 'result': {
'distribution': u'openSUSE',
'distribution_major_version': u'13', 'distribution_major_version': u'13',
'distribution_release': u'2', 'distribution_release': u'2',
'os_family': u'Suse', 'os_family': u'Suse',
'distribution_version': u'13.2'} 'distribution_version': u'13.2'
}
}, },
{ {
"platform.dist": [ "platform.dist": [
@ -219,9 +232,11 @@ ID_LIKE="suse"
"" ""
], ],
"input": { "input": {
"/etc/os-release": ("NAME=\"openSUSE Tumbleweed\"\n# VERSION=\"20160917\"\nID=opensuse\nID_LIKE=\"suse\"\nVERSION_ID=\"20160917\"\n" "/etc/os-release": (
"NAME=\"openSUSE Tumbleweed\"\n# VERSION=\"20160917\"\nID=opensuse\nID_LIKE=\"suse\"\nVERSION_ID=\"20160917\"\n"
"PRETTY_NAME=\"openSUSE Tumbleweed\"\nANSI_COLOR=\"0;32\"\nCPE_NAME=\"cpe:/o:opensuse:tumbleweed:20160917\"\n" "PRETTY_NAME=\"openSUSE Tumbleweed\"\nANSI_COLOR=\"0;32\"\nCPE_NAME=\"cpe:/o:opensuse:tumbleweed:20160917\"\n"
"BUG_REPORT_URL=\"https://bugs.opensuse.org\"\nHOME_URL=\"https://www.opensuse.org/\"\n") "BUG_REPORT_URL=\"https://bugs.opensuse.org\"\nHOME_URL=\"https://www.opensuse.org/\"\n"
)
}, },
"name": "openSUSE Tumbleweed 20160917", "name": "openSUSE Tumbleweed 20160917",
"result": { "result": {
@ -235,14 +250,14 @@ ID_LIKE="suse"
{ # see https://github.com/ansible/ansible/issues/14837 { # see https://github.com/ansible/ansible/issues/14837
"name": "SLES 11.3", "name": "SLES 11.3",
"input": { "input": {
"/etc/SuSE-release":""" "/etc/SuSE-release": """
SUSE Linux Enterprise Server 11 (x86_64) SUSE Linux Enterprise Server 11 (x86_64)
VERSION = 11 VERSION = 11
PATCHLEVEL = 3 PATCHLEVEL = 3
""" """
}, },
"platform.dist": ['SuSE', '11', 'x86_64'], "platform.dist": ['SuSE', '11', 'x86_64'],
"result":{ "result": {
"distribution": "SLES", "distribution": "SLES",
"distribution_major_version": "11", "distribution_major_version": "11",
"distribution_release": "3", "distribution_release": "3",
@ -253,12 +268,12 @@ PATCHLEVEL = 3
{ # see https://github.com/ansible/ansible/issues/14837 { # see https://github.com/ansible/ansible/issues/14837
"name": "SLES 11.4", "name": "SLES 11.4",
"input": { "input": {
"/etc/SuSE-release":""" "/etc/SuSE-release": """
SUSE Linux Enterprise Server 11 (x86_64) SUSE Linux Enterprise Server 11 (x86_64)
VERSION = 11 VERSION = 11
PATCHLEVEL = 4 PATCHLEVEL = 4
""", """,
"/etc/os-release":""" "/etc/os-release": """
NAME="SLES" NAME="SLES"
VERSION="11.4" VERSION="11.4"
VERSION_ID="11.4" VERSION_ID="11.4"
@ -266,7 +281,7 @@ PRETTY_NAME="SUSE Linux Enterprise Server 11 SP4"
ID="sles" ID="sles"
ANSI_COLOR="0;32" ANSI_COLOR="0;32"
CPE_NAME="cpe:/o:suse:sles:11:4" CPE_NAME="cpe:/o:suse:sles:11:4"
""", """,
}, },
"platform.dist": ['SuSE', '11', 'x86_64'], "platform.dist": ['SuSE', '11', 'x86_64'],
"result":{ "result":{
@ -280,14 +295,14 @@ CPE_NAME="cpe:/o:suse:sles:11:4"
{ # see https://github.com/ansible/ansible/issues/14837 { # see https://github.com/ansible/ansible/issues/14837
"name": "SLES 12 SP0", "name": "SLES 12 SP0",
"input": { "input": {
"/etc/SuSE-release":""" "/etc/SuSE-release": """
SUSE Linux Enterprise Server 12 (x86_64) SUSE Linux Enterprise Server 12 (x86_64)
VERSION = 12 VERSION = 12
PATCHLEVEL = 0 PATCHLEVEL = 0
# This file is deprecated and will be removed in a future service pack or release. # This file is deprecated and will be removed in a future service pack or release.
# Please check /etc/os-release for details about this release. # Please check /etc/os-release for details about this release.
""", """,
"/etc/os-release":""" "/etc/os-release": """
NAME="SLES" NAME="SLES"
VERSION="12" VERSION="12"
VERSION_ID="12" VERSION_ID="12"
@ -295,10 +310,10 @@ PRETTY_NAME="SUSE Linux Enterprise Server 12"
ID="sles" ID="sles"
ANSI_COLOR="0;32" ANSI_COLOR="0;32"
CPE_NAME="cpe:/o:suse:sles:12" CPE_NAME="cpe:/o:suse:sles:12"
""", """,
}, },
"platform.dist": ['SuSE', '12', 'x86_64'], "platform.dist": ['SuSE', '12', 'x86_64'],
"result":{ "result": {
"distribution": "SLES", "distribution": "SLES",
"distribution_major_version": "12", "distribution_major_version": "12",
"distribution_release": "0", "distribution_release": "0",
@ -306,18 +321,17 @@ CPE_NAME="cpe:/o:suse:sles:12"
"distribution_version": "12", "distribution_version": "12",
} }
}, },
{ # see https://github.com/ansible/ansible/issues/14837 { # see https://github.com/ansible/ansible/issues/14837
"name": "SLES 12 SP1", "name": "SLES 12 SP1",
"input": { "input": {
"/etc/SuSE-release":""" "/etc/SuSE-release": """
SUSE Linux Enterprise Server 12 (x86_64) SUSE Linux Enterprise Server 12 (x86_64)
VERSION = 12 VERSION = 12
PATCHLEVEL = 0 PATCHLEVEL = 0
# This file is deprecated and will be removed in a future service pack or release. # This file is deprecated and will be removed in a future service pack or release.
# Please check /etc/os-release for details about this release. # Please check /etc/os-release for details about this release.
""", """,
"/etc/os-release":""" "/etc/os-release": """
NAME="SLES" NAME="SLES"
VERSION="12-SP1" VERSION="12-SP1"
VERSION_ID="12.1" VERSION_ID="12.1"
@ -340,20 +354,20 @@ CPE_NAME="cpe:/o:suse:sles:12:sp1"
{ {
"name": "Debian stretch/sid", "name": "Debian stretch/sid",
"input": { "input": {
"/etc/os-release":""" "/etc/os-release": """
PRETTY_NAME="Debian GNU/Linux stretch/sid" PRETTY_NAME="Debian GNU/Linux stretch/sid"
NAME="Debian GNU/Linux" NAME="Debian GNU/Linux"
ID=debian ID=debian
HOME_URL="https://www.debian.org/" HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support" SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/" BUG_REPORT_URL="https://bugs.debian.org/"
""", """,
"/etc/debian_version":""" "/etc/debian_version": """
stretch/sid stretch/sid
""", """,
}, },
"platform.dist": ('debian', 'stretch/sid', ''), "platform.dist": ('debian', 'stretch/sid', ''),
"result":{ "result": {
"distribution": "Debian", "distribution": "Debian",
"distribution_major_version": "stretch/sid", "distribution_major_version": "stretch/sid",
"distribution_release": "NA", "distribution_release": "NA",
@ -363,7 +377,8 @@ BUG_REPORT_URL="https://bugs.debian.org/"
}, },
{ {
'name': "Debian 7.9", 'name': "Debian 7.9",
'input': {'/etc/os-release': """PRETTY_NAME="Debian GNU/Linux 7 (wheezy)" 'input': {
'/etc/os-release': """PRETTY_NAME="Debian GNU/Linux 7 (wheezy)"
NAME="Debian GNU/Linux" NAME="Debian GNU/Linux"
VERSION_ID="7" VERSION_ID="7"
VERSION="7 (wheezy)" VERSION="7 (wheezy)"
@ -372,13 +387,16 @@ ANSI_COLOR="1;31"
HOME_URL="http://www.debian.org/" HOME_URL="http://www.debian.org/"
SUPPORT_URL="http://www.debian.org/support/" SUPPORT_URL="http://www.debian.org/support/"
BUG_REPORT_URL="http://bugs.debian.org/" BUG_REPORT_URL="http://bugs.debian.org/"
"""}, """
},
'platform.dist': ('debian', '7.9', ''), 'platform.dist': ('debian', '7.9', ''),
'result': {'distribution': u'Debian', 'result': {
'distribution': u'Debian',
'distribution_major_version': u'7', 'distribution_major_version': u'7',
'distribution_release': u'wheezy', 'distribution_release': u'wheezy',
"os_family": "Debian", "os_family": "Debian",
'distribution_version': u'7.9'} 'distribution_version': u'7.9'
}
}, },
{ {
"platform.dist": [ "platform.dist": [
@ -387,9 +405,11 @@ BUG_REPORT_URL="http://bugs.debian.org/"
"xenial" "xenial"
], ],
"input": { "input": {
"/etc/os-release": ("NAME=\"Ubuntu\"\nVERSION=\"16.04 LTS (Xenial Xerus)\"\nID=ubuntu\nID_LIKE=debian\nPRETTY_NAME=\"Ubuntu 16.04 LTS\"\n" "/etc/os-release": (
"NAME=\"Ubuntu\"\nVERSION=\"16.04 LTS (Xenial Xerus)\"\nID=ubuntu\nID_LIKE=debian\nPRETTY_NAME=\"Ubuntu 16.04 LTS\"\n"
"VERSION_ID=\"16.04\"\nHOME_URL=\"http://www.ubuntu.com/\"\nSUPPORT_URL=\"http://help.ubuntu.com/\"\n" "VERSION_ID=\"16.04\"\nHOME_URL=\"http://www.ubuntu.com/\"\nSUPPORT_URL=\"http://help.ubuntu.com/\"\n"
"BUG_REPORT_URL=\"http://bugs.launchpad.net/ubuntu/\"\nUBUNTU_CODENAME=xenial\n"), "BUG_REPORT_URL=\"http://bugs.launchpad.net/ubuntu/\"\nUBUNTU_CODENAME=xenial\n"
),
"/etc/lsb-release": "DISTRIB_ID=Ubuntu\nDISTRIB_RELEASE=16.04\nDISTRIB_CODENAME=xenial\nDISTRIB_DESCRIPTION=\"Ubuntu 16.04 LTS\"\n" "/etc/lsb-release": "DISTRIB_ID=Ubuntu\nDISTRIB_RELEASE=16.04\nDISTRIB_CODENAME=xenial\nDISTRIB_DESCRIPTION=\"Ubuntu 16.04 LTS\"\n"
}, },
"name": "Ubuntu 16.04", "name": "Ubuntu 16.04",
@ -403,7 +423,8 @@ BUG_REPORT_URL="http://bugs.debian.org/"
}, },
{ {
'name': "Ubuntu 14.04", 'name': "Ubuntu 14.04",
'input': {'/etc/lsb-release': """DISTRIB_ID=Ubuntu 'input': {
'/etc/lsb-release': """DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04 DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.4 LTS" DISTRIB_DESCRIPTION="Ubuntu 14.04.4 LTS"
@ -417,13 +438,16 @@ VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/" HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/" SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/" BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
"""}, """
},
'platform.dist': ('Ubuntu', '14.04', 'trusty'), 'platform.dist': ('Ubuntu', '14.04', 'trusty'),
'result': {'distribution': u'Ubuntu', 'result': {
'distribution': u'Ubuntu',
'distribution_major_version': u'14', 'distribution_major_version': u'14',
'distribution_release': u'trusty', 'distribution_release': u'trusty',
"os_family": "Debian", "os_family": "Debian",
'distribution_version': u'14.04'} 'distribution_version': u'14.04'
}
}, },
{ {
'name': "Ubuntu 12.04", 'name': "Ubuntu 12.04",
@ -470,7 +494,7 @@ VERSION_ID="12.04"
{ {
'name': 'Core OS', 'name': 'Core OS',
'input': { 'input': {
'/etc/os-release':""" '/etc/os-release': """
NAME=CoreOS NAME=CoreOS
ID=coreos ID=coreos
VERSION=976.0.0 VERSION=976.0.0
@ -480,15 +504,15 @@ PRETTY_NAME="CoreOS 976.0.0 (Coeur Rouge)"
ANSI_COLOR="1;32" ANSI_COLOR="1;32"
HOME_URL="https://coreos.com/" HOME_URL="https://coreos.com/"
BUG_REPORT_URL="https://github.com/coreos/bugs/issues" BUG_REPORT_URL="https://github.com/coreos/bugs/issues"
""", """,
'/etc/lsb-release':"""DISTRIB_ID=CoreOS '/etc/lsb-release': """DISTRIB_ID=CoreOS
DISTRIB_RELEASE=976.0.0 DISTRIB_RELEASE=976.0.0
DISTRIB_CODENAME="Coeur Rouge" DISTRIB_CODENAME="Coeur Rouge"
DISTRIB_DESCRIPTION="CoreOS 976.0.0 (Coeur Rouge)" DISTRIB_DESCRIPTION="CoreOS 976.0.0 (Coeur Rouge)"
""", """,
}, },
'platform.dist': ('', '', ''), 'platform.dist': ('', '', ''),
'result' : { 'result': {
"distribution": "CoreOS", "distribution": "CoreOS",
"distribution_major_version": "NA", "distribution_major_version": "NA",
"distribution_release": "NA", "distribution_release": "NA",
@ -679,7 +703,6 @@ DISTRIB_DESCRIPTION="CoreOS 976.0.0 (Coeur Rouge)"
}, },
"platform.system": "SunOS" "platform.system": "SunOS"
}, },
{ {
"name": "Solaris 11.3", "name": "Solaris 11.3",
"platform.dist": [ "platform.dist": [
@ -688,8 +711,10 @@ DISTRIB_DESCRIPTION="CoreOS 976.0.0 (Coeur Rouge)"
"" ""
], ],
"input": { "input": {
"/etc/release": (" Oracle Solaris 11.3 X86\n Copyright (c) 1983, 2015, Oracle and/or its affiliates. " "/etc/release": (
"All rights reserved.\n Assembled 06 October 2015\n") " Oracle Solaris 11.3 X86\n Copyright (c) 1983, 2015, Oracle and/or its affiliates. "
"All rights reserved.\n Assembled 06 October 2015\n"
)
}, },
"platform.system": "SunOS", "platform.system": "SunOS",
"result": { "result": {
@ -699,7 +724,6 @@ DISTRIB_DESCRIPTION="CoreOS 976.0.0 (Coeur Rouge)"
"distribution_version": "11.3" "distribution_version": "11.3"
} }
}, },
{ {
"name": "Solaris 10", "name": "Solaris 10",
"platform.dist": [ "platform.dist": [
@ -719,7 +743,6 @@ DISTRIB_DESCRIPTION="CoreOS 976.0.0 (Coeur Rouge)"
"distribution_version": "10" "distribution_version": "10"
} }
}, },
{ {
"name": "Fedora 22", "name": "Fedora 22",
"platform.dist": [ "platform.dist": [
@ -729,11 +752,13 @@ DISTRIB_DESCRIPTION="CoreOS 976.0.0 (Coeur Rouge)"
], ],
"input": { "input": {
"/etc/redhat-release": "Fedora release 22 (Twenty Two)\n", "/etc/redhat-release": "Fedora release 22 (Twenty Two)\n",
"/etc/os-release": ("NAME=Fedora\nVERSION=\"22 (Twenty Two)\"\nID=fedora\nVERSION_ID=22\nPRETTY_NAME=\"Fedora 22 (Twenty Two)\"\n" "/etc/os-release": (
"NAME=Fedora\nVERSION=\"22 (Twenty Two)\"\nID=fedora\nVERSION_ID=22\nPRETTY_NAME=\"Fedora 22 (Twenty Two)\"\n"
"ANSI_COLOR=\"0;34\"\nCPE_NAME=\"cpe:/o:fedoraproject:fedora:22\"\nHOME_URL=\"https://fedoraproject.org/\"\n" "ANSI_COLOR=\"0;34\"\nCPE_NAME=\"cpe:/o:fedoraproject:fedora:22\"\nHOME_URL=\"https://fedoraproject.org/\"\n"
"BUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\nREDHAT_BUGZILLA_PRODUCT=\"Fedora\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=22\n" "BUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\nREDHAT_BUGZILLA_PRODUCT=\"Fedora\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=22\n"
"REDHAT_SUPPORT_PRODUCT=\"Fedora\"\nREDHAT_SUPPORT_PRODUCT_VERSION=22\n" "REDHAT_SUPPORT_PRODUCT=\"Fedora\"\nREDHAT_SUPPORT_PRODUCT_VERSION=22\n"
"PRIVACY_POLICY_URL=https://fedoraproject.org/wiki/Legal:PrivacyPolicy\n"), "PRIVACY_POLICY_URL=https://fedoraproject.org/wiki/Legal:PrivacyPolicy\n"
),
"/etc/system-release": "Fedora release 22 (Twenty Two)\n" "/etc/system-release": "Fedora release 22 (Twenty Two)\n"
}, },
"result": { "result": {
@ -752,12 +777,14 @@ DISTRIB_DESCRIPTION="CoreOS 976.0.0 (Coeur Rouge)"
], ],
"input": { "input": {
"/etc/redhat-release": "Fedora release 25 (Rawhide)\n", "/etc/redhat-release": "Fedora release 25 (Rawhide)\n",
"/etc/os-release": ("NAME=Fedora\nVERSION=\"25 (Workstation Edition)\"\nID=fedora\nVERSION_ID=25\n" "/etc/os-release": (
"NAME=Fedora\nVERSION=\"25 (Workstation Edition)\"\nID=fedora\nVERSION_ID=25\n"
"PRETTY_NAME=\"Fedora 25 (Workstation Edition)\"\nANSI_COLOR=\"0;34\"\nCPE_NAME=\"cpe:/o:fedoraproject:fedora:25\"\n" "PRETTY_NAME=\"Fedora 25 (Workstation Edition)\"\nANSI_COLOR=\"0;34\"\nCPE_NAME=\"cpe:/o:fedoraproject:fedora:25\"\n"
"HOME_URL=\"https://fedoraproject.org/\"\nBUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\n" "HOME_URL=\"https://fedoraproject.org/\"\nBUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\n"
"REDHAT_BUGZILLA_PRODUCT=\"Fedora\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=rawhide\nREDHAT_SUPPORT_PRODUCT=\"Fedora\"\n" "REDHAT_BUGZILLA_PRODUCT=\"Fedora\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=rawhide\nREDHAT_SUPPORT_PRODUCT=\"Fedora\"\n"
"REDHAT_SUPPORT_PRODUCT_VERSION=rawhide\nPRIVACY_POLICY_URL=https://fedoraproject.org/wiki/Legal:PrivacyPolicy\n" "REDHAT_SUPPORT_PRODUCT_VERSION=rawhide\nPRIVACY_POLICY_URL=https://fedoraproject.org/wiki/Legal:PrivacyPolicy\n"
"VARIANT=\"Workstation Edition\"\nVARIANT_ID=workstation\n"), "VARIANT=\"Workstation Edition\"\nVARIANT_ID=workstation\n"
),
"/etc/system-release": "Fedora release 25 (Rawhide)\n" "/etc/system-release": "Fedora release 25 (Rawhide)\n"
}, },
"name": "Fedora 25", "name": "Fedora 25",
@ -769,7 +796,6 @@ DISTRIB_DESCRIPTION="CoreOS 976.0.0 (Coeur Rouge)"
"distribution_version": "25" "distribution_version": "25"
} }
}, },
{ {
"platform.dist": [ "platform.dist": [
"", "",
@ -789,7 +815,6 @@ DISTRIB_DESCRIPTION="CoreOS 976.0.0 (Coeur Rouge)"
"distribution_version": "NA" "distribution_version": "NA"
} }
}, },
] ]
@ -815,6 +840,7 @@ def test_distribution_version(testcase):
_test_one_distribution(facts, module, testcase) _test_one_distribution(facts, module, testcase)
def _test_one_distribution(facts, module, testcase): def _test_one_distribution(facts, module, testcase):
"""run the test on one distribution testcase """run the test on one distribution testcase
@ -828,7 +854,7 @@ def _test_one_distribution(facts, module, testcase):
data = default data = default
if fname in testcase['input']: if fname in testcase['input']:
# for debugging # for debugging
print('faked '+fname+' for '+testcase['name']) print('faked %s for %s' % (fname, testcase['name']))
data = testcase['input'][fname].strip() data = testcase['input'][fname].strip()
if strip and data is not None: if strip and data is not None:
data = data.strip() data = data.strip()

View file

@ -244,165 +244,212 @@ grimlock.g.a:path_with'single_quotes /home/adrian/sshfs-grimlock-single-quote-2
grimlock.g.a:/mnt/data/foto's /home/adrian/fotos fuse.sshfs rw,nosuid,nodev,relatime,user_id=1000,group_id=1000 0 0 grimlock.g.a:/mnt/data/foto's /home/adrian/fotos fuse.sshfs rw,nosuid,nodev,relatime,user_id=1000,group_id=1000 0 0
""" """
MTAB_ENTRIES = \ MTAB_ENTRIES = [
[ [
['sysfs', 'sysfs',
'/sys', '/sys',
'sysfs', 'sysfs',
'rw,seclabel,nosuid,nodev,noexec,relatime', 'rw,seclabel,nosuid,nodev,noexec,relatime',
'0', '0',
'0'], '0'
],
['proc', '/proc', 'proc', 'rw,nosuid,nodev,noexec,relatime', '0', '0'], ['proc', '/proc', 'proc', 'rw,nosuid,nodev,noexec,relatime', '0', '0'],
['devtmpfs', [
'devtmpfs',
'/dev', '/dev',
'devtmpfs', 'devtmpfs',
'rw,seclabel,nosuid,size=8044400k,nr_inodes=2011100,mode=755', 'rw,seclabel,nosuid,size=8044400k,nr_inodes=2011100,mode=755',
'0', '0',
'0'], '0'
['securityfs', ],
[
'securityfs',
'/sys/kernel/security', '/sys/kernel/security',
'securityfs', 'securityfs',
'rw,nosuid,nodev,noexec,relatime', 'rw,nosuid,nodev,noexec,relatime',
'0', '0',
'0'], '0'
],
['tmpfs', '/dev/shm', 'tmpfs', 'rw,seclabel,nosuid,nodev', '0', '0'], ['tmpfs', '/dev/shm', 'tmpfs', 'rw,seclabel,nosuid,nodev', '0', '0'],
['devpts', [
'devpts',
'/dev/pts', '/dev/pts',
'devpts', 'devpts',
'rw,seclabel,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000', 'rw,seclabel,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000',
'0', '0',
'0'], '0'
],
['tmpfs', '/run', 'tmpfs', 'rw,seclabel,nosuid,nodev,mode=755', '0', '0'], ['tmpfs', '/run', 'tmpfs', 'rw,seclabel,nosuid,nodev,mode=755', '0', '0'],
['tmpfs', [
'tmpfs',
'/sys/fs/cgroup', '/sys/fs/cgroup',
'tmpfs', 'tmpfs',
'ro,seclabel,nosuid,nodev,noexec,mode=755', 'ro,seclabel,nosuid,nodev,noexec,mode=755',
'0', '0',
'0'], '0'
['cgroup', ],
[
'cgroup',
'/sys/fs/cgroup/systemd', '/sys/fs/cgroup/systemd',
'cgroup', 'cgroup',
'rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/usr/lib/systemd/systemd-cgroups-agent,name=systemd', 'rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/usr/lib/systemd/systemd-cgroups-agent,name=systemd',
'0', '0',
'0'], '0'
['pstore', ],
[
'pstore',
'/sys/fs/pstore', '/sys/fs/pstore',
'pstore', 'pstore',
'rw,seclabel,nosuid,nodev,noexec,relatime', 'rw,seclabel,nosuid,nodev,noexec,relatime',
'0', '0',
'0'], '0'
['cgroup', ],
[
'cgroup',
'/sys/fs/cgroup/devices', '/sys/fs/cgroup/devices',
'cgroup', 'cgroup',
'rw,nosuid,nodev,noexec,relatime,devices', 'rw,nosuid,nodev,noexec,relatime,devices',
'0', '0',
'0'], '0'
['cgroup', ],
[
'cgroup',
'/sys/fs/cgroup/freezer', '/sys/fs/cgroup/freezer',
'cgroup', 'cgroup',
'rw,nosuid,nodev,noexec,relatime,freezer', 'rw,nosuid,nodev,noexec,relatime,freezer',
'0', '0',
'0'], '0'
['cgroup', ],
[
'cgroup',
'/sys/fs/cgroup/memory', '/sys/fs/cgroup/memory',
'cgroup', 'cgroup',
'rw,nosuid,nodev,noexec,relatime,memory', 'rw,nosuid,nodev,noexec,relatime,memory',
'0', '0',
'0'], '0'
['cgroup', ],
[
'cgroup',
'/sys/fs/cgroup/pids', '/sys/fs/cgroup/pids',
'cgroup', 'cgroup',
'rw,nosuid,nodev,noexec,relatime,pids', 'rw,nosuid,nodev,noexec,relatime,pids',
'0', '0',
'0'], '0'
['cgroup', ],
[
'cgroup',
'/sys/fs/cgroup/blkio', '/sys/fs/cgroup/blkio',
'cgroup', 'cgroup',
'rw,nosuid,nodev,noexec,relatime,blkio', 'rw,nosuid,nodev,noexec,relatime,blkio',
'0', '0',
'0'], '0'
['cgroup', ],
[
'cgroup',
'/sys/fs/cgroup/cpuset', '/sys/fs/cgroup/cpuset',
'cgroup', 'cgroup',
'rw,nosuid,nodev,noexec,relatime,cpuset', 'rw,nosuid,nodev,noexec,relatime,cpuset',
'0', '0',
'0'], '0'
['cgroup', ],
[
'cgroup',
'/sys/fs/cgroup/cpu,cpuacct', '/sys/fs/cgroup/cpu,cpuacct',
'cgroup', 'cgroup',
'rw,nosuid,nodev,noexec,relatime,cpu,cpuacct', 'rw,nosuid,nodev,noexec,relatime,cpu,cpuacct',
'0', '0',
'0'], '0'
['cgroup', ],
[
'cgroup',
'/sys/fs/cgroup/hugetlb', '/sys/fs/cgroup/hugetlb',
'cgroup', 'cgroup',
'rw,nosuid,nodev,noexec,relatime,hugetlb', 'rw,nosuid,nodev,noexec,relatime,hugetlb',
'0', '0',
'0'], '0'
['cgroup', ],
[
'cgroup',
'/sys/fs/cgroup/perf_event', '/sys/fs/cgroup/perf_event',
'cgroup', 'cgroup',
'rw,nosuid,nodev,noexec,relatime,perf_event', 'rw,nosuid,nodev,noexec,relatime,perf_event',
'0', '0',
'0'], '0'
['cgroup', ],
[
'cgroup',
'/sys/fs/cgroup/net_cls,net_prio', '/sys/fs/cgroup/net_cls,net_prio',
'cgroup', 'cgroup',
'rw,nosuid,nodev,noexec,relatime,net_cls,net_prio', 'rw,nosuid,nodev,noexec,relatime,net_cls,net_prio',
'0', '0',
'0'], '0'
],
['configfs', '/sys/kernel/config', 'configfs', 'rw,relatime', '0', '0'], ['configfs', '/sys/kernel/config', 'configfs', 'rw,relatime', '0', '0'],
['/dev/mapper/fedora_dhcp129--186-root', [
'/dev/mapper/fedora_dhcp129--186-root',
'/', '/',
'ext4', 'ext4',
'rw,seclabel,relatime,data=ordered', 'rw,seclabel,relatime,data=ordered',
'0', '0',
'0'], '0'
],
['selinuxfs', '/sys/fs/selinux', 'selinuxfs', 'rw,relatime', '0', '0'], ['selinuxfs', '/sys/fs/selinux', 'selinuxfs', 'rw,relatime', '0', '0'],
['systemd-1', [
'systemd-1',
'/proc/sys/fs/binfmt_misc', '/proc/sys/fs/binfmt_misc',
'autofs', 'autofs',
'rw,relatime,fd=24,pgrp=1,timeout=0,minproto=5,maxproto=5,direct', 'rw,relatime,fd=24,pgrp=1,timeout=0,minproto=5,maxproto=5,direct',
'0', '0',
'0'], '0'
],
['debugfs', '/sys/kernel/debug', 'debugfs', 'rw,seclabel,relatime', '0', '0'], ['debugfs', '/sys/kernel/debug', 'debugfs', 'rw,seclabel,relatime', '0', '0'],
['hugetlbfs', [
'hugetlbfs',
'/dev/hugepages', '/dev/hugepages',
'hugetlbfs', 'hugetlbfs',
'rw,seclabel,relatime', 'rw,seclabel,relatime',
'0', '0',
'0'], '0'
],
['tmpfs', '/tmp', 'tmpfs', 'rw,seclabel', '0', '0'], ['tmpfs', '/tmp', 'tmpfs', 'rw,seclabel', '0', '0'],
['mqueue', '/dev/mqueue', 'mqueue', 'rw,seclabel,relatime', '0', '0'], ['mqueue', '/dev/mqueue', 'mqueue', 'rw,seclabel,relatime', '0', '0'],
['/dev/loop0', [
'/dev/loop0',
'/var/lib/machines', '/var/lib/machines',
'btrfs', 'btrfs',
'rw,seclabel,relatime,space_cache,subvolid=5,subvol=/', 'rw,seclabel,relatime,space_cache,subvolid=5,subvol=/',
'0', '0',
'0'], '0'
],
['/dev/sda1', '/boot', 'ext4', 'rw,seclabel,relatime,data=ordered', '0', '0'], ['/dev/sda1', '/boot', 'ext4', 'rw,seclabel,relatime,data=ordered', '0', '0'],
# A 'none' fstype # A 'none' fstype
['/dev/sdz3', '/not/a/real/device', 'none', 'rw,seclabel,relatime,data=ordered', '0', '0'], ['/dev/sdz3', '/not/a/real/device', 'none', 'rw,seclabel,relatime,data=ordered', '0', '0'],
# lets assume this is a bindmount # lets assume this is a bindmount
['/dev/sdz4', '/not/a/real/bind_mount', 'ext4', 'rw,seclabel,relatime,data=ordered', '0', '0'], ['/dev/sdz4', '/not/a/real/bind_mount', 'ext4', 'rw,seclabel,relatime,data=ordered', '0', '0'],
['/dev/mapper/fedora_dhcp129--186-home', [
'/dev/mapper/fedora_dhcp129--186-home',
'/home', '/home',
'ext4', 'ext4',
'rw,seclabel,relatime,data=ordered', 'rw,seclabel,relatime,data=ordered',
'0', '0',
'0'], '0'
['tmpfs', ],
[
'tmpfs',
'/run/user/1000', '/run/user/1000',
'tmpfs', 'tmpfs',
'rw,seclabel,nosuid,nodev,relatime,size=1611044k,mode=700,uid=1000,gid=1000', 'rw,seclabel,nosuid,nodev,relatime,size=1611044k,mode=700,uid=1000,gid=1000',
'0', '0',
'0'], '0'
['gvfsd-fuse', ],
[
'gvfsd-fuse',
'/run/user/1000/gvfs', '/run/user/1000/gvfs',
'fuse.gvfsd-fuse', 'fuse.gvfsd-fuse',
'rw,nosuid,nodev,relatime,user_id=1000,group_id=1000', 'rw,nosuid,nodev,relatime,user_id=1000,group_id=1000',
'0', '0',
'0'], '0'
],
['fusectl', '/sys/fs/fuse/connections', 'fusectl', 'rw,relatime', '0', '0']] ['fusectl', '/sys/fs/fuse/connections', 'fusectl', 'rw,relatime', '0', '0']]
BIND_MOUNTS = ['/not/a/real/bind_mount'] BIND_MOUNTS = ['/not/a/real/bind_mount']
@ -481,7 +528,7 @@ class TestFactsLinuxHardwareGetMountFacts(unittest.TestCase):
self.assertIsInstance(bind_mounts, set) self.assertIsInstance(bind_mounts, set)
self.assertEqual(len(bind_mounts), 0) self.assertEqual(len(bind_mounts), 0)
@patch('ansible.module_utils.facts.LinuxHardware._run_lsblk', return_value=(0, LSBLK_OUTPUT,'')) @patch('ansible.module_utils.facts.LinuxHardware._run_lsblk', return_value=(0, LSBLK_OUTPUT, ''))
def test_lsblk_uuid(self, mock_run_lsblk): def test_lsblk_uuid(self, mock_run_lsblk):
module = Mock() module = Mock()
lh = facts.LinuxHardware(module=module, load_on_init=False) lh = facts.LinuxHardware(module=module, load_on_init=False)
@ -492,7 +539,7 @@ class TestFactsLinuxHardwareGetMountFacts(unittest.TestCase):
self.assertIn(b'/dev/sda1', lsblk_uuids) self.assertIn(b'/dev/sda1', lsblk_uuids)
self.assertEquals(lsblk_uuids[b'/dev/sda1'], b'32caaec3-ef40-4691-a3b6-438c3f9bc1c0') self.assertEquals(lsblk_uuids[b'/dev/sda1'], b'32caaec3-ef40-4691-a3b6-438c3f9bc1c0')
@patch('ansible.module_utils.facts.LinuxHardware._run_lsblk', return_value=(37, LSBLK_OUTPUT,'')) @patch('ansible.module_utils.facts.LinuxHardware._run_lsblk', return_value=(37, LSBLK_OUTPUT, ''))
def test_lsblk_uuid_non_zero(self, mock_run_lsblk): def test_lsblk_uuid_non_zero(self, mock_run_lsblk):
module = Mock() module = Mock()
lh = facts.LinuxHardware(module=module, load_on_init=False) lh = facts.LinuxHardware(module=module, load_on_init=False)
@ -510,7 +557,7 @@ class TestFactsLinuxHardwareGetMountFacts(unittest.TestCase):
self.assertIsInstance(lsblk_uuids, dict) self.assertIsInstance(lsblk_uuids, dict)
self.assertEquals(len(lsblk_uuids), 0) self.assertEquals(len(lsblk_uuids), 0)
@patch('ansible.module_utils.facts.LinuxHardware._run_lsblk', return_value=(0, LSBLK_OUTPUT_2,'')) @patch('ansible.module_utils.facts.LinuxHardware._run_lsblk', return_value=(0, LSBLK_OUTPUT_2, ''))
def test_lsblk_uuid_dev_with_space_in_name(self, mock_run_lsblk): def test_lsblk_uuid_dev_with_space_in_name(self, mock_run_lsblk):
module = Mock() module = Mock()
lh = facts.LinuxHardware(module=module, load_on_init=False) lh = facts.LinuxHardware(module=module, load_on_init=False)

View file

@ -28,50 +28,73 @@ from units.mock.procenv import swap_stdin_and_argv
class TestAnsibleModuleKnownHosts(unittest.TestCase): class TestAnsibleModuleKnownHosts(unittest.TestCase):
urls = { urls = {
'ssh://one.example.org/example.git': 'ssh://one.example.org/example.git': {
{'is_ssh_url': True, 'get_fqdn': 'one.example.org', 'is_ssh_url': True,
'get_fqdn': 'one.example.org',
'add_host_key_cmd': " -t rsa one.example.org", 'add_host_key_cmd': " -t rsa one.example.org",
'port': None}, 'port': None,
'ssh+git://two.example.org/example.git': },
{'is_ssh_url': True, 'get_fqdn': 'two.example.org', 'ssh+git://two.example.org/example.git': {
'is_ssh_url': True,
'get_fqdn': 'two.example.org',
'add_host_key_cmd': " -t rsa two.example.org", 'add_host_key_cmd': " -t rsa two.example.org",
'port': None}, 'port': None,
'rsync://three.example.org/user/example.git': },
{'is_ssh_url': False, 'get_fqdn': 'three.example.org', 'rsync://three.example.org/user/example.git': {
'is_ssh_url': False,
'get_fqdn': 'three.example.org',
'add_host_key_cmd': None, # not called for non-ssh urls 'add_host_key_cmd': None, # not called for non-ssh urls
'port': None}, 'port': None,
'git@four.example.org:user/example.git': },
{'is_ssh_url': True, 'get_fqdn': 'four.example.org', 'git@four.example.org:user/example.git': {
'is_ssh_url': True,
'get_fqdn': 'four.example.org',
'add_host_key_cmd': " -t rsa four.example.org", 'add_host_key_cmd': " -t rsa four.example.org",
'port': None}, 'port': None,
'git+ssh://five.example.org/example.git': },
{'is_ssh_url': True, 'get_fqdn': 'five.example.org', 'git+ssh://five.example.org/example.git': {
'is_ssh_url': True,
'get_fqdn': 'five.example.org',
'add_host_key_cmd': " -t rsa five.example.org", 'add_host_key_cmd': " -t rsa five.example.org",
'port': None}, 'port': None,
'ssh://six.example.org:21/example.org': # ssh on FTP Port? },
{'is_ssh_url': True, 'get_fqdn': 'six.example.org', 'ssh://six.example.org:21/example.org': {
# ssh on FTP Port?
'is_ssh_url': True,
'get_fqdn': 'six.example.org',
'add_host_key_cmd': " -t rsa -p 21 six.example.org", 'add_host_key_cmd': " -t rsa -p 21 six.example.org",
'port': '21'}, 'port': '21',
'ssh://[2001:DB8::abcd:abcd]/example.git': },
{'is_ssh_url': True, 'get_fqdn': '[2001:DB8::abcd:abcd]', 'ssh://[2001:DB8::abcd:abcd]/example.git': {
'is_ssh_url': True,
'get_fqdn': '[2001:DB8::abcd:abcd]',
'add_host_key_cmd': " -t rsa [2001:DB8::abcd:abcd]", 'add_host_key_cmd': " -t rsa [2001:DB8::abcd:abcd]",
'port': None}, 'port': None,
'ssh://[2001:DB8::abcd:abcd]:22/example.git': },
{'is_ssh_url': True, 'get_fqdn': '[2001:DB8::abcd:abcd]', 'ssh://[2001:DB8::abcd:abcd]:22/example.git': {
'is_ssh_url': True,
'get_fqdn': '[2001:DB8::abcd:abcd]',
'add_host_key_cmd': " -t rsa -p 22 [2001:DB8::abcd:abcd]", 'add_host_key_cmd': " -t rsa -p 22 [2001:DB8::abcd:abcd]",
'port': '22'}, 'port': '22',
'username@[2001:DB8::abcd:abcd]/example.git': },
{'is_ssh_url': True, 'get_fqdn': '[2001:DB8::abcd:abcd]', 'username@[2001:DB8::abcd:abcd]/example.git': {
'is_ssh_url': True,
'get_fqdn': '[2001:DB8::abcd:abcd]',
'add_host_key_cmd': " -t rsa [2001:DB8::abcd:abcd]", 'add_host_key_cmd': " -t rsa [2001:DB8::abcd:abcd]",
'port': None}, 'port': None,
'username@[2001:DB8::abcd:abcd]:path/example.git': },
{'is_ssh_url': True, 'get_fqdn': '[2001:DB8::abcd:abcd]', 'username@[2001:DB8::abcd:abcd]:path/example.git': {
'is_ssh_url': True,
'get_fqdn': '[2001:DB8::abcd:abcd]',
'add_host_key_cmd': " -t rsa [2001:DB8::abcd:abcd]", 'add_host_key_cmd': " -t rsa [2001:DB8::abcd:abcd]",
'port': None}, 'port': None,
'ssh://internal.git.server:7999/repos/repo.git': },
{'is_ssh_url': True, 'get_fqdn': 'internal.git.server', 'ssh://internal.git.server:7999/repos/repo.git': {
'is_ssh_url': True,
'get_fqdn': 'internal.git.server',
'add_host_key_cmd': " -t rsa -p 7999 internal.git.server", 'add_host_key_cmd': " -t rsa -p 7999 internal.git.server",
'port': '7999'} 'port': '7999',
},
} }
def test_is_ssh_url(self): def test_is_ssh_url(self):

View file

@ -14,6 +14,7 @@ import pprint
realimport = builtins.__import__ realimport = builtins.__import__
class TestPostgres(unittest.TestCase): class TestPostgres(unittest.TestCase):
def clear_modules(self, mods): def clear_modules(self, mods):
for mod in mods: for mod in mods:
@ -72,4 +73,3 @@ class TestPostgres(unittest.TestCase):
with self.assertRaises(mod.module_utils.postgres.LibraryError) as context: with self.assertRaises(mod.module_utils.postgres.LibraryError) as context:
mod.module_utils.postgres.ensure_libs(sslrootcert='yes') mod.module_utils.postgres.ensure_libs(sslrootcert='yes')
self.assertIn('psycopg2 must be at least 2.4.3 in order to use', to_native(context.exception)) self.assertIn('psycopg2 must be at least 2.4.3 in order to use', to_native(context.exception))

View file

@ -37,16 +37,19 @@ VALID_STRINGS = (
# u'くらとみ' # u'くらとみ'
(b'\xe3\x81\x8f\xe3\x82\x89\xe3\x81\xa8\xe3\x81\xbf', u'\u304f\u3089\u3068\u307f', 'utf-8'), (b'\xe3\x81\x8f\xe3\x82\x89\xe3\x81\xa8\xe3\x81\xbf', u'\u304f\u3089\u3068\u307f', 'utf-8'),
(b'\x82\xad\x82\xe7\x82\xc6\x82\xdd', u'\u304f\u3089\u3068\u307f', 'shift-jis'), (b'\x82\xad\x82\xe7\x82\xc6\x82\xdd', u'\u304f\u3089\u3068\u307f', 'shift-jis'),
) )
def _check_to_text(self, in_string, encoding, expected): def _check_to_text(self, in_string, encoding, expected):
"""test happy path of decoding to text""" """test happy path of decoding to text"""
self.assertEqual(to_text(in_string, encoding), expected) self.assertEqual(to_text(in_string, encoding), expected)
def _check_to_bytes(self, in_string, encoding, expected): def _check_to_bytes(self, in_string, encoding, expected):
"""test happy path of encoding to bytes""" """test happy path of encoding to bytes"""
self.assertEqual(to_bytes(in_string, encoding), expected) self.assertEqual(to_bytes(in_string, encoding), expected)
def _check_to_native(self, in_string, encoding, py2_expected, py3_expected): def _check_to_native(self, in_string, encoding, py2_expected, py3_expected):
"""test happy path of encoding to native strings""" """test happy path of encoding to native strings"""
if PY3: if PY3:

View file

@ -1,9 +1,6 @@
import pytest import pytest
import unittest import unittest
boto3 = pytest.importorskip("boto3")
botocore = pytest.importorskip("botocore")
from collections import namedtuple from collections import namedtuple
from ansible.parsing.dataloader import DataLoader from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager from ansible.vars.manager import VariableManager
@ -13,6 +10,10 @@ from ansible.executor.task_queue_manager import TaskQueueManager
import ansible.modules.cloud.amazon.ec2_vpc_nat_gateway as ng import ansible.modules.cloud.amazon.ec2_vpc_nat_gateway as ng
boto3 = pytest.importorskip("boto3")
botocore = pytest.importorskip("botocore")
Options = ( Options = (
namedtuple( namedtuple(
'Options', [ 'Options', [
@ -44,6 +45,7 @@ aws_region = 'us-west-2'
inventory = InventoryManager(loader=loader) inventory = InventoryManager(loader=loader)
variable_manager.set_inventory(inventory) variable_manager.set_inventory(inventory)
def run(play): def run(play):
tqm = None tqm = None
results = None results = None
@ -62,14 +64,15 @@ def run(play):
tqm.cleanup() tqm.cleanup()
return tqm, results return tqm, results
class AnsibleVpcNatGatewayTasks(unittest.TestCase): class AnsibleVpcNatGatewayTasks(unittest.TestCase):
def test_create_gateway_using_allocation_id(self): def test_create_gateway_using_allocation_id(self):
play_source = dict( play_source = dict(
name = "Create new nat gateway with eip allocation-id", name="Create new nat gateway with eip allocation-id",
hosts = 'localhost', hosts='localhost',
gather_facts = 'no', gather_facts='no',
tasks = [ tasks=[
dict( dict(
action=dict( action=dict(
module='ec2_vpc_nat_gateway', module='ec2_vpc_nat_gateway',
@ -99,10 +102,10 @@ class AnsibleVpcNatGatewayTasks(unittest.TestCase):
def test_create_gateway_using_allocation_id_idempotent(self): def test_create_gateway_using_allocation_id_idempotent(self):
play_source = dict( play_source = dict(
name = "Create new nat gateway with eip allocation-id", name="Create new nat gateway with eip allocation-id",
hosts = 'localhost', hosts='localhost',
gather_facts = 'no', gather_facts='no',
tasks = [ tasks=[
dict( dict(
action=dict( action=dict(
module='ec2_vpc_nat_gateway', module='ec2_vpc_nat_gateway',
@ -132,10 +135,10 @@ class AnsibleVpcNatGatewayTasks(unittest.TestCase):
def test_create_gateway_using_eip_address(self): def test_create_gateway_using_eip_address(self):
play_source = dict( play_source = dict(
name = "Create new nat gateway with eip address", name="Create new nat gateway with eip address",
hosts = 'localhost', hosts='localhost',
gather_facts = 'no', gather_facts='no',
tasks = [ tasks=[
dict( dict(
action=dict( action=dict(
module='ec2_vpc_nat_gateway', module='ec2_vpc_nat_gateway',
@ -165,10 +168,10 @@ class AnsibleVpcNatGatewayTasks(unittest.TestCase):
def test_create_gateway_using_eip_address_idempotent(self): def test_create_gateway_using_eip_address_idempotent(self):
play_source = dict( play_source = dict(
name = "Create new nat gateway with eip address", name="Create new nat gateway with eip address",
hosts = 'localhost', hosts='localhost',
gather_facts = 'no', gather_facts='no',
tasks = [ tasks=[
dict( dict(
action=dict( action=dict(
module='ec2_vpc_nat_gateway', module='ec2_vpc_nat_gateway',
@ -198,10 +201,10 @@ class AnsibleVpcNatGatewayTasks(unittest.TestCase):
def test_create_gateway_in_subnet_only_if_one_does_not_exist_already(self): def test_create_gateway_in_subnet_only_if_one_does_not_exist_already(self):
play_source = dict( play_source = dict(
name = "Create new nat gateway only if one does not exist already", name="Create new nat gateway only if one does not exist already",
hosts = 'localhost', hosts='localhost',
gather_facts = 'no', gather_facts='no',
tasks = [ tasks=[
dict( dict(
action=dict( action=dict(
module='ec2_vpc_nat_gateway', module='ec2_vpc_nat_gateway',
@ -231,10 +234,10 @@ class AnsibleVpcNatGatewayTasks(unittest.TestCase):
def test_delete_gateway(self): def test_delete_gateway(self):
play_source = dict( play_source = dict(
name = "Delete Nat Gateway", name="Delete Nat Gateway",
hosts = 'localhost', hosts='localhost',
gather_facts = 'no', gather_facts='no',
tasks = [ tasks=[
dict( dict(
action=dict( action=dict(
module='ec2_vpc_nat_gateway', module='ec2_vpc_nat_gateway',
@ -262,6 +265,7 @@ class AnsibleVpcNatGatewayTasks(unittest.TestCase):
self.failUnless(tqm._stats.ok['localhost'] == 2) self.failUnless(tqm._stats.ok['localhost'] == 2)
self.assertTrue('localhost' in tqm._stats.changed) self.assertTrue('localhost' in tqm._stats.changed)
class AnsibleEc2VpcNatGatewayFunctions(unittest.TestCase): class AnsibleEc2VpcNatGatewayFunctions(unittest.TestCase):
def test_get_nat_gateways(self): def test_get_nat_gateways(self):

View file

@ -19,42 +19,45 @@
# Make coding more python3-ish # Make coding more python3-ish
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
import pytest
boto3 = pytest.importorskip("boto3")
import json
import copy import copy
from ansible.module_utils._text import to_bytes import json
from ansible.module_utils import basic import pytest
from ansible.compat.tests.mock import MagicMock, Mock, patch from ansible.compat.tests.mock import MagicMock, Mock, patch
from ansible.module_utils import basic
from ansible.module_utils._text import to_bytes
boto3 = pytest.importorskip("boto3")
# lambda is a keyword so we have to hack this. # lambda is a keyword so we have to hack this.
_temp = __import__("ansible.modules.cloud.amazon.lambda") _temp = __import__("ansible.modules.cloud.amazon.lambda")
lda = getattr(_temp.modules.cloud.amazon,"lambda") lda = getattr(_temp.modules.cloud.amazon, "lambda")
def set_module_args(args): def set_module_args(args):
args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
basic._ANSIBLE_ARGS = to_bytes(args) basic._ANSIBLE_ARGS = to_bytes(args)
base_lambda_config={ base_lambda_config = {
'FunctionName' : 'lambda_name', 'FunctionName': 'lambda_name',
'Role' : 'arn:aws:iam::987654321012:role/lambda_basic_execution', 'Role': 'arn:aws:iam::987654321012:role/lambda_basic_execution',
'Handler' : 'lambda_python.my_handler', 'Handler': 'lambda_python.my_handler',
'Description' : 'this that the other', 'Description': 'this that the other',
'Timeout' : 3, 'Timeout': 3,
'MemorySize' : 128, 'MemorySize': 128,
'Runtime' : 'python2.7', 'Runtime': 'python2.7',
'CodeSha256' : 'AqMZ+xptM7aC9VXu+5jyp1sqO+Nj4WFMNzQxtPMP2n8=', 'CodeSha256': 'AqMZ+xptM7aC9VXu+5jyp1sqO+Nj4WFMNzQxtPMP2n8=',
} }
one_change_lambda_config=copy.copy(base_lambda_config) one_change_lambda_config = copy.copy(base_lambda_config)
one_change_lambda_config['Timeout']=4 one_change_lambda_config['Timeout'] = 4
two_change_lambda_config=copy.copy(one_change_lambda_config) two_change_lambda_config = copy.copy(one_change_lambda_config)
two_change_lambda_config['Role']='arn:aws:iam::987654321012:role/lambda_advanced_execution' two_change_lambda_config['Role'] = 'arn:aws:iam::987654321012:role/lambda_advanced_execution'
code_change_lambda_config=copy.copy(base_lambda_config) code_change_lambda_config = copy.copy(base_lambda_config)
code_change_lambda_config['CodeSha256']='P+Zy8U4T4RiiHWElhL10VBKj9jw4rSJ5bm/TiW+4Rts=' code_change_lambda_config['CodeSha256'] = 'P+Zy8U4T4RiiHWElhL10VBKj9jw4rSJ5bm/TiW+4Rts='
base_module_args={ base_module_args = {
"region": "us-west-1", "region": "us-west-1",
"name": "lambda_name", "name": "lambda_name",
"state": "present", "state": "present",
@ -62,10 +65,10 @@ base_module_args={
"runtime": 'python2.7', "runtime": 'python2.7',
"role": 'arn:aws:iam::987654321012:role/lambda_basic_execution', "role": 'arn:aws:iam::987654321012:role/lambda_basic_execution',
"memory_size": 128, "memory_size": 128,
"timeout" : 3, "timeout": 3,
"handler": 'lambda_python.my_handler' "handler": 'lambda_python.my_handler'
} }
module_args_with_environment=dict(base_module_args, environment_variables={ module_args_with_environment = dict(base_module_args, environment_variables={
"variable_name": "variable_value" "variable_name": "variable_value"
}) })
@ -78,26 +81,27 @@ def make_mock_no_connection_connection(config):
) )
lambda_client_double.update_function_configuration.configure_mock( lambda_client_double.update_function_configuration.configure_mock(
return_value={ return_value={
'Version' : 1 'Version': 1
} }
) )
fake_boto3_conn=Mock(return_value=lambda_client_double) fake_boto3_conn = Mock(return_value=lambda_client_double)
return (fake_boto3_conn, lambda_client_double) return (fake_boto3_conn, lambda_client_double)
def make_mock_connection(config): def make_mock_connection(config):
"""return a mock of ansible's boto3_conn ready to return a mock AWS API client""" """return a mock of ansible's boto3_conn ready to return a mock AWS API client"""
lambda_client_double = MagicMock() lambda_client_double = MagicMock()
lambda_client_double.get_function.configure_mock( lambda_client_double.get_function.configure_mock(
return_value={ return_value={
'Configuration' : config 'Configuration': config
} }
) )
lambda_client_double.update_function_configuration.configure_mock( lambda_client_double.update_function_configuration.configure_mock(
return_value={ return_value={
'Version' : 1 'Version': 1
} }
) )
fake_boto3_conn=Mock(return_value=lambda_client_double) fake_boto3_conn = Mock(return_value=lambda_client_double)
return (fake_boto3_conn, lambda_client_double) return (fake_boto3_conn, lambda_client_double)
@ -111,13 +115,13 @@ def fail_json_double(*args, **kwargs):
raise AnsibleFailJson(kwargs) raise AnsibleFailJson(kwargs)
#TODO: def test_handle_different_types_in_config_params(): # TODO: def test_handle_different_types_in_config_params():
def test_create_lambda_if_not_exist(): def test_create_lambda_if_not_exist():
set_module_args(base_module_args) set_module_args(base_module_args)
(boto3_conn_double, lambda_client_double)=make_mock_no_connection_connection(code_change_lambda_config) (boto3_conn_double, lambda_client_double) = make_mock_no_connection_connection(code_change_lambda_config)
with patch.object(lda, 'boto3_conn', boto3_conn_double): with patch.object(lda, 'boto3_conn', boto3_conn_double):
try: try:
@ -133,7 +137,7 @@ def test_create_lambda_if_not_exist():
"update lambda function code when function should have been created only" "update lambda function code when function should have been created only"
assert(len(lambda_client_double.create_function.mock_calls) > 0), \ assert(len(lambda_client_double.create_function.mock_calls) > 0), \
"failed to call create_function " "failed to call create_function "
(create_args, create_kwargs)=lambda_client_double.create_function.call_args (create_args, create_kwargs) = lambda_client_double.create_function.call_args
assert (len(create_kwargs) > 0), "expected create called with keyword args, none found" assert (len(create_kwargs) > 0), "expected create called with keyword args, none found"
try: try:
@ -143,12 +147,13 @@ def test_create_lambda_if_not_exist():
create_kwargs["Environment"] create_kwargs["Environment"]
raise(Exception("Environment sent to boto when none expected")) raise(Exception("Environment sent to boto when none expected"))
except KeyError: except KeyError:
pass #We are happy, no environment is fine pass # We are happy, no environment is fine
def test_update_lambda_if_code_changed(): def test_update_lambda_if_code_changed():
set_module_args(base_module_args) set_module_args(base_module_args)
(boto3_conn_double, lambda_client_double)=make_mock_connection(code_change_lambda_config) (boto3_conn_double, lambda_client_double) = make_mock_connection(code_change_lambda_config)
with patch.object(lda, 'boto3_conn', boto3_conn_double): with patch.object(lda, 'boto3_conn', boto3_conn_double):
try: try:
@ -169,10 +174,11 @@ def test_update_lambda_if_code_changed():
assert(len(lambda_client_double.update_function_code.mock_calls) < 3), \ assert(len(lambda_client_double.update_function_code.mock_calls) < 3), \
"lambda function code update called multiple times when only one time should be needed" "lambda function code update called multiple times when only one time should be needed"
def test_update_lambda_if_config_changed(): def test_update_lambda_if_config_changed():
set_module_args(base_module_args) set_module_args(base_module_args)
(boto3_conn_double,lambda_client_double)=make_mock_connection(two_change_lambda_config) (boto3_conn_double, lambda_client_double) = make_mock_connection(two_change_lambda_config)
with patch.object(lda, 'boto3_conn', boto3_conn_double): with patch.object(lda, 'boto3_conn', boto3_conn_double):
try: try:
@ -189,10 +195,11 @@ def test_update_lambda_if_config_changed():
assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \ assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \
"updated lambda code when no change should have happened" "updated lambda code when no change should have happened"
def test_update_lambda_if_only_one_config_item_changed(): def test_update_lambda_if_only_one_config_item_changed():
set_module_args(base_module_args) set_module_args(base_module_args)
(boto3_conn_double,lambda_client_double)=make_mock_connection(one_change_lambda_config) (boto3_conn_double, lambda_client_double) = make_mock_connection(one_change_lambda_config)
with patch.object(lda, 'boto3_conn', boto3_conn_double): with patch.object(lda, 'boto3_conn', boto3_conn_double):
try: try:
@ -209,10 +216,11 @@ def test_update_lambda_if_only_one_config_item_changed():
assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \ assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \
"updated lambda code when no change should have happened" "updated lambda code when no change should have happened"
def test_update_lambda_if_added_environment_variable(): def test_update_lambda_if_added_environment_variable():
set_module_args(module_args_with_environment) set_module_args(module_args_with_environment)
(boto3_conn_double,lambda_client_double)=make_mock_connection(base_lambda_config) (boto3_conn_double, lambda_client_double) = make_mock_connection(base_lambda_config)
with patch.object(lda, 'boto3_conn', boto3_conn_double): with patch.object(lda, 'boto3_conn', boto3_conn_double):
try: try:
@ -229,14 +237,14 @@ def test_update_lambda_if_added_environment_variable():
assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \ assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \
"updated lambda code when no change should have happened" "updated lambda code when no change should have happened"
(update_args, update_kwargs)=lambda_client_double.update_function_configuration.call_args (update_args, update_kwargs) = lambda_client_double.update_function_configuration.call_args
assert (len(update_kwargs) > 0), "expected update configuration called with keyword args, none found" assert (len(update_kwargs) > 0), "expected update configuration called with keyword args, none found"
assert update_kwargs['Environment']['Variables'] == module_args_with_environment['environment_variables'] assert update_kwargs['Environment']['Variables'] == module_args_with_environment['environment_variables']
def test_dont_update_lambda_if_nothing_changed():
def test_dont_update_lambda_if_nothing_changed():
set_module_args(base_module_args) set_module_args(base_module_args)
(boto3_conn_double,lambda_client_double)=make_mock_connection(base_lambda_config) (boto3_conn_double, lambda_client_double) = make_mock_connection(base_lambda_config)
with patch.object(lda, 'boto3_conn', boto3_conn_double): with patch.object(lda, 'boto3_conn', boto3_conn_double):
try: try:
@ -248,9 +256,10 @@ def test_dont_update_lambda_if_nothing_changed():
assert(len(boto3_conn_double.mock_calls) == 1), "multiple boto connections used unexpectedly" assert(len(boto3_conn_double.mock_calls) == 1), "multiple boto connections used unexpectedly"
assert(len(lambda_client_double.update_function_configuration.mock_calls) == 0), \ assert(len(lambda_client_double.update_function_configuration.mock_calls) == 0), \
"updated lambda function when no configuration changed" "updated lambda function when no configuration changed"
assert(len(lambda_client_double.update_function_code.mock_calls) == 0 ), \ assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \
"updated lambda code when no change should have happened" "updated lambda code when no change should have happened"
def test_warn_region_not_specified(): def test_warn_region_not_specified():
set_module_args({ set_module_args({
@ -263,7 +272,7 @@ def test_warn_region_not_specified():
"role": 'arn:aws:iam::987654321012:role/lambda_basic_execution', "role": 'arn:aws:iam::987654321012:role/lambda_basic_execution',
"handler": 'lambda_python.my_handler'}) "handler": 'lambda_python.my_handler'})
get_aws_connection_info_double=Mock(return_value=(None,None,None)) get_aws_connection_info_double = Mock(return_value=(None, None, None))
with patch.object(lda, 'get_aws_connection_info', get_aws_connection_info_double): with patch.object(lda, 'get_aws_connection_info', get_aws_connection_info_double):
with patch.object(basic.AnsibleModule, 'fail_json', fail_json_double): with patch.object(basic.AnsibleModule, 'fail_json', fail_json_double):

View file

@ -1,10 +1,12 @@
import pytest import pytest
boto = pytest.importorskip("boto")
import unittest import unittest
import ansible.modules.cloud.amazon.s3 as s3 import ansible.modules.cloud.amazon.s3 as s3
from ansible.module_utils.six.moves.urllib.parse import urlparse from ansible.module_utils.six.moves.urllib.parse import urlparse
boto = pytest.importorskip("boto")
class TestUrlparse(unittest.TestCase): class TestUrlparse(unittest.TestCase):
def test_urlparse(self): def test_urlparse(self):
@ -19,7 +21,7 @@ class TestUrlparse(unittest.TestCase):
def test_is_walrus(self): def test_is_walrus(self):
actual = s3.is_walrus("trulywalrus_but_invalid_url") actual = s3.is_walrus("trulywalrus_but_invalid_url")
#I don't know if this makes sense, but this is the current behaviour... # I don't know if this makes sense, but this is the current behaviour...
self.assertEqual(True, actual) self.assertEqual(True, actual)
actual = s3.is_walrus("http://notwalrus.amazonaws.com") actual = s3.is_walrus("http://notwalrus.amazonaws.com")
self.assertEqual(False, actual) self.assertEqual(False, actual)
@ -27,8 +29,8 @@ class TestUrlparse(unittest.TestCase):
def test_get_s3_connection(self): def test_get_s3_connection(self):
aws_connect_kwargs = dict(aws_access_key_id="access_key", aws_connect_kwargs = dict(aws_access_key_id="access_key",
aws_secret_access_key="secret_key") aws_secret_access_key="secret_key")
location=None location = None
rgw=True rgw = True
s3_url="http://bla.blubb" s3_url = "http://bla.blubb"
actual = s3.get_s3_connection(aws_connect_kwargs, location, rgw, s3_url) actual = s3.get_s3_connection(aws_connect_kwargs, location, rgw, s3_url)
self.assertEqual("bla.blubb", actual.host) self.assertEqual("bla.blubb", actual.host)

View file

@ -4,6 +4,7 @@ import unittest
from ansible.modules.cloud.docker._docker import get_split_image_tag from ansible.modules.cloud.docker._docker import get_split_image_tag
class DockerSplitImageTagTestCase(unittest.TestCase): class DockerSplitImageTagTestCase(unittest.TestCase):
def test_trivial(self): def test_trivial(self):

View file

@ -2,6 +2,7 @@ import unittest
from ansible.modules.cloud.google.gce_tag import _get_changed_items, _intersect_items, _union_items from ansible.modules.cloud.google.gce_tag import _get_changed_items, _intersect_items, _union_items
class TestGCETag(unittest.TestCase): class TestGCETag(unittest.TestCase):
"""Unit tests for gce_tag module.""" """Unit tests for gce_tag module."""

View file

@ -1,8 +1,8 @@
import collections
import inspect
import mock import mock
import pytest import pytest
import yaml import yaml
import inspect
import collections
from ansible.module_utils.six import string_types from ansible.module_utils.six import string_types
from ansible.modules.cloud.openstack import os_server from ansible.modules.cloud.openstack import os_server
@ -188,12 +188,9 @@ class TestCreateServer(object):
os_server._create_server(self.module, self.cloud) os_server._create_server(self.module, self.cloud)
assert(self.cloud.create_server.call_count == 1) assert(self.cloud.create_server.call_count == 1)
assert(self.cloud.create_server.call_args[1]['image'] assert(self.cloud.create_server.call_args[1]['image'] == self.cloud.get_image_id('cirros'))
== self.cloud.get_image_id('cirros')) assert(self.cloud.create_server.call_args[1]['flavor'] == self.cloud.get_flavor('m1.tiny')['id'])
assert(self.cloud.create_server.call_args[1]['flavor'] assert(self.cloud.create_server.call_args[1]['nics'][0]['net-id'] == self.cloud.get_network('network1')['id'])
== self.cloud.get_flavor('m1.tiny')['id'])
assert(self.cloud.create_server.call_args[1]['nics'][0]['net-id']
== self.cloud.get_network('network1')['id'])
def test_create_server_bad_flavor(self): def test_create_server_bad_flavor(self):
''' '''

View file

@ -14,13 +14,12 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import unittest
from ansible.modules.network.cumulus import nclu
import sys import sys
import time import time
from ansible.module_utils.basic import * import unittest
from ansible.module_utils.basic import *
from ansible.modules.network.cumulus import nclu
class FakeModule(object): class FakeModule(object):
@ -172,7 +171,6 @@ class TestNclu(unittest.TestCase):
self.assertEqual(module.fail_code, {}) self.assertEqual(module.fail_code, {})
self.assertEqual(changed, True) self.assertEqual(changed, True)
def test_command_atomic(self): def test_command_atomic(self):
module = FakeModule() module = FakeModule()
changed, output = nclu.run_nclu(module, changed, output = nclu.run_nclu(module,

View file

@ -19,8 +19,8 @@
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
import os
import json import json
import os
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch from ansible.compat.tests.mock import patch
@ -35,6 +35,7 @@ def set_module_args(args):
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {} fixture_data = {}
def load_fixture(name): def load_fixture(name):
path = os.path.join(fixture_path, name) path = os.path.join(fixture_path, name)
@ -56,13 +57,14 @@ def load_fixture(name):
class AnsibleExitJson(Exception): class AnsibleExitJson(Exception):
pass pass
class AnsibleFailJson(Exception): class AnsibleFailJson(Exception):
pass pass
class TestEosModule(unittest.TestCase): class TestEosModule(unittest.TestCase):
def execute_module(self, failed=False, changed=False, commands=None, def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False, transport='cli'):
sort=True, defaults=False, transport='cli'):
self.load_fixtures(commands, transport=transport) self.load_fixtures(commands, transport=transport)
@ -110,4 +112,3 @@ class TestEosModule(unittest.TestCase):
def load_fixtures(self, commands=None, transport='cli'): def load_fixtures(self, commands=None, transport='cli'):
pass pass

View file

@ -25,6 +25,7 @@ from ansible.compat.tests.mock import patch
from ansible.modules.network.eos import eos_command from ansible.modules.network.eos import eos_command
from .eos_module import TestEosModule, load_fixture, set_module_args from .eos_module import TestEosModule, load_fixture, set_module_args
class TestEosCommandModule(TestEosModule): class TestEosCommandModule(TestEosModule):
module = eos_command module = eos_command

View file

@ -25,6 +25,7 @@ from ansible.compat.tests.mock import patch
from ansible.modules.network.eos import eos_system from ansible.modules.network.eos import eos_system
from .eos_module import TestEosModule, load_fixture, set_module_args from .eos_module import TestEosModule, load_fixture, set_module_args
class TestEosSystemModule(TestEosModule): class TestEosSystemModule(TestEosModule):
module = eos_system module = eos_system
@ -75,14 +76,14 @@ class TestEosSystemModule(TestEosModule):
'ip domain lookup source-interface Ethernet1'] 'ip domain lookup source-interface Ethernet1']
self.execute_module(changed=True, commands=commands) self.execute_module(changed=True, commands=commands)
#def test_eos_system_name_servers(self): # def test_eos_system_name_servers(self):
# name_servers = ['8.8.8.8', '8.8.4.4'] # name_servers = ['8.8.8.8', '8.8.4.4']
# set_module_args(dict(name_servers=name_servers)) # set_module_args(dict(name_servers=name_servers))
# commands = ['ip name-server 8.8.4.4', # commands = ['ip name-server 8.8.4.4',
# 'no ip name-server vrf mgmt 8.8.4.4'] # 'no ip name-server vrf mgmt 8.8.4.4']
# self.execute_module(changed=True, commands=commands) # self.execute_module(changed=True, commands=commands)
#def rest_eos_system_name_servers_complex(self): # def rest_eos_system_name_servers_complex(self):
# name_servers = dict(server='8.8.8.8', vrf='test') # name_servers = dict(server='8.8.8.8', vrf='test')
# set_module_args(dict(name_servers=name_servers)) # set_module_args(dict(name_servers=name_servers))
# commands = ['ip name-server vrf test 8.8.8.8', # commands = ['ip name-server vrf test 8.8.8.8',
@ -104,4 +105,3 @@ class TestEosSystemModule(TestEosModule):
name_servers = dict(server='8.8.8.8', vrf='missing') name_servers = dict(server='8.8.8.8', vrf='missing')
set_module_args(dict(name_servers=name_servers)) set_module_args(dict(name_servers=name_servers))
result = self.execute_module(failed=True) result = self.execute_module(failed=True)

View file

@ -95,5 +95,3 @@ class TestEosUserModule(TestEosModule):
set_module_args(dict(username='ansible', password='test', update_password='always')) set_module_args(dict(username='ansible', password='test', update_password='always'))
commands = ['username ansible secret test'] commands = ['username ansible secret test']
self.execute_module(changed=True, commands=commands) self.execute_module(changed=True, commands=commands)

View file

@ -35,6 +35,7 @@ def set_module_args(args):
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {} fixture_data = {}
def load_fixture(name): def load_fixture(name):
path = os.path.join(fixture_path, name) path = os.path.join(fixture_path, name)
@ -56,13 +57,14 @@ def load_fixture(name):
class AnsibleExitJson(Exception): class AnsibleExitJson(Exception):
pass pass
class AnsibleFailJson(Exception): class AnsibleFailJson(Exception):
pass pass
class TestIosModule(unittest.TestCase): class TestIosModule(unittest.TestCase):
def execute_module(self, failed=False, changed=False, commands=None, def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False):
sort=True, defaults=False):
self.load_fixtures(commands) self.load_fixtures(commands)
@ -110,4 +112,3 @@ class TestIosModule(unittest.TestCase):
def load_fixtures(self, commands=None): def load_fixtures(self, commands=None):
pass pass

View file

@ -40,8 +40,7 @@ class TestIosBannerModule(TestIosModule):
self.mock_load_config.stop() self.mock_load_config.stop()
def load_fixtures(self, commands=None): def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, self.exec_command.return_value = (0, load_fixture('ios_banner_show_banner.txt').strip(), None)
load_fixture('ios_banner_show_banner.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session') self.load_config.return_value = dict(diff=None, session='session')
def test_ios_banner_create(self): def test_ios_banner_create(self):

View file

@ -25,6 +25,7 @@ from ansible.compat.tests.mock import patch
from ansible.modules.network.ios import ios_command from ansible.modules.network.ios import ios_command
from .ios_module import TestIosModule, load_fixture, set_module_args from .ios_module import TestIosModule, load_fixture, set_module_args
class TestIosCommandModule(TestIosModule): class TestIosCommandModule(TestIosModule):
module = ios_command module = ios_command

View file

@ -89,19 +89,19 @@ class TestIosConfigModule(TestIosModule):
self.execute_module(changed=True, commands=commands) self.execute_module(changed=True, commands=commands)
def test_ios_config_before(self): def test_ios_config_before(self):
set_module_args(dict(lines=['hostname foo'], before=['test1','test2'])) set_module_args(dict(lines=['hostname foo'], before=['test1', 'test2']))
commands = ['test1', 'test2', 'hostname foo'] commands = ['test1', 'test2', 'hostname foo']
self.execute_module(changed=True, commands=commands, sort=False) self.execute_module(changed=True, commands=commands, sort=False)
def test_ios_config_after(self): def test_ios_config_after(self):
set_module_args(dict(lines=['hostname foo'], after=['test1','test2'])) set_module_args(dict(lines=['hostname foo'], after=['test1', 'test2']))
commands = ['hostname foo', 'test1', 'test2'] commands = ['hostname foo', 'test1', 'test2']
self.execute_module(changed=True, commands=commands, sort=False) self.execute_module(changed=True, commands=commands, sort=False)
def test_ios_config_before_after_no_change(self): def test_ios_config_before_after_no_change(self):
set_module_args(dict(lines=['hostname router'], set_module_args(dict(lines=['hostname router'],
before=['test1', 'test2'], before=['test1', 'test2'],
after=['test3','test4'])) after=['test3', 'test4']))
self.execute_module() self.execute_module()
def test_ios_config_config(self): def test_ios_config_config(self):

View file

@ -51,7 +51,6 @@ class TestIosSystemModule(TestIosModule):
commands = ['hostname foo'] commands = ['hostname foo']
self.execute_module(changed=True, commands=commands) self.execute_module(changed=True, commands=commands)
def test_ios_system_domain_name(self): def test_ios_system_domain_name(self):
set_module_args(dict(domain_name=['test.com'])) set_module_args(dict(domain_name=['test.com']))
commands = ['ip domain name test.com', commands = ['ip domain name test.com',
@ -120,4 +119,3 @@ class TestIosSystemModule(TestIosModule):
name_servers = dict(server='8.8.8.8', vrf='missing') name_servers = dict(server='8.8.8.8', vrf='missing')
set_module_args(dict(name_servers=name_servers)) set_module_args(dict(name_servers=name_servers))
self.execute_module(failed=True) self.execute_module(failed=True)

View file

@ -26,6 +26,7 @@ from ansible.compat.tests.mock import patch
from ansible.modules.network.ios import _ios_template from ansible.modules.network.ios import _ios_template
from .ios_module import TestIosModule, load_fixture, set_module_args from .ios_module import TestIosModule, load_fixture, set_module_args
class TestIosTemplateModule(TestIosModule): class TestIosTemplateModule(TestIosModule):
module = _ios_template module = _ios_template

View file

@ -122,5 +122,3 @@ class TestIosVrfModule(TestIosModule):
commands = ['no vrf definition test_1', 'vrf definition test_2', commands = ['no vrf definition test_1', 'vrf definition test_2',
'description test string'] 'description test string']
self.execute_module(changed=True, commands=commands, sort=False) self.execute_module(changed=True, commands=commands, sort=False)

View file

@ -35,6 +35,7 @@ def set_module_args(args):
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {} fixture_data = {}
def load_fixture(name): def load_fixture(name):
path = os.path.join(fixture_path, name) path = os.path.join(fixture_path, name)
@ -56,13 +57,14 @@ def load_fixture(name):
class AnsibleExitJson(Exception): class AnsibleExitJson(Exception):
pass pass
class AnsibleFailJson(Exception): class AnsibleFailJson(Exception):
pass pass
class TestIosxrModule(unittest.TestCase): class TestIosxrModule(unittest.TestCase):
def execute_module(self, failed=False, changed=False, commands=None, def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False):
sort=True, defaults=False):
self.load_fixtures(commands) self.load_fixtures(commands)
@ -110,4 +112,3 @@ class TestIosxrModule(unittest.TestCase):
def load_fixtures(self, commands=None): def load_fixtures(self, commands=None):
pass pass

View file

@ -26,6 +26,7 @@ from ansible.compat.tests.mock import patch
from ansible.modules.network.iosxr import iosxr_config from ansible.modules.network.iosxr import iosxr_config
from .iosxr_module import TestIosxrModule, load_fixture, set_module_args from .iosxr_module import TestIosxrModule, load_fixture, set_module_args
class TestIosxrConfigModule(TestIosxrModule): class TestIosxrConfigModule(TestIosxrModule):
module = iosxr_config module = iosxr_config
@ -73,19 +74,19 @@ class TestIosxrConfigModule(TestIosxrModule):
self.execute_module(changed=True, commands=commands) self.execute_module(changed=True, commands=commands)
def test_iosxr_config_before(self): def test_iosxr_config_before(self):
set_module_args(dict(lines=['hostname foo'], before=['test1','test2'])) set_module_args(dict(lines=['hostname foo'], before=['test1', 'test2']))
commands = ['test1', 'test2', 'hostname foo'] commands = ['test1', 'test2', 'hostname foo']
self.execute_module(changed=True, commands=commands, sort=False) self.execute_module(changed=True, commands=commands, sort=False)
def test_iosxr_config_after(self): def test_iosxr_config_after(self):
set_module_args(dict(lines=['hostname foo'], after=['test1','test2'])) set_module_args(dict(lines=['hostname foo'], after=['test1', 'test2']))
commands = ['hostname foo', 'test1', 'test2'] commands = ['hostname foo', 'test1', 'test2']
self.execute_module(changed=True, commands=commands, sort=False) self.execute_module(changed=True, commands=commands, sort=False)
def test_iosxr_config_before_after_no_change(self): def test_iosxr_config_before_after_no_change(self):
set_module_args(dict(lines=['hostname router'], set_module_args(dict(lines=['hostname router'],
before=['test1', 'test2'], before=['test1', 'test2'],
after=['test3','test4'])) after=['test3', 'test4']))
self.execute_module() self.execute_module()
def test_iosxr_config_config(self): def test_iosxr_config_config(self):

View file

@ -66,8 +66,7 @@ class TestIosxrFacts(TestIosxrModule):
self.assertIn('interfaces', ansible_facts['ansible_net_gather_subset']) self.assertIn('interfaces', ansible_facts['ansible_net_gather_subset'])
self.assertEquals('iosxr01', ansible_facts['ansible_net_hostname']) self.assertEquals('iosxr01', ansible_facts['ansible_net_hostname'])
self.assertEquals(['disk0:', 'flash0:'], ansible_facts['ansible_net_filesystems']) self.assertEquals(['disk0:', 'flash0:'], ansible_facts['ansible_net_filesystems'])
self.assertIn('GigabitEthernet0/0/0/0', self.assertIn('GigabitEthernet0/0/0/0', ansible_facts['ansible_net_interfaces'].keys())
ansible_facts['ansible_net_interfaces'].keys())
self.assertEquals('3095', ansible_facts['ansible_net_memtotal_mb']) self.assertEquals('3095', ansible_facts['ansible_net_memtotal_mb'])
self.assertEquals('1499', ansible_facts['ansible_net_memfree_mb']) self.assertEquals('1499', ansible_facts['ansible_net_memfree_mb'])

View file

@ -57,7 +57,7 @@ class TestIosxrSystemModule(TestIosxrModule):
def test_iosxr_system_domain_search(self): def test_iosxr_system_domain_search(self):
set_module_args(dict(domain_search=['ansible.com', 'redhat.com'])) set_module_args(dict(domain_search=['ansible.com', 'redhat.com']))
commands=['domain list ansible.com', 'no domain list cisco.com'] commands = ['domain list ansible.com', 'no domain list cisco.com']
self.execute_module(changed=True, commands=commands) self.execute_module(changed=True, commands=commands)
def test_iosxr_system_lookup_source(self): def test_iosxr_system_lookup_source(self):
@ -78,14 +78,18 @@ class TestIosxrSystemModule(TestIosxrModule):
def test_iosxr_system_state_absent(self): def test_iosxr_system_state_absent(self):
set_module_args(dict(state='absent')) set_module_args(dict(state='absent'))
commands = ['no hostname', 'no domain name', commands = [
'no hostname',
'no domain name',
'no domain lookup disable', 'no domain lookup disable',
'no domain lookup source-interface MgmtEth0/0/CPU0/0', 'no domain lookup source-interface MgmtEth0/0/CPU0/0',
'no domain list redhat.com', 'no domain list cisco.com', 'no domain list redhat.com',
'no domain name-server 8.8.8.8', 'no domain name-server 8.8.4.4'] 'no domain list cisco.com',
'no domain name-server 8.8.8.8',
'no domain name-server 8.8.4.4'
]
self.execute_module(changed=True, commands=commands) self.execute_module(changed=True, commands=commands)
def test_iosxr_system_no_change(self): def test_iosxr_system_no_change(self):
set_module_args(dict(hostname='iosxr01', domain_name='eng.ansible.com')) set_module_args(dict(hostname='iosxr01', domain_name='eng.ansible.com'))
self.execute_module() self.execute_module()

View file

@ -35,6 +35,7 @@ def set_module_args(args):
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {} fixture_data = {}
def load_fixture(name): def load_fixture(name):
path = os.path.join(fixture_path, name) path = os.path.join(fixture_path, name)
@ -56,13 +57,14 @@ def load_fixture(name):
class AnsibleExitJson(Exception): class AnsibleExitJson(Exception):
pass pass
class AnsibleFailJson(Exception): class AnsibleFailJson(Exception):
pass pass
class TestNxosModule(unittest.TestCase): class TestNxosModule(unittest.TestCase):
def execute_module(self, failed=False, changed=False, commands=None, def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False):
sort=True, defaults=False):
self.load_fixtures(commands) self.load_fixtures(commands)
@ -110,4 +112,3 @@ class TestNxosModule(unittest.TestCase):
def load_fixtures(self, commands=None): def load_fixtures(self, commands=None):
pass pass

View file

@ -25,6 +25,7 @@ from ansible.compat.tests.mock import patch
from ansible.modules.network.nxos import nxos_command from ansible.modules.network.nxos import nxos_command
from .nxos_module import TestNxosModule, load_fixture, set_module_args from .nxos_module import TestNxosModule, load_fixture, set_module_args
class TestNxosCommandModule(TestNxosModule): class TestNxosCommandModule(TestNxosModule):
module = nxos_command module = nxos_command

View file

@ -134,6 +134,3 @@ class TestNxosConfigModule(TestNxosModule):
set_module_args(args) set_module_args(args)
result = self.execute_module() result = self.execute_module()
self.assertIn('__backup__', result) self.assertIn('__backup__', result)

View file

@ -61,4 +61,3 @@ class TestNxosEvpnGlobalModule(TestNxosModule):
set_module_args(dict(nv_overlay_evpn=False)) set_module_args(dict(nv_overlay_evpn=False))
commands = ['no nv overlay evpn'] commands = ['no nv overlay evpn']
self.start_configured(changed=True, commands=commands) self.start_configured(changed=True, commands=commands)

View file

@ -126,5 +126,3 @@ class TestNxosSystemModule(TestNxosModule):
'vrf context management', 'no ip name-server 172.26.1.1', 'exit', 'vrf context management', 'no ip name-server 172.26.1.1', 'exit',
'no system jumbomtu'] 'no system jumbomtu']
self.execute_module(changed=True, commands=commands) self.execute_module(changed=True, commands=commands)

View file

@ -25,6 +25,7 @@ from ansible.compat.tests.mock import patch
from ansible.modules.network.vyos import vyos_command from ansible.modules.network.vyos import vyos_command
from .vyos_module import TestVyosModule, load_fixture, set_module_args from .vyos_module import TestVyosModule, load_fixture, set_module_args
class TestVyosCommandModule(TestVyosModule): class TestVyosCommandModule(TestVyosModule):
module = vyos_command module = vyos_command

View file

@ -35,6 +35,7 @@ def set_module_args(args):
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {} fixture_data = {}
def load_fixture(name): def load_fixture(name):
path = os.path.join(fixture_path, name) path = os.path.join(fixture_path, name)
@ -56,14 +57,14 @@ def load_fixture(name):
class AnsibleExitJson(Exception): class AnsibleExitJson(Exception):
pass pass
class AnsibleFailJson(Exception): class AnsibleFailJson(Exception):
pass pass
class TestVyosModule(unittest.TestCase): class TestVyosModule(unittest.TestCase):
def execute_module(self, failed=False, changed=False, commands=None, def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False):
sort=True, defaults=False):
self.load_fixtures(commands) self.load_fixtures(commands)
if failed: if failed:
@ -110,4 +111,3 @@ class TestVyosModule(unittest.TestCase):
def load_fixtures(self, commands=None): def load_fixtures(self, commands=None):
pass pass

View file

@ -20,7 +20,8 @@ class AptExpandPkgspecTestCase(unittest.TestCase):
def setUp(self): def setUp(self):
FakePackage = collections.namedtuple("Package", ("name",)) FakePackage = collections.namedtuple("Package", ("name",))
self.fake_cache = [ FakePackage("apt"), self.fake_cache = [
FakePackage("apt"),
FakePackage("apt-utils"), FakePackage("apt-utils"),
FakePackage("not-selected"), FakePackage("not-selected"),
] ]

View file

@ -36,11 +36,8 @@ class KnownHostsDiffTestCase(unittest.TestCase):
self.assertEqual(diff, { self.assertEqual(diff, {
'before_header': path, 'before_header': path,
'after_header': path, 'after_header': path,
'before': 'before': 'two.example.com ssh-rsa BBBBetc\n',
'two.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\none.example.com ssh-rsa AAAAetc\n',
'after':
'two.example.com ssh-rsa BBBBetc\n'
'one.example.com ssh-rsa AAAAetc\n',
}) })
def test_no_change(self): def test_no_change(self):
@ -53,12 +50,8 @@ class KnownHostsDiffTestCase(unittest.TestCase):
self.assertEqual(diff, { self.assertEqual(diff, {
'before_header': path, 'before_header': path,
'after_header': path, 'after_header': path,
'before': 'before': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n',
'one.example.com ssh-rsa AAAAetc\n' 'after': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n',
'two.example.com ssh-rsa BBBBetc\n',
'after':
'one.example.com ssh-rsa AAAAetc\n'
'two.example.com ssh-rsa BBBBetc\n',
}) })
def test_key_change(self): def test_key_change(self):
@ -71,12 +64,8 @@ class KnownHostsDiffTestCase(unittest.TestCase):
self.assertEqual(diff, { self.assertEqual(diff, {
'before_header': path, 'before_header': path,
'after_header': path, 'after_header': path,
'before': 'before': 'one.example.com ssh-rsa AAAaetc\ntwo.example.com ssh-rsa BBBBetc\n',
'one.example.com ssh-rsa AAAaetc\n' 'after': 'two.example.com ssh-rsa BBBBetc\none.example.com ssh-rsa AAAAetc\n',
'two.example.com ssh-rsa BBBBetc\n',
'after':
'two.example.com ssh-rsa BBBBetc\n'
'one.example.com ssh-rsa AAAAetc\n',
}) })
def test_key_removal(self): def test_key_removal(self):
@ -89,11 +78,8 @@ class KnownHostsDiffTestCase(unittest.TestCase):
self.assertEqual(diff, { self.assertEqual(diff, {
'before_header': path, 'before_header': path,
'after_header': path, 'after_header': path,
'before': 'before': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n',
'one.example.com ssh-rsa AAAAetc\n' 'after': 'two.example.com ssh-rsa BBBBetc\n',
'two.example.com ssh-rsa BBBBetc\n',
'after':
'two.example.com ssh-rsa BBBBetc\n',
}) })
def test_key_removal_no_change(self): def test_key_removal_no_change(self):
@ -105,8 +91,6 @@ class KnownHostsDiffTestCase(unittest.TestCase):
self.assertEqual(diff, { self.assertEqual(diff, {
'before_header': path, 'before_header': path,
'after_header': path, 'after_header': path,
'before': 'before': 'two.example.com ssh-rsa BBBBetc\n',
'two.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\n',
'after':
'two.example.com ssh-rsa BBBBetc\n',
}) })

View file

@ -21,12 +21,11 @@ __metaclass__ = type
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, mock_open from ansible.compat.tests.mock import patch, mock_open
from ansible.errors import AnsibleParserError from ansible.errors import AnsibleParserError, yaml_strings
from ansible.errors import yaml_strings
from ansible.module_utils.six import PY3 from ansible.module_utils.six import PY3
from ansible.parsing.dataloader import DataLoader from ansible.parsing.dataloader import DataLoader
class TestDataLoader(unittest.TestCase): class TestDataLoader(unittest.TestCase):
def setUp(self): def setUp(self):
@ -39,7 +38,7 @@ class TestDataLoader(unittest.TestCase):
def test_parse_json_from_file(self, mock_def): def test_parse_json_from_file(self, mock_def):
mock_def.return_value = (b"""{"a": 1, "b": 2, "c": 3}""", True) mock_def.return_value = (b"""{"a": 1, "b": 2, "c": 3}""", True)
output = self._loader.load_from_file('dummy_json.txt') output = self._loader.load_from_file('dummy_json.txt')
self.assertEqual(output, dict(a=1,b=2,c=3)) self.assertEqual(output, dict(a=1, b=2, c=3))
@patch.object(DataLoader, '_get_file_contents') @patch.object(DataLoader, '_get_file_contents')
def test_parse_yaml_from_file(self, mock_def): def test_parse_yaml_from_file(self, mock_def):
@ -49,7 +48,7 @@ class TestDataLoader(unittest.TestCase):
c: 3 c: 3
""", True) """, True)
output = self._loader.load_from_file('dummy_yaml.txt') output = self._loader.load_from_file('dummy_yaml.txt')
self.assertEqual(output, dict(a=1,b=2,c=3)) self.assertEqual(output, dict(a=1, b=2, c=3))
@patch.object(DataLoader, '_get_file_contents') @patch.object(DataLoader, '_get_file_contents')
def test_parse_fail_from_file(self, mock_def): def test_parse_fail_from_file(self, mock_def):

View file

@ -19,10 +19,10 @@
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
from ansible.parsing.mod_args import ModuleArgsParser
from ansible.errors import AnsibleParserError
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.errors import AnsibleParserError
from ansible.parsing.mod_args import ModuleArgsParser
class TestModArgsDwim(unittest.TestCase): class TestModArgsDwim(unittest.TestCase):
@ -47,8 +47,8 @@ class TestModArgsDwim(unittest.TestCase):
self._debug(mod, args, to) self._debug(mod, args, to)
self.assertEqual(mod, 'command') self.assertEqual(mod, 'command')
self.assertEqual(args, dict( self.assertEqual(args, dict(
_raw_params = 'echo hi', _raw_params='echo hi',
_uses_shell = True, _uses_shell=True,
)) ))
self.assertIsNone(to) self.assertIsNone(to)
@ -58,7 +58,7 @@ class TestModArgsDwim(unittest.TestCase):
self._debug(mod, args, to) self._debug(mod, args, to)
self.assertEqual(mod, 'command') self.assertEqual(mod, 'command')
self.assertEqual(args, dict( self.assertEqual(args, dict(
_raw_params = 'echo hi', _raw_params='echo hi',
)) ))
self.assertIsNone(to) self.assertIsNone(to)
@ -68,10 +68,10 @@ class TestModArgsDwim(unittest.TestCase):
self._debug(mod, args, to) self._debug(mod, args, to)
self.assertEqual(mod, 'command') self.assertEqual(mod, 'command')
self.assertEqual(args, dict( self.assertEqual(args, dict(
creates = '/tmp/baz', creates='/tmp/baz',
removes = '/tmp/bleep', removes='/tmp/bleep',
_raw_params = '/bin/foo', _raw_params='/bin/foo',
_uses_shell = True, _uses_shell=True,
)) ))
self.assertIsNone(to) self.assertIsNone(to)
@ -127,4 +127,3 @@ class TestModArgsDwim(unittest.TestCase):
m = ModuleArgsParser(dict(ping='data=hi', shell='echo hi')) m = ModuleArgsParser(dict(ping='data=hi', shell='echo hi'))
self.assertRaises(AnsibleParserError, m.parse) self.assertRaises(AnsibleParserError, m.parse)

View file

@ -4,6 +4,7 @@ import unittest
from ansible.parsing.utils.addresses import parse_address from ansible.parsing.utils.addresses import parse_address
class TestParseAddress(unittest.TestCase): class TestParseAddress(unittest.TestCase):
tests = { tests = {

View file

@ -22,6 +22,7 @@ __metaclass__ = type
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.parsing.utils.jsonify import jsonify from ansible.parsing.utils.jsonify import jsonify
class TestJsonify(unittest.TestCase): class TestJsonify(unittest.TestCase):
def test_jsonify_simple(self): def test_jsonify_simple(self):
self.assertEqual(jsonify(dict(a=1, b=2, c=3)), '{"a": 1, "b": 2, "c": 3}') self.assertEqual(jsonify(dict(a=1, b=2, c=3)), '{"a": 1, "b": 2, "c": 3}')

View file

@ -77,11 +77,11 @@ class TestVaultIsEncrypted(unittest.TestCase):
self.assertTrue(vault.is_encrypted(b_data)) self.assertTrue(vault.is_encrypted(b_data))
def test_invalid_text_not_ascii(self): def test_invalid_text_not_ascii(self):
data = u"$ANSIBLE_VAULT;9.9;TEST\n%s"% u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ "
self.assertFalse(vault.is_encrypted(data)) self.assertFalse(vault.is_encrypted(data))
def test_invalid_bytes_not_ascii(self): def test_invalid_bytes_not_ascii(self):
data = u"$ANSIBLE_VAULT;9.9;TEST\n%s"% u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ " data = u"$ANSIBLE_VAULT;9.9;TEST\n%s" % u"ァ ア ィ イ ゥ ウ ェ エ ォ オ カ ガ キ ギ ク グ ケ "
b_data = to_bytes(data, encoding='utf-8') b_data = to_bytes(data, encoding='utf-8')
self.assertFalse(vault.is_encrypted(b_data)) self.assertFalse(vault.is_encrypted(b_data))

View file

@ -74,7 +74,7 @@ class TestVaultEditor(unittest.TestCase):
def tearDown(self): def tearDown(self):
if self._test_dir: if self._test_dir:
pass pass
#shutil.rmtree(self._test_dir) # shutil.rmtree(self._test_dir)
self._test_dir = None self._test_dir = None
def test_methods_exist(self): def test_methods_exist(self):
@ -361,7 +361,7 @@ class TestVaultEditor(unittest.TestCase):
self.assertEqual(src_file_plaintext, new_src_contents) self.assertEqual(src_file_plaintext, new_src_contents)
#self.assertEqual(src_file_plaintext, new_src_contents, # self.assertEqual(src_file_plaintext, new_src_contents,
# 'The decrypted plaintext of the editted file is not the expected contents.') # 'The decrypted plaintext of the editted file is not the expected contents.')
@patch('ansible.parsing.vault.call') @patch('ansible.parsing.vault.call')

View file

@ -26,15 +26,14 @@ try:
except ImportError: except ImportError:
from yaml.parser import ParserError from yaml.parser import ParserError
from ansible.parsing.yaml import dumper from ansible.compat.tests import unittest
from ansible.parsing import vault
from ansible.parsing.yaml import dumper, objects
from ansible.parsing.yaml.loader import AnsibleLoader from ansible.parsing.yaml.loader import AnsibleLoader
from ansible.compat.tests import unittest
from ansible.parsing.yaml import objects
from ansible.parsing import vault
from units.mock.yaml_helper import YamlTestUtils from units.mock.yaml_helper import YamlTestUtils
class TestAnsibleDumper(unittest.TestCase, YamlTestUtils): class TestAnsibleDumper(unittest.TestCase, YamlTestUtils):
def setUp(self): def setUp(self):
self.vault_password = "hunter42" self.vault_password = "hunter42"
@ -43,7 +42,7 @@ class TestAnsibleDumper(unittest.TestCase, YamlTestUtils):
self.stream = self._build_stream() self.stream = self._build_stream()
self.dumper = dumper.AnsibleDumper self.dumper = dumper.AnsibleDumper
def _build_stream(self,yaml_text=None): def _build_stream(self, yaml_text=None):
text = yaml_text or u'' text = yaml_text or u''
stream = io.StringIO(text) stream = io.StringIO(text)
return stream return stream

View file

@ -341,13 +341,14 @@ class TestAnsibleLoaderPlay(unittest.TestCase):
self.assertEqual(self.data[0][u'vars'][u'number'], 1) self.assertEqual(self.data[0][u'vars'][u'number'], 1)
self.assertEqual(self.data[0][u'vars'][u'string'], u'Ansible') self.assertEqual(self.data[0][u'vars'][u'string'], u'Ansible')
self.assertEqual(self.data[0][u'vars'][u'utf8_string'], u'Cafè Eñyei') self.assertEqual(self.data[0][u'vars'][u'utf8_string'], u'Cafè Eñyei')
self.assertEqual(self.data[0][u'vars'][u'dictionary'], self.assertEqual(self.data[0][u'vars'][u'dictionary'], {
{u'webster': u'daniel', u'webster': u'daniel',
u'oed': u'oxford'}) u'oed': u'oxford'
})
self.assertEqual(self.data[0][u'vars'][u'list'], [u'a', u'b', 1, 2]) self.assertEqual(self.data[0][u'vars'][u'list'], [u'a', u'b', 1, 2])
self.assertEqual(self.data[0][u'tasks'], self.assertEqual(self.data[0][u'tasks'], [
[{u'name': u'Test case', u'ping': {u'data': u'{{ utf8_string }}'}}, {u'name': u'Test case', u'ping': {u'data': u'{{ utf8_string }}'}},
{u'name': u'Test 2', u'ping': {u'data': u'Cafè Eñyei'}}, {u'name': u'Test 2', u'ping': {u'data': u'Cafè Eñyei'}},
{u'name': u'Test 3', u'command': u'printf \'Cafè Eñyei\n\''}, {u'name': u'Test 3', u'command': u'printf \'Cafè Eñyei\n\''},
]) ])

View file

@ -104,22 +104,22 @@ class TestAnsibleVaultEncryptedUnicode(unittest.TestCase, YamlTestUtils):
def test_empty_string_init_from_plaintext(self): def test_empty_string_init_from_plaintext(self):
seq = '' seq = ''
avu = self._from_plaintext(seq) avu = self._from_plaintext(seq)
self.assert_values(avu,seq) self.assert_values(avu, seq)
def test_empty_unicode_init_from_plaintext(self): def test_empty_unicode_init_from_plaintext(self):
seq = u'' seq = u''
avu = self._from_plaintext(seq) avu = self._from_plaintext(seq)
self.assert_values(avu,seq) self.assert_values(avu, seq)
def test_string_from_plaintext(self): def test_string_from_plaintext(self):
seq = 'some letters' seq = 'some letters'
avu = self._from_plaintext(seq) avu = self._from_plaintext(seq)
self.assert_values(avu,seq) self.assert_values(avu, seq)
def test_unicode_from_plaintext(self): def test_unicode_from_plaintext(self):
seq = u'some letters' seq = u'some letters'
avu = self._from_plaintext(seq) avu = self._from_plaintext(seq)
self.assert_values(avu,seq) self.assert_values(avu, seq)
def test_unicode_from_plaintext_encode(self): def test_unicode_from_plaintext_encode(self):
seq = u'some text here' seq = u'some text here'

View file

@ -274,4 +274,3 @@ class TestRole(unittest.TestCase):
r = Role.load(i, play=mock_play) r = Role.load(i, play=mock_play)
self.assertEqual(r.get_name(), "foo_complex") self.assertEqual(r.get_name(), "foo_complex")

View file

@ -52,4 +52,3 @@ class TestAttribute(unittest.TestCase):
self.assertTrue(self.one >= self.one) self.assertTrue(self.one >= self.one)
self.assertFalse(self.one >= self.two) self.assertFalse(self.one >= self.two)
self.assertTrue(self.two >= self.one) self.assertTrue(self.two >= self.one)

View file

@ -114,7 +114,7 @@ class TestBase(unittest.TestCase):
data = {'no_log': False, data = {'no_log': False,
'remote_user': None, 'remote_user': None,
'vars': self.assorted_vars, 'vars': self.assorted_vars,
#'check_mode': False, # 'check_mode': False,
'always_run': False, 'always_run': False,
'environment': [], 'environment': [],
'run_once': False, 'run_once': False,
@ -340,8 +340,7 @@ class BaseSubClass(base.Base):
_test_attr_unknown_isa = FieldAttribute(isa='not_a_real_isa', always_post_validate=True) _test_attr_unknown_isa = FieldAttribute(isa='not_a_real_isa', always_post_validate=True)
_test_attr_example = FieldAttribute(isa='string', default='the_default', _test_attr_example = FieldAttribute(isa='string', default='the_default',
always_post_validate=True) always_post_validate=True)
_test_attr_none = FieldAttribute(isa='string', _test_attr_none = FieldAttribute(isa='string', always_post_validate=True)
always_post_validate=True)
_test_attr_preprocess = FieldAttribute(isa='string', default='the default for preprocess') _test_attr_preprocess = FieldAttribute(isa='string', default='the default for preprocess')
_test_attr_method = FieldAttribute(isa='string', default='some attr with a getter', _test_attr_method = FieldAttribute(isa='string', default='some attr with a getter',
always_post_validate=True) always_post_validate=True)

View file

@ -19,9 +19,10 @@
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
from ansible.compat.tests import unittest
from ansible.playbook.block import Block from ansible.playbook.block import Block
from ansible.playbook.task import Task from ansible.playbook.task import Task
from ansible.compat.tests import unittest
class TestBlock(unittest.TestCase): class TestBlock(unittest.TestCase):
@ -39,24 +40,24 @@ class TestBlock(unittest.TestCase):
def test_load_block_simple(self): def test_load_block_simple(self):
ds = dict( ds = dict(
block = [], block=[],
rescue = [], rescue=[],
always = [], always=[],
#otherwise = [], # otherwise=[],
) )
b = Block.load(ds) b = Block.load(ds)
self.assertEqual(b.block, []) self.assertEqual(b.block, [])
self.assertEqual(b.rescue, []) self.assertEqual(b.rescue, [])
self.assertEqual(b.always, []) self.assertEqual(b.always, [])
# not currently used # not currently used
#self.assertEqual(b.otherwise, []) # self.assertEqual(b.otherwise, [])
def test_load_block_with_tasks(self): def test_load_block_with_tasks(self):
ds = dict( ds = dict(
block = [dict(action='block')], block=[dict(action='block')],
rescue = [dict(action='rescue')], rescue=[dict(action='rescue')],
always = [dict(action='always')], always=[dict(action='always')],
#otherwise = [dict(action='otherwise')], # otherwise=[dict(action='otherwise')],
) )
b = Block.load(ds) b = Block.load(ds)
self.assertEqual(len(b.block), 1) self.assertEqual(len(b.block), 1)
@ -66,8 +67,8 @@ class TestBlock(unittest.TestCase):
self.assertEqual(len(b.always), 1) self.assertEqual(len(b.always), 1)
self.assertIsInstance(b.always[0], Task) self.assertIsInstance(b.always[0], Task)
# not currently used # not currently used
#self.assertEqual(len(b.otherwise), 1) # self.assertEqual(len(b.otherwise), 1)
#self.assertIsInstance(b.otherwise[0], Task) # self.assertIsInstance(b.otherwise[0], Task)
def test_load_implicit_block(self): def test_load_implicit_block(self):
ds = [dict(action='foo')] ds = [dict(action='foo')]
@ -77,12 +78,11 @@ class TestBlock(unittest.TestCase):
def test_deserialize(self): def test_deserialize(self):
ds = dict( ds = dict(
block = [dict(action='block')], block=[dict(action='block')],
rescue = [dict(action='rescue')], rescue=[dict(action='rescue')],
always = [dict(action='always')], always=[dict(action='always')],
) )
b = Block.load(ds) b = Block.load(ds)
data = dict(parent = ds, parent_type = 'Block') data = dict(parent=ds, parent_type='Block')
b.deserialize(data) b.deserialize(data)
self.assertIsInstance(b._parent, Block) self.assertIsInstance(b._parent, Block)

View file

@ -97,11 +97,11 @@ class TestConditional(unittest.TestCase):
} }
when = [u"some_dict.some_dict_key1 == hostvars['host3']"] when = [u"some_dict.some_dict_key1 == hostvars['host3']"]
#self._eval_con(when, variables) # self._eval_con(when, variables)
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegexp(errors.AnsibleError,
"The conditional check 'some_dict.some_dict_key1 == hostvars\['host3'\]' failed", "The conditional check 'some_dict.some_dict_key1 == hostvars\['host3'\]' failed",
#"The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed", # "The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed",
#"The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed.", # "The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed.",
self._eval_con, self._eval_con,
when, variables) when, variables)

View file

@ -222,7 +222,7 @@ class TestLoadListOfTasks(unittest.TestCase, MixinForMocks):
# TODO/FIXME: do this non deprecated way # TODO/FIXME: do this non deprecated way
def test_one_parent_include_tags(self): def test_one_parent_include_tags(self):
ds = [{'include': '/dev/null/includes/test_include.yml', ds = [{'include': '/dev/null/includes/test_include.yml',
#'vars': {'tags': ['test_one_parent_include_tags_tag1', 'and_another_tag2']} # 'vars': {'tags': ['test_one_parent_include_tags_tag1', 'and_another_tag2']}
'tags': ['test_one_parent_include_tags_tag1', 'and_another_tag2'] 'tags': ['test_one_parent_include_tags_tag1', 'and_another_tag2']
} }
] ]
@ -281,7 +281,7 @@ class TestLoadListOfTasks(unittest.TestCase, MixinForMocks):
'include': '/dev/null/includes/static_test_include.yml', 'include': '/dev/null/includes/static_test_include.yml',
'static': False 'static': False
}] }]
#a_block = Block() # a_block = Block()
ti_ds = {'include': '/dev/null/includes/ssdftatic_test_include.yml'} ti_ds = {'include': '/dev/null/includes/ssdftatic_test_include.yml'}
a_task_include = TaskInclude() a_task_include = TaskInclude()
ti = a_task_include.load(ti_ds) ti = a_task_include.load(ti_ds)

View file

@ -21,30 +21,30 @@ __metaclass__ = type
import os import os
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible import constants as C from ansible import constants as C
from ansible.cli import CLI from ansible.cli import CLI
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible.errors import AnsibleError, AnsibleParserError from ansible.errors import AnsibleError, AnsibleParserError
from ansible.module_utils.six.moves import shlex_quote from ansible.module_utils.six.moves import shlex_quote
from ansible.playbook.play_context import PlayContext from ansible.playbook.play_context import PlayContext
from units.mock.loader import DictDataLoader from units.mock.loader import DictDataLoader
class TestPlayContext(unittest.TestCase): class TestPlayContext(unittest.TestCase):
def setUp(self): def setUp(self):
self._parser = CLI.base_parser( self._parser = CLI.base_parser(
runas_opts = True, runas_opts=True,
meta_opts = True, meta_opts=True,
runtask_opts = True, runtask_opts=True,
vault_opts = True, vault_opts=True,
async_opts = True, async_opts=True,
connect_opts = True, connect_opts=True,
subset_opts = True, subset_opts=True,
check_opts = True, check_opts=True,
inventory_opts = True, inventory_opts=True,
) )
def tearDown(self): def tearDown(self):
@ -95,8 +95,8 @@ class TestPlayContext(unittest.TestCase):
mock_task.delegate_to = None mock_task.delegate_to = None
all_vars = dict( all_vars = dict(
ansible_connection = 'mock_inventory', ansible_connection='mock_inventory',
ansible_ssh_port = 4321, ansible_ssh_port=4321,
) )
mock_templar = MagicMock() mock_templar = MagicMock()
@ -152,7 +152,7 @@ class TestPlayContext(unittest.TestCase):
cmd = play_context.make_become_cmd(cmd=default_cmd, executable=default_exe) cmd = play_context.make_become_cmd(cmd=default_cmd, executable=default_exe)
self.assertEqual( self.assertEqual(
cmd, cmd,
"""%s %s -p "%s" -u %s %s -c 'echo %s; %s'""" % (sudo_exe, sudo_flags.replace('-n',''), play_context.prompt, play_context.become_user, default_exe, """%s %s -p "%s" -u %s %s -c 'echo %s; %s'""" % (sudo_exe, sudo_flags.replace('-n', ''), play_context.prompt, play_context.become_user, default_exe,
play_context.success_key, default_cmd) play_context.success_key, default_cmd)
) )
@ -207,52 +207,76 @@ class TestPlayContext(unittest.TestCase):
class TestTaskAndVariableOverrride(unittest.TestCase): class TestTaskAndVariableOverrride(unittest.TestCase):
inventory_vars = ( inventory_vars = (
('preferred_names', (
dict(ansible_connection='local', 'preferred_names',
dict(
ansible_connection='local',
ansible_user='ansibull', ansible_user='ansibull',
ansible_become_user='ansibull', ansible_become_user='ansibull',
ansible_become_method='su', ansible_become_method='su',
ansible_become_pass='ansibullwuzhere',), ansible_become_pass='ansibullwuzhere',
dict(connection='local', ),
dict(
connection='local',
remote_user='ansibull', remote_user='ansibull',
become_user='ansibull', become_user='ansibull',
become_method='su', become_method='su',
become_pass='ansibullwuzhere',) become_pass='ansibullwuzhere',
)
), ),
('alternate_names', (
'alternate_names',
dict(ansible_become_password='ansibullwuzhere',), dict(ansible_become_password='ansibullwuzhere',),
dict(become_pass='ansibullwuzhere',) dict(become_pass='ansibullwuzhere',)
), ),
('deprecated_names', (
dict(ansible_ssh_user='ansibull', 'deprecated_names',
dict(
ansible_ssh_user='ansibull',
ansible_sudo_user='ansibull', ansible_sudo_user='ansibull',
ansible_sudo_pass='ansibullwuzhere',), ansible_sudo_pass='ansibullwuzhere',
dict(remote_user='ansibull', ),
dict(
remote_user='ansibull',
become_method='sudo', become_method='sudo',
become_user='ansibull', become_user='ansibull',
become_pass='ansibullwuzhere',) become_pass='ansibullwuzhere',
)
), ),
('deprecated_names2', (
dict(ansible_ssh_user='ansibull', 'deprecated_names2',
dict(
ansible_ssh_user='ansibull',
ansible_su_user='ansibull', ansible_su_user='ansibull',
ansible_su_pass='ansibullwuzhere',), ansible_su_pass='ansibullwuzhere',
dict(remote_user='ansibull', ),
dict(
remote_user='ansibull',
become_method='su', become_method='su',
become_user='ansibull', become_user='ansibull',
become_pass='ansibullwuzhere',) become_pass='ansibullwuzhere',
)
), ),
('deprecated_alt_names', (
'deprecated_alt_names',
dict(ansible_sudo_password='ansibullwuzhere',), dict(ansible_sudo_password='ansibullwuzhere',),
dict(become_method='sudo', dict(
become_pass='ansibullwuzhere',) become_method='sudo',
become_pass='ansibullwuzhere',
)
), ),
('deprecated_alt_names2', (
'deprecated_alt_names2',
dict(ansible_su_password='ansibullwuzhere',), dict(ansible_su_password='ansibullwuzhere',),
dict(become_method='su', dict(
become_pass='ansibullwuzhere',) become_method='su',
become_pass='ansibullwuzhere',
)
), ),
('deprecated_and_preferred_names', (
dict(ansible_user='ansibull', 'deprecated_and_preferred_names',
dict(
ansible_user='ansibull',
ansible_ssh_user='badbull', ansible_ssh_user='badbull',
ansible_become_user='ansibull', ansible_become_user='ansibull',
ansible_sudo_user='badbull', ansible_sudo_user='badbull',
@ -260,25 +284,27 @@ class TestTaskAndVariableOverrride(unittest.TestCase):
ansible_become_pass='ansibullwuzhere', ansible_become_pass='ansibullwuzhere',
ansible_sudo_pass='badbull', ansible_sudo_pass='badbull',
), ),
dict(connection='local', dict(
connection='local',
remote_user='ansibull', remote_user='ansibull',
become_user='ansibull', become_user='ansibull',
become_method='su', become_method='su',
become_pass='ansibullwuzhere',) become_pass='ansibullwuzhere',
)
), ),
) )
def setUp(self): def setUp(self):
parser = CLI.base_parser( parser = CLI.base_parser(
runas_opts = True, runas_opts=True,
meta_opts = True, meta_opts=True,
runtask_opts = True, runtask_opts=True,
vault_opts = True, vault_opts=True,
async_opts = True, async_opts=True,
connect_opts = True, connect_opts=True,
subset_opts = True, subset_opts=True,
check_opts = True, check_opts=True,
inventory_opts = True, inventory_opts=True,
) )
(options, args) = parser.parse_args(['-vv', '--check']) (options, args) = parser.parse_args(['-vv', '--check'])

View file

@ -21,13 +21,13 @@ __metaclass__ = type
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock from ansible.compat.tests.mock import patch, MagicMock
from ansible.errors import AnsibleError, AnsibleParserError from ansible.errors import AnsibleError, AnsibleParserError
from ansible.playbook import Playbook from ansible.playbook import Playbook
from ansible.vars.manager import VariableManager from ansible.vars.manager import VariableManager
from units.mock.loader import DictDataLoader from units.mock.loader import DictDataLoader
class TestPlaybook(unittest.TestCase): class TestPlaybook(unittest.TestCase):
def setUp(self): def setUp(self):
@ -42,7 +42,7 @@ class TestPlaybook(unittest.TestCase):
def test_basic_playbook(self): def test_basic_playbook(self):
fake_loader = DictDataLoader({ fake_loader = DictDataLoader({
"test_file.yml":""" "test_file.yml": """
- hosts: all - hosts: all
""", """,
}) })

View file

@ -23,6 +23,7 @@ from ansible.compat.tests import unittest
from ansible.playbook.taggable import Taggable from ansible.playbook.taggable import Taggable
from units.mock.loader import DictDataLoader from units.mock.loader import DictDataLoader
class TaggableTestObj(Taggable): class TaggableTestObj(Taggable):
def __init__(self): def __init__(self):

View file

@ -19,18 +19,20 @@
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
from ansible.playbook.task import Task
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.playbook.task import Task
basic_shell_task = dict( basic_shell_task = dict(
name = 'Test Task', name='Test Task',
shell = 'echo hi' shell='echo hi'
) )
kv_shell_task = dict( kv_shell_task = dict(
action = 'shell echo hi' action='shell echo hi'
) )
class TestTask(unittest.TestCase): class TestTask(unittest.TestCase):
def setUp(self): def setUp(self):
@ -66,7 +68,7 @@ class TestTask(unittest.TestCase):
def test_task_auto_name(self): def test_task_auto_name(self):
assert 'name' not in kv_shell_task assert 'name' not in kv_shell_task
t = Task.load(kv_shell_task) t = Task.load(kv_shell_task)
#self.assertEqual(t.name, 'shell echo hi') # self.assertEqual(t.name, 'shell echo hi')
def test_task_auto_name_with_role(self): def test_task_auto_name_with_role(self):
pass pass

View file

@ -436,10 +436,19 @@ class TestActionBase(unittest.TestCase):
action_base._make_tmp_path.return_value = '/the/tmp/path' action_base._make_tmp_path.return_value = '/the/tmp/path'
action_base._low_level_execute_command.return_value = dict(stdout='{"rc": 0, "stdout": "ok"}') action_base._low_level_execute_command.return_value = dict(stdout='{"rc": 0, "stdout": "ok"}')
self.assertEqual(action_base._execute_module(module_name=None, module_args=None), dict(_ansible_parsed=True, rc=0, stdout="ok", stdout_lines=['ok'])) self.assertEqual(action_base._execute_module(module_name=None, module_args=None), dict(_ansible_parsed=True, rc=0, stdout="ok", stdout_lines=['ok']))
self.assertEqual(action_base._execute_module(module_name='foo', self.assertEqual(
module_args=dict(z=9, y=8, x=7), task_vars=dict(a=1)), action_base._execute_module(
dict(_ansible_parsed=True, rc=0, stdout="ok", module_name='foo',
stdout_lines=['ok'])) module_args=dict(z=9, y=8, x=7),
task_vars=dict(a=1)
),
dict(
_ansible_parsed=True,
rc=0,
stdout="ok",
stdout_lines=['ok'],
)
)
# test with needing/removing a remote tmp path # test with needing/removing a remote tmp path
action_base._configure_module.return_value = ('old', '#!/usr/bin/python', 'this is the module data', 'path') action_base._configure_module.return_value = ('old', '#!/usr/bin/python', 'this is the module data', 'path')
@ -525,9 +534,9 @@ class TestActionBaseCleanReturnedData(unittest.TestCase):
mock_shared_loader_obj.connection_loader = mock_connection_loader mock_shared_loader_obj.connection_loader = mock_connection_loader
mock_connection = MagicMock() mock_connection = MagicMock()
#mock_connection._shell.env_prefix.side_effect = env_prefix # mock_connection._shell.env_prefix.side_effect = env_prefix
#action_base = DerivedActionBase(mock_task, mock_connection, play_context, None, None, None) # action_base = DerivedActionBase(mock_task, mock_connection, play_context, None, None, None)
action_base = DerivedActionBase(task=None, action_base = DerivedActionBase(task=None,
connection=mock_connection, connection=mock_connection,
play_context=None, play_context=None,
@ -535,7 +544,7 @@ class TestActionBaseCleanReturnedData(unittest.TestCase):
templar=None, templar=None,
shared_loader_obj=mock_shared_loader_obj) shared_loader_obj=mock_shared_loader_obj)
data = {'ansible_playbook_python': '/usr/bin/python', data = {'ansible_playbook_python': '/usr/bin/python',
#'ansible_rsync_path': '/usr/bin/rsync', # 'ansible_rsync_path': '/usr/bin/rsync',
'ansible_python_interpreter': '/usr/bin/python', 'ansible_python_interpreter': '/usr/bin/python',
'ansible_ssh_some_var': 'whatever', 'ansible_ssh_some_var': 'whatever',
'ansible_ssh_host_key_somehost': 'some key here', 'ansible_ssh_host_key_somehost': 'some key here',
@ -610,7 +619,7 @@ class TestActionBaseParseReturnedData(unittest.TestCase):
self.assertTrue(res['ansible_facts']) self.assertTrue(res['ansible_facts'])
self.assertIn('ansible_blip', res['ansible_facts']) self.assertIn('ansible_blip', res['ansible_facts'])
# TODO: Should this be an AnsibleUnsafe? # TODO: Should this be an AnsibleUnsafe?
#self.assertIsInstance(res['ansible_facts'], AnsibleUnsafe) # self.assertIsInstance(res['ansible_facts'], AnsibleUnsafe)
def test_json_facts_add_host(self): def test_json_facts_add_host(self):
action_base = self._action_base() action_base = self._action_base()
@ -630,4 +639,4 @@ class TestActionBaseParseReturnedData(unittest.TestCase):
self.assertIn('ansible_blip', res['ansible_facts']) self.assertIn('ansible_blip', res['ansible_facts'])
self.assertIn('add_host', res) self.assertIn('add_host', res)
# TODO: Should this be an AnsibleUnsafe? # TODO: Should this be an AnsibleUnsafe?
#self.assertIsInstance(res['ansible_facts'], AnsibleUnsafe) # self.assertIsInstance(res['ansible_facts'], AnsibleUnsafe)

View file

@ -24,6 +24,7 @@ from ansible.compat.tests.mock import patch, MagicMock, Mock
from ansible.plugins.action.raw import ActionModule from ansible.plugins.action.raw import ActionModule
from ansible.playbook.task import Task from ansible.playbook.task import Task
class TestCopyResultExclude(unittest.TestCase): class TestCopyResultExclude(unittest.TestCase):
def setUp(self): def setUp(self):
@ -38,7 +39,6 @@ class TestCopyResultExclude(unittest.TestCase):
# Issue: https://github.com/ansible/ansible/issues/16054 # Issue: https://github.com/ansible/ansible/issues/16054
# PR: https://github.com/ansible/ansible/pull/16085 # PR: https://github.com/ansible/ansible/pull/16085
def test_raw_executable_is_not_empty_string(self): def test_raw_executable_is_not_empty_string(self):
play_context = Mock() play_context = Mock()
@ -50,7 +50,7 @@ class TestCopyResultExclude(unittest.TestCase):
play_context.check_mode = False play_context.check_mode = False
self.mock_am = ActionModule(task, connection, play_context, loader=None, templar=None, shared_loader_obj=None) self.mock_am = ActionModule(task, connection, play_context, loader=None, templar=None, shared_loader_obj=None)
self.mock_am._low_level_execute_command = Mock(return_value = {}) self.mock_am._low_level_execute_command = Mock(return_value={})
self.mock_am.display = Mock() self.mock_am.display = Mock()
self.mock_am.run() self.mock_am.run()
@ -83,7 +83,7 @@ class TestCopyResultExclude(unittest.TestCase):
play_context.check_mode = False play_context.check_mode = False
self.mock_am = ActionModule(task, connection, play_context, loader=None, templar=None, shared_loader_obj=None) self.mock_am = ActionModule(task, connection, play_context, loader=None, templar=None, shared_loader_obj=None)
self.mock_am._low_level_execute_command = Mock(return_value = {}) self.mock_am._low_level_execute_command = Mock(return_value={})
self.mock_am.display = Mock() self.mock_am.display = Mock()
self.assertEqual(task.environment, None) self.assertEqual(task.environment, None)
@ -100,10 +100,8 @@ class TestCopyResultExclude(unittest.TestCase):
play_context.check_mode = False play_context.check_mode = False
self.mock_am = ActionModule(task, connection, play_context, loader=None, templar=None, shared_loader_obj=None) self.mock_am = ActionModule(task, connection, play_context, loader=None, templar=None, shared_loader_obj=None)
self.mock_am._low_level_execute_command = Mock(return_value = {}) self.mock_am._low_level_execute_command = Mock(return_value={})
self.mock_am.display = Mock() self.mock_am.display = Mock()
self.mock_am.run(task_vars={'a': 'b'}) self.mock_am.run(task_vars={'a': 'b'})
self.assertEqual(task.environment, None) self.assertEqual(task.environment, None)

View file

@ -17,11 +17,12 @@ import unittest
import yaml import yaml
from pprint import pprint from pprint import pprint
from ansible import plugins
import ansible.plugins import ansible.plugins
from ansible.compat.tests.mock import patch, MagicMock from ansible.compat.tests.mock import patch, MagicMock
from ansible.plugins.action.synchronize import ActionModule from ansible.plugins.action.synchronize import ActionModule
# Getting the incoming and outgoing task vars from the plugin's run method # Getting the incoming and outgoing task vars from the plugin's run method
''' '''
@ -41,8 +42,6 @@ with open('task_vars.json', 'wb') as f:
''' '''
class TaskMock(object): class TaskMock(object):
args = {'src': u'/tmp/deleteme', args = {'src': u'/tmp/deleteme',
'dest': '/tmp/deleteme', 'dest': '/tmp/deleteme',
@ -52,16 +51,19 @@ class TaskMock(object):
become_user = None become_user = None
become_method = None become_method = None
class StdinMock(object): class StdinMock(object):
shell = None shell = None
class ConnectionMock(object): class ConnectionMock(object):
ismock = True ismock = True
_play_context = None _play_context = None
#transport = 'ssh' # transport = 'ssh'
transport = None transport = None
_new_stdin = StdinMock() _new_stdin = StdinMock()
class PlayContextMock(object): class PlayContextMock(object):
shell = None shell = None
private_key_file = None private_key_file = None
@ -75,13 +77,16 @@ class PlayContextMock(object):
remote_user = None remote_user = None
password = None password = None
class ModuleLoaderMock(object): class ModuleLoaderMock(object):
def find_plugin(self, module_name, mod_type): def find_plugin(self, module_name, mod_type):
pass pass
class SharedLoaderMock(object): class SharedLoaderMock(object):
module_loader = ModuleLoaderMock() module_loader = ModuleLoaderMock()
class SynchronizeTester(object): class SynchronizeTester(object):
''' A wrapper for mocking out synchronize environments ''' ''' A wrapper for mocking out synchronize environments '''
@ -96,7 +101,6 @@ class SynchronizeTester(object):
final_task_vars = None final_task_vars = None
execute_called = False execute_called = False
def _execute_module(self, module_name, module_args=None, task_vars=None): def _execute_module(self, module_name, module_args=None, task_vars=None):
self.execute_called = True self.execute_called = True
self.final_module_args = module_args self.final_module_args = module_args
@ -114,7 +118,7 @@ class SynchronizeTester(object):
if '_play_context' in test_meta: if '_play_context' in test_meta:
if test_meta['_play_context']: if test_meta['_play_context']:
self.task.args = {} self.task.args = {}
for k,v in test_meta['_play_context'].items(): for (k, v) in test_meta['_play_context'].items():
if v == 'None': if v == 'None':
v = None v = None
setattr(self._play_context, k, v) setattr(self._play_context, k, v)
@ -123,8 +127,8 @@ class SynchronizeTester(object):
if '_task' in test_meta: if '_task' in test_meta:
if test_meta['_task']: if test_meta['_task']:
self.task.args = {} self.task.args = {}
for k,v in test_meta['_task'].items(): for (k, v) in test_meta['_task'].items():
#import epdb; epdb.st() # import epdb; epdb.st()
if v == 'None': if v == 'None':
v = None v = None
setattr(self.task, k, v) setattr(self.task, k, v)
@ -133,32 +137,30 @@ class SynchronizeTester(object):
if 'task_args' in test_meta: if 'task_args' in test_meta:
if test_meta['task_args']: if test_meta['task_args']:
self.task.args = {} self.task.args = {}
for k,v in test_meta['task_args'].items(): for (k, v) in test_meta['task_args'].items():
self.task.args[k] = v self.task.args[k] = v
# load inital task vars # load inital task vars
invarspath = os.path.join(fixturepath, invarspath = os.path.join(fixturepath, test_meta.get('fixtures', {}).get('taskvars_in', 'taskvars_in.json'))
test_meta.get('fixtures', {}).get('taskvars_in', 'taskvars_in.json'))
with open(invarspath, 'rb') as f: with open(invarspath, 'rb') as f:
fdata = f.read() fdata = f.read()
fdata = fdata.decode("utf-8") fdata = fdata.decode("utf-8")
in_task_vars = json.loads(fdata) in_task_vars = json.loads(fdata)
# load expected final task vars # load expected final task vars
outvarspath = os.path.join(fixturepath, outvarspath = os.path.join(fixturepath, test_meta.get('fixtures', {}).get('taskvars_out', 'taskvars_out.json'))
test_meta.get('fixtures', {}).get('taskvars_out', 'taskvars_out.json'))
with open(outvarspath, 'rb') as f: with open(outvarspath, 'rb') as f:
fdata = f.read() fdata = f.read()
fdata = fdata.decode("utf-8") fdata = fdata.decode("utf-8")
out_task_vars = json.loads(fdata) out_task_vars = json.loads(fdata)
# fixup the connection # fixup the connection
for k,v in test_meta['connection'].items(): for (k, v) in test_meta['connection'].items():
setattr(self.connection, k, v) setattr(self.connection, k, v)
# fixup the hostvars # fixup the hostvars
if test_meta['hostvars']: if test_meta['hostvars']:
for k,v in test_meta['hostvars'].items(): for (k, v) in test_meta['hostvars'].items():
in_task_vars['hostvars'][k] = v in_task_vars['hostvars'][k] = v
# initalize and run the module # initalize and run the module
@ -170,7 +172,7 @@ class SynchronizeTester(object):
# run assertions # run assertions
for check in test_meta['asserts']: for check in test_meta['asserts']:
value = eval(check) value = eval(check)
#if not value: # if not value:
# print(check, value) # print(check, value)
# import epdb; epdb.st() # import epdb; epdb.st()
assert value, check assert value, check
@ -190,54 +192,52 @@ class FakePluginLoader(object):
class TestSynchronizeAction(unittest.TestCase): class TestSynchronizeAction(unittest.TestCase):
fixturedir = os.path.dirname(__file__) fixturedir = os.path.dirname(__file__)
fixturedir = os.path.join(fixturedir, 'fixtures', 'synchronize') fixturedir = os.path.join(fixturedir, 'fixtures', 'synchronize')
#print(basedir) # print(basedir)
@patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader) @patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader)
def test_basic(self): def test_basic(self):
x = SynchronizeTester() x = SynchronizeTester()
x.runtest(fixturepath=os.path.join(self.fixturedir,'basic')) x.runtest(fixturepath=os.path.join(self.fixturedir, 'basic'))
@patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader) @patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader)
def test_basic_become(self): def test_basic_become(self):
x = SynchronizeTester() x = SynchronizeTester()
x.runtest(fixturepath=os.path.join(self.fixturedir,'basic_become')) x.runtest(fixturepath=os.path.join(self.fixturedir, 'basic_become'))
@patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader) @patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader)
def test_basic_become_cli(self): def test_basic_become_cli(self):
# --become on the cli sets _play_context.become # --become on the cli sets _play_context.become
x = SynchronizeTester() x = SynchronizeTester()
x.runtest(fixturepath=os.path.join(self.fixturedir,'basic_become_cli')) x.runtest(fixturepath=os.path.join(self.fixturedir, 'basic_become_cli'))
@patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader) @patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader)
def test_basic_vagrant(self): def test_basic_vagrant(self):
# simple vagrant example # simple vagrant example
x = SynchronizeTester() x = SynchronizeTester()
x.runtest(fixturepath=os.path.join(self.fixturedir,'basic_vagrant')) x.runtest(fixturepath=os.path.join(self.fixturedir, 'basic_vagrant'))
@patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader) @patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader)
def test_basic_vagrant_sudo(self): def test_basic_vagrant_sudo(self):
# vagrant plus sudo # vagrant plus sudo
x = SynchronizeTester() x = SynchronizeTester()
x.runtest(fixturepath=os.path.join(self.fixturedir,'basic_vagrant_sudo')) x.runtest(fixturepath=os.path.join(self.fixturedir, 'basic_vagrant_sudo'))
@patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader) @patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader)
def test_basic_vagrant_become_cli(self): def test_basic_vagrant_become_cli(self):
# vagrant plus sudo # vagrant plus sudo
x = SynchronizeTester() x = SynchronizeTester()
x.runtest(fixturepath=os.path.join(self.fixturedir,'basic_vagrant_become_cli')) x.runtest(fixturepath=os.path.join(self.fixturedir, 'basic_vagrant_become_cli'))
@patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader) @patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader)
def test_delegate_remote(self): def test_delegate_remote(self):
# delegate to other remote host # delegate to other remote host
x = SynchronizeTester() x = SynchronizeTester()
x.runtest(fixturepath=os.path.join(self.fixturedir,'delegate_remote')) x.runtest(fixturepath=os.path.join(self.fixturedir, 'delegate_remote'))
@patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader) @patch('ansible.plugins.action.synchronize.connection_loader', FakePluginLoader)
def test_delegate_remote_su(self): def test_delegate_remote_su(self):
# delegate to other remote host with su enabled # delegate to other remote host with su enabled
x = SynchronizeTester() x = SynchronizeTester()
x.runtest(fixturepath=os.path.join(self.fixturedir,'delegate_remote_su')) x.runtest(fixturepath=os.path.join(self.fixturedir, 'delegate_remote_su'))

View file

@ -25,19 +25,18 @@ from ansible.compat.tests import mock
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.errors import AnsibleError from ansible.errors import AnsibleError
from ansible.playbook.play_context import PlayContext from ansible.playbook.play_context import PlayContext
from ansible.plugins.connection import ConnectionBase from ansible.plugins.connection import ConnectionBase
#from ansible.plugins.connection.accelerate import Connection as AccelerateConnection # from ansible.plugins.connection.accelerate import Connection as AccelerateConnection
#from ansible.plugins.connection.chroot import Connection as ChrootConnection # from ansible.plugins.connection.chroot import Connection as ChrootConnection
#from ansible.plugins.connection.funcd import Connection as FuncdConnection # from ansible.plugins.connection.funcd import Connection as FuncdConnection
#from ansible.plugins.connection.jail import Connection as JailConnection # from ansible.plugins.connection.jail import Connection as JailConnection
#from ansible.plugins.connection.libvirt_lxc import Connection as LibvirtLXCConnection # from ansible.plugins.connection.libvirt_lxc import Connection as LibvirtLXCConnection
from ansible.plugins.connection.lxc import Connection as LxcConnection from ansible.plugins.connection.lxc import Connection as LxcConnection
from ansible.plugins.connection.local import Connection as LocalConnection from ansible.plugins.connection.local import Connection as LocalConnection
from ansible.plugins.connection.paramiko_ssh import Connection as ParamikoConnection from ansible.plugins.connection.paramiko_ssh import Connection as ParamikoConnection
from ansible.plugins.connection.ssh import Connection as SSHConnection from ansible.plugins.connection.ssh import Connection as SSHConnection
from ansible.plugins.connection.docker import Connection as DockerConnection from ansible.plugins.connection.docker import Connection as DockerConnection
#from ansible.plugins.connection.winrm import Connection as WinRmConnection # from ansible.plugins.connection.winrm import Connection as WinRmConnection
from ansible.plugins.connection.network_cli import Connection as NetworkCliConnection from ansible.plugins.connection.network_cli import Connection as NetworkCliConnection
@ -68,19 +67,26 @@ class TestConnectionBaseClass(unittest.TestCase):
def test_subclass_success(self): def test_subclass_success(self):
class ConnectionModule3(ConnectionBase): class ConnectionModule3(ConnectionBase):
@property @property
def transport(self): def transport(self):
pass pass
def _connect(self): def _connect(self):
pass pass
def exec_command(self): def exec_command(self):
pass pass
def put_file(self): def put_file(self):
pass pass
def fetch_file(self): def fetch_file(self):
pass pass
def close(self): def close(self):
pass pass
self.assertIsInstance(ConnectionModule3(self.play_context, self.in_stream), ConnectionModule3) self.assertIsInstance(ConnectionModule3(self.play_context, self.in_stream), ConnectionModule3)
# def test_accelerate_connection_module(self): # def test_accelerate_connection_module(self):
@ -190,17 +196,23 @@ debug1: Sending command: /bin/sh -c 'sudo -H -S -p "[sudo via ansible, key=ouzm
''' '''
class ConnectionFoo(ConnectionBase): class ConnectionFoo(ConnectionBase):
@property @property
def transport(self): def transport(self):
pass pass
def _connect(self): def _connect(self):
pass pass
def exec_command(self): def exec_command(self):
pass pass
def put_file(self): def put_file(self):
pass pass
def fetch_file(self): def fetch_file(self):
pass pass
def close(self): def close(self):
pass pass

View file

@ -28,7 +28,6 @@ from io import StringIO
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock, PropertyMock from ansible.compat.tests.mock import patch, MagicMock, PropertyMock
from ansible.errors import AnsibleConnectionFailure from ansible.errors import AnsibleConnectionFailure
from ansible.playbook.play_context import PlayContext from ansible.playbook.play_context import PlayContext
@ -38,6 +37,7 @@ builtin_import = __import__
mock_ncclient = MagicMock(name='ncclient') mock_ncclient = MagicMock(name='ncclient')
def import_mock(name, *args): def import_mock(name, *args):
if name.startswith('ncclient'): if name.startswith('ncclient'):
return mock_ncclient return mock_ncclient
@ -50,6 +50,7 @@ else:
with patch('__builtin__.__import__', side_effect=import_mock): with patch('__builtin__.__import__', side_effect=import_mock):
from ansible.plugins.connection import netconf from ansible.plugins.connection import netconf
class TestNetconfConnectionClass(unittest.TestCase): class TestNetconfConnectionClass(unittest.TestCase):
def test_netconf_init(self): def test_netconf_init(self):
@ -117,5 +118,3 @@ class TestNetconfConnectionClass(unittest.TestCase):
self.assertEqual(1, rc) self.assertEqual(1, rc)
self.assertEqual('', out) self.assertEqual('', out)
self.assertEqual('unable to parse request', err) self.assertEqual('unable to parse request', err)

View file

@ -143,7 +143,6 @@ class TestConnectionClass(unittest.TestCase):
self.assertFalse(mock_open_shell.called) self.assertFalse(mock_open_shell.called)
mock_send.assert_called_with({'command': b'command'}) mock_send.assert_called_with({'command': b'command'})
def test_network_cli_send(self): def test_network_cli_send(self):
pc = PlayContext() pc = PlayContext()
new_stdin = StringIO() new_stdin = StringIO()

View file

@ -21,19 +21,18 @@ from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
from io import StringIO from io import StringIO
import pytest import pytest
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock, PropertyMock
from ansible import constants as C from ansible import constants as C
from ansible.compat.selectors import SelectorKey, EVENT_READ from ansible.compat.selectors import SelectorKey, EVENT_READ
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock, PropertyMock
from ansible.errors import AnsibleError, AnsibleConnectionFailure, AnsibleFileNotFound from ansible.errors import AnsibleError, AnsibleConnectionFailure, AnsibleFileNotFound
from ansible.module_utils.six.moves import shlex_quote from ansible.module_utils.six.moves import shlex_quote
from ansible.module_utils._text import to_bytes
from ansible.playbook.play_context import PlayContext from ansible.playbook.play_context import PlayContext
from ansible.plugins.connection import ssh from ansible.plugins.connection import ssh
from ansible.module_utils._text import to_bytes
class TestConnectionBaseClass(unittest.TestCase): class TestConnectionBaseClass(unittest.TestCase):
@ -123,10 +122,10 @@ class TestConnectionBaseClass(unittest.TestCase):
# test examining output for prompt # test examining output for prompt
conn._flags = dict( conn._flags = dict(
become_prompt = False, become_prompt=False,
become_success = False, become_success=False,
become_error = False, become_error=False,
become_nopasswd_error = False, become_nopasswd_error=False,
) )
pc.prompt = True pc.prompt = True
@ -140,10 +139,10 @@ class TestConnectionBaseClass(unittest.TestCase):
# test examining output for become prompt # test examining output for become prompt
conn._flags = dict( conn._flags = dict(
become_prompt = False, become_prompt=False,
become_success = False, become_success=False,
become_error = False, become_error=False,
become_nopasswd_error = False, become_nopasswd_error=False,
) )
pc.prompt = False pc.prompt = False
@ -158,10 +157,10 @@ class TestConnectionBaseClass(unittest.TestCase):
# test examining output for become failure # test examining output for become failure
conn._flags = dict( conn._flags = dict(
become_prompt = False, become_prompt=False,
become_success = False, become_success=False,
become_error = False, become_error=False,
become_nopasswd_error = False, become_nopasswd_error=False,
) )
pc.prompt = False pc.prompt = False
@ -176,10 +175,10 @@ class TestConnectionBaseClass(unittest.TestCase):
# test examining output for missing password # test examining output for missing password
conn._flags = dict( conn._flags = dict(
become_prompt = False, become_prompt=False,
become_success = False, become_success=False,
become_error = False, become_error=False,
become_nopasswd_error = False, become_nopasswd_error=False,
) )
pc.prompt = False pc.prompt = False

View file

@ -29,27 +29,32 @@ class TestINILookup(unittest.TestCase):
# Currently there isn't a new-style # Currently there isn't a new-style
old_style_params_data = ( old_style_params_data = (
# Simple case # Simple case
dict(term=u'keyA section=sectionA file=/path/to/file', dict(
term=u'keyA section=sectionA file=/path/to/file',
expected=[u'keyA', u'section=sectionA', u'file=/path/to/file'], expected=[u'keyA', u'section=sectionA', u'file=/path/to/file'],
), ),
dict(term=u'keyB section=sectionB with space file=/path/with/embedded spaces and/file', dict(
term=u'keyB section=sectionB with space file=/path/with/embedded spaces and/file',
expected=[u'keyB', u'section=sectionB with space', u'file=/path/with/embedded spaces and/file'], expected=[u'keyB', u'section=sectionB with space', u'file=/path/with/embedded spaces and/file'],
), ),
dict(term=u'keyC section=sectionC file=/path/with/equals/cn=com.ansible', dict(
term=u'keyC section=sectionC file=/path/with/equals/cn=com.ansible',
expected=[u'keyC', u'section=sectionC', u'file=/path/with/equals/cn=com.ansible'], expected=[u'keyC', u'section=sectionC', u'file=/path/with/equals/cn=com.ansible'],
), ),
dict(term=u'keyD section=sectionD file=/path/with space and/equals/cn=com.ansible', dict(
term=u'keyD section=sectionD file=/path/with space and/equals/cn=com.ansible',
expected=[u'keyD', u'section=sectionD', u'file=/path/with space and/equals/cn=com.ansible'], expected=[u'keyD', u'section=sectionD', u'file=/path/with space and/equals/cn=com.ansible'],
), ),
dict(term=u'keyE section=sectionE file=/path/with/unicode/くらとみ/file', dict(
term=u'keyE section=sectionE file=/path/with/unicode/くらとみ/file',
expected=[u'keyE', u'section=sectionE', u'file=/path/with/unicode/くらとみ/file'], expected=[u'keyE', u'section=sectionE', u'file=/path/with/unicode/くらとみ/file'],
), ),
dict(term=u'keyF section=sectionF file=/path/with/utf 8 and spaces/くらとみ/file', dict(
term=u'keyF section=sectionF file=/path/with/utf 8 and spaces/くらとみ/file',
expected=[u'keyF', u'section=sectionF', u'file=/path/with/utf 8 and spaces/くらとみ/file'], expected=[u'keyF', u'section=sectionF', u'file=/path/with/utf 8 and spaces/くらとみ/file'],
), ),
) )
def setUp(self): def setUp(self):
pass pass
@ -58,6 +63,6 @@ class TestINILookup(unittest.TestCase):
def test_parse_parameters(self): def test_parse_parameters(self):
for testcase in self.old_style_params_data: for testcase in self.old_style_params_data:
#print(testcase) # print(testcase)
params = _parse_params(testcase['term']) params = _parse_params(testcase['term'])
self.assertEqual(params, testcase['expected']) self.assertEqual(params, testcase['expected'])

View file

@ -22,6 +22,7 @@ __metaclass__ = type
import passlib import passlib
from passlib.handlers import pbkdf2 from passlib.handlers import pbkdf2
from units.mock.loader import DictDataLoader
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import mock_open, patch from ansible.compat.tests.mock import mock_open, patch
@ -29,11 +30,8 @@ from ansible.errors import AnsibleError
from ansible.module_utils.six import text_type from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import builtins from ansible.module_utils.six.moves import builtins
from ansible.plugins import PluginLoader from ansible.plugins import PluginLoader
from ansible.utils import encrypt
from units.mock.loader import DictDataLoader
from ansible.plugins.lookup import password from ansible.plugins.lookup import password
from ansible.utils import encrypt
DEFAULT_CHARS = sorted([u'ascii_letters', u'digits', u".,:-_"]) DEFAULT_CHARS = sorted([u'ascii_letters', u'digits', u".,:-_"])
@ -42,106 +40,124 @@ DEFAULT_CANDIDATE_CHARS = u'.,:-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU
# Currently there isn't a new-style # Currently there isn't a new-style
old_style_params_data = ( old_style_params_data = (
# Simple case # Simple case
dict(term=u'/path/to/file', dict(
term=u'/path/to/file',
filename=u'/path/to/file', filename=u'/path/to/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS),
candidate_chars=DEFAULT_CANDIDATE_CHARS, candidate_chars=DEFAULT_CANDIDATE_CHARS,
), ),
# Special characters in path # Special characters in path
dict(term=u'/path/with/embedded spaces and/file', dict(
term=u'/path/with/embedded spaces and/file',
filename=u'/path/with/embedded spaces and/file', filename=u'/path/with/embedded spaces and/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS),
candidate_chars=DEFAULT_CANDIDATE_CHARS, candidate_chars=DEFAULT_CANDIDATE_CHARS,
), ),
dict(term=u'/path/with/equals/cn=com.ansible', dict(
term=u'/path/with/equals/cn=com.ansible',
filename=u'/path/with/equals/cn=com.ansible', filename=u'/path/with/equals/cn=com.ansible',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS),
candidate_chars=DEFAULT_CANDIDATE_CHARS, candidate_chars=DEFAULT_CANDIDATE_CHARS,
), ),
dict(term=u'/path/with/unicode/くらとみ/file', dict(
term=u'/path/with/unicode/くらとみ/file',
filename=u'/path/with/unicode/くらとみ/file', filename=u'/path/with/unicode/くらとみ/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS),
candidate_chars=DEFAULT_CANDIDATE_CHARS, candidate_chars=DEFAULT_CANDIDATE_CHARS,
), ),
# Mix several special chars # Mix several special chars
dict(term=u'/path/with/utf 8 and spaces/くらとみ/file', dict(
term=u'/path/with/utf 8 and spaces/くらとみ/file',
filename=u'/path/with/utf 8 and spaces/くらとみ/file', filename=u'/path/with/utf 8 and spaces/くらとみ/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS),
candidate_chars=DEFAULT_CANDIDATE_CHARS, candidate_chars=DEFAULT_CANDIDATE_CHARS,
), ),
dict(term=u'/path/with/encoding=unicode/くらとみ/file', dict(
term=u'/path/with/encoding=unicode/くらとみ/file',
filename=u'/path/with/encoding=unicode/くらとみ/file', filename=u'/path/with/encoding=unicode/くらとみ/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS),
candidate_chars=DEFAULT_CANDIDATE_CHARS, candidate_chars=DEFAULT_CANDIDATE_CHARS,
), ),
dict(term=u'/path/with/encoding=unicode/くらとみ/and spaces file', dict(
term=u'/path/with/encoding=unicode/くらとみ/and spaces file',
filename=u'/path/with/encoding=unicode/くらとみ/and spaces file', filename=u'/path/with/encoding=unicode/くらとみ/and spaces file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=DEFAULT_CHARS),
candidate_chars=DEFAULT_CANDIDATE_CHARS, candidate_chars=DEFAULT_CANDIDATE_CHARS,
), ),
# Simple parameters # Simple parameters
dict(term=u'/path/to/file length=42', dict(
term=u'/path/to/file length=42',
filename=u'/path/to/file', filename=u'/path/to/file',
params=dict(length=42, encrypt=None, chars=DEFAULT_CHARS), params=dict(length=42, encrypt=None, chars=DEFAULT_CHARS),
candidate_chars=DEFAULT_CANDIDATE_CHARS, candidate_chars=DEFAULT_CANDIDATE_CHARS,
), ),
dict(term=u'/path/to/file encrypt=pbkdf2_sha256', dict(
term=u'/path/to/file encrypt=pbkdf2_sha256',
filename=u'/path/to/file', filename=u'/path/to/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt='pbkdf2_sha256', chars=DEFAULT_CHARS), params=dict(length=password.DEFAULT_LENGTH, encrypt='pbkdf2_sha256', chars=DEFAULT_CHARS),
candidate_chars=DEFAULT_CANDIDATE_CHARS, candidate_chars=DEFAULT_CANDIDATE_CHARS,
), ),
dict(term=u'/path/to/file chars=abcdefghijklmnop', dict(
term=u'/path/to/file chars=abcdefghijklmnop',
filename=u'/path/to/file', filename=u'/path/to/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=[u'abcdefghijklmnop']), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=[u'abcdefghijklmnop']),
candidate_chars=u'abcdefghijklmnop', candidate_chars=u'abcdefghijklmnop',
), ),
dict(term=u'/path/to/file chars=digits,abc,def', dict(
term=u'/path/to/file chars=digits,abc,def',
filename=u'/path/to/file', filename=u'/path/to/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'digits', u'abc', u'def'])), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'digits', u'abc', u'def'])),
candidate_chars=u'abcdef0123456789', candidate_chars=u'abcdef0123456789',
), ),
# Including comma in chars # Including comma in chars
dict(term=u'/path/to/file chars=abcdefghijklmnop,,digits', dict(
term=u'/path/to/file chars=abcdefghijklmnop,,digits',
filename=u'/path/to/file', filename=u'/path/to/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'abcdefghijklmnop', u',', u'digits'])), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'abcdefghijklmnop', u',', u'digits'])),
candidate_chars = u',abcdefghijklmnop0123456789', candidate_chars=u',abcdefghijklmnop0123456789',
), ),
dict(term=u'/path/to/file chars=,,', dict(
term=u'/path/to/file chars=,,',
filename=u'/path/to/file', filename=u'/path/to/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=[u',']), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=[u',']),
candidate_chars=u',', candidate_chars=u',',
), ),
# Including = in chars # Including = in chars
dict(term=u'/path/to/file chars=digits,=,,', dict(
term=u'/path/to/file chars=digits,=,,',
filename=u'/path/to/file', filename=u'/path/to/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'digits', u'=', u','])), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'digits', u'=', u','])),
candidate_chars=u',=0123456789', candidate_chars=u',=0123456789',
), ),
dict(term=u'/path/to/file chars=digits,abc=def', dict(
term=u'/path/to/file chars=digits,abc=def',
filename=u'/path/to/file', filename=u'/path/to/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'digits', u'abc=def'])), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'digits', u'abc=def'])),
candidate_chars=u'abc=def0123456789', candidate_chars=u'abc=def0123456789',
), ),
# Including unicode in chars # Including unicode in chars
dict(term=u'/path/to/file chars=digits,くらとみ,,', dict(
term=u'/path/to/file chars=digits,くらとみ,,',
filename=u'/path/to/file', filename=u'/path/to/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'digits', u'くらとみ', u','])), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'digits', u'くらとみ', u','])),
candidate_chars=u',0123456789くらとみ', candidate_chars=u',0123456789くらとみ',
), ),
# Including only unicode in chars # Including only unicode in chars
dict(term=u'/path/to/file chars=くらとみ', dict(
term=u'/path/to/file chars=くらとみ',
filename=u'/path/to/file', filename=u'/path/to/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'くらとみ'])), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'くらとみ'])),
candidate_chars=u'くらとみ', candidate_chars=u'くらとみ',
), ),
# Include ':' in path # Include ':' in path
dict(term=u'/path/to/file_with:colon chars=ascii_letters,digits', dict(
term=u'/path/to/file_with:colon chars=ascii_letters,digits',
filename=u'/path/to/file_with:colon', filename=u'/path/to/file_with:colon',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'ascii_letters', u'digits'])), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=sorted([u'ascii_letters', u'digits'])),
candidate_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', candidate_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
@ -149,17 +165,20 @@ old_style_params_data = (
# Including special chars in both path and chars # Including special chars in both path and chars
# Special characters in path # Special characters in path
dict(term=u'/path/with/embedded spaces and/file chars=abc=def', dict(
term=u'/path/with/embedded spaces and/file chars=abc=def',
filename=u'/path/with/embedded spaces and/file', filename=u'/path/with/embedded spaces and/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=[u'abc=def']), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=[u'abc=def']),
candidate_chars=u'abc=def', candidate_chars=u'abc=def',
), ),
dict(term=u'/path/with/equals/cn=com.ansible chars=abc=def', dict(
term=u'/path/with/equals/cn=com.ansible chars=abc=def',
filename=u'/path/with/equals/cn=com.ansible', filename=u'/path/with/equals/cn=com.ansible',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=[u'abc=def']), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=[u'abc=def']),
candidate_chars=u'abc=def', candidate_chars=u'abc=def',
), ),
dict(term=u'/path/with/unicode/くらとみ/file chars=くらとみ', dict(
term=u'/path/with/unicode/くらとみ/file chars=くらとみ',
filename=u'/path/with/unicode/くらとみ/file', filename=u'/path/with/unicode/くらとみ/file',
params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=[u'くらとみ']), params=dict(length=password.DEFAULT_LENGTH, encrypt=None, chars=[u'くらとみ']),
candidate_chars=u'くらとみ', candidate_chars=u'くらとみ',
@ -325,8 +344,7 @@ class TestFormatContent(unittest.TestCase):
u'hunter42 salt=87654321') u'hunter42 salt=87654321')
def test_encrypt_no_salt(self): def test_encrypt_no_salt(self):
self.assertRaises(AssertionError, password._format_content, self.assertRaises(AssertionError, password._format_content, u'hunter42', None, 'pbkdf2_sha256')
u'hunter42', None, 'pbkdf2_sha256')
class TestWritePasswordFile(unittest.TestCase): class TestWritePasswordFile(unittest.TestCase):
@ -351,7 +369,7 @@ class TestWritePasswordFile(unittest.TestCase):
class TestLookupModule(unittest.TestCase): class TestLookupModule(unittest.TestCase):
def setUp(self): def setUp(self):
self.fake_loader = DictDataLoader({'/path/to/somewhere':'sdfsdf'}) self.fake_loader = DictDataLoader({'/path/to/somewhere': 'sdfsdf'})
self.password_lookup = password.LookupModule(loader=self.fake_loader) self.password_lookup = password.LookupModule(loader=self.fake_loader)
self.os_path_exists = password.os.path.exists self.os_path_exists = password.os.path.exists
@ -369,8 +387,7 @@ class TestLookupModule(unittest.TestCase):
def test_no_encrypt(self, mock_get_paths, mock_write_file): def test_no_encrypt(self, mock_get_paths, mock_write_file):
mock_get_paths.return_value = ['/path/one', '/path/two', '/path/three'] mock_get_paths.return_value = ['/path/one', '/path/two', '/path/three']
results = self.password_lookup.run([u'/path/to/somewhere'], results = self.password_lookup.run([u'/path/to/somewhere'], None)
None)
# FIXME: assert something useful # FIXME: assert something useful
for result in results: for result in results:
@ -382,8 +399,7 @@ class TestLookupModule(unittest.TestCase):
def test_encrypt(self, mock_get_paths, mock_write_file): def test_encrypt(self, mock_get_paths, mock_write_file):
mock_get_paths.return_value = ['/path/one', '/path/two', '/path/three'] mock_get_paths.return_value = ['/path/one', '/path/two', '/path/three']
results = self.password_lookup.run([u'/path/to/somewhere encrypt=pbkdf2_sha256'], results = self.password_lookup.run([u'/path/to/somewhere encrypt=pbkdf2_sha256'], None)
None)
# pbkdf2 format plus hash # pbkdf2 format plus hash
expected_password_length = 76 expected_password_length = 76
@ -412,8 +428,7 @@ class TestLookupModule(unittest.TestCase):
password.os.path.exists = lambda x: True password.os.path.exists = lambda x: True
with patch.object(builtins, 'open', mock_open(read_data=b'hunter42 salt=87654321\n')) as m: with patch.object(builtins, 'open', mock_open(read_data=b'hunter42 salt=87654321\n')) as m:
results = self.password_lookup.run([u'/path/to/somewhere chars=anything encrypt=pbkdf2_sha256'], results = self.password_lookup.run([u'/path/to/somewhere chars=anything encrypt=pbkdf2_sha256'], None)
None)
for result in results: for result in results:
self.assertEqual(result, u'$pbkdf2-sha256$20000$ODc2NTQzMjE$Uikde0cv0BKaRaAXMrUQB.zvG4GmnjClwjghwIRf2gU') self.assertEqual(result, u'$pbkdf2-sha256$20000$ODc2NTQzMjE$Uikde0cv0BKaRaAXMrUQB.zvG4GmnjClwjghwIRf2gU')
@ -424,8 +439,7 @@ class TestLookupModule(unittest.TestCase):
password.os.path.exists = lambda x: True password.os.path.exists = lambda x: True
with patch.object(builtins, 'open', mock_open(read_data=b'hunter42 salt=87654321\n')) as m: with patch.object(builtins, 'open', mock_open(read_data=b'hunter42 salt=87654321\n')) as m:
results = self.password_lookup.run([u'/path/to/somewhere chars=anything'], results = self.password_lookup.run([u'/path/to/somewhere chars=anything'], None)
None)
for result in results: for result in results:
self.assertEqual(result, u'hunter42') self.assertEqual(result, u'hunter42')
@ -435,7 +449,6 @@ class TestLookupModule(unittest.TestCase):
def test_only_a(self, mock_get_paths, mock_write_file): def test_only_a(self, mock_get_paths, mock_write_file):
mock_get_paths.return_value = ['/path/one', '/path/two', '/path/three'] mock_get_paths.return_value = ['/path/one', '/path/two', '/path/three']
results = self.password_lookup.run([u'/path/to/somewhere chars=a'], results = self.password_lookup.run([u'/path/to/somewhere chars=a'], None)
None)
for result in results: for result in results:
self.assertEquals(result, u'a' * password.DEFAULT_LENGTH) self.assertEquals(result, u'a' * password.DEFAULT_LENGTH)

View file

@ -19,11 +19,11 @@
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
from units.mock.loader import DictDataLoader
import uuid import uuid
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock from ansible.compat.tests.mock import patch, MagicMock
from ansible.errors import AnsibleError, AnsibleParserError from ansible.errors import AnsibleError, AnsibleParserError
from ansible.executor.process.worker import WorkerProcess from ansible.executor.process.worker import WorkerProcess
from ansible.executor.task_queue_manager import TaskQueueManager from ansible.executor.task_queue_manager import TaskQueueManager
@ -34,7 +34,6 @@ from ansible.playbook.block import Block
from ansible.playbook.handler import Handler from ansible.playbook.handler import Handler
from ansible.plugins.strategy import StrategyBase from ansible.plugins.strategy import StrategyBase
from units.mock.loader import DictDataLoader
class TestStrategyBase(unittest.TestCase): class TestStrategyBase(unittest.TestCase):
@ -46,13 +45,16 @@ class TestStrategyBase(unittest.TestCase):
def test_strategy_base_init(self): def test_strategy_base_init(self):
queue_items = [] queue_items = []
def _queue_empty(*args, **kwargs): def _queue_empty(*args, **kwargs):
return len(queue_items) == 0 return len(queue_items) == 0
def _queue_get(*args, **kwargs): def _queue_get(*args, **kwargs):
if len(queue_items) == 0: if len(queue_items) == 0:
raise Queue.Empty raise Queue.Empty
else: else:
return queue_items.pop() return queue_items.pop()
def _queue_put(item, *args, **kwargs): def _queue_put(item, *args, **kwargs):
queue_items.append(item) queue_items.append(item)
@ -71,13 +73,16 @@ class TestStrategyBase(unittest.TestCase):
def test_strategy_base_run(self): def test_strategy_base_run(self):
queue_items = [] queue_items = []
def _queue_empty(*args, **kwargs): def _queue_empty(*args, **kwargs):
return len(queue_items) == 0 return len(queue_items) == 0
def _queue_get(*args, **kwargs): def _queue_get(*args, **kwargs):
if len(queue_items) == 0: if len(queue_items) == 0:
raise Queue.Empty raise Queue.Empty
else: else:
return queue_items.pop() return queue_items.pop()
def _queue_put(item, *args, **kwargs): def _queue_put(item, *args, **kwargs):
queue_items.append(item) queue_items.append(item)
@ -124,13 +129,16 @@ class TestStrategyBase(unittest.TestCase):
def test_strategy_base_get_hosts(self): def test_strategy_base_get_hosts(self):
queue_items = [] queue_items = []
def _queue_empty(*args, **kwargs): def _queue_empty(*args, **kwargs):
return len(queue_items) == 0 return len(queue_items) == 0
def _queue_get(*args, **kwargs): def _queue_get(*args, **kwargs):
if len(queue_items) == 0: if len(queue_items) == 0:
raise Queue.Empty raise Queue.Empty
else: else:
return queue_items.pop() return queue_items.pop()
def _queue_put(item, *args, **kwargs): def _queue_put(item, *args, **kwargs):
queue_items.append(item) queue_items.append(item)
@ -142,7 +150,7 @@ class TestStrategyBase(unittest.TestCase):
mock_hosts = [] mock_hosts = []
for i in range(0, 5): for i in range(0, 5):
mock_host = MagicMock() mock_host = MagicMock()
mock_host.name = "host%02d" % (i+1) mock_host.name = "host%02d" % (i + 1)
mock_host.has_hostkey = True mock_host.has_hostkey = True
mock_hosts.append(mock_host) mock_hosts.append(mock_host)
@ -156,7 +164,7 @@ class TestStrategyBase(unittest.TestCase):
mock_tqm.get_inventory.return_value = mock_inventory mock_tqm.get_inventory.return_value = mock_inventory
mock_play = MagicMock() mock_play = MagicMock()
mock_play.hosts = ["host%02d" % (i+1) for i in range(0, 5)] mock_play.hosts = ["host%02d" % (i + 1) for i in range(0, 5)]
strategy_base = StrategyBase(tqm=mock_tqm) strategy_base = StrategyBase(tqm=mock_tqm)
@ -213,7 +221,6 @@ class TestStrategyBase(unittest.TestCase):
finally: finally:
tqm.cleanup() tqm.cleanup()
def test_strategy_base_process_pending_results(self): def test_strategy_base_process_pending_results(self):
mock_tqm = MagicMock() mock_tqm = MagicMock()
mock_tqm._terminated = False mock_tqm._terminated = False
@ -224,13 +231,16 @@ class TestStrategyBase(unittest.TestCase):
mock_tqm._listening_handlers = {} mock_tqm._listening_handlers = {}
queue_items = [] queue_items = []
def _queue_empty(*args, **kwargs): def _queue_empty(*args, **kwargs):
return len(queue_items) == 0 return len(queue_items) == 0
def _queue_get(*args, **kwargs): def _queue_get(*args, **kwargs):
if len(queue_items) == 0: if len(queue_items) == 0:
raise Queue.Empty raise Queue.Empty
else: else:
return queue_items.pop() return queue_items.pop()
def _queue_put(item, *args, **kwargs): def _queue_put(item, *args, **kwargs):
queue_items.append(item) queue_items.append(item)
@ -290,6 +300,7 @@ class TestStrategyBase(unittest.TestCase):
if host_name == 'test01': if host_name == 'test01':
return mock_host return mock_host
return None return None
def _get_group(group_name): def _get_group(group_name):
if group_name in ('all', 'foo'): if group_name in ('all', 'foo'):
return mock_group return mock_group
@ -341,8 +352,8 @@ class TestStrategyBase(unittest.TestCase):
self.assertEqual(results[0], task_result) self.assertEqual(results[0], task_result)
self.assertEqual(strategy_base._pending_results, 0) self.assertEqual(strategy_base._pending_results, 0)
self.assertNotIn('test01', strategy_base._blocked_hosts) self.assertNotIn('test01', strategy_base._blocked_hosts)
#self.assertIn('test01', mock_tqm._failed_hosts) # self.assertIn('test01', mock_tqm._failed_hosts)
#del mock_tqm._failed_hosts['test01'] # del mock_tqm._failed_hosts['test01']
mock_iterator.is_failed.return_value = False mock_iterator.is_failed.return_value = False
task_result = TaskResult(host=mock_host.name, task=mock_task._uuid, return_data='{"unreachable": true}') task_result = TaskResult(host=mock_host.name, task=mock_task._uuid, return_data='{"unreachable": true}')
@ -393,18 +404,18 @@ class TestStrategyBase(unittest.TestCase):
self.assertIn(mock_handler_task._uuid, strategy_base._notified_handlers) self.assertIn(mock_handler_task._uuid, strategy_base._notified_handlers)
self.assertIn(mock_host, strategy_base._notified_handlers[mock_handler_task._uuid]) self.assertIn(mock_host, strategy_base._notified_handlers[mock_handler_task._uuid])
#queue_items.append(('set_host_var', mock_host, mock_task, None, 'foo', 'bar')) # queue_items.append(('set_host_var', mock_host, mock_task, None, 'foo', 'bar'))
#results = strategy_base._process_pending_results(iterator=mock_iterator) # results = strategy_base._process_pending_results(iterator=mock_iterator)
#self.assertEqual(len(results), 0) # self.assertEqual(len(results), 0)
#self.assertEqual(strategy_base._pending_results, 1) # self.assertEqual(strategy_base._pending_results, 1)
#queue_items.append(('set_host_facts', mock_host, mock_task, None, 'foo', dict())) # queue_items.append(('set_host_facts', mock_host, mock_task, None, 'foo', dict()))
#results = strategy_base._process_pending_results(iterator=mock_iterator) # results = strategy_base._process_pending_results(iterator=mock_iterator)
#self.assertEqual(len(results), 0) # self.assertEqual(len(results), 0)
#self.assertEqual(strategy_base._pending_results, 1) # self.assertEqual(strategy_base._pending_results, 1)
#queue_items.append(('bad')) # queue_items.append(('bad'))
#self.assertRaises(AnsibleError, strategy_base._process_pending_results, iterator=mock_iterator) # self.assertRaises(AnsibleError, strategy_base._process_pending_results, iterator=mock_iterator)
strategy_base.cleanup() strategy_base.cleanup()
def test_strategy_base_load_included_file(self): def test_strategy_base_load_included_file(self):
@ -417,13 +428,16 @@ class TestStrategyBase(unittest.TestCase):
}) })
queue_items = [] queue_items = []
def _queue_empty(*args, **kwargs): def _queue_empty(*args, **kwargs):
return len(queue_items) == 0 return len(queue_items) == 0
def _queue_get(*args, **kwargs): def _queue_get(*args, **kwargs):
if len(queue_items) == 0: if len(queue_items) == 0:
raise Queue.Empty raise Queue.Empty
else: else:
return queue_items.pop() return queue_items.pop()
def _queue_put(item, *args, **kwargs): def _queue_put(item, *args, **kwargs):
queue_items.append(item) queue_items.append(item)

View file

@ -21,13 +21,12 @@ from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
import os import os
from ansible.compat.tests import unittest
from ansible.compat.tests import BUILTINS
from ansible.compat.tests import BUILTINS, unittest
from ansible.compat.tests.mock import mock_open, patch, MagicMock from ansible.compat.tests.mock import mock_open, patch, MagicMock
from ansible.plugins import MODULE_CACHE, PATH_CACHE, PLUGIN_PATH_CACHE, PluginLoader from ansible.plugins import MODULE_CACHE, PATH_CACHE, PLUGIN_PATH_CACHE, PluginLoader
class TestErrors(unittest.TestCase): class TestErrors(unittest.TestCase):
def setUp(self): def setUp(self):
@ -69,14 +68,14 @@ class TestErrors(unittest.TestCase):
self.assertEqual(pl._get_paths(), ['/path/one', '/path/two']) self.assertEqual(pl._get_paths(), ['/path/one', '/path/two'])
# NOT YET WORKING # NOT YET WORKING
#def fake_glob(path): # def fake_glob(path):
# if path == 'test/*': # if path == 'test/*':
# return ['test/foo', 'test/bar', 'test/bam'] # return ['test/foo', 'test/bar', 'test/bam']
# elif path == 'test/*/*' # elif path == 'test/*/*'
#m._paths = None # m._paths = None
#mock_glob = MagicMock() # mock_glob = MagicMock()
#mock_glob.return_value = [] # mock_glob.return_value = []
#with patch('glob.glob', mock_glob): # with patch('glob.glob', mock_glob):
# pass # pass
def assertPluginLoaderConfigBecomes(self, arg, expected): def assertPluginLoaderConfigBecomes(self, arg, expected):

View file

@ -24,9 +24,9 @@ from collections import defaultdict
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock from ansible.compat.tests.mock import patch, MagicMock
from ansible.template.safe_eval import safe_eval from ansible.template.safe_eval import safe_eval
class TestSafeEval(unittest.TestCase): class TestSafeEval(unittest.TestCase):
def setUp(self): def setUp(self):

Some files were not shown because too many files have changed in this diff Show more