Initial commit

This commit is contained in:
Jon Ervine
2021-03-02 20:53:43 +08:00
parent 89d3a2dfe1
commit f961b728fa
2919 changed files with 388582 additions and 0 deletions
+292
View File
@@ -0,0 +1,292 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import io
import os
import json
import datetime
import importlib
from contextlib import redirect_stdout, suppress
from unittest import mock
import logging
from requests.models import Response, PreparedRequest
import pytest
from awx.main.tests.functional.conftest import _request
from awx.main.models import Organization, Project, Inventory, JobTemplate, Credential, CredentialType
from django.db import transaction
try:
import tower_cli # noqa
HAS_TOWER_CLI = True
except ImportError:
HAS_TOWER_CLI = False
try:
# Because awxkit will be a directory at the root of this makefile and we are using python3, import awxkit will work even if its not installed.
# However, awxkit will not contain api whih causes a stack failure down on line 170 when we try to mock it.
# So here we are importing awxkit.api to prevent that. Then you only get an error on tests for awxkit functionality.
import awxkit.api
HAS_AWX_KIT = True
except ImportError:
HAS_AWX_KIT = False
logger = logging.getLogger('awx.main.tests')
def sanitize_dict(din):
'''Sanitize Django response data to purge it of internal types
so it may be used to cast a requests response object
'''
if isinstance(din, (int, str, type(None), bool)):
return din # native JSON types, no problem
elif isinstance(din, datetime.datetime):
return din.isoformat()
elif isinstance(din, list):
for i in range(len(din)):
din[i] = sanitize_dict(din[i])
return din
elif isinstance(din, dict):
for k in din.copy().keys():
din[k] = sanitize_dict(din[k])
return din
else:
return str(din) # translation proxies often not string but stringlike
@pytest.fixture(autouse=True)
def collection_path_set(monkeypatch):
"""Monkey patch sys.path, insert the root of the collection folder
so that content can be imported without being fully packaged
"""
base_folder = os.path.abspath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
)
monkeypatch.syspath_prepend(base_folder)
@pytest.fixture
def collection_import():
"""These tests run assuming that the awx_collection folder is inserted
into the PATH before-hand by collection_path_set.
But all imports internally to the collection
go through this fixture so that can be changed if needed.
For instance, we could switch to fully-qualified import paths.
"""
def rf(path):
return importlib.import_module(path)
return rf
@pytest.fixture
def run_module(request, collection_import):
def rf(module_name, module_params, request_user):
def new_request(self, method, url, **kwargs):
kwargs_copy = kwargs.copy()
if 'data' in kwargs:
if isinstance(kwargs['data'], dict):
kwargs_copy['data'] = kwargs['data']
elif kwargs['data'] is None:
pass
elif isinstance(kwargs['data'], str):
kwargs_copy['data'] = json.loads(kwargs['data'])
else:
raise RuntimeError('Expected data to be dict or str, got {0}, data: {1}'.format(
type(kwargs['data']), kwargs['data']))
if 'params' in kwargs and method == 'GET':
# query params for GET are handled a bit differently by
# tower-cli and python requests as opposed to REST framework APIRequestFactory
if not kwargs_copy.get('data'):
kwargs_copy['data'] = {}
if isinstance(kwargs['params'], dict):
kwargs_copy['data'].update(kwargs['params'])
elif isinstance(kwargs['params'], list):
for k, v in kwargs['params']:
kwargs_copy['data'][k] = v
# make request
with transaction.atomic():
rf = _request(method.lower())
django_response = rf(url, user=request_user, expect=None, **kwargs_copy)
# requests library response object is different from the Django response, but they are the same concept
# this converts the Django response object into a requests response object for consumption
resp = Response()
py_data = django_response.data
sanitize_dict(py_data)
resp._content = bytes(json.dumps(django_response.data), encoding='utf8')
resp.status_code = django_response.status_code
resp.headers = {'X-API-Product-Name': 'AWX', 'X-API-Product-Version': '0.0.1-devel'}
if request.config.getoption('verbose') > 0:
logger.info(
'%s %s by %s, code:%s',
method, '/api/' + url.split('/api/')[1],
request_user.username, resp.status_code
)
resp.request = PreparedRequest()
resp.request.prepare(method=method, url=url)
return resp
def new_open(self, method, url, **kwargs):
r = new_request(self, method, url, **kwargs)
m = mock.MagicMock(read=mock.MagicMock(return_value=r._content),
status=r.status_code,
getheader=mock.MagicMock(side_effect=r.headers.get)
)
return m
stdout_buffer = io.StringIO()
# Requies specific PYTHONPATH, see docs
# Note that a proper Ansiballz explosion of the modules will have an import path like:
# ansible_collections.awx.awx.plugins.modules.{}
# We should consider supporting that in the future
resource_module = collection_import('plugins.modules.{0}'.format(module_name))
if not isinstance(module_params, dict):
raise RuntimeError('Module params must be dict, got {0}'.format(type(module_params)))
# Ansible params can be passed as an invocation argument or over stdin
# this short circuits within the AnsibleModule interface
def mock_load_params(self):
self.params = module_params
if getattr(resource_module, 'TowerAWXKitModule', None):
resource_class = resource_module.TowerAWXKitModule
elif getattr(resource_module, 'TowerAPIModule', None):
resource_class = resource_module.TowerAPIModule
elif getattr(resource_module, 'TowerLegacyModule', None):
resource_class = resource_module.TowerLegacyModule
else:
raise("The module has neither a TowerLegacyModule, TowerAWXKitModule or a TowerAPIModule")
with mock.patch.object(resource_class, '_load_params', new=mock_load_params):
# Call the test utility (like a mock server) instead of issuing HTTP requests
with mock.patch('ansible.module_utils.urls.Request.open', new=new_open):
if HAS_TOWER_CLI:
tower_cli_mgr = mock.patch('tower_cli.api.Session.request', new=new_request)
elif HAS_AWX_KIT:
tower_cli_mgr = mock.patch('awxkit.api.client.requests.Session.request', new=new_request)
else:
tower_cli_mgr = suppress()
with tower_cli_mgr:
try:
# Ansible modules return data to the mothership over stdout
with redirect_stdout(stdout_buffer):
resource_module.main()
except SystemExit:
pass # A system exit indicates successful execution
except Exception:
# dump the stdout back to console for debugging
print(stdout_buffer.getvalue())
raise
module_stdout = stdout_buffer.getvalue().strip()
try:
result = json.loads(module_stdout)
except Exception as e:
raise Exception('Module did not write valid JSON, error: {0}, stdout:\n{1}'.format(str(e), module_stdout))
# A module exception should never be a test expectation
if 'exception' in result:
if "ModuleNotFoundError: No module named 'tower_cli'" in result['exception']:
pytest.skip('The tower-cli library is needed to run this test, module no longer supported.')
raise Exception('Module encountered error:\n{0}'.format(result['exception']))
return result
return rf
@pytest.fixture
def survey_spec():
return {
"spec": [
{
"index": 0,
"question_name": "my question?",
"default": "mydef",
"variable": "myvar",
"type": "text",
"required": False
}
],
"description": "test",
"name": "test"
}
@pytest.fixture
def organization():
return Organization.objects.create(name='Default')
@pytest.fixture
def project(organization):
return Project.objects.create(
name="test-proj",
description="test-proj-desc",
organization=organization,
playbook_files=['helloworld.yml'],
local_path='_92__test_proj',
scm_revision='1234567890123456789012345678901234567890',
scm_url='localhost',
scm_type='git'
)
@pytest.fixture
def inventory(organization):
return Inventory.objects.create(
name='test-inv',
organization=organization
)
@pytest.fixture
def job_template(project, inventory):
return JobTemplate.objects.create(
name='test-jt',
project=project,
inventory=inventory,
playbook='helloworld.yml'
)
@pytest.fixture
def machine_credential(organization):
ssh_type = CredentialType.defaults['ssh']()
ssh_type.save()
return Credential.objects.create(
credential_type=ssh_type, name='machine-cred',
inputs={'username': 'test_user', 'password': 'pas4word'}
)
@pytest.fixture
def vault_credential(organization):
ct = CredentialType.defaults['vault']()
ct.save()
return Credential.objects.create(
credential_type=ct, name='vault-cred',
inputs={'vault_id': 'foo', 'vault_password': 'pas4word'}
)
@pytest.fixture
def silence_deprecation():
"""The deprecation warnings are stored in a global variable
they will create cross-test interference. Use this to turn them off.
"""
with mock.patch('ansible.module_utils.basic.AnsibleModule.deprecate') as this_mock:
yield this_mock
@pytest.fixture(autouse=True)
def silence_warning():
"""Warnings use global variable, same as deprecations."""
with mock.patch('ansible.module_utils.basic.AnsibleModule.warn') as this_mock:
yield this_mock
@@ -0,0 +1,55 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from django.utils.timezone import now
from awx.main.models.ad_hoc_commands import AdHocCommand
@pytest.mark.django_db
def test_ad_hoc_command_wait_successful(run_module, admin_user):
command = AdHocCommand.objects.create(status='successful', started=now(), finished=now())
result = run_module('tower_ad_hoc_command_wait', dict(
command_id=command.id
), admin_user)
result.pop('invocation', None)
assert result.pop('finished', '')[:10] == str(command.finished)[:10]
assert result.pop('started', '')[:10] == str(command.started)[:10]
assert result == {
"status": "successful",
"changed": False,
"elapsed": str(command.elapsed),
"id": command.id
}
@pytest.mark.django_db
def test_ad_hoc_command_wait_failed(run_module, admin_user):
command = AdHocCommand.objects.create(status='failed', started=now(), finished=now())
result = run_module('tower_ad_hoc_command_wait', dict(
command_id=command.id
), admin_user)
result.pop('invocation', None)
assert result.pop('finished', '')[:10] == str(command.finished)[:10]
assert result.pop('started', '')[:10] == str(command.started)[:10]
assert result == {
"status": "failed",
"failed": True,
"changed": False,
"elapsed": str(command.elapsed),
"id": command.id,
"msg": "The ad hoc command - 1, failed"
}
@pytest.mark.django_db
def test_ad_hoc_command_wait_not_found(run_module, admin_user):
result = run_module('tower_ad_hoc_command_wait', dict(
command_id=42
), admin_user)
result.pop('invocation', None)
assert result == {
"failed": True,
"msg": "Unable to wait on ad hoc command 42; that ID does not exist in Tower."
}
@@ -0,0 +1,28 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import Organization
from awx.main.models.oauth import OAuth2AccessToken, OAuth2Application
@pytest.mark.django_db
def test_create_application(run_module, admin_user):
org = Organization.objects.create(name='foo')
module_args = {
'name': 'foo_app',
'description': 'barfoo',
'state': 'present',
'authorization_grant_type': 'password',
'client_type': 'public',
'organization': 'foo',
}
result = run_module('tower_application', module_args, admin_user)
assert result.get('changed'), result
application = OAuth2Application.objects.get(name='foo_app')
assert application.description == 'barfoo'
assert application.organization_id == org.id
@@ -0,0 +1,269 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.tests.functional.conftest import _request
from ansible.module_utils.six import PY2, string_types
import yaml
import os
import re
# Analysis variables
# -----------------------------------------------------------------------------------------------------------
# Read-only endpoints are dynamically created by an options page with no POST section.
# Normally a read-only endpoint should not have a module (i.e. /api/v2/me) but sometimes we reuse a name
# For example, we have a tower_role module but /api/v2/roles is a read only endpoint.
# This list indicates which read-only endpoints have associated modules with them.
read_only_endpoints_with_modules = ['tower_settings', 'tower_role', 'tower_project_update']
# If a module should not be created for an endpoint and the endpoint is not read-only add it here
# THINK HARD ABOUT DOING THIS
no_module_for_endpoint = []
# Some modules work on the related fields of an endpoint. These modules will not have an auto-associated endpoint
no_endpoint_for_module = [
'tower_import', 'tower_meta', 'tower_export', 'tower_inventory_source_update', 'tower_job_launch', 'tower_job_wait',
'tower_job_list', 'tower_license', 'tower_ping', 'tower_receive', 'tower_send', 'tower_workflow_launch',
'tower_job_cancel', 'tower_workflow_template', 'tower_ad_hoc_command_wait', 'tower_ad_hoc_command_cancel',
]
# Global module parameters we can ignore
ignore_parameters = [
'state', 'new_name', 'update_secrets'
]
# Some modules take additional parameters that do not appear in the API
# Add the module name as the key with the value being the list of params to ignore
no_api_parameter_ok = {
# The wait is for whether or not to wait for a project update on change
'tower_project': ['wait', 'interval', 'update_project'],
# Existing_token and id are for working with an existing tokens
'tower_token': ['existing_token', 'existing_token_id'],
# /survey spec is now how we handle associations
# We take an organization here to help with the lookups only
'tower_job_template': ['survey_spec', 'organization'],
'tower_inventory_source': ['organization'],
# Organization is how we are looking up job templates, Approval node is for workflow_approval_templates
'tower_workflow_job_template_node': ['organization', 'approval_node'],
# Survey is how we handle associations
'tower_workflow_job_template': ['survey_spec'],
# ad hoc commands support interval and timeout since its more like tower_job_launc
'tower_ad_hoc_command': ['interval', 'timeout', 'wait'],
}
# When this tool was created we were not feature complete. Adding something in here indicates a module
# that needs to be developed. If the module is found on the file system it will auto-detect that the
# work is being done and will bypass this check. At some point this module should be removed from this list.
needs_development = [
'tower_inventory_script', 'tower_workflow_approval'
]
needs_param_development = {
'tower_host': ['instance_id'],
}
# -----------------------------------------------------------------------------------------------------------
return_value = 0
read_only_endpoint = []
def cause_error(msg):
global return_value
return_value = 255
return msg
def determine_state(module_id, endpoint, module, parameter, api_option, module_option):
# This is a hierarchical list of things that are ok/failures based on conditions
# If we know this module needs development this is a non-blocking failure
if module_id in needs_development and module == 'N/A':
return "Failed (non-blocking), module needs development"
# If the module is a read only endpoint:
# If it has no module on disk that is ok.
# If it has a module on disk but its listed in read_only_endpoints_with_modules that is ok
# Else we have a module for a read only endpoint that should not exit
if module_id in read_only_endpoint:
if module == 'N/A':
# There may be some cases where a read only endpoint has a module
return "OK, this endpoint is read-only and should not have a module"
elif module_id in read_only_endpoints_with_modules:
return "OK, module params can not be checked to read-only"
else:
return cause_error("Failed, read-only endpoint should not have an associated module")
# If the endpoint is listed as not needing a module and we don't have one we are ok
if module_id in no_module_for_endpoint and module == 'N/A':
return "OK, this endpoint should not have a module"
# If module is listed as not needing an endpoint and we don't have one we are ok
if module_id in no_endpoint_for_module and endpoint == 'N/A':
return "OK, this module does not require an endpoint"
# All of the end/point module conditionals are done so if we don't have a module or endpoint we have a problem
if module == 'N/A':
return cause_error('Failed, missing module')
if endpoint == 'N/A':
return cause_error('Failed, why does this module have no endpoint')
# Now perform parameter checks
# First, if the parameter is in the ignore_parameters list we are ok
if parameter in ignore_parameters:
return "OK, globally ignored parameter"
# If both the api option and the module option are both either objects or none
if (api_option is None) ^ (module_option is None):
# If the API option is node and the parameter is in the no_api_parameter list we are ok
if api_option is None and parameter in no_api_parameter_ok.get(module, {}):
return 'OK, no api parameter is ok'
# If we know this parameter needs development and we don't have a module option we are non-blocking
if module_option is None and parameter in needs_param_development.get(module_id, {}):
return "Failed (non-blocking), parameter needs development"
# Check for deprecated in the node, if its deprecated and has no api option we are ok, otherwise we have a problem
if module_option and module_option.get('description'):
description = ''
if isinstance(module_option.get('description'), string_types):
description = module_option.get('description')
else:
description = " ".join(module_option.get('description'))
if 'deprecated' in description.lower():
if api_option is None:
return 'OK, deprecated module option'
else:
return cause_error('Failed, module marks option as deprecated but option still exists in API')
# If we don't have a corresponding API option but we are a list then we are likely a relation
if not api_option and module_option and module_option.get('type', 'str') == 'list':
return "OK, Field appears to be relation"
# TODO, at some point try and check the object model to confirm its actually a relation
return cause_error('Failed, option mismatch')
# We made it through all of the checks so we are ok
return 'OK'
def test_completeness(collection_import, request, admin_user, job_template):
option_comparison = {}
# Load a list of existing module files from disk
base_folder = os.path.abspath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
)
module_directory = os.path.join(base_folder, 'plugins', 'modules')
for root, dirs, files in os.walk(module_directory):
if root == module_directory:
for filename in files:
if re.match('^tower_.*.py$', filename):
module_name = filename[:-3]
option_comparison[module_name] = {
'endpoint': 'N/A',
'api_options': {},
'module_options': {},
'module_name': module_name,
}
resource_module = collection_import('plugins.modules.{0}'.format(module_name))
option_comparison[module_name]['module_options'] = yaml.load(
resource_module.DOCUMENTATION,
Loader=yaml.SafeLoader
)['options']
endpoint_response = _request('get')(
url='/api/v2/',
user=admin_user,
expect=None,
)
for endpoint in endpoint_response.data.keys():
# Module names are singular and endpoints are plural so we need to convert to singular
singular_endpoint = '{0}'.format(endpoint)
if singular_endpoint.endswith('ies'):
singular_endpoint = singular_endpoint[:-3]
if singular_endpoint != 'settings' and singular_endpoint.endswith('s'):
singular_endpoint = singular_endpoint[:-1]
module_name = 'tower_{0}'.format(singular_endpoint)
endpoint_url = endpoint_response.data.get(endpoint)
# If we don't have a module for this endpoint then we can create an empty one
if module_name not in option_comparison:
option_comparison[module_name] = {}
option_comparison[module_name]['module_name'] = 'N/A'
option_comparison[module_name]['module_options'] = {}
# Add in our endpoint and an empty api_options
option_comparison[module_name]['endpoint'] = endpoint_url
option_comparison[module_name]['api_options'] = {}
# Get out the endpoint, load and parse its options page
options_response = _request('options')(
url=endpoint_url,
user=admin_user,
expect=None,
)
if 'POST' in options_response.data.get('actions', {}):
option_comparison[module_name]['api_options'] = options_response.data.get('actions').get('POST')
else:
read_only_endpoint.append(module_name)
# Parse through our data to get string lengths to make a pretty report
longest_module_name = 0
longest_option_name = 0
longest_endpoint = 0
for module in option_comparison:
if len(option_comparison[module]['module_name']) > longest_module_name:
longest_module_name = len(option_comparison[module]['module_name'])
if len(option_comparison[module]['endpoint']) > longest_endpoint:
longest_endpoint = len(option_comparison[module]['endpoint'])
for option in option_comparison[module]['api_options'], option_comparison[module]['module_options']:
if len(option) > longest_option_name:
longest_option_name = len(option)
# Print out some headers
print("".join([
"End Point", " " * (longest_endpoint - len("End Point")),
" | Module Name", " " * (longest_module_name - len("Module Name")),
" | Option", " " * (longest_option_name - len("Option")),
" | API | Module | State",
]))
print("-|-".join([
"-" * longest_endpoint,
"-" * longest_module_name,
"-" * longest_option_name,
"---",
"------",
"---------------------------------------------",
]))
# Print out all of our data
for module in sorted(option_comparison):
module_data = option_comparison[module]
all_param_names = list(set(module_data['api_options']) | set(module_data['module_options']))
for parameter in sorted(all_param_names):
print("".join([
module_data['endpoint'], " " * (longest_endpoint - len(module_data['endpoint'])), " | ",
module_data['module_name'], " " * (longest_module_name - len(module_data['module_name'])), " | ",
parameter, " " * (longest_option_name - len(parameter)), " | ",
" X " if (parameter in module_data['api_options']) else ' ', " | ",
' X ' if (parameter in module_data['module_options']) else ' ', " | ",
determine_state(
module,
module_data['endpoint'],
module_data['module_name'],
parameter,
module_data['api_options'][parameter] if (parameter in module_data['api_options']) else None,
module_data['module_options'][parameter] if (parameter in module_data['module_options']) else None,
),
]))
# This handles cases were we got no params from the options page nor from the modules
if len(all_param_names) == 0:
print("".join([
module_data['endpoint'], " " * (longest_endpoint - len(module_data['endpoint'])), " | ",
module_data['module_name'], " " * (longest_module_name - len(module_data['module_name'])), " | ",
"N/A", " " * (longest_option_name - len("N/A")), " | ",
' ', " | ",
' ', " | ",
determine_state(module, module_data['endpoint'], module_data['module_name'], 'N/A', None, None),
]))
if return_value != 0:
raise Exception("One or more failures caused issues")
+178
View File
@@ -0,0 +1,178 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import Credential, CredentialType, Organization
@pytest.fixture
def cred_type():
# Make a credential type which will be used by the credential
ct = CredentialType.objects.create(
name='Ansible Galaxy Token',
inputs={
"fields": [
{
"id": "token",
"type": "string",
"secret": True,
"label": "Ansible Galaxy Secret Token Value"
}
],
"required": ["token"]
},
injectors={
"extra_vars": {
"galaxy_token": "{{token}}",
}
}
)
return ct
@pytest.mark.django_db
def test_create_machine_credential(run_module, admin_user, organization, silence_deprecation):
Organization.objects.create(name='test-org')
# create the ssh credential type
ct = CredentialType.defaults['ssh']()
ct.save()
# Example from docs
result = run_module('tower_credential', dict(
name='Test Machine Credential',
organization=organization.name,
kind='ssh',
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
cred = Credential.objects.get(name='Test Machine Credential')
assert cred.credential_type == ct
assert result['name'] == "Test Machine Credential"
assert result['id'] == cred.pk
@pytest.mark.django_db
def test_create_vault_credential(run_module, admin_user, organization, silence_deprecation):
# https://github.com/ansible/ansible/issues/61324
Organization.objects.create(name='test-org')
ct = CredentialType.defaults['vault']()
ct.save()
result = run_module('tower_credential', dict(
name='Test Vault Credential',
organization=organization.name,
kind='vault',
vault_id='bar',
vault_password='foobar',
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
cred = Credential.objects.get(name='Test Vault Credential')
assert cred.credential_type == ct
assert 'vault_id' in cred.inputs
assert 'vault_password' in cred.inputs
assert result['name'] == "Test Vault Credential"
assert result['id'] == cred.pk
@pytest.mark.django_db
def test_ct_precedence_over_kind(run_module, admin_user, organization, cred_type, silence_deprecation):
result = run_module('tower_credential', dict(
name='A credential',
organization=organization.name,
kind='ssh',
credential_type=cred_type.name,
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
cred = Credential.objects.get(name='A credential')
assert cred.credential_type == cred_type
@pytest.mark.django_db
def test_input_overrides_old_fields(run_module, admin_user, organization, silence_deprecation):
# create the vault credential type
ct = CredentialType.defaults['vault']()
ct.save()
result = run_module('tower_credential', dict(
name='A Vault credential',
organization=organization.name,
kind='vault',
vault_id='1234',
inputs={'vault_id': 'asdf'},
state='present',
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
cred = Credential.objects.get(name='A Vault credential')
assert cred.inputs['vault_id'] == 'asdf'
@pytest.mark.django_db
def test_missing_credential_type(run_module, admin_user, organization):
Organization.objects.create(name='test-org')
result = run_module('tower_credential', dict(
name='A credential',
organization=organization.name,
credential_type='foobar',
state='present'
), admin_user)
assert result.get('failed', False), result
assert 'credential_type' in result['msg']
assert 'foobar' in result['msg']
assert 'returned 0 items, expected 1' in result['msg']
@pytest.mark.django_db
def test_make_use_of_custom_credential_type(run_module, organization, admin_user, cred_type):
result = run_module('tower_credential', dict(
name='Galaxy Token for Steve',
organization=organization.name,
credential_type=cred_type.name,
inputs={'token': '7rEZK38DJl58A7RxA6EC7lLvUHbBQ1'}
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', False), result
cred = Credential.objects.get(name='Galaxy Token for Steve')
assert cred.credential_type_id == cred_type.id
assert list(cred.inputs.keys()) == ['token']
assert cred.inputs['token'].startswith('$encrypted$')
assert len(cred.inputs['token']) >= len('$encrypted$') + len('7rEZK38DJl58A7RxA6EC7lLvUHbBQ1')
assert result['name'] == "Galaxy Token for Steve"
assert result['id'] == cred.pk
@pytest.mark.django_db
@pytest.mark.parametrize('update_secrets', [True, False])
def test_secret_field_write_twice(run_module, organization, admin_user, cred_type, update_secrets):
val1 = '7rEZK38DJl58A7RxA6EC7lLvUHbBQ1'
val2 = '7rEZ238DJl5837rxA6xxxlLvUHbBQ1'
for val in (val1, val2):
result = run_module('tower_credential', dict(
name='Galaxy Token for Steve',
organization=organization.name,
credential_type=cred_type.name,
inputs={'token': val},
update_secrets=update_secrets
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
if update_secrets:
assert Credential.objects.get(id=result['id']).get_input('token') == val
if update_secrets:
assert result.get('changed'), result
else:
assert result.get('changed') is False, result
assert Credential.objects.get(id=result['id']).get_input('token') == val1
@@ -0,0 +1,334 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import CredentialInputSource, Credential, CredentialType, Organization
@pytest.fixture
def aim_cred_type():
ct = CredentialType.defaults['aim']()
ct.save()
return ct
# Test CyberArk AIM credential source
@pytest.fixture
def source_cred_aim(aim_cred_type):
return Credential.objects.create(
name='CyberArk AIM Cred',
credential_type=aim_cred_type,
inputs={
"url": "https://cyberark.example.com",
"app_id": "myAppID",
"verify": "false"
}
)
@pytest.mark.django_db
def test_aim_credential_source(run_module, admin_user, organization, source_cred_aim, silence_deprecation):
ct = CredentialType.defaults['ssh']()
ct.save()
tgt_cred = Credential.objects.create(
name='Test Machine Credential',
organization=organization,
credential_type=ct,
inputs={'username': 'bob'}
)
result = run_module('tower_credential_input_source', dict(
source_credential=source_cred_aim.name,
target_credential=tgt_cred.name,
input_field_name='password',
metadata={"object_query": "Safe=SUPERSAFE;Object=MyAccount"},
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
assert CredentialInputSource.objects.count() == 1
cis = CredentialInputSource.objects.first()
assert cis.metadata['object_query'] == "Safe=SUPERSAFE;Object=MyAccount"
assert cis.source_credential.name == source_cred_aim.name
assert cis.target_credential.name == tgt_cred.name
assert cis.input_field_name == 'password'
assert result['id'] == cis.pk
# Test CyberArk Conjur credential source
@pytest.fixture
def source_cred_conjur(organization):
# Make a credential type which will be used by the credential
ct = CredentialType.defaults['conjur']()
ct.save()
return Credential.objects.create(
name='CyberArk CONJUR Cred',
credential_type=ct,
inputs={
"url": "https://cyberark.example.com",
"api_key": "myApiKey",
"account": "account",
"username": "username"
}
)
@pytest.mark.django_db
def test_conjur_credential_source(run_module, admin_user, organization, source_cred_conjur, silence_deprecation):
ct = CredentialType.defaults['ssh']()
ct.save()
tgt_cred = Credential.objects.create(
name='Test Machine Credential',
organization=organization,
credential_type=ct,
inputs={'username': 'bob'}
)
result = run_module('tower_credential_input_source', dict(
source_credential=source_cred_conjur.name,
target_credential=tgt_cred.name,
input_field_name='password',
metadata={"secret_path": "/path/to/secret"},
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
assert CredentialInputSource.objects.count() == 1
cis = CredentialInputSource.objects.first()
assert cis.metadata['secret_path'] == "/path/to/secret"
assert cis.source_credential.name == source_cred_conjur.name
assert cis.target_credential.name == tgt_cred.name
assert cis.input_field_name == 'password'
assert result['id'] == cis.pk
# Test Hashicorp Vault secret credential source
@pytest.fixture
def source_cred_hashi_secret(organization):
# Make a credential type which will be used by the credential
ct = CredentialType.defaults['hashivault_kv']()
ct.save()
return Credential.objects.create(
name='HashiCorp secret Cred',
credential_type=ct,
inputs={
"url": "https://secret.hash.example.com",
"token": "myApiKey",
"role_id": "role",
"secret_id": "secret",
"default_auth_path": "path-to-approle"
}
)
@pytest.mark.django_db
def test_hashi_secret_credential_source(run_module, admin_user, organization, source_cred_hashi_secret, silence_deprecation):
ct = CredentialType.defaults['ssh']()
ct.save()
tgt_cred = Credential.objects.create(
name='Test Machine Credential',
organization=organization,
credential_type=ct,
inputs={'username': 'bob'}
)
result = run_module('tower_credential_input_source', dict(
source_credential=source_cred_hashi_secret.name,
target_credential=tgt_cred.name,
input_field_name='password',
metadata={"secret_path": "/path/to/secret", "auth_path": "/path/to/auth", "secret_backend": "backend", "secret_key": "a_key"},
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
assert CredentialInputSource.objects.count() == 1
cis = CredentialInputSource.objects.first()
assert cis.metadata['secret_path'] == "/path/to/secret"
assert cis.metadata['auth_path'] == "/path/to/auth"
assert cis.metadata['secret_backend'] == "backend"
assert cis.metadata['secret_key'] == "a_key"
assert cis.source_credential.name == source_cred_hashi_secret.name
assert cis.target_credential.name == tgt_cred.name
assert cis.input_field_name == 'password'
assert result['id'] == cis.pk
# Test Hashicorp Vault signed ssh credential source
@pytest.fixture
def source_cred_hashi_ssh(organization):
# Make a credential type which will be used by the credential
ct = CredentialType.defaults['hashivault_ssh']()
ct.save()
return Credential.objects.create(
name='HashiCorp ssh Cred',
credential_type=ct,
inputs={
"url": "https://ssh.hash.example.com",
"token": "myApiKey",
"role_id": "role",
"secret_id": "secret"
}
)
@pytest.mark.django_db
def test_hashi_ssh_credential_source(run_module, admin_user, organization, source_cred_hashi_ssh, silence_deprecation):
ct = CredentialType.defaults['ssh']()
ct.save()
tgt_cred = Credential.objects.create(
name='Test Machine Credential',
organization=organization,
credential_type=ct,
inputs={'username': 'bob'}
)
result = run_module('tower_credential_input_source', dict(
source_credential=source_cred_hashi_ssh.name,
target_credential=tgt_cred.name,
input_field_name='password',
metadata={"secret_path": "/path/to/secret", "auth_path": "/path/to/auth", "role": "role", "public_key": "a_key", "valid_principals": "some_value"},
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
assert CredentialInputSource.objects.count() == 1
cis = CredentialInputSource.objects.first()
assert cis.metadata['secret_path'] == "/path/to/secret"
assert cis.metadata['auth_path'] == "/path/to/auth"
assert cis.metadata['role'] == "role"
assert cis.metadata['public_key'] == "a_key"
assert cis.metadata['valid_principals'] == "some_value"
assert cis.source_credential.name == source_cred_hashi_ssh.name
assert cis.target_credential.name == tgt_cred.name
assert cis.input_field_name == 'password'
assert result['id'] == cis.pk
# Test Azure Key Vault credential source
@pytest.fixture
def source_cred_azure_kv(organization):
# Make a credential type which will be used by the credential
ct = CredentialType.defaults['azure_kv']()
ct.save()
return Credential.objects.create(
name='Azure KV Cred',
credential_type=ct,
inputs={
"url": "https://key.azure.example.com",
"client": "client",
"secret": "secret",
"tenant": "tenant",
"cloud_name": "the_cloud",
}
)
@pytest.mark.django_db
def test_azure_kv_credential_source(run_module, admin_user, organization, source_cred_azure_kv, silence_deprecation):
ct = CredentialType.defaults['ssh']()
ct.save()
tgt_cred = Credential.objects.create(
name='Test Machine Credential',
organization=organization,
credential_type=ct,
inputs={'username': 'bob'}
)
result = run_module('tower_credential_input_source', dict(
source_credential=source_cred_azure_kv.name,
target_credential=tgt_cred.name,
input_field_name='password',
metadata={"secret_field": "my_pass"},
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
assert CredentialInputSource.objects.count() == 1
cis = CredentialInputSource.objects.first()
assert cis.metadata['secret_field'] == "my_pass"
assert cis.source_credential.name == source_cred_azure_kv.name
assert cis.target_credential.name == tgt_cred.name
assert cis.input_field_name == 'password'
assert result['id'] == cis.pk
# Test Changing Credential Source
@pytest.fixture
def source_cred_aim_alt(aim_cred_type):
return Credential.objects.create(
name='Alternate CyberArk AIM Cred',
credential_type=aim_cred_type,
inputs={
"url": "https://cyberark-alt.example.com",
"app_id": "myAltID",
"verify": "false"
}
)
@pytest.mark.django_db
def test_aim_credential_source(run_module, admin_user, organization, source_cred_aim, source_cred_aim_alt, silence_deprecation):
ct = CredentialType.defaults['ssh']()
ct.save()
tgt_cred = Credential.objects.create(
name='Test Machine Credential',
organization=organization,
credential_type=ct,
inputs={'username': 'bob'}
)
result = run_module('tower_credential_input_source', dict(
source_credential=source_cred_aim.name,
target_credential=tgt_cred.name,
input_field_name='password',
metadata={"object_query": "Safe=SUPERSAFE;Object=MyAccount"},
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
unchangedResult = run_module('tower_credential_input_source', dict(
source_credential=source_cred_aim.name,
target_credential=tgt_cred.name,
input_field_name='password',
metadata={"object_query": "Safe=SUPERSAFE;Object=MyAccount"},
state='present'
), admin_user)
assert not unchangedResult.get('failed', False), result.get('msg', result)
assert not unchangedResult.get('changed'), result
changedResult = run_module('tower_credential_input_source', dict(
source_credential=source_cred_aim_alt.name,
target_credential=tgt_cred.name,
input_field_name='password',
state='present'
), admin_user)
assert not changedResult.get('failed', False), changedResult.get('msg', result)
assert changedResult.get('changed'), result
assert CredentialInputSource.objects.count() == 1
cis = CredentialInputSource.objects.first()
assert cis.metadata['object_query'] == "Safe=SUPERSAFE;Object=MyAccount"
assert cis.source_credential.name == source_cred_aim_alt.name
assert cis.target_credential.name == tgt_cred.name
assert cis.input_field_name == 'password'
@@ -0,0 +1,49 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import CredentialType
@pytest.mark.django_db
def test_create_custom_credential_type(run_module, admin_user, silence_deprecation):
# Example from docs
result = run_module('tower_credential_type', dict(
name='Nexus',
description='Credentials type for Nexus',
kind='cloud',
inputs={"fields": [{"id": "server", "type": "string", "default": "", "label": ""}], "required": []},
injectors={'extra_vars': {'nexus_credential': 'test'}},
state='present',
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
ct = CredentialType.objects.get(name='Nexus')
assert result['name'] == 'Nexus'
assert result['id'] == ct.pk
assert ct.inputs == {"fields": [{"id": "server", "type": "string", "default": "", "label": ""}], "required": []}
assert ct.injectors == {'extra_vars': {'nexus_credential': 'test'}}
@pytest.mark.django_db
def test_changed_false_with_api_changes(run_module, admin_user):
result = run_module('tower_credential_type', dict(
name='foo',
kind='cloud',
inputs={"fields": [{"id": "env_value", "label": "foo", "default": "foo"}]},
injectors={'env': {'TEST_ENV_VAR': '{{ env_value }}'}},
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
result = run_module('tower_credential_type', dict(
name='foo',
inputs={"fields": [{"id": "env_value", "label": "foo", "default": "foo"}]},
injectors={'env': {'TEST_ENV_VAR': '{{ env_value }}'}},
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert not result.get('changed'), result
+117
View File
@@ -0,0 +1,117 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import Organization, Inventory, Group, Host
@pytest.mark.django_db
def test_create_group(run_module, admin_user):
org = Organization.objects.create(name='test-org')
inv = Inventory.objects.create(name='test-inv', organization=org)
variables = {"ansible_network_os": "iosxr"}
result = run_module('tower_group', dict(
name='Test Group',
inventory='test-inv',
variables=variables,
state='present'
), admin_user)
assert result.get('changed'), result
group = Group.objects.get(name='Test Group')
assert group.inventory == inv
assert group.variables == '{"ansible_network_os": "iosxr"}'
result.pop('invocation')
assert result == {
'id': group.id,
'name': 'Test Group',
'changed': True,
}
@pytest.mark.django_db
def test_associate_hosts_and_children(run_module, admin_user, organization):
inv = Inventory.objects.create(name='test-inv', organization=organization)
group = Group.objects.create(name='Test Group', inventory=inv)
inv_hosts = [Host.objects.create(inventory=inv, name='foo{0}'.format(i)) for i in range(3)]
group.hosts.add(inv_hosts[0], inv_hosts[1])
child = Group.objects.create(inventory=inv, name='child_group')
result = run_module('tower_group', dict(
name='Test Group',
inventory='test-inv',
hosts=[inv_hosts[1].name, inv_hosts[2].name],
children=[child.name],
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result['changed'] is True
assert set(group.hosts.all()) == set([inv_hosts[1], inv_hosts[2]])
assert set(group.children.all()) == set([child])
@pytest.mark.django_db
def test_associate_on_create(run_module, admin_user, organization):
inv = Inventory.objects.create(name='test-inv', organization=organization)
child = Group.objects.create(name='test-child', inventory=inv)
host = Host.objects.create(name='test-host', inventory=inv)
result = run_module('tower_group', dict(
name='Test Group',
inventory='test-inv',
hosts=[host.name],
groups=[child.name],
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result['changed'] is True
group = Group.objects.get(pk=result['id'])
assert set(group.hosts.all()) == set([host])
assert set(group.children.all()) == set([child])
@pytest.mark.django_db
def test_children_alias_of_groups(run_module, admin_user, organization):
inv = Inventory.objects.create(name='test-inv', organization=organization)
group = Group.objects.create(name='Test Group', inventory=inv)
child = Group.objects.create(inventory=inv, name='child_group')
result = run_module('tower_group', dict(
name='Test Group',
inventory='test-inv',
groups=[child.name],
state='present'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result['changed'] is True
assert set(group.children.all()) == set([child])
@pytest.mark.django_db
def test_tower_group_idempotent(run_module, admin_user):
# https://github.com/ansible/ansible/issues/46803
org = Organization.objects.create(name='test-org')
inv = Inventory.objects.create(name='test-inv', organization=org)
group = Group.objects.create(
name='Test Group',
inventory=inv,
)
result = run_module('tower_group', dict(
name='Test Group',
inventory='test-inv',
state='present'
), admin_user)
result.pop('invocation')
assert result == {
'id': group.id,
'changed': False, # idempotency assertion
}
@@ -0,0 +1,71 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import InstanceGroup, Instance
from awx.main.tests.functional.conftest import kube_credential, credentialtype_kube
@pytest.mark.django_db
def test_instance_group_create(run_module, admin_user):
result = run_module('tower_instance_group', {
'name': 'foo-group',
'policy_instance_percentage': 34,
'policy_instance_minimum': 12,
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result
assert result['changed']
ig = InstanceGroup.objects.get(name='foo-group')
assert ig.policy_instance_percentage == 34
assert ig.policy_instance_minimum == 12
# Create a new instance in the DB
new_instance = Instance.objects.create(hostname='foo.example.com')
# Set the new instance group only to the one instnace
result = run_module('tower_instance_group', {
'name': 'foo-group',
'instances': [new_instance.hostname],
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result
assert result['changed']
ig = InstanceGroup.objects.get(name='foo-group')
all_instance_names = []
for instance in ig.instances.all():
all_instance_names.append(instance.hostname)
assert new_instance.hostname in all_instance_names, 'Failed to add instance to group'
assert len(all_instance_names) == 1, 'Too many instances in group {0}'.format(','.join(all_instance_names))
@pytest.mark.django_db
def test_container_group_create(run_module, admin_user, kube_credential):
pod_spec = "{ 'Nothing': True }"
result = run_module('tower_instance_group', {
'name': 'foo-c-group',
'credential': kube_credential.id,
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result['msg']
assert result['changed']
ig = InstanceGroup.objects.get(name='foo-c-group')
assert ig.pod_spec_override == ''
result = run_module('tower_instance_group', {
'name': 'foo-c-group',
'credential': kube_credential.id,
'pod_spec_override': pod_spec,
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result['msg']
assert result['changed']
ig = InstanceGroup.objects.get(name='foo-c-group')
assert ig.pod_spec_override == pod_spec
+66
View File
@@ -0,0 +1,66 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import Inventory, Credential
from awx.main.tests.functional.conftest import insights_credential, credentialtype_insights
@pytest.mark.django_db
def test_inventory_create(run_module, admin_user, organization, insights_credential):
# Create an insights credential
result = run_module('tower_inventory', {
'name': 'foo-inventory',
'organization': organization.name,
'variables': {'foo': 'bar', 'another-foo': {'barz': 'bar2'}},
'insights_credential': insights_credential.name,
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
inv = Inventory.objects.get(name='foo-inventory')
assert inv.variables == '{"foo": "bar", "another-foo": {"barz": "bar2"}}'
assert inv.insights_credential.name == insights_credential.name
result.pop('module_args', None)
result.pop('invocation', None)
assert result == {
"name": "foo-inventory",
"id": inv.id,
"changed": True
}
assert inv.organization_id == organization.id
@pytest.mark.django_db
def test_invalid_smart_inventory_create(run_module, admin_user, organization):
result = run_module('tower_inventory', {
'name': 'foo-inventory',
'organization': organization.name,
'kind': 'smart',
'host_filter': 'ansible',
'state': 'present'
}, admin_user)
assert result.get('failed', False), result
assert 'Invalid query ansible' in result['msg']
@pytest.mark.django_db
def test_valid_smart_inventory_create(run_module, admin_user, organization):
result = run_module('tower_inventory', {
'name': 'foo-inventory',
'organization': organization.name,
'kind': 'smart',
'host_filter': 'name=my_host',
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result
inv = Inventory.objects.get(name='foo-inventory')
assert inv.host_filter == 'name=my_host'
assert inv.kind == 'smart'
assert inv.organization_id == organization.id
@@ -0,0 +1,254 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import Organization, Inventory, InventorySource, Project
@pytest.fixture
def base_inventory():
org = Organization.objects.create(name='test-org')
inv = Inventory.objects.create(name='test-inv', organization=org)
return inv
@pytest.fixture
def project(base_inventory):
return Project.objects.create(
name='test-proj',
organization=base_inventory.organization,
scm_type='git',
scm_url='https://github.com/ansible/test-playbooks.git',
)
@pytest.mark.django_db
def test_inventory_source_create(run_module, admin_user, base_inventory, project):
source_path = '/var/lib/awx/example_source_path/'
result = run_module('tower_inventory_source', dict(
name='foo',
inventory=base_inventory.name,
state='present',
source='scm',
source_path=source_path,
source_project=project.name
), admin_user)
assert result.pop('changed', None), result
inv_src = InventorySource.objects.get(name='foo')
assert inv_src.inventory == base_inventory
result.pop('invocation')
assert result == {
'id': inv_src.id,
'name': 'foo',
}
@pytest.mark.django_db
def test_create_inventory_source_implied_org(run_module, admin_user):
org = Organization.objects.create(name='test-org')
inv = Inventory.objects.create(name='test-inv', organization=org)
# Credential is not required for ec2 source, because of IAM roles
result = run_module('tower_inventory_source', dict(
name='Test Inventory Source',
inventory='test-inv',
source='ec2',
state='present'
), admin_user)
assert result.pop('changed', None), result
inv_src = InventorySource.objects.get(name='Test Inventory Source')
assert inv_src.inventory == inv
result.pop('invocation')
assert result == {
"name": "Test Inventory Source",
"id": inv_src.id,
}
@pytest.mark.django_db
def test_create_inventory_source_multiple_orgs(run_module, admin_user):
org = Organization.objects.create(name='test-org')
Inventory.objects.create(name='test-inv', organization=org)
# make another inventory by same name in another org
org2 = Organization.objects.create(name='test-org-number-two')
inv2 = Inventory.objects.create(name='test-inv', organization=org2)
result = run_module('tower_inventory_source', dict(
name='Test Inventory Source',
inventory=inv2.name,
organization='test-org-number-two',
source='ec2',
state='present'
), admin_user)
assert result.pop('changed', None), result
inv_src = InventorySource.objects.get(name='Test Inventory Source')
assert inv_src.inventory == inv2
result.pop('invocation')
assert result == {
"name": "Test Inventory Source",
"id": inv_src.id,
}
@pytest.mark.django_db
def test_create_inventory_source_with_venv(run_module, admin_user, base_inventory, mocker, project):
path = '/var/lib/awx/venv/custom-venv/foobar13489435/'
source_path = '/var/lib/awx/example_source_path/'
with mocker.patch('awx.main.models.mixins.get_custom_venv_choices', return_value=[path]):
result = run_module('tower_inventory_source', dict(
name='foo',
inventory=base_inventory.name,
state='present',
source='scm',
source_project=project.name,
custom_virtualenv=path,
source_path=source_path
), admin_user)
assert result.pop('changed'), result
inv_src = InventorySource.objects.get(name='foo')
assert inv_src.inventory == base_inventory
result.pop('invocation')
assert inv_src.custom_virtualenv == path
@pytest.mark.django_db
def test_custom_venv_no_op(run_module, admin_user, base_inventory, mocker, project):
"""If the inventory source is modified, then it should not blank fields
unrelated to the params that the user passed.
This enforces assumptions about the behavior of the AnsibleModule
default argument_spec behavior.
"""
source_path = '/var/lib/awx/example_source_path/'
inv_src = InventorySource.objects.create(
name='foo',
inventory=base_inventory,
source_project=project,
source='scm',
custom_virtualenv='/var/lib/awx/venv/foobar/'
)
# mock needed due to API behavior, not incorrect client behavior
with mocker.patch('awx.main.models.mixins.get_custom_venv_choices', return_value=['/var/lib/awx/venv/foobar/']):
result = run_module('tower_inventory_source', dict(
name='foo',
description='this is the changed description',
inventory=base_inventory.name,
source='scm', # is required, but behavior is arguable
state='present',
source_project=project.name,
source_path=source_path
), admin_user)
assert result.pop('changed', None), result
inv_src.refresh_from_db()
assert inv_src.custom_virtualenv == '/var/lib/awx/venv/foobar/'
assert inv_src.description == 'this is the changed description'
@pytest.mark.django_db
def test_falsy_value(run_module, admin_user, base_inventory):
result = run_module('tower_inventory_source', dict(
name='falsy-test',
inventory=base_inventory.name,
source='ec2',
update_on_launch=True
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', None), result
inv_src = InventorySource.objects.get(name='falsy-test')
assert inv_src.update_on_launch is True
result = run_module('tower_inventory_source', dict(
name='falsy-test',
inventory=base_inventory.name,
source='ec2',
update_on_launch=False
), admin_user)
inv_src.refresh_from_db()
assert inv_src.update_on_launch is False
# Tests related to source-specific parameters
#
# We want to let the API return issues with "this doesn't support that", etc.
#
# GUI OPTIONS:
# - - - - - - - manual: file: scm: ec2: gce azure_rm vmware sat openstack rhv tower custom
# credential ? ? o o r r r r r r r o
# source_project ? ? r - - - - - - - - -
# source_path ? ? r - - - - - - - - -
# verbosity ? ? o o o o o o o o o o
# overwrite ? ? o o o o o o o o o o
# overwrite_vars ? ? o o o o o o o o o o
# update_on_launch ? ? o o o o o o o o o o
# UoPL ? ? o - - - - - - - - -
# source_vars* ? ? - o - o o o o - - -
# environmet vars* ? ? o - - - - - - - - o
# source_script ? ? - - - - - - - - - r
#
# UoPL - update_on_project_launch
# * - source_vars are labeled environment_vars on project and custom sources
@pytest.mark.django_db
def test_missing_required_credential(run_module, admin_user, base_inventory):
result = run_module('tower_inventory_source', dict(
name='Test Azure Source',
inventory=base_inventory.name,
source='azure_rm',
state='present'
), admin_user)
assert result.pop('failed', None) is True, result
assert 'Credential is required for a cloud source' in result.get('msg', '')
@pytest.mark.django_db
def test_source_project_not_for_cloud(run_module, admin_user, base_inventory, project):
result = run_module('tower_inventory_source', dict(
name='Test ec2 Inventory Source',
inventory=base_inventory.name,
source='ec2',
state='present',
source_project=project.name
), admin_user)
assert result.pop('failed', None) is True, result
assert 'Cannot set source_project if not SCM type' in result.get('msg', '')
@pytest.mark.django_db
def test_source_path_not_for_cloud(run_module, admin_user, base_inventory):
result = run_module('tower_inventory_source', dict(
name='Test ec2 Inventory Source',
inventory=base_inventory.name,
source='ec2',
state='present',
source_path='where/am/I'
), admin_user)
assert result.pop('failed', None) is True, result
assert 'Cannot set source_path if not SCM type' in result.get('msg', '')
@pytest.mark.django_db
def test_scm_source_needs_project(run_module, admin_user, base_inventory):
result = run_module('tower_inventory_source', dict(
name='SCM inventory without project',
inventory=base_inventory.name,
state='present',
source='scm',
source_path='/var/lib/awx/example_source_path/'
), admin_user)
assert result.pop('failed', None), result
assert 'Project required for scm type sources' in result.get('msg', '')
+55
View File
@@ -0,0 +1,55 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from django.utils.timezone import now
from awx.main.models import Job
@pytest.mark.django_db
def test_job_wait_successful(run_module, admin_user):
job = Job.objects.create(status='successful', started=now(), finished=now())
result = run_module('tower_job_wait', dict(
job_id=job.id
), admin_user)
result.pop('invocation', None)
assert result.pop('finished', '')[:10] == str(job.finished)[:10]
assert result.pop('started', '')[:10] == str(job.started)[:10]
assert result == {
"status": "successful",
"changed": False,
"elapsed": str(job.elapsed),
"id": job.id
}
@pytest.mark.django_db
def test_job_wait_failed(run_module, admin_user):
job = Job.objects.create(status='failed', started=now(), finished=now())
result = run_module('tower_job_wait', dict(
job_id=job.id
), admin_user)
result.pop('invocation', None)
assert result.pop('finished', '')[:10] == str(job.finished)[:10]
assert result.pop('started', '')[:10] == str(job.started)[:10]
assert result == {
"status": "failed",
"failed": True,
"changed": False,
"elapsed": str(job.elapsed),
"id": job.id,
"msg": "Job with id 1 failed"
}
@pytest.mark.django_db
def test_job_wait_not_found(run_module, admin_user):
result = run_module('tower_job_wait', dict(
job_id=42
), admin_user)
result.pop('invocation', None)
assert result == {
"failed": True,
"msg": "Unable to wait on job 42; that ID does not exist in Tower."
}
@@ -0,0 +1,295 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import ActivityStream, JobTemplate, Job, NotificationTemplate
@pytest.mark.django_db
def test_create_job_template(run_module, admin_user, project, inventory):
module_args = {
'name': 'foo', 'playbook': 'helloworld.yml',
'project': project.name, 'inventory': inventory.name,
'extra_vars': {'foo': 'bar'},
'job_type': 'run',
'state': 'present'
}
result = run_module('tower_job_template', module_args, admin_user)
jt = JobTemplate.objects.get(name='foo')
assert jt.extra_vars == '{"foo": "bar"}'
assert result == {
"name": "foo",
"id": jt.id,
"changed": True,
"invocation": {
"module_args": module_args
}
}
assert jt.project_id == project.id
assert jt.inventory_id == inventory.id
@pytest.mark.django_db
def test_resets_job_template_values(run_module, admin_user, project, inventory):
module_args = {
'name': 'foo', 'playbook': 'helloworld.yml',
'project': project.name, 'inventory': inventory.name,
'extra_vars': {'foo': 'bar'},
'job_type': 'run',
'state': 'present',
'forks': 20,
'timeout': 50,
'allow_simultaneous': True,
'ask_limit_on_launch': True,
}
result = run_module('tower_job_template', module_args, admin_user)
jt = JobTemplate.objects.get(name='foo')
assert jt.forks == 20
assert jt.timeout == 50
assert jt.allow_simultaneous
assert jt.ask_limit_on_launch
module_args = {
'name': 'foo', 'playbook': 'helloworld.yml',
'project': project.name, 'inventory': inventory.name,
'extra_vars': {'foo': 'bar'},
'job_type': 'run',
'state': 'present',
'forks': 0,
'timeout': 0,
'allow_simultaneous': False,
'ask_limit_on_launch': False,
}
result = run_module('tower_job_template', module_args, admin_user)
assert result['changed']
jt = JobTemplate.objects.get(name='foo')
assert jt.forks == 0
assert jt.timeout == 0
assert not jt.allow_simultaneous
assert not jt.ask_limit_on_launch
@pytest.mark.django_db
def test_job_launch_with_prompting(run_module, admin_user, project, organization, inventory, machine_credential):
JobTemplate.objects.create(
name='foo',
project=project,
organization=organization,
playbook='helloworld.yml',
ask_variables_on_launch=True,
ask_inventory_on_launch=True,
ask_credential_on_launch=True
)
result = run_module('tower_job_launch', dict(
job_template='foo',
inventory=inventory.name,
credential=machine_credential.name,
extra_vars={"var1": "My First Variable",
"var2": "My Second Variable",
"var3": "My Third Variable"
}
), admin_user)
assert result.pop('changed', None), result
job = Job.objects.get(id=result['id'])
assert job.extra_vars == '{"var1": "My First Variable", "var2": "My Second Variable", "var3": "My Third Variable"}'
assert job.inventory == inventory
assert [cred.id for cred in job.credentials.all()] == [machine_credential.id]
@pytest.mark.django_db
def test_job_template_with_new_credentials(
run_module, admin_user, project, inventory,
machine_credential, vault_credential):
result = run_module('tower_job_template', dict(
name='foo',
playbook='helloworld.yml',
project=project.name,
inventory=inventory.name,
credentials=[machine_credential.name, vault_credential.name]
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', False), result
jt = JobTemplate.objects.get(pk=result['id'])
assert set([machine_credential.id, vault_credential.id]) == set([
cred.pk for cred in jt.credentials.all()])
prior_ct = ActivityStream.objects.count()
result = run_module('tower_job_template', dict(
name='foo',
playbook='helloworld.yml',
project=project.name,
inventory=inventory.name,
credentials=[machine_credential.name, vault_credential.name]
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert not result.get('changed', True), result
jt.refresh_from_db()
assert result['id'] == jt.id
assert set([machine_credential.id, vault_credential.id]) == set([
cred.pk for cred in jt.credentials.all()])
assert ActivityStream.objects.count() == prior_ct
@pytest.mark.django_db
def test_job_template_with_survey_spec(run_module, admin_user, project, inventory, survey_spec):
result = run_module('tower_job_template', dict(
name='foo',
playbook='helloworld.yml',
project=project.name,
inventory=inventory.name,
survey_spec=survey_spec,
survey_enabled=True
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', False), result
jt = JobTemplate.objects.get(pk=result['id'])
assert jt.survey_spec == survey_spec
prior_ct = ActivityStream.objects.count()
result = run_module('tower_job_template', dict(
name='foo',
playbook='helloworld.yml',
project=project.name,
inventory=inventory.name,
survey_spec=survey_spec,
survey_enabled=True
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert not result.get('changed', True), result
jt.refresh_from_db()
assert result['id'] == jt.id
assert jt.survey_spec == survey_spec
assert ActivityStream.objects.count() == prior_ct
@pytest.mark.django_db
def test_job_template_with_wrong_survey_spec(run_module, admin_user, project, inventory, survey_spec):
result = run_module('tower_job_template', dict(
name='foo',
playbook='helloworld.yml',
project=project.name,
inventory=inventory.name,
survey_spec=survey_spec,
survey_enabled=True
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', False), result
jt = JobTemplate.objects.get(pk=result['id'])
assert jt.survey_spec == survey_spec
prior_ct = ActivityStream.objects.count()
del survey_spec['description']
result = run_module('tower_job_template', dict(
name='foo',
playbook='helloworld.yml',
project=project.name,
inventory=inventory.name,
survey_spec=survey_spec,
survey_enabled=True
), admin_user)
assert result.get('failed', True)
assert result.get('msg') == "Failed to update survey: Field 'description' is missing from survey spec."
@pytest.mark.django_db
def test_job_template_with_survey_encrypted_default(run_module, admin_user, project, inventory, silence_warning):
spec = {
"spec": [
{
"index": 0,
"question_name": "my question?",
"default": "very_secret_value",
"variable": "myvar",
"type": "password",
"required": False
}
],
"description": "test",
"name": "test"
}
for i in range(2):
result = run_module('tower_job_template', dict(
name='foo',
playbook='helloworld.yml',
project=project.name,
inventory=inventory.name,
survey_spec=spec,
survey_enabled=True
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', False), result # not actually desired, but assert for sanity
silence_warning.assert_called_once_with(
"The field survey_spec of job_template {0} has encrypted data and "
"may inaccurately report task is changed.".format(result['id']))
@pytest.mark.django_db
def test_associate_only_on_success(run_module, admin_user, organization, project):
jt = JobTemplate.objects.create(
name='foo',
project=project,
playbook='helloworld.yml',
ask_inventory_on_launch=True,
)
create_kwargs = dict(
notification_configuration={
'url': 'http://www.example.com/hook',
'headers': {
'X-Custom-Header': 'value123'
},
'password': 'bar'
},
notification_type='webhook',
organization=organization
)
nt1 = NotificationTemplate.objects.create(name='nt1', **create_kwargs)
nt2 = NotificationTemplate.objects.create(name='nt2', **create_kwargs)
jt.notification_templates_error.add(nt1)
# test preservation of error NTs when success NTs are added
result = run_module('tower_job_template', dict(
name='foo',
playbook='helloworld.yml',
project=project.name,
notification_templates_success=['nt2']
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', True), result
assert list(jt.notification_templates_success.values_list('id', flat=True)) == [nt2.id]
assert list(jt.notification_templates_error.values_list('id', flat=True)) == [nt1.id]
# test removal to empty list
result = run_module('tower_job_template', dict(
name='foo',
playbook='helloworld.yml',
project=project.name,
notification_templates_success=[]
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', True), result
assert list(jt.notification_templates_success.values_list('id', flat=True)) == []
assert list(jt.notification_templates_error.values_list('id', flat=True)) == [nt1.id]
+47
View File
@@ -0,0 +1,47 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import Label
@pytest.mark.django_db
def test_create_label(run_module, admin_user, organization):
result = run_module('tower_label', dict(
name='test-label',
organization=organization.name
), admin_user)
assert not result.get('failed'), result.get('msg', result)
assert result.get('changed', False)
assert Label.objects.get(name='test-label').organization == organization
@pytest.mark.django_db
def test_create_label_using_org_id(run_module, admin_user, organization):
result = run_module('tower_label', dict(
name='test-label',
organization=organization.id
), admin_user)
assert not result.get('failed'), result.get('msg', result)
assert result.get('changed', False)
assert Label.objects.get(name='test-label').organization == organization
@pytest.mark.django_db
def test_modify_label(run_module, admin_user, organization):
label = Label.objects.create(name='test-label', organization=organization)
result = run_module('tower_label', dict(
name='test-label',
new_name='renamed-label',
organization=organization.name
), admin_user)
assert not result.get('failed'), result.get('msg', result)
assert result.get('changed', False)
label.refresh_from_db()
assert label.organization == organization
assert label.name == 'renamed-label'
@@ -0,0 +1,143 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import sys
from awx.main.models import Organization, Team, Project, Inventory
from requests.models import Response
from unittest import mock
def getheader(self, header_name, default):
mock_headers = {'X-API-Product-Name': 'not-junk', 'X-API-Product-Version': '1.2.3'}
return mock_headers.get(header_name, default)
def read(self):
return json.dumps({})
def status(self):
return 200
def mock_ping_response(self, method, url, **kwargs):
r = Response()
r.getheader = getheader.__get__(r)
r.read = read.__get__(r)
r.status = status.__get__(r)
return r
def test_version_warning(collection_import, silence_warning):
TowerAPIModule = collection_import('plugins.module_utils.tower_api').TowerAPIModule
cli_data = {'ANSIBLE_MODULE_ARGS': {}}
testargs = ['module_file2.py', json.dumps(cli_data)]
with mock.patch.object(sys, 'argv', testargs):
with mock.patch('ansible.module_utils.urls.Request.open', new=mock_ping_response):
my_module = TowerAPIModule(argument_spec=dict())
my_module._COLLECTION_VERSION = "1.0.0"
my_module._COLLECTION_TYPE = "not-junk"
my_module.collection_to_version['not-junk'] = 'not-junk'
my_module.get_endpoint('ping')
silence_warning.assert_called_once_with(
'You are running collection version 1.0.0 but connecting to tower version 1.2.3'
)
def test_type_warning(collection_import, silence_warning):
TowerAPIModule = collection_import('plugins.module_utils.tower_api').TowerAPIModule
cli_data = {'ANSIBLE_MODULE_ARGS': {}}
testargs = ['module_file2.py', json.dumps(cli_data)]
with mock.patch.object(sys, 'argv', testargs):
with mock.patch('ansible.module_utils.urls.Request.open', new=mock_ping_response):
my_module = TowerAPIModule(argument_spec={})
my_module._COLLECTION_VERSION = "1.2.3"
my_module._COLLECTION_TYPE = "junk"
my_module.collection_to_version['junk'] = 'junk'
my_module.get_endpoint('ping')
silence_warning.assert_called_once_with(
'You are using the junk version of this collection but connecting to not-junk'
)
def test_duplicate_config(collection_import, silence_warning):
# imports done here because of PATH issues unique to this test suite
TowerAPIModule = collection_import('plugins.module_utils.tower_api').TowerAPIModule
data = {
'name': 'zigzoom',
'zig': 'zoom',
'tower_username': 'bob',
'tower_config_file': 'my_config'
}
with mock.patch.object(TowerAPIModule, 'load_config') as mock_load:
argument_spec = dict(
name=dict(required=True),
zig=dict(type='str'),
)
TowerAPIModule(argument_spec=argument_spec, direct_params=data)
assert mock_load.mock_calls[-1] == mock.call('my_config')
silence_warning.assert_called_once_with(
'The parameter(s) tower_username were provided at the same time as '
'tower_config_file. Precedence may be unstable, '
'we suggest either using config file or params.'
)
def test_no_templated_values(collection_import):
"""This test corresponds to replacements done by
awx_collection/tools/roles/template_galaxy/tasks/main.yml
Those replacements should happen at build time, so they should not be
checked into source.
"""
TowerAPIModule = collection_import('plugins.module_utils.tower_api').TowerAPIModule
assert TowerAPIModule._COLLECTION_VERSION == "0.0.1-devel", (
'The collection version is templated when the collection is built '
'and the code should retain the placeholder of "0.0.1-devel".'
)
InventoryModule = collection_import('plugins.inventory.tower').InventoryModule
assert InventoryModule.NAME == 'awx.awx.tower', (
'The inventory plugin FQCN is templated when the collection is built '
'and the code should retain the default of awx.awx.'
)
def test_conflicting_name_and_id(run_module, admin_user):
"""In the event that 2 related items match our search criteria in this way:
one item has an id that matches input
one item has a name that matches input
We should preference the id over the name.
Otherwise, the universality of the tower_api lookup plugin is compromised.
"""
org_by_id = Organization.objects.create(name='foo')
slug = str(org_by_id.id)
org_by_name = Organization.objects.create(name=slug)
result = run_module('tower_team', {
'name': 'foo_team', 'description': 'fooin around',
'organization': slug
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
team = Team.objects.filter(name='foo_team').first()
assert str(team.organization_id) == slug, (
'Lookup by id should be preferenced over name in cases of conflict.'
)
assert team.organization.name == 'foo'
def test_multiple_lookup(run_module, admin_user):
org1 = Organization.objects.create(name='foo')
org2 = Organization.objects.create(name='bar')
inv = Inventory.objects.create(name='Foo Inv')
proj1 = Project.objects.create(name='foo', organization=org1, scm_type='git', scm_url="https://github.com/ansible/ansible-tower-samples",)
proj2 = Project.objects.create(name='foo', organization=org2, scm_type='git', scm_url="https://github.com/ansible/ansible-tower-samples",)
result = run_module('tower_job_template', {
'name': 'Demo Job Template', 'project': proj1.name, 'inventory': inv.id, 'playbook': 'hello_world.yml'
}, admin_user)
assert result.get('failed', False)
assert 'projects' in result['msg']
assert 'foo' in result['msg']
assert 'returned 2 items, expected 1' in result['msg']
assert 'query' in result
@@ -0,0 +1,140 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import NotificationTemplate, Job
def compare_with_encrypted(model_config, param_config):
'''Given a model_config from the database, assure that this is consistent
with the config given in the notification_configuration parameter
this requires handling of password fields
'''
for key, model_val in model_config.items():
param_val = param_config.get(key, 'missing')
if isinstance(model_val, str) and (model_val.startswith('$encrypted$') or param_val.startswith('$encrypted$')):
assert model_val.startswith('$encrypted$') # must be saved as encrypted
assert len(model_val) > len('$encrypted$')
else:
assert model_val == param_val, 'Config key {0} did not match, (model: {1}, input: {2})'.format(
key, model_val, param_val
)
@pytest.mark.django_db
def test_create_modify_notification_template(run_module, admin_user, organization):
nt_config = {
'username': 'user',
'password': 'password',
'sender': 'foo@invalid.com',
'recipients': ['foo2@invalid.com'],
'host': 'smtp.example.com',
'port': 25,
'use_tls': False, 'use_ssl': False,
'timeout': 4
}
result = run_module('tower_notification_template', dict(
name='foo-notification-template',
organization=organization.name,
notification_type='email',
notification_configuration=nt_config,
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.pop('changed', None), result
nt = NotificationTemplate.objects.get(id=result['id'])
compare_with_encrypted(nt.notification_configuration, nt_config)
assert nt.organization == organization
# Test no-op, this is impossible if the notification_configuration is given
# because we cannot determine if password fields changed
result = run_module('tower_notification_template', dict(
name='foo-notification-template',
organization=organization.name,
notification_type='email',
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert not result.pop('changed', None), result
# Test a change in the configuration
nt_config['timeout'] = 12
result = run_module('tower_notification_template', dict(
name='foo-notification-template',
organization=organization.name,
notification_type='email',
notification_configuration=nt_config,
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.pop('changed', None), result
nt.refresh_from_db()
compare_with_encrypted(nt.notification_configuration, nt_config)
@pytest.mark.django_db
def test_invalid_notification_configuration(run_module, admin_user, organization):
result = run_module('tower_notification_template', dict(
name='foo-notification-template',
organization=organization.name,
notification_type='email',
notification_configuration={},
), admin_user)
assert result.get('failed', False), result.get('msg', result)
assert 'Missing required fields for Notification Configuration' in result['msg']
@pytest.mark.django_db
def test_deprecated_to_modern_no_op(run_module, admin_user, organization):
nt_config = {
'url': 'http://www.example.com/hook',
'headers': {
'X-Custom-Header': 'value123'
}
}
result = run_module('tower_notification_template', dict(
name='foo-notification-template',
organization=organization.name,
notification_type='webhook',
notification_configuration=nt_config,
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.pop('changed', None), result
result = run_module('tower_notification_template', dict(
name='foo-notification-template',
organization=organization.name,
notification_type='webhook',
notification_configuration=nt_config,
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert not result.pop('changed', None), result
@pytest.mark.django_db
def test_build_notification_message_undefined(run_module, admin_user, organization):
"""Job notification templates may encounter undefined values in the context when they are
rendered. Make sure that accessing attributes or items of an undefined value returns another
instance of Undefined, rather than raising an UndefinedError. This enables the use of expressions
like "{{ job.created_by.first_name | default('unknown') }}"."""
job = Job.objects.create(name='foobar')
nt_config = {
'url': 'http://www.example.com/hook',
'headers': {
'X-Custom-Header': 'value123'
}
}
custom_start_template = {'body': '{"started_by": "{{ job.summary_fields.created_by.username | default(\'My Placeholder\') }}"}'}
messages = {'started': custom_start_template, 'success': None, 'error': None, 'workflow_approval': None}
result = run_module('tower_notification_template', dict(
name='foo-notification-template',
organization=organization.name,
notification_type='webhook',
notification_configuration=nt_config,
messages=messages,
), admin_user)
nt = NotificationTemplate.objects.get(id=result['id'])
body = job.build_notification_message(nt, 'running')
assert '{"started_by": "My Placeholder"}' in body[1]
@@ -0,0 +1,60 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import Organization
@pytest.mark.django_db
def test_create_organization(run_module, admin_user):
module_args = {
'name': 'foo',
'description': 'barfoo',
'state': 'present',
'max_hosts': '0',
'tower_host': None,
'tower_username': None,
'tower_password': None,
'validate_certs': None,
'tower_oauthtoken': None,
'tower_config_file': None,
'custom_virtualenv': None
}
result = run_module('tower_organization', module_args, admin_user)
assert result.get('changed'), result
org = Organization.objects.get(name='foo')
assert result == {
"name": "foo",
"changed": True,
"id": org.id,
"invocation": {
"module_args": module_args
}
}
assert org.description == 'barfoo'
@pytest.mark.django_db
def test_create_organization_with_venv(run_module, admin_user, mocker):
path = '/var/lib/awx/venv/custom-venv/foobar13489435/'
with mocker.patch('awx.main.models.mixins.get_custom_venv_choices', return_value=[path]):
result = run_module('tower_organization', {
'name': 'foo',
'custom_virtualenv': path,
'state': 'present'
}, admin_user)
assert result.pop('changed'), result
org = Organization.objects.get(name='foo')
result.pop('invocation')
assert result == {
"name": "foo",
"id": org.id
}
assert org.custom_virtualenv == path
+33
View File
@@ -0,0 +1,33 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import Project
@pytest.mark.django_db
def test_create_project(run_module, admin_user, organization, silence_warning):
result = run_module('tower_project', dict(
name='foo',
organization=organization.name,
scm_type='git',
scm_url='https://foo.invalid',
wait=False,
scm_update_cache_timeout=5
), admin_user)
silence_warning.assert_called_once_with(
'scm_update_cache_timeout will be ignored since scm_update_on_launch '
'was not set to true')
assert result.pop('changed', None), result
proj = Project.objects.get(name='foo')
assert proj.scm_url == 'https://foo.invalid'
assert proj.organization == organization
result.pop('invocation')
assert result == {
'name': 'foo',
'id': proj.id
}
+109
View File
@@ -0,0 +1,109 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import WorkflowJobTemplate, User
@pytest.mark.django_db
@pytest.mark.parametrize('state', ('present', 'absent'))
def test_grant_organization_permission(run_module, admin_user, organization, state):
rando = User.objects.create(username='rando')
if state == 'absent':
organization.admin_role.members.add(rando)
result = run_module('tower_role', {
'user': rando.username,
'organization': organization.name,
'role': 'admin',
'state': state
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
if state == 'present':
assert rando in organization.execute_role
else:
assert rando not in organization.execute_role
@pytest.mark.django_db
@pytest.mark.parametrize('state', ('present', 'absent'))
def test_grant_workflow_permission(run_module, admin_user, organization, state):
wfjt = WorkflowJobTemplate.objects.create(organization=organization, name='foo-workflow')
rando = User.objects.create(username='rando')
if state == 'absent':
wfjt.execute_role.members.add(rando)
result = run_module('tower_role', {
'user': rando.username,
'workflow': wfjt.name,
'role': 'execute',
'state': state
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
if state == 'present':
assert rando in wfjt.execute_role
else:
assert rando not in wfjt.execute_role
@pytest.mark.django_db
@pytest.mark.parametrize('state', ('present', 'absent'))
def test_grant_workflow_list_permission(run_module, admin_user, organization, state):
wfjt = WorkflowJobTemplate.objects.create(organization=organization, name='foo-workflow')
rando = User.objects.create(username='rando')
if state == 'absent':
wfjt.execute_role.members.add(rando)
result = run_module('tower_role', {
'user': rando.username,
'lookup_organization': wfjt.organization.name,
'workflows': [wfjt.name],
'role': 'execute',
'state': state
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
if state == 'present':
assert rando in wfjt.execute_role
else:
assert rando not in wfjt.execute_role
@pytest.mark.django_db
@pytest.mark.parametrize('state', ('present', 'absent'))
def test_grant_workflow_approval_permission(run_module, admin_user, organization, state):
wfjt = WorkflowJobTemplate.objects.create(organization=organization, name='foo-workflow')
rando = User.objects.create(username='rando')
if state == 'absent':
wfjt.execute_role.members.add(rando)
result = run_module('tower_role', {
'user': rando.username,
'workflow': wfjt.name,
'role': 'approval',
'state': state
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
if state == 'present':
assert rando in wfjt.approval_role
else:
assert rando not in wfjt.approval_role
@pytest.mark.django_db
def test_invalid_role(run_module, admin_user, project):
rando = User.objects.create(username='rando')
result = run_module('tower_role', {
'user': rando.username,
'project': project.name,
'role': 'adhoc',
'state': 'present'
}, admin_user)
assert result.get('failed', False)
msg = result.get('msg')
assert 'has no role adhoc_role' in msg
assert 'available roles: admin_role, use_role, update_role, read_role' in msg
+107
View File
@@ -0,0 +1,107 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from ansible.errors import AnsibleError
from awx.main.models import Schedule
from awx.api.serializers import SchedulePreviewSerializer
@pytest.mark.django_db
def test_create_schedule(run_module, job_template, admin_user):
my_rrule = 'DTSTART;TZID=Zulu:20200416T034507 RRULE:FREQ=MONTHLY;INTERVAL=1'
result = run_module('tower_schedule', {
'name': 'foo_schedule',
'unified_job_template': job_template.name,
'rrule': my_rrule
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
schedule = Schedule.objects.filter(name='foo_schedule').first()
assert result['id'] == schedule.id
assert result['changed']
assert schedule.rrule == my_rrule
@pytest.mark.parametrize("freq, kwargs, expect", [
# Test with a valid start date (no time) (also tests none frequency and count)
('none', {'start_date': '2020-04-16'}, 'DTSTART;TZID=America/New_York:20200416T000000 RRULE:FREQ=DAILY;COUNT=1;INTERVAL=1'),
# Test with a valid start date and time
('none', {'start_date': '2020-04-16 03:45:07'}, 'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=DAILY;COUNT=1;INTERVAL=1'),
# Test end_on as count (also integration test)
('minute', {'start_date': '2020-4-16 03:45:07', 'end_on': '2'}, 'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=MINUTELY;COUNT=2;INTERVAL=1'),
# Test end_on as date
('minute', {'start_date': '2020-4-16 03:45:07', 'end_on': '2020-4-17 03:45:07'},
'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=MINUTELY;UNTIL=20200417T034507;INTERVAL=1'),
# Test on_days as a single day
('week', {'start_date': '2020-4-16 03:45:07', 'on_days': 'saturday'},
'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=WEEKLY;BYDAY=SA;INTERVAL=1'),
# Test on_days as multiple days (with some whitespaces)
('week', {'start_date': '2020-4-16 03:45:07', 'on_days': 'saturday,monday , friday'},
'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=WEEKLY;BYDAY=MO,FR,SA;INTERVAL=1'),
# Test valid month_day_number
('month', {'start_date': '2020-4-16 03:45:07', 'month_day_number': '18'},
'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=MONTHLY;BYMONTHDAY=18;INTERVAL=1'),
# Test a valid on_the
('month', {'start_date': '2020-4-16 03:45:07', 'on_the': 'second sunday'},
'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=MONTHLY;BYSETPOS=2;BYDAY=SU;INTERVAL=1'),
# Test an valid timezone
('month', {'start_date': '2020-4-16 03:45:07', 'timezone': 'Zulu'},
'DTSTART;TZID=Zulu:20200416T034507 RRULE:FREQ=MONTHLY;INTERVAL=1'),
])
def test_rrule_lookup_plugin(collection_import, freq, kwargs, expect):
LookupModule = collection_import('plugins.lookup.tower_schedule_rrule').LookupModule
generated_rule = LookupModule.get_rrule(freq, kwargs)
assert generated_rule == expect
rrule_checker = SchedulePreviewSerializer()
# Try to run our generated rrule through the awx validator
# This will raise its own exception on failure
rrule_checker.validate_rrule(generated_rule)
@pytest.mark.parametrize("freq", ('none', 'minute', 'hour', 'day', 'week', 'month'))
def test_empty_schedule_rrule(collection_import, freq):
LookupModule = collection_import('plugins.lookup.tower_schedule_rrule').LookupModule
if freq == 'day':
pfreq = 'DAILY'
elif freq == 'none':
pfreq = 'DAILY;COUNT=1'
else:
pfreq = freq.upper() + 'LY'
assert LookupModule.get_rrule(freq, {}).endswith(' RRULE:FREQ={0};INTERVAL=1'.format(pfreq))
@pytest.mark.parametrize("freq, kwargs, msg", [
# Test end_on as junk
('minute', {'start_date': '2020-4-16 03:45:07', 'end_on': 'junk'},
'Parameter end_on must either be an integer or in the format YYYY-MM-DD'),
# Test on_days as junk
('week', {'start_date': '2020-4-16 03:45:07', 'on_days': 'junk'},
'Parameter on_days must only contain values monday, tuesday, wednesday, thursday, friday, saturday, sunday'),
# Test combo of both month_day_number and on_the
('month', dict(start_date='2020-4-16 03:45:07', on_the='something', month_day_number='else'),
"Month based frequencies can have month_day_number or on_the but not both"),
# Test month_day_number as not an integer
('month', dict(start_date='2020-4-16 03:45:07', month_day_number='junk'), "month_day_number must be between 1 and 31"),
# Test month_day_number < 1
('month', dict(start_date='2020-4-16 03:45:07', month_day_number='0'), "month_day_number must be between 1 and 31"),
# Test month_day_number > 31
('month', dict(start_date='2020-4-16 03:45:07', month_day_number='32'), "month_day_number must be between 1 and 31"),
# Test on_the as junk
('month', dict(start_date='2020-4-16 03:45:07', on_the='junk'), "on_the parameter must be two words separated by a space"),
# Test on_the with invalid occurance
('month', dict(start_date='2020-4-16 03:45:07', on_the='junk wednesday'), "The first string of the on_the parameter is not valid"),
# Test on_the with invalid weekday
('month', dict(start_date='2020-4-16 03:45:07', on_the='second junk'), "Weekday portion of on_the parameter is not valid"),
# Test an invalid timezone
('month', dict(start_date='2020-4-16 03:45:07', timezone='junk'), 'Timezone parameter is not valid'),
])
def test_rrule_lookup_plugin_failure(collection_import, freq, kwargs, msg):
LookupModule = collection_import('plugins.lookup.tower_schedule_rrule').LookupModule
with pytest.raises(AnsibleError) as e:
assert LookupModule.get_rrule(freq, kwargs)
assert msg in str(e.value)
@@ -0,0 +1,76 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
import json
from awx.main.models import (
Organization,
Project,
Inventory,
Host,
CredentialType,
Credential,
JobTemplate
)
# warns based on password_management param, but not security issue
@pytest.mark.django_db
def test_receive_send_jt(run_module, admin_user, mocker, silence_deprecation):
org = Organization.objects.create(name='SRtest')
proj = Project.objects.create(
name='SRtest',
playbook_files=['debug.yml'],
scm_type='git',
scm_url='https://github.com/ansible/test-playbooks.git',
organization=org,
allow_override=True # so we do not require playbooks populated
)
inv = Inventory.objects.create(name='SRtest', organization=org)
Host.objects.create(name='SRtest', inventory=inv)
ct = CredentialType.defaults['ssh']()
ct.save()
cred = Credential.objects.create(
name='SRtest',
credential_type=ct,
organization=org
)
jt = JobTemplate.objects.create(
name='SRtest',
project=proj,
inventory=inv,
playbook='helloworld.yml'
)
jt.credentials.add(cred)
jt.admin_role.members.add(admin_user) # work around send/receive bug
# receive everything
result = run_module('tower_receive', dict(all=True), admin_user)
assert 'assets' in result, result
assets = result['assets']
assert not result.get('changed', True)
assert set(a['asset_type'] for a in assets) == set((
'organization', 'inventory', 'job_template', 'credential', 'project',
'user'
))
# delete everything
for obj in (jt, inv, proj, cred, org):
obj.delete()
def fake_wait(self, pk, parent_pk=None, **kwargs):
return {"changed": True}
# recreate everything
with mocker.patch('sys.stdin.isatty', return_value=True):
with mocker.patch('tower_cli.models.base.MonitorableResource.wait'):
result = run_module('tower_send', dict(assets=json.dumps(assets)), admin_user)
assert not result.get('failed'), result
new = JobTemplate.objects.get(name='SRtest')
assert new.project.name == 'SRtest'
assert new.inventory.name == 'SRtest'
assert [cred.name for cred in new.credentials.all()] == ['SRtest']
+67
View File
@@ -0,0 +1,67 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.conf.models import Setting
@pytest.mark.django_db
def test_setting_flat_value(run_module, admin_user):
the_value = 'CN=service_account,OU=ServiceAccounts,DC=domain,DC=company,DC=org'
result = run_module('tower_settings', dict(
name='AUTH_LDAP_BIND_DN',
value=the_value
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
assert Setting.objects.get(key='AUTH_LDAP_BIND_DN').value == the_value
@pytest.mark.django_db
def test_setting_dict_value(run_module, admin_user):
the_value = {
'email': 'mail',
'first_name': 'givenName',
'last_name': 'surname'
}
result = run_module('tower_settings', dict(
name='AUTH_LDAP_USER_ATTR_MAP',
value=the_value
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
assert Setting.objects.get(key='AUTH_LDAP_USER_ATTR_MAP').value == the_value
@pytest.mark.django_db
def test_setting_nested_type(run_module, admin_user):
the_value = {
'email': 'mail',
'first_name': 'givenName',
'last_name': 'surname'
}
result = run_module('tower_settings', dict(
settings={
'AUTH_LDAP_USER_ATTR_MAP': the_value
}
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
assert Setting.objects.get(key='AUTH_LDAP_USER_ATTR_MAP').value == the_value
@pytest.mark.django_db
def test_setting_bool_value(run_module, admin_user):
for the_value in (True, False):
result = run_module('tower_settings', dict(
name='ACTIVITY_STREAM_ENABLED_FOR_INVENTORY_SYNC',
value=the_value
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
assert Setting.objects.get(key='ACTIVITY_STREAM_ENABLED_FOR_INVENTORY_SYNC').value is the_value
+66
View File
@@ -0,0 +1,66 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import Organization, Team
@pytest.mark.django_db
def test_create_team(run_module, admin_user):
org = Organization.objects.create(name='foo')
result = run_module('tower_team', {
'name': 'foo_team',
'description': 'fooin around',
'state': 'present',
'organization': 'foo'
}, admin_user)
team = Team.objects.filter(name='foo_team').first()
result.pop('invocation')
assert result == {
"changed": True,
"name": "foo_team",
"id": team.id if team else None,
}
team = Team.objects.get(name='foo_team')
assert team.description == 'fooin around'
assert team.organization_id == org.id
@pytest.mark.django_db
def test_modify_team(run_module, admin_user):
org = Organization.objects.create(name='foo')
team = Team.objects.create(
name='foo_team',
organization=org,
description='flat foo'
)
assert team.description == 'flat foo'
result = run_module('tower_team', {
'name': 'foo_team',
'description': 'fooin around',
'organization': 'foo'
}, admin_user)
team.refresh_from_db()
result.pop('invocation')
assert result == {
"changed": True,
"id": team.id,
}
assert team.description == 'fooin around'
# 2nd modification, should cause no change
result = run_module('tower_team', {
'name': 'foo_team',
'description': 'fooin around',
'organization': 'foo'
}, admin_user)
result.pop('invocation')
assert result == {
"id": team.id,
"changed": False
}
+29
View File
@@ -0,0 +1,29 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import OAuth2AccessToken
@pytest.mark.django_db
def test_create_token(run_module, admin_user):
module_args = {
'description': 'barfoo',
'state': 'present',
'scope': 'read',
'tower_host': None,
'tower_username': None,
'tower_password': None,
'validate_certs': None,
'tower_oauthtoken': None,
'tower_config_file': None,
}
result = run_module('tower_token', module_args, admin_user)
assert result.get('changed'), result
tokens = OAuth2AccessToken.objects.filter(description='barfoo')
assert len(tokens) == 1, 'Tokens with description of barfoo != 0: {0}'.format(len(tokens))
assert tokens[0].scope == 'read', 'Token was not given read access'
+59
View File
@@ -0,0 +1,59 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from unittest import mock
from awx.main.models import User
@pytest.fixture
def mock_auth_stuff():
"""Some really specific session-related stuff is done for changing or setting
passwords, so we will just avoid that here.
"""
with mock.patch('awx.api.serializers.update_session_auth_hash'):
yield
@pytest.mark.django_db
def test_create_user(run_module, admin_user, mock_auth_stuff):
result = run_module('tower_user', dict(
username='Bob',
password='pass4word'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed'), result
user = User.objects.get(id=result['id'])
assert user.username == 'Bob'
@pytest.mark.django_db
def test_password_no_op_warning(run_module, admin_user, mock_auth_stuff, silence_warning):
for i in range(2):
result = run_module('tower_user', dict(
username='Bob',
password='pass4word'
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed') # not actually desired, but assert for sanity
silence_warning.assert_called_once_with(
"The field password of user {0} has encrypted data and "
"may inaccurately report task is changed.".format(result['id']))
@pytest.mark.django_db
def test_update_password_on_create(run_module, admin_user, mock_auth_stuff):
for i in range(2):
result = run_module('tower_user', dict(
username='Bob',
password='pass4word',
update_secrets=False
), admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert not result.get('changed')
@@ -0,0 +1,174 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import WorkflowJobTemplate, NotificationTemplate
@pytest.mark.django_db
def test_create_workflow_job_template(run_module, admin_user, organization, survey_spec):
result = run_module('tower_workflow_job_template', {
'name': 'foo-workflow',
'organization': organization.name,
'extra_vars': {'foo': 'bar', 'another-foo': {'barz': 'bar2'}},
'survey_spec': survey_spec,
'survey_enabled': True,
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
wfjt = WorkflowJobTemplate.objects.get(name='foo-workflow')
assert wfjt.extra_vars == '{"foo": "bar", "another-foo": {"barz": "bar2"}}'
result.pop('invocation', None)
assert result == {"name": "foo-workflow", "id": wfjt.id, "changed": True}
assert wfjt.organization_id == organization.id
assert wfjt.survey_spec == survey_spec
@pytest.mark.django_db
def test_create_modify_no_survey(run_module, admin_user, organization, survey_spec):
result = run_module('tower_workflow_job_template', {
'name': 'foo-workflow',
'organization': organization.name
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', False), result
wfjt = WorkflowJobTemplate.objects.get(name='foo-workflow')
assert wfjt.organization_id == organization.id
assert wfjt.survey_spec == {}
result.pop('invocation', None)
assert result == {"name": "foo-workflow", "id": wfjt.id, "changed": True}
result = run_module('tower_workflow_job_template', {
'name': 'foo-workflow',
'organization': organization.name
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert not result.get('changed', True), result
@pytest.mark.django_db
def test_survey_spec_only_changed(run_module, admin_user, organization, survey_spec):
wfjt = WorkflowJobTemplate.objects.create(
organization=organization, name='foo-workflow',
survey_enabled=True, survey_spec=survey_spec
)
result = run_module('tower_workflow_job_template', {
'name': 'foo-workflow',
'organization': organization.name,
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert not result.get('changed', True), result
wfjt.refresh_from_db()
assert wfjt.survey_spec == survey_spec
survey_spec['description'] = 'changed description'
result = run_module('tower_workflow_job_template', {
'name': 'foo-workflow',
'organization': organization.name,
'survey_spec': survey_spec,
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', True), result
wfjt.refresh_from_db()
assert wfjt.survey_spec == survey_spec
@pytest.mark.django_db
def test_survey_spec_only_changed(run_module, admin_user, organization, survey_spec):
wfjt = WorkflowJobTemplate.objects.create(
organization=organization, name='foo-workflow',
survey_enabled=True, survey_spec=survey_spec
)
result = run_module('tower_workflow_job_template', {
'name': 'foo-workflow',
'organization': organization.name,
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert not result.get('changed', True), result
wfjt.refresh_from_db()
assert wfjt.survey_spec == survey_spec
del survey_spec['description']
result = run_module('tower_workflow_job_template', {
'name': 'foo-workflow',
'organization': organization.name,
'survey_spec': survey_spec,
'state': 'present'
}, admin_user)
assert result.get('failed', True)
assert result.get('msg') == "Failed to update survey: Field 'description' is missing from survey spec."
@pytest.mark.django_db
def test_associate_only_on_success(run_module, admin_user, organization, project):
wfjt = WorkflowJobTemplate.objects.create(
organization=organization, name='foo-workflow',
# survey_enabled=True, survey_spec=survey_spec
)
create_kwargs = dict(
notification_configuration={
'url': 'http://www.example.com/hook',
'headers': {
'X-Custom-Header': 'value123'
},
'password': 'bar'
},
notification_type='webhook',
organization=organization
)
nt1 = NotificationTemplate.objects.create(name='nt1', **create_kwargs)
nt2 = NotificationTemplate.objects.create(name='nt2', **create_kwargs)
wfjt.notification_templates_error.add(nt1)
# test preservation of error NTs when success NTs are added
result = run_module('tower_workflow_job_template', {
'name': 'foo-workflow',
'organization': organization.name,
'notification_templates_success': ['nt2']
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', True), result
assert list(wfjt.notification_templates_success.values_list('id', flat=True)) == [nt2.id]
assert list(wfjt.notification_templates_error.values_list('id', flat=True)) == [nt1.id]
# test removal to empty list
result = run_module('tower_workflow_job_template', {
'name': 'foo-workflow',
'organization': organization.name,
'notification_templates_success': []
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', True), result
assert list(wfjt.notification_templates_success.values_list('id', flat=True)) == []
assert list(wfjt.notification_templates_error.values_list('id', flat=True)) == [nt1.id]
@pytest.mark.django_db
def test_delete_with_spec(run_module, admin_user, organization, survey_spec):
WorkflowJobTemplate.objects.create(
organization=organization, name='foo-workflow',
survey_enabled=True, survey_spec=survey_spec
)
result = run_module('tower_workflow_job_template', {
'name': 'foo-workflow',
'organization': organization.name,
'state': 'absent'
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', True), result
assert WorkflowJobTemplate.objects.filter(
name='foo-workflow', organization=organization).count() == 0
@@ -0,0 +1,127 @@
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import WorkflowJobTemplateNode, WorkflowJobTemplate, JobTemplate, UnifiedJobTemplate
@pytest.fixture
def job_template(project, inventory):
return JobTemplate.objects.create(
project=project,
inventory=inventory,
playbook='helloworld.yml',
name='foo-jt',
ask_variables_on_launch=True,
ask_credential_on_launch=True,
ask_limit_on_launch=True
)
@pytest.fixture
def wfjt(organization):
WorkflowJobTemplate.objects.create(organization=None, name='foo-workflow') # to test org scoping
return WorkflowJobTemplate.objects.create(organization=organization, name='foo-workflow')
@pytest.mark.django_db
def test_create_workflow_job_template_node(run_module, admin_user, wfjt, job_template):
this_identifier = '42🐉'
result = run_module('tower_workflow_job_template_node', {
'identifier': this_identifier,
'workflow_job_template': 'foo-workflow',
'organization': wfjt.organization.name,
'unified_job_template': 'foo-jt',
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
node = WorkflowJobTemplateNode.objects.get(identifier=this_identifier)
result.pop('invocation', None)
assert result == {
"name": this_identifier, # FIXME: should this be identifier instead
"id": node.id,
"changed": True
}
assert node.identifier == this_identifier
assert node.workflow_job_template_id == wfjt.id
assert node.unified_job_template_id == job_template.id
@pytest.mark.django_db
def test_create_workflow_job_template_node_approval_node(run_module, admin_user, wfjt, job_template):
"""This is a part of the API contract for creating approval nodes"""
this_identifier = '42🐉'
result = run_module('tower_workflow_job_template_node', {
'identifier': this_identifier,
'workflow_job_template': wfjt.name,
'organization': wfjt.organization.name,
'approval_node': {'name': 'foo-jt-approval'}
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', False), result
node = WorkflowJobTemplateNode.objects.get(identifier=this_identifier)
approval_node = UnifiedJobTemplate.objects.get(name='foo-jt-approval')
assert result['id'] == approval_node.id
assert node.identifier == this_identifier
assert node.workflow_job_template_id == wfjt.id
assert node.unified_job_template_id is approval_node.id
@pytest.mark.django_db
def test_make_use_of_prompts(run_module, admin_user, wfjt, job_template, machine_credential, vault_credential):
result = run_module('tower_workflow_job_template_node', {
'identifier': '42',
'workflow_job_template': 'foo-workflow',
'organization': wfjt.organization.name,
'unified_job_template': 'foo-jt',
'extra_data': {'foo': 'bar', 'another-foo': {'barz': 'bar2'}},
'limit': 'foo_hosts',
'credentials': [machine_credential.name, vault_credential.name],
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', False)
node = WorkflowJobTemplateNode.objects.get(identifier='42')
assert node.limit == 'foo_hosts'
assert node.extra_data == {'foo': 'bar', 'another-foo': {'barz': 'bar2'}}
assert set(node.credentials.all()) == set([machine_credential, vault_credential])
@pytest.mark.django_db
def test_create_with_edges(run_module, admin_user, wfjt, job_template):
next_nodes = [
WorkflowJobTemplateNode.objects.create(
identifier='foo{0}'.format(i),
workflow_job_template=wfjt,
unified_job_template=job_template
) for i in range(3)
]
result = run_module('tower_workflow_job_template_node', {
'identifier': '42',
'workflow_job_template': 'foo-workflow',
'organization': wfjt.organization.name,
'unified_job_template': 'foo-jt',
'success_nodes': ['foo0'],
'always_nodes': ['foo1'],
'failure_nodes': ['foo2'],
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
assert result.get('changed', False)
node = WorkflowJobTemplateNode.objects.get(identifier='42')
assert list(node.success_nodes.all()) == [next_nodes[0]]
assert list(node.always_nodes.all()) == [next_nodes[1]]
assert list(node.failure_nodes.all()) == [next_nodes[2]]
@@ -0,0 +1,130 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from awx.main.models import (
WorkflowJobTemplate, JobTemplate, Project, InventorySource,
Inventory, WorkflowJobTemplateNode
)
@pytest.mark.django_db
def test_create_workflow_job_template(run_module, admin_user, organization, survey_spec, silence_deprecation):
result = run_module('tower_workflow_template', {
'name': 'foo-workflow',
'organization': organization.name,
'extra_vars': {'foo': 'bar', 'another-foo': {'barz': 'bar2'}},
'survey': survey_spec,
'survey_enabled': True,
'state': 'present'
}, admin_user)
wfjt = WorkflowJobTemplate.objects.get(name='foo-workflow')
assert wfjt.extra_vars == '{"foo": "bar", "another-foo": {"barz": "bar2"}}'
result.pop('invocation', None)
assert result == {
"workflow_template": "foo-workflow", # TODO: remove after refactor
"state": "present",
"id": wfjt.id,
"changed": True
}
assert wfjt.organization_id == organization.id
assert wfjt.survey_spec == survey_spec
@pytest.mark.django_db
def test_with_nested_workflow(run_module, admin_user, organization, silence_deprecation):
wfjt1 = WorkflowJobTemplate.objects.create(name='first', organization=organization)
result = run_module('tower_workflow_template', {
'name': 'foo-workflow',
'organization': organization.name,
'schema': [
{'workflow': wfjt1.name}
],
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
wfjt = WorkflowJobTemplate.objects.get(name='foo-workflow')
node = wfjt.workflow_nodes.first()
assert node is not None
assert node.unified_job_template == wfjt1
@pytest.mark.django_db
def test_schema_with_branches(run_module, admin_user, organization, silence_deprecation):
proj = Project.objects.create(organization=organization, name='Ansible Examples')
inv = Inventory.objects.create(organization=organization, name='test-inv')
jt = JobTemplate.objects.create(
project=proj,
playbook='helloworld.yml',
inventory=inv,
name='Hello world'
)
inv_src = InventorySource.objects.create(
inventory=inv,
name='AWS servers',
source='ec2'
)
result = run_module('tower_workflow_template', {
'name': 'foo-workflow',
'organization': organization.name,
'schema': [
{
'job_template': 'Hello world',
'failure': [
{
'inventory_source': 'AWS servers',
'success': [
{
'project': 'Ansible Examples',
'always': [
{
'job_template': "Hello world"
}
]
}
]
}
]
}
],
'state': 'present'
}, admin_user)
assert not result.get('failed', False), result.get('msg', result)
wfjt = WorkflowJobTemplate.objects.get(name='foo-workflow')
root_nodes = wfjt.workflow_nodes.filter(**{
'%ss_success__isnull' % WorkflowJobTemplateNode.__name__.lower(): True,
'%ss_failure__isnull' % WorkflowJobTemplateNode.__name__.lower(): True,
'%ss_always__isnull' % WorkflowJobTemplateNode.__name__.lower(): True,
})
assert len(root_nodes) == 1
node = root_nodes[0]
assert node.unified_job_template == jt
second = node.failure_nodes.first()
assert second.unified_job_template == inv_src
third = second.success_nodes.first()
assert third.unified_job_template == proj
fourth = third.always_nodes.first()
assert fourth.unified_job_template == jt
@pytest.mark.django_db
def test_with_missing_ujt(run_module, admin_user, organization, silence_deprecation):
result = run_module('tower_workflow_template', {
'name': 'foo-workflow',
'organization': organization.name,
'schema': [
{'foo': 'bar'}
],
'state': 'present'
}, admin_user)
assert result.get('failed', False), result
assert 'You should provide exactly one of the attributes job_template,' in result['msg']