Rename tests to test, use old directory name.

This commit is contained in:
Michael DeHaan 2014-02-20 19:11:15 -05:00
commit 2177b773c8
132 changed files with 0 additions and 0 deletions

5
test/units/README.md Normal file
View file

@ -0,0 +1,5 @@
Unit tests
==========
Tests at code level. Should be concise and to the point, and organized by subject.

View file

@ -0,0 +1,64 @@
# -*- coding: utf-8 -*-
import unittest
from ansible.constants import get_config
import ConfigParser
import random
import string
import os
def random_string(length):
return ''.join(random.choice(string.ascii_uppercase) for x in range(6))
p = ConfigParser.ConfigParser()
p.read(os.path.join(os.path.dirname(__file__), 'ansible.cfg'))
class TestConstants(unittest.TestCase):
#####################################
### get_config unit tests
def test_configfile_and_env_both_set(self):
r = random_string(6)
env_var = 'ANSIBLE_TEST_%s' % r
os.environ[env_var] = r
res = get_config(p, 'defaults', 'test_key', env_var, 'default')
del os.environ[env_var]
assert res == r
def test_configfile_set_env_not_set(self):
r = random_string(6)
env_var = 'ANSIBLE_TEST_%s' % r
assert env_var not in os.environ
res = get_config(p, 'defaults', 'test_key', env_var, 'default')
print res
assert res == 'test_value'
def test_configfile_not_set_env_set(self):
r = random_string(6)
env_var = 'ANSIBLE_TEST_%s' % r
os.environ[env_var] = r
res = get_config(p, 'defaults', 'doesnt_exist', env_var, 'default')
del os.environ[env_var]
assert res == r
def test_configfile_not_set_env_not_set(self):
r = random_string(6)
env_var = 'ANSIBLE_TEST_%s' % r
assert env_var not in os.environ
res = get_config(p, 'defaults', 'doesnt_exist', env_var, 'default')
assert res == 'default'

139
test/units/TestFilters.py Normal file
View file

@ -0,0 +1,139 @@
'''
Test bundled filters
'''
import os.path
import unittest, tempfile, shutil
from ansible import playbook, inventory, callbacks
import ansible.runner.filter_plugins.core
INVENTORY = inventory.Inventory(['localhost'])
BOOK = '''
- hosts: localhost
vars:
var: { a: [1,2,3] }
tasks:
- template: src=%s dest=%s
'''
SRC = '''
-
{{ var|to_json }}
-
{{ var|to_nice_json }}
-
{{ var|to_yaml }}
-
{{ var|to_nice_yaml }}
'''
DEST = '''
-
{"a": [1, 2, 3]}
-
{
"a": [
1,
2,
3
]
}
-
a: [1, 2, 3]
-
a:
- 1
- 2
- 3
'''
class TestFilters(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp(dir='/tmp')
def tearDown(self):
shutil.rmtree(self.tmpdir)
def temp(self, name, data=''):
'''write a temporary file and return the name'''
name = self.tmpdir + '/' + name
with open(name, 'w') as f:
f.write(data)
return name
def test_bool_none(self):
a = ansible.runner.filter_plugins.core.bool(None)
assert a == None
def test_bool_true(self):
a = ansible.runner.filter_plugins.core.bool(True)
assert a == True
def test_bool_yes(self):
a = ansible.runner.filter_plugins.core.bool('Yes')
assert a == True
def test_bool_no(self):
a = ansible.runner.filter_plugins.core.bool('Foo')
assert a == False
def test_quotes(self):
a = ansible.runner.filter_plugins.core.quote('ls | wc -l')
assert a == "'ls | wc -l'"
def test_fileglob(self):
pathname = os.path.join(os.path.dirname(__file__), '*')
a = ansible.runner.filter_plugins.core.fileglob(pathname)
assert __file__ in a
def test_regex(self):
a = ansible.runner.filter_plugins.core.regex('ansible', 'ansible',
match_type='findall')
assert a == True
def test_match_case_sensitive(self):
a = ansible.runner.filter_plugins.core.match('ansible', 'ansible')
assert a == True
def test_match_case_insensitive(self):
a = ansible.runner.filter_plugins.core.match('ANSIBLE', 'ansible',
True)
assert a == True
def test_match_no_match(self):
a = ansible.runner.filter_plugins.core.match(' ansible', 'ansible')
assert a == False
def test_search_case_sensitive(self):
a = ansible.runner.filter_plugins.core.search(' ansible ', 'ansible')
assert a == True
def test_search_case_insensitive(self):
a = ansible.runner.filter_plugins.core.search(' ANSIBLE ', 'ansible',
True)
assert a == True
#def test_filters(self):
# this test is pretty low level using a playbook, hence I am disabling it for now -- MPD.
#return
#src = self.temp('src.j2', SRC)
#dest = self.temp('dest.txt')
#book = self.temp('book', BOOK % (src, dest))
#playbook.PlayBook(
# playbook = book,
# inventory = INVENTORY,
# transport = 'local',
# callbacks = callbacks.PlaybookCallbacks(),
# runner_callbacks = callbacks.DefaultRunnerCallbacks(),
# stats = callbacks.AggregateStats(),
#).run()
#out = open(dest).read()
#self.assertEqual(DEST, out)

421
test/units/TestInventory.py Normal file
View file

@ -0,0 +1,421 @@
import os
import unittest
from nose.tools import raises
from ansible import errors
from ansible.inventory import Inventory
class TestInventory(unittest.TestCase):
def setUp(self):
self.cwd = os.getcwd()
self.test_dir = os.path.join(self.cwd, 'test', 'inventory_test_data')
self.inventory_file = os.path.join(self.test_dir, 'simple_hosts')
self.large_range_inventory_file = os.path.join(self.test_dir, 'large_range')
self.complex_inventory_file = os.path.join(self.test_dir, 'complex_hosts')
self.inventory_script = os.path.join(self.test_dir, 'inventory_api.py')
self.inventory_dir = os.path.join(self.test_dir, 'inventory_dir')
os.chmod(self.inventory_script, 0755)
def tearDown(self):
os.chmod(self.inventory_script, 0644)
def compare(self, left, right, sort=True):
if sort:
left = sorted(left)
right = sorted(right)
print left
print right
assert left == right
def empty_inventory(self):
return Inventory(None)
def simple_inventory(self):
return Inventory(self.inventory_file)
def large_range_inventory(self):
return Inventory(self.large_range_inventory_file)
def script_inventory(self):
return Inventory(self.inventory_script)
def complex_inventory(self):
return Inventory(self.complex_inventory_file)
def dir_inventory(self):
return Inventory(self.inventory_dir)
all_simple_hosts=['jupiter', 'saturn', 'zeus', 'hera',
'cerberus001','cerberus002','cerberus003',
'cottus99', 'cottus100',
'poseidon', 'thor', 'odin', 'loki',
'thrudgelmir0', 'thrudgelmir1', 'thrudgelmir2',
'thrudgelmir3', 'thrudgelmir4', 'thrudgelmir5',
'Hotep-a', 'Hotep-b', 'Hotep-c',
'BastC', 'BastD', 'neptun', ]
#####################################
### Empty inventory format tests
def test_empty(self):
inventory = self.empty_inventory()
hosts = inventory.list_hosts()
self.assertEqual(hosts, [])
#####################################
### Simple inventory format tests
def test_simple(self):
inventory = self.simple_inventory()
hosts = inventory.list_hosts()
self.assertEqual(sorted(hosts), sorted(self.all_simple_hosts))
def test_simple_all(self):
inventory = self.simple_inventory()
hosts = inventory.list_hosts('all')
self.assertEqual(sorted(hosts), sorted(self.all_simple_hosts))
def test_get_hosts(self):
inventory = Inventory('127.0.0.1,192.168.1.1')
hosts = inventory.get_hosts('!10.0.0.1')
hosts_all = inventory.get_hosts('all')
self.assertEqual(sorted(hosts), sorted(hosts_all))
def test_no_src(self):
inventory = Inventory('127.0.0.1,')
self.assertEqual(inventory.src(), None)
def test_simple_norse(self):
inventory = self.simple_inventory()
hosts = inventory.list_hosts("norse")
expected_hosts=['thor', 'odin', 'loki']
assert sorted(hosts) == sorted(expected_hosts)
def test_simple_ungrouped(self):
inventory = self.simple_inventory()
hosts = inventory.list_hosts("ungrouped")
expected_hosts=['jupiter', 'saturn',
'thrudgelmir0', 'thrudgelmir1', 'thrudgelmir2',
'thrudgelmir3', 'thrudgelmir4', 'thrudgelmir5']
assert sorted(hosts) == sorted(expected_hosts)
def test_simple_combined(self):
inventory = self.simple_inventory()
hosts = inventory.list_hosts("norse:greek")
expected_hosts=['zeus', 'hera', 'poseidon',
'cerberus001','cerberus002','cerberus003',
'cottus99','cottus100',
'thor', 'odin', 'loki']
assert sorted(hosts) == sorted(expected_hosts)
def test_simple_restrict(self):
inventory = self.simple_inventory()
restricted_hosts = ['hera', 'poseidon', 'thor']
expected_hosts=['zeus', 'hera', 'poseidon',
'cerberus001','cerberus002','cerberus003',
'cottus99', 'cottus100',
'thor', 'odin', 'loki']
inventory.restrict_to(restricted_hosts)
hosts = inventory.list_hosts("norse:greek")
assert sorted(hosts) == sorted(restricted_hosts)
inventory.lift_restriction()
hosts = inventory.list_hosts("norse:greek")
assert sorted(hosts) == sorted(expected_hosts)
def test_simple_string_ipv4(self):
inventory = Inventory('127.0.0.1,192.168.1.1')
hosts = inventory.list_hosts()
self.assertEqual(sorted(hosts), sorted(['127.0.0.1','192.168.1.1']))
def test_simple_string_ipv4_port(self):
inventory = Inventory('127.0.0.1:2222,192.168.1.1')
hosts = inventory.list_hosts()
self.assertEqual(sorted(hosts), sorted(['127.0.0.1','192.168.1.1']))
def test_simple_string_ipv4_vars(self):
inventory = Inventory('127.0.0.1:2222,192.168.1.1')
var = inventory.get_variables('127.0.0.1')
self.assertEqual(var['ansible_ssh_port'], 2222)
def test_simple_string_ipv6(self):
inventory = Inventory('FE80:EF45::12:1,192.168.1.1')
hosts = inventory.list_hosts()
self.assertEqual(sorted(hosts), sorted(['FE80:EF45::12:1','192.168.1.1']))
def test_simple_string_ipv6_port(self):
inventory = Inventory('[FE80:EF45::12:1]:2222,192.168.1.1')
hosts = inventory.list_hosts()
self.assertEqual(sorted(hosts), sorted(['FE80:EF45::12:1','192.168.1.1']))
def test_simple_string_ipv6_vars(self):
inventory = Inventory('[FE80:EF45::12:1]:2222,192.168.1.1')
var = inventory.get_variables('FE80:EF45::12:1')
self.assertEqual(var['ansible_ssh_port'], 2222)
def test_simple_string_fqdn(self):
inventory = Inventory('foo.example.com,bar.example.com')
hosts = inventory.list_hosts()
self.assertEqual(sorted(hosts), sorted(['foo.example.com','bar.example.com']))
def test_simple_string_fqdn_port(self):
inventory = Inventory('foo.example.com:2222,bar.example.com')
hosts = inventory.list_hosts()
self.assertEqual(sorted(hosts), sorted(['foo.example.com','bar.example.com']))
def test_simple_string_fqdn_vars(self):
inventory = Inventory('foo.example.com:2222,bar.example.com')
var = inventory.get_variables('foo.example.com')
self.assertEqual(var['ansible_ssh_port'], 2222)
def test_simple_vars(self):
inventory = self.simple_inventory()
vars = inventory.get_variables('thor')
assert vars == {'group_names': ['norse'],
'inventory_hostname': 'thor',
'inventory_hostname_short': 'thor'}
def test_simple_port(self):
inventory = self.simple_inventory()
vars = inventory.get_variables('hera')
expected = { 'ansible_ssh_port': 3000,
'group_names': ['greek'],
'inventory_hostname': 'hera',
'inventory_hostname_short': 'hera' }
assert vars == expected
def test_large_range(self):
inventory = self.large_range_inventory()
hosts = inventory.list_hosts()
self.assertEqual(sorted(hosts), sorted('bob%03i' %i for i in range(0, 143)))
def test_subset(self):
inventory = self.simple_inventory()
inventory.subset('odin;thor,loki')
self.assertEqual(sorted(inventory.list_hosts()), sorted(['thor','odin','loki']))
def test_subset_filename(self):
inventory = self.simple_inventory()
inventory.subset('@' + os.path.join(self.test_dir, 'restrict_pattern'))
self.assertEqual(sorted(inventory.list_hosts()), sorted(['thor','odin']))
@raises(errors.AnsibleError)
def testinvalid_entry(self):
Inventory('1234')
###################################################
### INI file advanced tests
def test_complex_vars(self):
inventory = self.complex_inventory()
vars = inventory.get_variables('rtp_a')
print vars
expected = dict(
a='1', b='2', c='3', d='10002', e='10003', f='10004 != 10005',
g=' g ', h=' h ', i="' i \"", j='" j',
rga='1', rgb='2', rgc='3',
inventory_hostname='rtp_a', inventory_hostname_short='rtp_a',
group_names=[ 'eastcoast', 'nc', 'redundantgroup', 'redundantgroup2', 'redundantgroup3', 'rtp', 'us' ]
)
print vars
print expected
assert vars == expected
def test_complex_group_names(self):
inventory = self.complex_inventory()
tests = {
'host1': [ 'role1', 'role3' ],
'host2': [ 'role1', 'role2' ],
'host3': [ 'role2', 'role3' ]
}
for host, roles in tests.iteritems():
group_names = inventory.get_variables(host)['group_names']
assert sorted(group_names) == sorted(roles)
def test_complex_exclude(self):
inventory = self.complex_inventory()
hosts = inventory.list_hosts("nc:florida:!triangle:!orlando")
expected_hosts = ['miami', 'rtp_a', 'rtp_b', 'rtp_c']
print "HOSTS=%s" % sorted(hosts)
print "EXPECTED=%s" % sorted(expected_hosts)
assert sorted(hosts) == sorted(expected_hosts)
def test_regex_exclude(self):
inventory = self.complex_inventory()
hosts = inventory.list_hosts("~rtp_[ac]")
expected_hosts = ['rtp_a', 'rtp_c']
print "HOSTS=%s" % sorted(hosts)
print "EXPECTED=%s" % sorted(expected_hosts)
assert sorted(hosts) == sorted(expected_hosts)
def test_complex_enumeration(self):
expected1 = ['rtp_b']
expected2 = ['rtp_a', 'rtp_b']
expected3 = ['rtp_a', 'rtp_b', 'rtp_c', 'tri_a', 'tri_b', 'tri_c']
expected4 = ['rtp_b', 'orlando' ]
expected5 = ['blade-a-1']
inventory = self.complex_inventory()
hosts = inventory.list_hosts("nc[1]")
self.compare(hosts, expected1, sort=False)
hosts = inventory.list_hosts("nc[0-2]")
self.compare(hosts, expected2, sort=False)
hosts = inventory.list_hosts("nc[0-99999]")
self.compare(hosts, expected3, sort=False)
hosts = inventory.list_hosts("nc[1-2]:florida[0-1]")
self.compare(hosts, expected4, sort=False)
hosts = inventory.list_hosts("blade-a-1")
self.compare(hosts, expected5, sort=False)
def test_complex_intersect(self):
inventory = self.complex_inventory()
hosts = inventory.list_hosts("nc:&redundantgroup:!rtp_c")
self.compare(hosts, ['rtp_a'])
hosts = inventory.list_hosts("nc:&triangle:!tri_c")
self.compare(hosts, ['tri_a', 'tri_b'])
@raises(errors.AnsibleError)
def test_invalid_range(self):
Inventory(os.path.join(self.test_dir, 'inventory','test_incorrect_range'))
@raises(errors.AnsibleError)
def test_missing_end(self):
Inventory(os.path.join(self.test_dir, 'inventory','test_missing_end'))
@raises(errors.AnsibleError)
def test_incorrect_format(self):
Inventory(os.path.join(self.test_dir, 'inventory','test_incorrect_format'))
@raises(errors.AnsibleError)
def test_alpha_end_before_beg(self):
Inventory(os.path.join(self.test_dir, 'inventory','test_alpha_end_before_beg'))
def test_combined_range(self):
i = Inventory(os.path.join(self.test_dir, 'inventory','test_combined_range'))
hosts = i.list_hosts('test')
expected_hosts=['host1A','host2A','host1B','host2B']
assert sorted(hosts) == sorted(expected_hosts)
def test_leading_range(self):
i = Inventory(os.path.join(self.test_dir, 'inventory','test_leading_range'))
hosts = i.list_hosts('test')
expected_hosts=['1.host','2.host','A.host','B.host']
assert sorted(hosts) == sorted(expected_hosts)
hosts2 = i.list_hosts('test2')
expected_hosts2=['1.host','2.host','3.host']
assert sorted(hosts2) == sorted(expected_hosts2)
###################################################
### Inventory API tests
def test_script(self):
inventory = self.script_inventory()
hosts = inventory.list_hosts()
expected_hosts=['jupiter', 'saturn', 'zeus', 'hera', 'poseidon', 'thor', 'odin', 'loki']
print "Expected: %s"%(expected_hosts)
print "Got : %s"%(hosts)
assert sorted(hosts) == sorted(expected_hosts)
def test_script_all(self):
inventory = self.script_inventory()
hosts = inventory.list_hosts('all')
expected_hosts=['jupiter', 'saturn', 'zeus', 'hera', 'poseidon', 'thor', 'odin', 'loki']
assert sorted(hosts) == sorted(expected_hosts)
def test_script_norse(self):
inventory = self.script_inventory()
hosts = inventory.list_hosts("norse")
expected_hosts=['thor', 'odin', 'loki']
assert sorted(hosts) == sorted(expected_hosts)
def test_script_combined(self):
inventory = self.script_inventory()
hosts = inventory.list_hosts("norse:greek")
expected_hosts=['zeus', 'hera', 'poseidon', 'thor', 'odin', 'loki']
assert sorted(hosts) == sorted(expected_hosts)
def test_script_restrict(self):
inventory = self.script_inventory()
restricted_hosts = ['hera', 'poseidon', 'thor']
expected_hosts=['zeus', 'hera', 'poseidon', 'thor', 'odin', 'loki']
inventory.restrict_to(restricted_hosts)
hosts = inventory.list_hosts("norse:greek")
assert sorted(hosts) == sorted(restricted_hosts)
inventory.lift_restriction()
hosts = inventory.list_hosts("norse:greek")
assert sorted(hosts) == sorted(expected_hosts)
def test_script_vars(self):
inventory = self.script_inventory()
vars = inventory.get_variables('thor')
print "VARS=%s" % vars
assert vars == {'hammer':True,
'group_names': ['norse'],
'inventory_hostname': 'thor',
'inventory_hostname_short': 'thor'}
def test_hosts_list(self):
# Test the case when playbook 'hosts' var is a list.
inventory = self.script_inventory()
host_names = sorted(['thor', 'loki', 'odin']) # Not sure if sorting is in the contract or not
actual_hosts = inventory.get_hosts(host_names)
actual_host_names = [host.name for host in actual_hosts]
assert host_names == actual_host_names
def test_script_multiple_groups(self):
inventory = self.script_inventory()
vars = inventory.get_variables('zeus')
print "VARS=%s" % vars
assert vars == {'inventory_hostname': 'zeus',
'inventory_hostname_short': 'zeus',
'group_names': ['greek', 'major-god']}
def test_allows_equals_sign_in_var(self):
inventory = self.simple_inventory()
auth = inventory.get_variables('neptun')['auth']
assert auth == 'YWRtaW46YWRtaW4='
# test disabled as needs to be updated to model desired behavior
#
#def test_dir_inventory(self):
# inventory = self.dir_inventory()
# vars = inventory.get_variables('zeus')
#
# print "VARS=%s" % vars
#
# assert vars == {'inventory_hostname': 'zeus',
# 'inventory_hostname_short': 'zeus',
# 'group_names': ['greek', 'major-god', 'ungrouped'],
# 'var_a': '1#2'}

View file

@ -0,0 +1,132 @@
import unittest
import getpass
import os
import shutil
import time
import tempfile
from nose.plugins.skip import SkipTest
from ansible.runner.action_plugins.synchronize import ActionModule as Synchronize
class FakeRunner(object):
def __init__(self):
self.connection = None
self.transport = None
self.basedir = None
self.sudo = None
self.remote_user = None
self.private_key_file = None
def _execute_module(self, conn, tmp, module_name, args, inject=None):
self.executed_conn = conn
self.executed_tmp = tmp
self.executed_module_name = module_name
self.executed_args = args
self.executed_inject = inject
class FakeConn(object):
def __init__(self):
self.host = None
self.delegate = None
class TestSynchronize(unittest.TestCase):
def test_synchronize_action_basic(self):
""" verify the synchronize action plugin sets
the delegate to 127.0.0.1 and remote path to user@host:/path """
runner = FakeRunner()
runner.remote_user = "root"
runner.transport = "ssh"
conn = FakeConn()
inject = {
'inventory_hostname': "el6.lab.net",
'inventory_hostname_short': "el6",
'ansible_connection': None,
'ansible_ssh_user': 'root',
'delegate_to': None,
'playbook_dir': '.',
}
x = Synchronize(runner)
x.setup("synchronize", inject)
x.run(conn, "/tmp", "synchronize", "src=/tmp/foo dest=/tmp/bar", inject)
assert runner.executed_inject['delegate_to'] == "127.0.0.1", "was not delegated to 127.0.0.1"
assert runner.executed_args == "dest=root@el6.lab.net:/tmp/bar src=/tmp/foo", "wrong args used"
assert runner.sudo == False, "sudo not set to false"
def test_synchronize_action_local(self):
""" verify the synchronize action plugin sets
the delegate to 127.0.0.1 and does not alter the dest """
runner = FakeRunner()
runner.remote_user = "jtanner"
runner.transport = "paramiko"
conn = FakeConn()
conn.host = "127.0.0.1"
conn.delegate = "thishost"
inject = {
'inventory_hostname': "thishost",
'ansible_ssh_host': '127.0.0.1',
'ansible_connection': 'local',
'delegate_to': None,
'playbook_dir': '.',
}
x = Synchronize(runner)
x.setup("synchronize", inject)
x.run(conn, "/tmp", "synchronize", "src=/tmp/foo dest=/tmp/bar", inject)
assert runner.transport == "paramiko", "runner transport was changed"
assert runner.remote_user == "jtanner", "runner remote_user was changed"
assert runner.executed_inject['delegate_to'] == "127.0.0.1", "was not delegated to 127.0.0.1"
assert "dest_port" not in runner.executed_args, "dest_port should not have been set"
assert "src=/tmp/foo" in runner.executed_args, "source was set incorrectly"
assert "dest=/tmp/bar" in runner.executed_args, "dest was set incorrectly"
def test_synchronize_action_vagrant(self):
""" Verify the action plugin accomodates the common
scenarios for vagrant boxes. """
runner = FakeRunner()
runner.remote_user = "jtanner"
runner.transport = "ssh"
conn = FakeConn()
conn.host = "127.0.0.1"
conn.delegate = "thishost"
inject = {
'inventory_hostname': "thishost",
'ansible_ssh_user': 'vagrant',
'ansible_ssh_host': '127.0.0.1',
'ansible_ssh_port': '2222',
'delegate_to': None,
'playbook_dir': '.',
'hostvars': {
'thishost': {
'inventory_hostname': 'thishost',
'ansible_ssh_port': '2222',
'ansible_ssh_host': '127.0.0.1',
'ansible_ssh_user': 'vagrant'
}
}
}
x = Synchronize(runner)
x.setup("synchronize", inject)
x.run(conn, "/tmp", "synchronize", "src=/tmp/foo dest=/tmp/bar", inject)
assert runner.transport == "ssh", "runner transport was changed"
assert runner.remote_user == "jtanner", "runner remote_user was changed"
assert runner.executed_inject['delegate_to'] == "127.0.0.1", "was not delegated to 127.0.0.1"
assert runner.executed_inject['ansible_ssh_user'] == "vagrant", "runner user was changed"
assert "dest_port=2222" in runner.executed_args, "remote port was not set to 2222"
assert "src=/tmp/foo" in runner.executed_args, "source was set incorrectly"
assert "dest=vagrant@127.0.0.1:/tmp/bar" in runner.executed_args, "dest was set incorrectly"

118
test/units/TestUtils.py Normal file
View file

@ -0,0 +1,118 @@
# -*- coding: utf-8 -*-
import unittest
import os
import os.path
import tempfile
from nose.plugins.skip import SkipTest
import ansible.utils
import ansible.utils.template as template2
import sys
reload(sys)
sys.setdefaultencoding("utf8")
class TestUtils(unittest.TestCase):
#####################################
### check_conditional tests
def test_check_conditional_jinja2_literals(self):
# see http://jinja.pocoo.org/docs/templates/#literals
# boolean
assert(ansible.utils.check_conditional(
'true', '/', {}) == True)
assert(ansible.utils.check_conditional(
'false', '/', {}) == False)
assert(ansible.utils.check_conditional(
'True', '/', {}) == True)
assert(ansible.utils.check_conditional(
'False', '/', {}) == False)
# integer
assert(ansible.utils.check_conditional(
'1', '/', {}) == True)
assert(ansible.utils.check_conditional(
'0', '/', {}) == False)
# string, beware, a string is truthy unless empty
assert(ansible.utils.check_conditional(
'"yes"', '/', {}) == True)
assert(ansible.utils.check_conditional(
'"no"', '/', {}) == True)
assert(ansible.utils.check_conditional(
'""', '/', {}) == False)
def test_check_conditional_jinja2_variable_literals(self):
# see http://jinja.pocoo.org/docs/templates/#literals
# boolean
assert(ansible.utils.check_conditional(
'var', '/', {'var': 'True'}) == True)
assert(ansible.utils.check_conditional(
'var', '/', {'var': 'true'}) == True)
assert(ansible.utils.check_conditional(
'var', '/', {'var': 'False'}) == False)
assert(ansible.utils.check_conditional(
'var', '/', {'var': 'false'}) == False)
# integer
assert(ansible.utils.check_conditional(
'var', '/', {'var': '1'}) == True)
assert(ansible.utils.check_conditional(
'var', '/', {'var': 1}) == True)
assert(ansible.utils.check_conditional(
'var', '/', {'var': '0'}) == False)
assert(ansible.utils.check_conditional(
'var', '/', {'var': 0}) == False)
# string, beware, a string is truthy unless empty
assert(ansible.utils.check_conditional(
'var', '/', {'var': '"yes"'}) == True)
assert(ansible.utils.check_conditional(
'var', '/', {'var': '"no"'}) == True)
assert(ansible.utils.check_conditional(
'var', '/', {'var': '""'}) == False)
# Python boolean in Jinja2 expression
assert(ansible.utils.check_conditional(
'var', '/', {'var': True}) == True)
assert(ansible.utils.check_conditional(
'var', '/', {'var': False}) == False)
def test_check_conditional_jinja2_expression(self):
assert(ansible.utils.check_conditional(
'1 == 1', '/', {}) == True)
assert(ansible.utils.check_conditional(
'bar == 42', '/', {'bar': 42}) == True)
assert(ansible.utils.check_conditional(
'bar != 42', '/', {'bar': 42}) == False)
def test_check_conditional_jinja2_expression_in_variable(self):
assert(ansible.utils.check_conditional(
'var', '/', {'var': '1 == 1'}) == True)
assert(ansible.utils.check_conditional(
'var', '/', {'var': 'bar == 42', 'bar': 42}) == True)
assert(ansible.utils.check_conditional(
'var', '/', {'var': 'bar != 42', 'bar': 42}) == False)
def test_check_conditional_jinja2_unicode(self):
assert(ansible.utils.check_conditional(
u'"\u00df"', '/', {}) == True)
assert(ansible.utils.check_conditional(
u'var == "\u00df"', '/', {'var': u'\u00df'}) == True)
#####################################
### key-value parsing
def test_parse_kv_basic(self):
assert (ansible.utils.parse_kv('a=simple b="with space" c="this=that"') ==
{'a': 'simple', 'b': 'with space', 'c': 'this=that'})

3
test/units/ansible.cfg Normal file
View file

@ -0,0 +1,3 @@
[defaults]
test_key = test_value

View file

@ -0,0 +1,2 @@
[somegroup]
localhost

View file

@ -0,0 +1,4 @@
---
duck: quack
cow: moo
extguard: " '$favcolor' == 'blue' "

View file

@ -0,0 +1,95 @@
# order of groups, children, and vars is not signficant
# so this example mixes them up for maximum testing
[nc:children]
rtp
triangle
[eastcoast:children]
nc
florida
[us:children]
eastcoast
[redundantgroup]
rtp_a
[redundantgroup2]
rtp_a
[redundantgroup3:children]
rtp
[redundantgroup:vars]
rga=1
[redundantgroup2:vars]
rgb=2
[redundantgroup3:vars]
rgc=3
[nc:vars]
b=10000
c=10001
d=10002
e = 10003
f = 10004 != 10005
g = " g "
h = ' h '
i = ' i "
j = " j
[rtp]
rtp_a
rtp_b
rtp_c
[rtp:vars]
a=1
b=2
c=3
[triangle]
tri_a
tri_b
tri_c
[triangle:vars]
a=11
b=12
c=13
[florida]
orlando
miami
[florida:vars]
a=100
b=101
c=102
[eastcoast:vars]
b=100000
c=100001
d=100002
[us:vars]
c=1000000
[role1]
host[1:2]
[role2]
host[2:3]
[role3]
host[1:3:2]
[role4]
blade-[a:c]-[1:16]
blade-[d:z]-[01:16].example.com
blade-[1:10]-[1:16]
host-e-[10:16].example.net:1234

View file

@ -0,0 +1,6 @@
# Test that playbooks support YAML lists of hosts.
---
- hosts: [host1, host2, host3]
connection: local
tasks:
- action: command true

View file

@ -0,0 +1,2 @@
[test]
host[Z:T]

View file

@ -0,0 +1,2 @@
[test]
host[1:2][A:B]

View file

@ -0,0 +1,2 @@
[test]
host[001:10]

View file

@ -0,0 +1,2 @@
[test]
host[1:2:3:4]

View file

@ -0,0 +1,6 @@
[test]
[1:2].host
[A:B].host
[test2] # comment
[1:3].host

View file

@ -0,0 +1,2 @@
[test]
host[1:]

View file

@ -0,0 +1,41 @@
#!/usr/bin/env python
import json
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-l', '--list', default=False, dest="list_hosts", action="store_true")
parser.add_option('-H', '--host', default=None, dest="host")
parser.add_option('-e', '--extra-vars', default=None, dest="extra")
options, args = parser.parse_args()
systems = {
"ungrouped": [ "jupiter", "saturn" ],
"greek": [ "zeus", "hera", "poseidon" ],
"norse": [ "thor", "odin", "loki" ],
"major-god": [ "zeus", "odin" ],
}
variables = {
"thor": {
"hammer": True
},
"zeus": {},
}
if options.list_hosts == True:
print json.dumps(systems)
sys.exit(0)
if options.host is not None:
if options.extra:
k,v = options.extra.split("=")
variables[options.host][k] = v
print json.dumps(variables[options.host])
sys.exit(0)
parser.print_help()
sys.exit(1)

View file

@ -0,0 +1,3 @@
zeus var_a=2
morpheus
thor

View file

@ -0,0 +1,6 @@
[greek]
zeus
morpheus
[norse]
thor

View file

@ -0,0 +1,6 @@
[major-god]
zeus var_a=1
thor
[minor-god]
morpheus

View file

@ -0,0 +1,8 @@
[major-god] # group with inline comments
zeus var_a="1#2" # host with inline comments and "#" in the var string
# A comment
thor
[minor-god] # group with inline comment and unbalanced quotes: ' "
morpheus # host with inline comments and unbalanced quotes: ' "
# A comment with unbalanced quotes: ' "

View file

@ -0,0 +1 @@
bob[000:142]

View file

@ -0,0 +1,2 @@
odin
thor

View file

@ -0,0 +1,22 @@
jupiter
saturn
thrudgelmir[:5]
[greek]
zeus
hera:3000
poseidon
cerberus[001:003]
cottus[99:100]
[norse]
thor
odin
loki
[egyptian]
Hotep-[a:c]
Bast[C:D]
[auth]
neptun auth="YWRtaW46YWRtaW4="