Initial commit
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
import os
|
||||
import os.path
|
||||
|
||||
import pytest
|
||||
|
||||
from awx.main.tests import data
|
||||
from awx.main.utils.ansible import could_be_playbook, could_be_inventory
|
||||
|
||||
DATA = os.path.join(os.path.dirname(data.__file__), 'ansible_utils')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename', os.listdir(os.path.join(DATA, 'playbooks', 'valid')))
|
||||
def test_could_be_playbook(filename):
|
||||
path = os.path.join(DATA, 'playbooks', 'valid')
|
||||
assert could_be_playbook(DATA, path, filename).endswith(filename)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename', os.listdir(os.path.join(DATA, 'playbooks', 'invalid')))
|
||||
def test_is_not_playbook(filename):
|
||||
path = os.path.join(DATA, 'playbooks', 'invalid')
|
||||
assert could_be_playbook(DATA, path, filename) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename', os.listdir(os.path.join(DATA, 'inventories', 'valid')))
|
||||
def test_could_be_inventory(filename):
|
||||
path = os.path.join(DATA, 'inventories', 'valid')
|
||||
assert could_be_inventory(DATA, path, filename).endswith(filename)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename', os.listdir(os.path.join(DATA, 'inventories', 'invalid')))
|
||||
def test_is_not_inventory(filename):
|
||||
path = os.path.join(DATA, 'inventories', 'invalid')
|
||||
assert could_be_inventory(DATA, path, filename) is None
|
||||
@@ -0,0 +1,217 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2017 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
import os
|
||||
import pytest
|
||||
from uuid import uuid4
|
||||
import json
|
||||
import yaml
|
||||
from unittest import mock
|
||||
|
||||
from backports.tempfile import TemporaryDirectory
|
||||
from django.conf import settings
|
||||
|
||||
from rest_framework.exceptions import ParseError
|
||||
|
||||
from awx.main.utils import common
|
||||
|
||||
from awx.main.models import (
|
||||
Job,
|
||||
AdHocCommand,
|
||||
InventoryUpdate,
|
||||
ProjectUpdate,
|
||||
SystemJob,
|
||||
WorkflowJob,
|
||||
Inventory,
|
||||
JobTemplate,
|
||||
UnifiedJobTemplate,
|
||||
UnifiedJob
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('input_, output', [
|
||||
({"foo": "bar"}, {"foo": "bar"}),
|
||||
('{"foo": "bar"}', {"foo": "bar"}),
|
||||
('---\nfoo: bar', {"foo": "bar"}),
|
||||
(4399, {}),
|
||||
])
|
||||
def test_parse_yaml_or_json(input_, output):
|
||||
assert common.parse_yaml_or_json(input_) == output
|
||||
|
||||
|
||||
def test_recursive_vars_not_allowed():
|
||||
rdict = {}
|
||||
rdict['a'] = rdict
|
||||
# YAML dumper will use a tag to give recursive data
|
||||
data = yaml.dump(rdict, default_flow_style=False)
|
||||
with pytest.raises(ParseError) as exc:
|
||||
common.parse_yaml_or_json(data, silent_failure=False)
|
||||
assert 'Circular reference detected' in str(exc)
|
||||
|
||||
|
||||
class TestParserExceptions:
|
||||
|
||||
@staticmethod
|
||||
def json_error(data):
|
||||
try:
|
||||
json.loads(data)
|
||||
return None
|
||||
except Exception as e:
|
||||
return str(e)
|
||||
|
||||
@staticmethod
|
||||
def yaml_error(data):
|
||||
try:
|
||||
yaml.safe_load(data)
|
||||
return None
|
||||
except Exception as e:
|
||||
return str(e)
|
||||
|
||||
def test_invalid_JSON_and_YAML(self):
|
||||
data = "{key:val"
|
||||
with pytest.raises(ParseError) as exc:
|
||||
common.parse_yaml_or_json(data, silent_failure=False)
|
||||
message = str(exc.value)
|
||||
assert "Cannot parse as" in message
|
||||
assert self.json_error(data) in message
|
||||
assert self.yaml_error(data) in message
|
||||
|
||||
def test_invalid_vars_type(self):
|
||||
data = "[1, 2, 3]"
|
||||
with pytest.raises(ParseError) as exc:
|
||||
common.parse_yaml_or_json(data, silent_failure=False)
|
||||
message = str(exc.value)
|
||||
assert "Cannot parse as" in message
|
||||
assert "Input type `list` is not a dictionary" in message
|
||||
|
||||
|
||||
def test_set_environ():
|
||||
key = str(uuid4())
|
||||
old_environ = os.environ.copy()
|
||||
with common.set_environ(**{key: 'bar'}):
|
||||
assert os.environ[key] == 'bar'
|
||||
assert set(os.environ.keys()) - set(old_environ.keys()) == set([key])
|
||||
assert os.environ == old_environ
|
||||
assert key not in os.environ
|
||||
|
||||
|
||||
TEST_MODELS = [
|
||||
(Job, 'job'),
|
||||
(AdHocCommand, 'ad_hoc_command'),
|
||||
(InventoryUpdate, 'inventory_update'),
|
||||
(ProjectUpdate, 'project_update'),
|
||||
(SystemJob, 'system_job'),
|
||||
(WorkflowJob, 'workflow_job'),
|
||||
(UnifiedJob, 'unified_job'),
|
||||
(Inventory, 'inventory'),
|
||||
(JobTemplate, 'job_template'),
|
||||
(UnifiedJobTemplate, 'unified_job_template')
|
||||
]
|
||||
|
||||
|
||||
# Cases relied on for scheduler dependent jobs list
|
||||
@pytest.mark.parametrize('model,name', TEST_MODELS)
|
||||
def test_get_type_for_model(model, name):
|
||||
assert common.get_type_for_model(model) == name
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_get_model_for_invalid_type():
|
||||
with pytest.raises(LookupError):
|
||||
common.get_model_for_type('foobar')
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("model_type,model_class", [
|
||||
(name, cls) for cls, name in TEST_MODELS
|
||||
])
|
||||
def test_get_model_for_valid_type(model_type, model_class):
|
||||
assert common.get_model_for_type(model_type) == model_class
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def memoized_function(mocker, mock_cache):
|
||||
with mock.patch('awx.main.utils.common.get_memoize_cache', return_value=mock_cache):
|
||||
@common.memoize(track_function=True)
|
||||
def myfunction(key, value):
|
||||
if key not in myfunction.calls:
|
||||
myfunction.calls[key] = 0
|
||||
|
||||
myfunction.calls[key] += 1
|
||||
|
||||
if myfunction.calls[key] == 1:
|
||||
return value
|
||||
else:
|
||||
return '%s called %s times' % (value, myfunction.calls[key])
|
||||
myfunction.calls = dict()
|
||||
return myfunction
|
||||
|
||||
|
||||
def test_memoize_track_function(memoized_function, mock_cache):
|
||||
assert memoized_function('scott', 'scotterson') == 'scotterson'
|
||||
assert mock_cache.get('myfunction') == {u'scott-scotterson': 'scotterson'}
|
||||
assert memoized_function('scott', 'scotterson') == 'scotterson'
|
||||
|
||||
assert memoized_function.calls['scott'] == 1
|
||||
|
||||
assert memoized_function('john', 'smith') == 'smith'
|
||||
assert mock_cache.get('myfunction') == {u'scott-scotterson': 'scotterson', u'john-smith': 'smith'}
|
||||
assert memoized_function('john', 'smith') == 'smith'
|
||||
|
||||
assert memoized_function.calls['john'] == 1
|
||||
|
||||
|
||||
def test_memoize_delete(memoized_function, mock_cache):
|
||||
assert memoized_function('john', 'smith') == 'smith'
|
||||
assert memoized_function('john', 'smith') == 'smith'
|
||||
assert memoized_function.calls['john'] == 1
|
||||
|
||||
assert mock_cache.get('myfunction') == {u'john-smith': 'smith'}
|
||||
|
||||
with mock.patch('awx.main.utils.common.memoize_delete', side_effect=mock_cache.delete):
|
||||
common.memoize_delete('myfunction')
|
||||
|
||||
assert mock_cache.get('myfunction') is None
|
||||
|
||||
assert memoized_function('john', 'smith') == 'smith called 2 times'
|
||||
assert memoized_function.calls['john'] == 2
|
||||
|
||||
|
||||
def test_memoize_parameter_error():
|
||||
|
||||
with pytest.raises(common.IllegalArgumentError):
|
||||
@common.memoize(cache_key='foo', track_function=True)
|
||||
def fn():
|
||||
return
|
||||
|
||||
|
||||
def test_extract_ansible_vars():
|
||||
my_dict = {
|
||||
"foobar": "baz",
|
||||
"ansible_connetion_setting": "1928"
|
||||
}
|
||||
redacted, var_list = common.extract_ansible_vars(json.dumps(my_dict))
|
||||
assert var_list == set(['ansible_connetion_setting'])
|
||||
assert redacted == {"foobar": "baz"}
|
||||
|
||||
|
||||
def test_get_custom_venv_choices():
|
||||
bundled_venv = os.path.join(settings.BASE_VENV_PATH, 'ansible', '')
|
||||
assert sorted(common.get_custom_venv_choices()) == [bundled_venv]
|
||||
|
||||
with TemporaryDirectory(dir=settings.BASE_VENV_PATH, prefix='tmp') as temp_dir:
|
||||
os.makedirs(os.path.join(temp_dir, 'bin', 'activate'))
|
||||
|
||||
custom_venv_dir = os.path.join(temp_dir, 'custom')
|
||||
custom_venv_1 = os.path.join(custom_venv_dir, 'venv-1')
|
||||
custom_venv_awx = os.path.join(custom_venv_dir, 'custom', 'awx')
|
||||
|
||||
os.makedirs(os.path.join(custom_venv_1, 'bin', 'activate'))
|
||||
os.makedirs(os.path.join(custom_venv_awx, 'bin', 'activate'))
|
||||
|
||||
assert sorted(common.get_custom_venv_choices([custom_venv_dir])) == [
|
||||
bundled_venv,
|
||||
os.path.join(temp_dir, ''),
|
||||
os.path.join(custom_venv_1, '')
|
||||
]
|
||||
@@ -0,0 +1,78 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2017 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
import pytest
|
||||
|
||||
from awx.conf.models import Setting
|
||||
from awx.main.utils import encryption
|
||||
|
||||
|
||||
def test_encrypt_field():
|
||||
field = Setting(pk=123, value='ANSIBLE')
|
||||
encrypted = field.value = encryption.encrypt_field(field, 'value')
|
||||
assert encryption.decrypt_field(field, 'value') == 'ANSIBLE'
|
||||
assert encrypted.startswith('$encrypted$UTF8$AESCBC$')
|
||||
|
||||
|
||||
def test_encrypt_field_without_pk():
|
||||
field = Setting(value='ANSIBLE')
|
||||
encrypted = field.value = encryption.encrypt_field(field, 'value')
|
||||
assert encryption.decrypt_field(field, 'value') == 'ANSIBLE'
|
||||
assert encrypted.startswith('$encrypted$UTF8$AESCBC$')
|
||||
|
||||
|
||||
def test_encrypt_field_with_unicode_string():
|
||||
value = u'Iñtërnâtiônàlizætiøn'
|
||||
field = Setting(value=value)
|
||||
encrypted = field.value = encryption.encrypt_field(field, 'value')
|
||||
assert encryption.decrypt_field(field, 'value') == value
|
||||
assert encrypted.startswith('$encrypted$UTF8$AESCBC$')
|
||||
|
||||
|
||||
def test_encrypt_subfield():
|
||||
field = Setting(value={'name': 'ANSIBLE'})
|
||||
encrypted = field.value = encryption.encrypt_field(field, 'value', subfield='name')
|
||||
assert encryption.decrypt_field(field, 'value', subfield='name') == 'ANSIBLE'
|
||||
assert encrypted.startswith('$encrypted$UTF8$AESCBC$')
|
||||
|
||||
|
||||
def test_encrypt_field_with_ask():
|
||||
encrypted = encryption.encrypt_field(Setting(value='ASK'), 'value', ask=True)
|
||||
assert encrypted == 'ASK'
|
||||
|
||||
|
||||
def test_encrypt_field_with_empty_value():
|
||||
encrypted = encryption.encrypt_field(Setting(value=None), 'value')
|
||||
assert encrypted is None
|
||||
|
||||
|
||||
def test_encrypt_field_with_undefined_attr_raises_expected_exception():
|
||||
with pytest.raises(AttributeError):
|
||||
encryption.encrypt_field({}, 'undefined_attr')
|
||||
|
||||
|
||||
def test_decrypt_field_with_undefined_attr_raises_expected_exception():
|
||||
with pytest.raises(AttributeError):
|
||||
encryption.decrypt_field({}, 'undefined_attr')
|
||||
|
||||
|
||||
class TestSurveyReversibilityValue:
|
||||
'''
|
||||
Tests to enforce the contract with survey password question encrypted values
|
||||
'''
|
||||
_key = encryption.get_encryption_key('value', None)
|
||||
|
||||
def test_encrypt_empty_string(self):
|
||||
assert encryption.encrypt_value('') == ''
|
||||
# the reverse, decryption, does not work
|
||||
|
||||
def test_encrypt_encryption_key(self):
|
||||
assert encryption.encrypt_value('$encrypted$') == '$encrypted$'
|
||||
# the reverse, decryption, does not work
|
||||
|
||||
def test_encrypt_empty_string_twice(self):
|
||||
# Encryption is idempotent
|
||||
val = encryption.encrypt_value('foobar')
|
||||
val2 = encryption.encrypt_value(val)
|
||||
assert encryption.decrypt_value(self._key, val2) == 'foobar'
|
||||
@@ -0,0 +1,229 @@
|
||||
|
||||
# Python
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
# AWX
|
||||
from awx.main.utils.filters import SmartFilter, ExternalLoggerEnabled
|
||||
from awx.main.models import Host
|
||||
|
||||
# Django
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
|
||||
@pytest.mark.parametrize('params, logger_name, expected', [
|
||||
# skip all records if enabled_flag = False
|
||||
({'enabled_flag': False}, 'awx.main', False),
|
||||
# skip all records if the host is undefined
|
||||
({'enabled_flag': True}, 'awx.main', False),
|
||||
# skip all records if underlying logger is used by handlers themselves
|
||||
({'enabled_flag': True}, 'awx.main.utils.handlers', False),
|
||||
({'enabled_flag': True, 'enabled_loggers': ['awx']}, 'awx.main', True),
|
||||
({'enabled_flag': True, 'enabled_loggers': ['abc']}, 'awx.analytics.xyz', False),
|
||||
({'enabled_flag': True, 'enabled_loggers': ['xyz']}, 'awx.analytics.xyz', True),
|
||||
])
|
||||
def test_base_logging_handler_skip_log(params, logger_name, expected, dummy_log_record):
|
||||
filter = ExternalLoggerEnabled(**params)
|
||||
dummy_log_record.name = logger_name
|
||||
assert filter.filter(dummy_log_record) is expected, (params, logger_name)
|
||||
|
||||
|
||||
class Field(object):
|
||||
|
||||
def __init__(self, name, related_model=None, __prevent_search__=None):
|
||||
self.name = name
|
||||
self.related_model = related_model
|
||||
self.__prevent_search__ = __prevent_search__
|
||||
|
||||
|
||||
class Meta(object):
|
||||
|
||||
def __init__(self, fields):
|
||||
self._fields = {
|
||||
f.name: f for f in fields
|
||||
}
|
||||
self.object_name = 'Host'
|
||||
self.fields_map = {}
|
||||
self.fields = self._fields.values()
|
||||
|
||||
def get_field(self, f):
|
||||
return self._fields.get(f)
|
||||
|
||||
|
||||
class mockObjects:
|
||||
def filter(self, *args, **kwargs):
|
||||
return Q(*args, **kwargs)
|
||||
|
||||
|
||||
class mockUser:
|
||||
def __init__(self):
|
||||
print("Host user created")
|
||||
self._meta = Meta(fields=[
|
||||
Field(name='password', __prevent_search__=True)
|
||||
])
|
||||
|
||||
|
||||
class mockHost:
|
||||
def __init__(self):
|
||||
print("Host mock created")
|
||||
self.objects = mockObjects()
|
||||
fields = [
|
||||
Field(name='name'),
|
||||
Field(name='description'),
|
||||
Field(name='created_by', related_model=mockUser())
|
||||
]
|
||||
self._meta = Meta(fields=fields)
|
||||
|
||||
|
||||
@mock.patch('awx.main.utils.filters.get_model', return_value=mockHost())
|
||||
class TestSmartFilterQueryFromString():
|
||||
@mock.patch(
|
||||
'awx.api.filters.get_fields_from_path',
|
||||
lambda model, path: ([model], path) # disable field filtering, because a__b isn't a real Host field
|
||||
)
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('facts__facts__blank=""', Q(**{u"facts__facts__blank": u""})),
|
||||
('"facts__facts__ space "="f"', Q(**{u"facts__facts__ space ": u"f"})),
|
||||
('"facts__facts__ e "=no_quotes_here', Q(**{u"facts__facts__ e ": u"no_quotes_here"})),
|
||||
('a__b__c=3', Q(**{u"a__b__c": 3})),
|
||||
('a__b__c=3.14', Q(**{u"a__b__c": 3.14})),
|
||||
('a__b__c=true', Q(**{u"a__b__c": True})),
|
||||
('a__b__c=false', Q(**{u"a__b__c": False})),
|
||||
('a__b__c=null', Q(**{u"a__b__c": None})),
|
||||
('ansible_facts__a="true"', Q(**{u"ansible_facts__contains": {u"a": u"true"}})),
|
||||
('ansible_facts__a__exact="true"', Q(**{u"ansible_facts__contains": {u"a": u"true"}})),
|
||||
#('"a__b\"__c"="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
#('a__b\"__c="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
])
|
||||
def test_query_generated(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
@pytest.mark.parametrize("filter_string", [
|
||||
'ansible_facts__facts__facts__blank='
|
||||
'ansible_facts__a__b__c__ space =ggg',
|
||||
])
|
||||
def test_invalid_filter_strings(self, mock_get_host_model, filter_string):
|
||||
with pytest.raises(RuntimeError) as e:
|
||||
SmartFilter.query_from_string(filter_string)
|
||||
assert str(e.value) == u"Invalid query " + filter_string
|
||||
|
||||
@pytest.mark.parametrize("filter_string", [
|
||||
'created_by__password__icontains=pbkdf2'
|
||||
'search=foo or created_by__password__icontains=pbkdf2',
|
||||
'created_by__password__icontains=pbkdf2 or search=foo',
|
||||
])
|
||||
def test_forbidden_filter_string(self, mock_get_host_model, filter_string):
|
||||
with pytest.raises(Exception) as e:
|
||||
SmartFilter.query_from_string(filter_string)
|
||||
"Filtering on password is not allowed." in str(e)
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
(u'(a=abc\u1F5E3def)', Q(**{u"a": u"abc\u1F5E3def"})),
|
||||
(u'(ansible_facts__a=abc\u1F5E3def)', Q(**{u"ansible_facts__contains": {u"a": u"abc\u1F5E3def"}})),
|
||||
])
|
||||
def test_unicode(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('(a=b)', Q(**{u"a": u"b"})),
|
||||
('a=b and c=d', Q(**{u"a": u"b"}) & Q(**{u"c": u"d"})),
|
||||
('(a=b and c=d)', Q(**{u"a": u"b"}) & Q(**{u"c": u"d"})),
|
||||
('a=b or c=d', Q(**{u"a": u"b"}) | Q(**{u"c": u"d"})),
|
||||
('(a=b and c=d) or (e=f)', (Q(**{u"a": u"b"}) & Q(**{u"c": u"d"})) | (Q(**{u"e": u"f"}))),
|
||||
(
|
||||
'a=b or a=d or a=e or a=z and b=h and b=i and b=j and b=k',
|
||||
Q(**{u"a": u"b"}) | Q(**{u"a": u"d"}) | Q(**{u"a": u"e"}) | Q(**{u"a": u"z"}) &
|
||||
Q(**{u"b": u"h"}) & Q(**{u"b": u"i"}) & Q(**{u"b": u"j"}) & Q(**{u"b": u"k"})
|
||||
)
|
||||
])
|
||||
def test_boolean_parenthesis(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('ansible_facts__a__b__c[]=3', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [3]}}}})),
|
||||
('ansible_facts__a__b__c[]=3.14', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [3.14]}}}})),
|
||||
('ansible_facts__a__b__c[]=true', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [True]}}}})),
|
||||
('ansible_facts__a__b__c[]=false', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [False]}}}})),
|
||||
('ansible_facts__a__b__c[]="true"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [u"true"]}}}})),
|
||||
('ansible_facts__a__b__c[]="hello world"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [u"hello world"]}}}})),
|
||||
('ansible_facts__a__b__c[]__d[]="foobar"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": [u"foobar"]}]}}}})),
|
||||
('ansible_facts__a__b__c[]__d="foobar"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": u"foobar"}]}}}})),
|
||||
('ansible_facts__a__b__c[]__d__e="foobar"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": {u"e": u"foobar"}}]}}}})),
|
||||
('ansible_facts__a__b__c[]__d__e[]="foobar"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": {u"e": [u"foobar"]}}]}}}})),
|
||||
('ansible_facts__a__b__c[]__d__e__f[]="foobar"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": {u"e": {u"f": [u"foobar"]}}}]}}}})),
|
||||
(
|
||||
'(ansible_facts__a__b__c[]__d__e__f[]="foobar") and (ansible_facts__a__b__c[]__d__e[]="foobar")',
|
||||
Q(**{ u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": {u"e": {u"f": [u"foobar"]}}}]}}}}) &
|
||||
Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": {u"e": [u"foobar"]}}]}}}})),
|
||||
#('"a__b\"__c"="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
#('a__b\"__c="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
])
|
||||
def test_contains_query_generated(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
#('a__b__c[]="true"', Q(**{u"a__b__c__contains": u"\"true\""})),
|
||||
('ansible_facts__a="true"', Q(**{u"ansible_facts__contains": {u"a": u"true"}})),
|
||||
#('"a__b\"__c"="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
#('a__b\"__c="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
])
|
||||
def test_contains_query_generated_unicode(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('ansible_facts__a=null', Q(**{u"ansible_facts__contains": {u"a": None}})),
|
||||
('ansible_facts__c="null"', Q(**{u"ansible_facts__contains": {u"c": u"\"null\""}})),
|
||||
])
|
||||
def test_contains_query_generated_null(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('group__search=foo', Q(Q(**{u"group__name__icontains": u"foo"}) | Q(**{u"group__description__icontains": u"foo"}))),
|
||||
('search=foo and group__search=foo', Q(
|
||||
Q(**{u"name__icontains": u"foo"}) | Q(**{ u"description__icontains": u"foo"}),
|
||||
Q(**{u"group__name__icontains": u"foo"}) | Q(**{u"group__description__icontains": u"foo"}))),
|
||||
('search=foo or ansible_facts__a=null',
|
||||
Q(Q(**{u"name__icontains": u"foo"}) | Q(**{u"description__icontains": u"foo"})) |
|
||||
Q(**{u"ansible_facts__contains": {u"a": None}})),
|
||||
])
|
||||
def test_search_related_fields(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
|
||||
class TestSmartFilterQueryFromStringNoDB():
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('ansible_facts__a="true" and ansible_facts__b="true" and ansible_facts__c="true"',
|
||||
(Q(**{u"ansible_facts__contains": {u"a": u"true"}}) &
|
||||
Q(**{u"ansible_facts__contains": {u"b": u"true"}}) &
|
||||
Q(**{u"ansible_facts__contains": {u"c": u"true"}}))),
|
||||
('ansible_facts__a="true" or ansible_facts__b="true" or ansible_facts__c="true"',
|
||||
(Q(**{u"ansible_facts__contains": {u"a": u"true"}}) |
|
||||
Q(**{u"ansible_facts__contains": {u"b": u"true"}}) |
|
||||
Q(**{u"ansible_facts__contains": {u"c": u"true"}}))),
|
||||
('search=foo',
|
||||
Q(Q(**{ u"description__icontains": u"foo"}) | Q(**{u"name__icontains": u"foo"}))),
|
||||
('search=foo and ansible_facts__a="null"',
|
||||
Q(Q(**{u"description__icontains": u"foo"}) | Q(**{u"name__icontains": u"foo"})) &
|
||||
Q(**{u"ansible_facts__contains": {u"a": u"\"null\""}})),
|
||||
('name=foo or name=bar and name=foobar',
|
||||
Q(name="foo") | Q(name="bar") & Q(name="foobar"))
|
||||
])
|
||||
def test_does_not_invoke_db(self, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q.query) == str(Host.objects.filter(q_expected).query)
|
||||
|
||||
|
||||
'''
|
||||
#('"facts__quoted_val"="f\"oo"', 1),
|
||||
#('facts__facts__arr[]="foo"', 1),
|
||||
#('facts__facts__arr_nested[]__a[]="foo"', 1),
|
||||
'''
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
from awx.main.models import Job, JobEvent
|
||||
|
||||
from awx.main.utils.formatters import LogstashFormatter
|
||||
|
||||
|
||||
def test_log_from_job_event_object():
|
||||
job = Job(id=4)
|
||||
event = JobEvent(job_id=job.id)
|
||||
formatter = LogstashFormatter()
|
||||
|
||||
data_for_log = formatter.reformat_data_for_log(
|
||||
dict(python_objects=dict(job_event=event)), kind='job_events')
|
||||
|
||||
# Check entire body of data for any exceptions from getattr on event object
|
||||
for fd in data_for_log:
|
||||
if not isinstance(data_for_log[fd], str):
|
||||
continue
|
||||
assert 'Exception' not in data_for_log[fd], 'Exception delivered in data: {}'.format(data_for_log[fd])
|
||||
|
||||
# Verify existence of certain high-importance fields
|
||||
for fd in ['changed', 'uuid', 'start_line', 'end_line', 'id', 'counter', 'host_name', 'stdout']:
|
||||
assert fd in data_for_log
|
||||
|
||||
assert data_for_log['job'] == 4
|
||||
@@ -0,0 +1,27 @@
|
||||
# Copyright (c) 2017 Ansible Tower by Red Hat
|
||||
# All Rights Reserved.
|
||||
|
||||
|
||||
from awx.main.utils.insights import filter_insights_api_response
|
||||
from awx.main.tests.data.insights import TEST_INSIGHTS_HOSTS, TEST_INSIGHTS_PLANS, TEST_INSIGHTS_REMEDIATIONS
|
||||
|
||||
|
||||
def test_filter_insights_api_response():
|
||||
actual = filter_insights_api_response(
|
||||
TEST_INSIGHTS_HOSTS['results'][0], TEST_INSIGHTS_PLANS, TEST_INSIGHTS_REMEDIATIONS)
|
||||
|
||||
assert actual['last_check_in'] == '2019-03-19T21:59:09.213151-04:00'
|
||||
assert len(actual['reports']) == 5
|
||||
assert len(actual['reports'][0]['maintenance_actions']) == 1
|
||||
assert actual['reports'][0]['maintenance_actions'][0]['name'] == "Fix Critical CVEs"
|
||||
rule = actual['reports'][0]['rule']
|
||||
|
||||
assert rule['severity'] == 'WARN'
|
||||
assert rule['description'] == (
|
||||
"Kernel vulnerable to side-channel attacks in modern microprocessors (CVE-2017-5715/Spectre)")
|
||||
assert rule['category'] == 'Security'
|
||||
assert rule['summary'] == (
|
||||
"A vulnerability was discovered in modern microprocessors supported by the kernel,"
|
||||
" whereby an unprivileged attacker can use this flaw to bypass restrictions to gain read"
|
||||
" access to privileged memory.\nThe issue was reported as [CVE-2017-5715 / Spectre]"
|
||||
"(https://access.redhat.com/security/cve/CVE-2017-5715).\n")
|
||||
@@ -0,0 +1,128 @@
|
||||
# AWX utils
|
||||
from awx.main.utils.mem_inventory import (
|
||||
MemInventory,
|
||||
mem_data_to_dict, dict_to_mem_data
|
||||
)
|
||||
|
||||
import pytest
|
||||
import json
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def memory_inventory():
|
||||
inventory = MemInventory()
|
||||
h = inventory.get_host('my_host')
|
||||
h.variables = {'foo': 'bar'}
|
||||
g = inventory.get_group('my_group')
|
||||
g.variables = {'foobar': 'barfoo'}
|
||||
h2 = inventory.get_host('group_host')
|
||||
g.add_host(h2)
|
||||
return inventory
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def JSON_of_inv():
|
||||
# Implemented as fixture becuase it may be change inside of tests
|
||||
return {
|
||||
"_meta": {
|
||||
"hostvars": {
|
||||
"group_host": {},
|
||||
"my_host": {"foo": "bar"}
|
||||
}
|
||||
},
|
||||
"all": {"children": ["my_group", "ungrouped"]},
|
||||
"my_group": {
|
||||
"hosts": ["group_host"],
|
||||
"vars": {"foobar": "barfoo"}
|
||||
},
|
||||
"ungrouped": {"hosts": ["my_host"]}
|
||||
}
|
||||
|
||||
|
||||
# Structure mentioned in official docs
|
||||
# https://docs.ansible.com/ansible/dev_guide/developing_inventory.html
|
||||
@pytest.fixture
|
||||
def JSON_with_lists():
|
||||
docs_example = '''{
|
||||
"databases" : {
|
||||
"hosts" : [ "host1.example.com", "host2.example.com" ],
|
||||
"vars" : {
|
||||
"a" : true
|
||||
}
|
||||
},
|
||||
"webservers" : [ "host2.example.com", "host3.example.com" ],
|
||||
"atlanta" : {
|
||||
"hosts" : [ "host1.example.com", "host4.example.com", "host5.example.com" ],
|
||||
"vars" : {
|
||||
"b" : false
|
||||
},
|
||||
"children": [ "marietta", "5points" ]
|
||||
},
|
||||
"marietta" : [ "host6.example.com" ],
|
||||
"5points" : [ "host7.example.com" ]
|
||||
}'''
|
||||
return json.loads(docs_example)
|
||||
|
||||
|
||||
# MemObject basic operations tests
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_inventory_create_all_group():
|
||||
inventory = MemInventory()
|
||||
assert inventory.all_group.name == 'all'
|
||||
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_create_child_group():
|
||||
inventory = MemInventory()
|
||||
g1 = inventory.get_group('g1')
|
||||
# Create new group by name as child of g1
|
||||
g2 = inventory.get_group('g2', g1)
|
||||
# Check that child is in the children of the parent group
|
||||
assert g1.children == [g2]
|
||||
# Check that _only_ the parent group is listed as a root group
|
||||
assert inventory.all_group.children == [g1]
|
||||
# Check that _both_ are tracked by the global `all_groups` dict
|
||||
assert set(inventory.all_group.all_groups.values()) == set([g1, g2])
|
||||
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_ungrouped_mechanics():
|
||||
# ansible-inventory returns a group called `ungrouped`
|
||||
# we can safely treat this the same as the `all_group`
|
||||
inventory = MemInventory()
|
||||
ug = inventory.get_group('ungrouped')
|
||||
assert ug is inventory.all_group
|
||||
|
||||
|
||||
# MemObject --> JSON tests
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_convert_memory_to_JSON_with_vars(memory_inventory):
|
||||
data = mem_data_to_dict(memory_inventory)
|
||||
# Assertions about the variables on the objects
|
||||
assert data['_meta']['hostvars']['my_host'] == {'foo': 'bar'}
|
||||
assert data['my_group']['vars'] == {'foobar': 'barfoo'}
|
||||
# Orphan host should be found in ungrouped false group
|
||||
assert data['ungrouped']['hosts'] == ['my_host']
|
||||
|
||||
|
||||
# JSON --> MemObject tests
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_convert_JSON_to_memory_with_vars(JSON_of_inv):
|
||||
inventory = dict_to_mem_data(JSON_of_inv)
|
||||
# Assertions about the variables on the objects
|
||||
assert inventory.get_host('my_host').variables == {'foo': 'bar'}
|
||||
assert inventory.get_group('my_group').variables == {'foobar': 'barfoo'}
|
||||
# Host should be child of group
|
||||
assert inventory.get_host('group_host') in inventory.get_group('my_group').hosts
|
||||
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_host_lists_accepted(JSON_with_lists):
|
||||
inventory = dict_to_mem_data(JSON_with_lists)
|
||||
assert inventory.get_group('marietta').name == 'marietta'
|
||||
# Check that marietta's hosts was saved
|
||||
h = inventory.get_host('host6.example.com')
|
||||
assert h.name == 'host6.example.com'
|
||||
@@ -0,0 +1,15 @@
|
||||
# awx.main.utils.reload
|
||||
from awx.main.utils import reload
|
||||
|
||||
|
||||
def test_produce_supervisor_command(mocker):
|
||||
communicate_mock = mocker.MagicMock(return_value=('Everything is fine', ''))
|
||||
mock_process = mocker.MagicMock()
|
||||
mock_process.communicate = communicate_mock
|
||||
Popen_mock = mocker.MagicMock(return_value=mock_process)
|
||||
with mocker.patch.object(reload.subprocess, 'Popen', Popen_mock):
|
||||
reload.supervisor_service_command("restart")
|
||||
reload.subprocess.Popen.assert_called_once_with(
|
||||
['supervisorctl', 'restart', 'tower-processes:*',],
|
||||
stderr=-1, stdin=-1, stdout=-1)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from copy import deepcopy
|
||||
import pytest
|
||||
import yaml
|
||||
from awx.main.utils.safe_yaml import safe_dump
|
||||
|
||||
|
||||
@pytest.mark.parametrize('value', [None, 1, 1.5, []])
|
||||
def test_native_types(value):
|
||||
# Native non-string types should dump the same way that `yaml.safe_dump` does
|
||||
assert safe_dump(value) == yaml.safe_dump(value)
|
||||
|
||||
|
||||
def test_empty():
|
||||
assert safe_dump({}) == ''
|
||||
|
||||
|
||||
def test_raw_string():
|
||||
assert safe_dump('foo') == "!unsafe 'foo'\n"
|
||||
|
||||
|
||||
def test_kv_null():
|
||||
assert safe_dump({'a': None}) == "!unsafe 'a': null\n"
|
||||
|
||||
|
||||
def test_kv_null_safe():
|
||||
assert safe_dump({'a': None}, {'a': None}) == "a: null\n"
|
||||
|
||||
|
||||
def test_kv_null_unsafe():
|
||||
assert safe_dump({'a': ''}, {'a': None}) == "!unsafe 'a': !unsafe ''\n"
|
||||
|
||||
|
||||
def test_kv_int():
|
||||
assert safe_dump({'a': 1}) == "!unsafe 'a': 1\n"
|
||||
|
||||
|
||||
def test_kv_float():
|
||||
assert safe_dump({'a': 1.5}) == "!unsafe 'a': 1.5\n"
|
||||
|
||||
|
||||
def test_kv_unsafe():
|
||||
assert safe_dump({'a': 'b'}) == "!unsafe 'a': !unsafe 'b'\n"
|
||||
|
||||
|
||||
def test_kv_unsafe_unicode():
|
||||
assert safe_dump({'a': u'🐉'}) == '!unsafe \'a\': !unsafe "\\U0001F409"\n'
|
||||
|
||||
|
||||
def test_kv_unsafe_in_list():
|
||||
assert safe_dump({'a': ['b']}) == "!unsafe 'a':\n- !unsafe 'b'\n"
|
||||
|
||||
|
||||
def test_kv_unsafe_in_mixed_list():
|
||||
assert safe_dump({'a': [1, 'b']}) == "!unsafe 'a':\n- 1\n- !unsafe 'b'\n"
|
||||
|
||||
|
||||
def test_kv_unsafe_deep_nesting():
|
||||
yaml = safe_dump({'a': [1, [{'b': {'c': [{'d': 'e'}]}}]]})
|
||||
for x in ('a', 'b', 'c', 'd', 'e'):
|
||||
assert "!unsafe '{}'".format(x) in yaml
|
||||
|
||||
|
||||
def test_kv_unsafe_multiple():
|
||||
assert safe_dump({'a': 'b', 'c': 'd'}) == '\n'.join([
|
||||
"!unsafe 'a': !unsafe 'b'",
|
||||
"!unsafe 'c': !unsafe 'd'",
|
||||
""
|
||||
])
|
||||
|
||||
|
||||
def test_safe_marking():
|
||||
assert safe_dump({'a': 'b'}, safe_dict={'a': 'b'}) == "a: b\n"
|
||||
|
||||
|
||||
def test_safe_marking_mixed():
|
||||
assert safe_dump({'a': 'b', 'c': 'd'}, safe_dict={'a': 'b'}) == '\n'.join([
|
||||
"a: b",
|
||||
"!unsafe 'c': !unsafe 'd'",
|
||||
""
|
||||
])
|
||||
|
||||
|
||||
def test_safe_marking_deep_nesting():
|
||||
deep = {'a': [1, [{'b': {'c': [{'d': 'e'}]}}]]}
|
||||
yaml = safe_dump(deep, deepcopy(deep))
|
||||
for x in ('a', 'b', 'c', 'd', 'e'):
|
||||
assert "!unsafe '{}'".format(x) not in yaml
|
||||
|
||||
|
||||
def test_deep_diff_unsafe_marking():
|
||||
deep = {'a': [1, [{'b': {'c': [{'d': 'e'}]}}]]}
|
||||
jt_vars = deepcopy(deep)
|
||||
deep['a'][1][0]['b']['z'] = 'not safe'
|
||||
yaml = safe_dump(deep, jt_vars)
|
||||
assert "!unsafe 'z'" in yaml
|
||||
Reference in New Issue
Block a user