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
pull/25219/head
Dag Wieers 7 years ago committed by John R Barker
parent 31c59ad5f9
commit 4efec414e7

@ -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 os
import re
import sys
import boto import boto
import boto.ec2.elb
import optparse import optparse
import yaml import os
import os.path import os.path
import boto.ec2.elb import re
import sys
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
@ -51,6 +53,7 @@ def delete_autoscaling_group(get_func, attr, opts):
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):
# the file might not be there if the integration test wasn't run # the file might not be there if the integration test wasn't run
@ -65,11 +68,13 @@ 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'
@ -82,6 +87,7 @@ def prompt_and_delete(item, prompt, assumeyes):
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
default_aws_access_key = os.environ.get('AWS_ACCESS_KEY', None) default_aws_access_key = os.environ.get('AWS_ACCESS_KEY', None)
@ -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()

@ -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,6 +34,7 @@ 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'
@ -38,18 +43,25 @@ def prompt_and_delete(item, prompt, 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():

@ -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)

@ -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()
@ -36,7 +40,6 @@ if __name__ == '__main__':
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.")

@ -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,7 +13,8 @@ def main():
) )
)) ))
module = AnsibleModule(argument_spec = dict( module = AnsibleModule(
argument_spec=dict(
fail_mode=dict(type='list', default=['success']) fail_mode=dict(type='list', default=['success'])
) )
) )

@ -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()

@ -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,7 +141,6 @@ 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):
@ -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_')

@ -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

@ -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.module_utils.six import PY3
import ansible
from ansible.errors import AnsibleError, AnsibleOptionsError from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.module_utils.six import PY3
from ansible.cli.galaxy import GalaxyCLI
class TestGalaxy(unittest.TestCase): class TestGalaxy(unittest.TestCase):
@classmethod @classmethod

@ -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,15 +19,19 @@ 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
write_dumpfile = None write_dumpfile = None
@ -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):

@ -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.compat.tests.mock import mock_open, patch
from ansible.errors import AnsibleError from ansible.errors import AnsibleError
from ansible.parsing.yaml.objects import AnsibleBaseYAMLObject
from ansible.compat.tests import BUILTINS
from ansible.compat.tests.mock import mock_open, patch
class TestErrors(unittest.TestCase): class TestErrors(unittest.TestCase):

@ -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

@ -57,7 +57,6 @@ 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()

@ -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):
@ -103,19 +103,28 @@ class TestPlaybookExecutor(unittest.TestCase):
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]

@ -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):
@ -211,9 +211,7 @@ class TestTaskExecutor(unittest.TestCase):
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'])
@ -269,9 +267,7 @@ 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}}'}
@ -333,9 +329,11 @@ class TestTaskExecutor(unittest.TestCase):
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)
@ -344,9 +342,11 @@ class TestTaskExecutor(unittest.TestCase):
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)
@ -356,7 +356,6 @@ class TestTaskExecutor(unittest.TestCase):
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({})
@ -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))

@ -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()

@ -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 = {

@ -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):

@ -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,11 +31,9 @@ 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
@ -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]',

@ -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/',

@ -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)

@ -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'])

@ -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())

@ -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'لرئيسية')

@ -57,18 +57,22 @@ 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)

@ -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):
@ -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
@ -85,16 +89,10 @@ SYNONYMS_0660 = (
[['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()

@ -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
) )

@ -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):

@ -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": {
@ -158,8 +168,7 @@ 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"
@ -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": {
@ -306,7 +321,6 @@ 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": {
@ -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",
@ -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()

@ -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']

@ -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):

@ -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))

@ -39,14 +39,17 @@ VALID_STRINGS = (
(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:

@ -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,6 +64,7 @@ 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):
@ -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):

@ -19,19 +19,22 @@
# 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 copy
import json
import pytest import pytest
boto3 = pytest.importorskip("boto3")
import json
import copy
from ansible.module_utils._text import to_bytes
from ansible.module_utils import basic
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)
@ -84,6 +87,7 @@ def make_mock_no_connection_connection(config):
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()
@ -145,6 +149,7 @@ def test_create_lambda_if_not_exist():
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)
@ -169,6 +174,7 @@ 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)
@ -189,6 +195,7 @@ 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)
@ -209,6 +216,7 @@ 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)
@ -233,8 +241,8 @@ def test_update_lambda_if_added_environment_variable():
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)
@ -251,6 +259,7 @@ def test_dont_update_lambda_if_nothing_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({

@ -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):

@ -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):

@ -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."""

@ -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):
''' '''

@ -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,

@ -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

@ -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

@ -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
@ -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)

@ -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)

@ -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

@ -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):

@ -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

@ -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)

@ -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

@ -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)

@ -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

@ -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

@ -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'])

@ -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()

@ -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

@ -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

@ -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)

@ -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)

@ -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)

@ -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

@ -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):
def execute_module(self, failed=False, changed=False, commands=None, class TestVyosModule(unittest.TestCase):
sort=True, defaults=False):
def execute_module(self, failed=False, changed=False, commands=None, 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

@ -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"),
] ]

@ -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',
}) })

@ -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):

@ -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.compat.tests import unittest
from ansible.errors import AnsibleParserError from ansible.errors import AnsibleParserError
from ansible.parsing.mod_args import ModuleArgsParser
from ansible.compat.tests import unittest
class TestModArgsDwim(unittest.TestCase): class TestModArgsDwim(unittest.TestCase):
@ -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)

@ -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 = {

@ -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}')

@ -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.parsing.yaml.loader import AnsibleLoader
from ansible.compat.tests import unittest from ansible.compat.tests import unittest
from ansible.parsing.yaml import objects
from ansible.parsing import vault from ansible.parsing import vault
from ansible.parsing.yaml import dumper, objects
from ansible.parsing.yaml.loader import AnsibleLoader
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"

@ -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\''},
]) ])

@ -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")

@ -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)

@ -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)

@ -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):
@ -85,4 +86,3 @@ class TestBlock(unittest.TestCase):
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)

@ -21,17 +21,17 @@ __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):
@ -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,11 +284,13 @@ 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',
)
), ),
) )

@ -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):

@ -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):

@ -19,8 +19,9 @@
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',
@ -31,6 +32,7 @@ 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):

@ -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')

@ -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()
@ -105,5 +105,3 @@ class TestCopyResultExclude(unittest.TestCase):
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)

@ -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,9 +51,11 @@ 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
@ -62,6 +63,7 @@ class ConnectionMock(object):
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,7 +127,7 @@ 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
@ -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
@ -190,12 +192,10 @@ 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()

@ -25,7 +25,6 @@ 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
@ -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

@ -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)

@ -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()

@ -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):

@ -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

@ -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):
@ -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)

@ -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)
@ -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
@ -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)

@ -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):

@ -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):

@ -27,6 +27,7 @@ from ansible.template import _escape_backslashes, _count_newlines_from_end
# These are internal utility functions only needed for templating. They're # These are internal utility functions only needed for templating. They're
# algorithmic so good candidates for unittesting by themselves # algorithmic so good candidates for unittesting by themselves
class TestBackslashEscape(unittest.TestCase): class TestBackslashEscape(unittest.TestCase):
test_data = ( test_data = (
@ -69,6 +70,7 @@ class TestBackslashEscape(unittest.TestCase):
args=dict(var1=u'\\1 %s') args=dict(var1=u'\\1 %s')
), ),
) )
def setUp(self): def setUp(self):
self.env = jinja2.Environment() self.env = jinja2.Environment()
@ -84,6 +86,7 @@ class TestBackslashEscape(unittest.TestCase):
args = test['args'] args = test['args']
self.assertEquals(template.render(**args), test['expectation']) self.assertEquals(template.render(**args), test['expectation'])
class TestCountNewlines(unittest.TestCase): class TestCountNewlines(unittest.TestCase):
def setUp(self): def setUp(self):

@ -18,4 +18,3 @@
# 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)
__metaclass__ = type __metaclass__ = type

@ -56,6 +56,7 @@ def user():
return user return user
@pytest.fixture @pytest.fixture
def cfg_file(): def cfg_file():
data = '/ansible/test/cfg/path' data = '/ansible/test/cfg/path'
@ -215,4 +216,3 @@ class TestGetConfig:
# Need to test this # Need to test this
# def test_load_config_file(): # def test_load_config_file():
# pass # pass

@ -19,6 +19,7 @@ import unittest
from ansible.utils.helpers import pct_to_int from ansible.utils.helpers import pct_to_int
class TestHelpers(unittest.TestCase): class TestHelpers(unittest.TestCase):
def test_pct_to_int(self): def test_pct_to_int(self):
@ -28,4 +29,3 @@ class TestHelpers(unittest.TestCase):
self.assertEqual(pct_to_int("1%", 10, 0), 0) self.assertEqual(pct_to_int("1%", 10, 0), 0)
self.assertEqual(pct_to_int("1", 100), 1) self.assertEqual(pct_to_int("1", 100), 1)
self.assertEqual(pct_to_int("10%", 100), 10) self.assertEqual(pct_to_int("10%", 100), 10)

@ -36,4 +36,3 @@ class TestSplit(unittest.TestCase):
def test_error(self): def test_error(self):
self.assertRaises(ValueError, shlex_split, 'a "b') self.assertRaises(ValueError, shlex_split, 'a "b')

@ -24,9 +24,9 @@ from collections import defaultdict
from ansible.compat.tests import mock, unittest from ansible.compat.tests import mock, unittest
from ansible.errors import AnsibleError from ansible.errors import AnsibleError
from ansible.utils.vars import combine_vars, merge_hash from ansible.utils.vars import combine_vars, merge_hash
class TestVariableUtils(unittest.TestCase): class TestVariableUtils(unittest.TestCase):
test_merge_data = ( test_merge_data = (

Loading…
Cancel
Save