Initial commit
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from awx.main.models import Credential, CredentialType
|
||||
|
||||
|
||||
def test_unique_hash_with_unicode():
|
||||
ct = CredentialType(name=u'Väult', kind='vault')
|
||||
cred = Credential(
|
||||
id=4,
|
||||
name=u'Iñtërnâtiônàlizætiøn',
|
||||
credential_type=ct,
|
||||
inputs={
|
||||
u'vault_id': u'🐉🐉🐉'
|
||||
},
|
||||
credential_type_id=42
|
||||
)
|
||||
assert cred.unique_hash(display=True) == u'Väult (id=🐉🐉🐉)'
|
||||
|
||||
|
||||
def test_custom_cred_with_empty_encrypted_field():
|
||||
ct = CredentialType(
|
||||
name='My Custom Cred',
|
||||
kind='custom',
|
||||
inputs={
|
||||
'fields': [{
|
||||
'id': 'some_field',
|
||||
'label': 'My Field',
|
||||
'secret': True
|
||||
}]
|
||||
}
|
||||
)
|
||||
cred = Credential(
|
||||
id=4,
|
||||
name='Testing 1 2 3',
|
||||
credential_type=ct,
|
||||
inputs={}
|
||||
)
|
||||
assert cred.encrypt_field('some_field', None) is None
|
||||
@@ -0,0 +1,51 @@
|
||||
from datetime import datetime
|
||||
from django.utils.timezone import utc
|
||||
import pytest
|
||||
|
||||
from awx.main.models import (JobEvent, ProjectUpdateEvent, AdHocCommandEvent,
|
||||
InventoryUpdateEvent, SystemJobEvent)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('job_identifier, cls', [
|
||||
['job_id', JobEvent],
|
||||
['project_update_id', ProjectUpdateEvent],
|
||||
['ad_hoc_command_id', AdHocCommandEvent],
|
||||
['inventory_update_id', InventoryUpdateEvent],
|
||||
['system_job_id', SystemJobEvent],
|
||||
])
|
||||
@pytest.mark.parametrize('created', [
|
||||
datetime(2018, 1, 1).isoformat(), datetime(2018, 1, 1)
|
||||
])
|
||||
def test_event_parse_created(job_identifier, cls, created):
|
||||
event = cls.create_from_data(**{
|
||||
job_identifier: 123,
|
||||
'created': created
|
||||
})
|
||||
assert event.created == datetime(2018, 1, 1).replace(tzinfo=utc)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('job_identifier, cls', [
|
||||
['job_id', JobEvent],
|
||||
['project_update_id', ProjectUpdateEvent],
|
||||
['ad_hoc_command_id', AdHocCommandEvent],
|
||||
['inventory_update_id', InventoryUpdateEvent],
|
||||
['system_job_id', SystemJobEvent],
|
||||
])
|
||||
def test_playbook_event_strip_invalid_keys(job_identifier, cls):
|
||||
event = cls.create_from_data(**{
|
||||
job_identifier: 123,
|
||||
'extra_key': 'extra_value'
|
||||
})
|
||||
assert getattr(event, job_identifier) == 123
|
||||
assert not hasattr(event, 'extra_key')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('field', [
|
||||
'play', 'role', 'task', 'playbook'
|
||||
])
|
||||
def test_really_long_event_fields(field):
|
||||
event = JobEvent.create_from_data(**{
|
||||
'job_id': 123,
|
||||
'event_data': {field: 'X' * 4096}
|
||||
})
|
||||
assert event.event_data[field] == 'X' * 1023 + '…'
|
||||
@@ -0,0 +1,76 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
from unittest.mock import Mock
|
||||
|
||||
from awx.main.models import (
|
||||
Job,
|
||||
InstanceGroup,
|
||||
)
|
||||
|
||||
|
||||
def T(impact):
|
||||
j = mock.Mock(Job())
|
||||
j.task_impact = impact
|
||||
return j
|
||||
|
||||
|
||||
def Is(param):
|
||||
'''
|
||||
param:
|
||||
[remaining_capacity1, remaining_capacity2, remaining_capacity3, ...]
|
||||
[(jobs_running1, capacity1), (jobs_running2, capacity2), (jobs_running3, capacity3), ...]
|
||||
'''
|
||||
|
||||
instances = []
|
||||
if isinstance(param[0], tuple):
|
||||
for (jobs_running, capacity) in param:
|
||||
inst = Mock()
|
||||
inst.capacity = capacity
|
||||
inst.jobs_running = jobs_running
|
||||
instances.append(inst)
|
||||
else:
|
||||
for i in param:
|
||||
inst = Mock()
|
||||
inst.remaining_capacity = i
|
||||
instances.append(inst)
|
||||
return instances
|
||||
|
||||
|
||||
class TestInstanceGroup(object):
|
||||
@pytest.mark.parametrize('task,instances,instance_fit_index,reason', [
|
||||
(T(100), Is([100]), 0, "Only one, pick it"),
|
||||
(T(100), Is([100, 100]), 0, "Two equally good fits, pick the first"),
|
||||
(T(100), Is([50, 100]), 1, "First instance not as good as second instance"),
|
||||
(T(100), Is([50, 0, 20, 100, 100, 100, 30, 20]), 3, "Pick Instance [3] as it is the first that the task fits in."),
|
||||
(T(100), Is([50, 0, 20, 99, 11, 1, 5, 99]), None, "The task don't a fit, you must a quit!"),
|
||||
])
|
||||
def test_fit_task_to_most_remaining_capacity_instance(self, task, instances, instance_fit_index, reason):
|
||||
ig = InstanceGroup(id=10)
|
||||
|
||||
instance_picked = ig.fit_task_to_most_remaining_capacity_instance(task, instances)
|
||||
|
||||
if instance_fit_index is None:
|
||||
assert instance_picked is None, reason
|
||||
else:
|
||||
assert instance_picked == instances[instance_fit_index], reason
|
||||
|
||||
@pytest.mark.parametrize('instances,instance_fit_index,reason', [
|
||||
(Is([(0, 100)]), 0, "One idle instance, pick it"),
|
||||
(Is([(1, 100)]), None, "One un-idle instance, pick nothing"),
|
||||
(Is([(0, 100), (0, 200), (1, 500), (0, 700)]), 3, "Pick the largest idle instance"),
|
||||
(Is([(0, 100), (0, 200), (1, 10000), (0, 700), (0, 699)]), 3, "Pick the largest idle instance"),
|
||||
(Is([(0, 0)]), None, "One idle but down instance, don't pick it"),
|
||||
])
|
||||
def test_find_largest_idle_instance(self, instances, instance_fit_index, reason):
|
||||
def filter_offline_instances(*args):
|
||||
return filter(lambda i: i.capacity > 0, instances)
|
||||
|
||||
ig = InstanceGroup(id=10)
|
||||
instances_online_only = filter_offline_instances(instances)
|
||||
|
||||
if instance_fit_index is None:
|
||||
assert ig.find_largest_idle_instance(instances_online_only) is None, reason
|
||||
else:
|
||||
assert ig.find_largest_idle_instance(instances_online_only) == \
|
||||
instances[instance_fit_index], reason
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
import json
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
from awx.main.models import (
|
||||
UnifiedJob,
|
||||
InventoryUpdate,
|
||||
Inventory,
|
||||
Credential,
|
||||
CredentialType,
|
||||
InventorySource,
|
||||
)
|
||||
|
||||
|
||||
def test_cancel(mocker):
|
||||
with mock.patch.object(UnifiedJob, 'cancel', return_value=True) as parent_cancel:
|
||||
iu = InventoryUpdate()
|
||||
|
||||
iu.save = mocker.MagicMock()
|
||||
build_job_explanation_mock = mocker.MagicMock()
|
||||
iu._build_job_explanation = mocker.MagicMock(return_value=build_job_explanation_mock)
|
||||
|
||||
iu.cancel()
|
||||
|
||||
parent_cancel.assert_called_with(is_chain=False, job_explanation=None)
|
||||
|
||||
|
||||
def test__build_job_explanation():
|
||||
iu = InventoryUpdate(id=3, name='I_am_an_Inventory_Update')
|
||||
|
||||
job_explanation = iu._build_job_explanation()
|
||||
|
||||
assert job_explanation == 'Previous Task Canceled: {"job_type": "%s", "job_name": "%s", "job_id": "%s"}' % \
|
||||
('inventory_update', 'I_am_an_Inventory_Update', 3)
|
||||
|
||||
|
||||
def test_valid_clean_insights_credential():
|
||||
cred_type = CredentialType.defaults['insights']()
|
||||
insights_cred = Credential(credential_type=cred_type)
|
||||
inv = Inventory(insights_credential=insights_cred)
|
||||
|
||||
inv.clean_insights_credential()
|
||||
|
||||
|
||||
def test_invalid_clean_insights_credential():
|
||||
cred_type = CredentialType.defaults['scm']()
|
||||
cred = Credential(credential_type=cred_type)
|
||||
inv = Inventory(insights_credential=cred)
|
||||
|
||||
with pytest.raises(ValidationError) as e:
|
||||
inv.clean_insights_credential()
|
||||
|
||||
assert json.dumps(str(e.value)) == json.dumps(str([u"Credential kind must be 'insights'."]))
|
||||
|
||||
|
||||
def test_valid_kind_clean_insights_credential():
|
||||
inv = Inventory(kind='smart')
|
||||
|
||||
inv.clean_insights_credential()
|
||||
|
||||
|
||||
def test_invalid_kind_clean_insights_credential():
|
||||
cred_type = CredentialType.defaults['insights']()
|
||||
insights_cred = Credential(credential_type=cred_type)
|
||||
inv = Inventory(kind='smart', insights_credential=insights_cred)
|
||||
|
||||
with pytest.raises(ValidationError) as e:
|
||||
inv.clean_insights_credential()
|
||||
|
||||
assert json.dumps(str(e.value)) == json.dumps(str([u'Assignment not allowed for Smart Inventory']))
|
||||
|
||||
|
||||
class TestControlledBySCM():
|
||||
def test_clean_source_path_valid(self):
|
||||
inv_src = InventorySource(source_path='/not_real/',
|
||||
source='scm')
|
||||
|
||||
inv_src.clean_source_path()
|
||||
|
||||
@pytest.mark.parametrize('source', [
|
||||
'ec2',
|
||||
'manual',
|
||||
])
|
||||
def test_clean_source_path_invalid(self, source):
|
||||
inv_src = InventorySource(source_path='/not_real/',
|
||||
source=source)
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
inv_src.clean_source_path()
|
||||
|
||||
def test_clean_update_on_launch_update_on_project_update(self):
|
||||
inv_src = InventorySource(update_on_project_update=True,
|
||||
update_on_launch=True,
|
||||
source='scm')
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
inv_src.clean_update_on_launch()
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import pytest
|
||||
|
||||
# AWX
|
||||
from awx.main.models.jobs import JobTemplate
|
||||
|
||||
from unittest import mock
|
||||
|
||||
|
||||
def test_missing_project_error(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'missing-project-jt',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
persisted=False)
|
||||
obj = objects.job_template
|
||||
assert 'project' in obj.resources_needed_to_start
|
||||
assert 'project' in obj.validation_errors
|
||||
|
||||
|
||||
def test_inventory_need_to_start(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'job-template-few-resources',
|
||||
project='project1',
|
||||
persisted=False)
|
||||
obj = objects.job_template
|
||||
assert 'inventory' in obj.resources_needed_to_start
|
||||
|
||||
|
||||
def test_inventory_contradictions(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'job-template-paradox',
|
||||
project='project1',
|
||||
persisted=False)
|
||||
obj = objects.job_template
|
||||
obj.ask_inventory_on_launch = False
|
||||
assert 'inventory' in obj.validation_errors
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
def test_job_template_survey_password_redaction(job_template_with_survey_passwords_unit):
|
||||
"""Tests the JobTemplate model's funciton to redact passwords from
|
||||
extra_vars - used when creating a new job"""
|
||||
assert job_template_with_survey_passwords_unit.survey_password_variables() == ['secret_key', 'SSN']
|
||||
|
||||
|
||||
def test_job_template_survey_mixin(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'survey_mixin_test',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
credential='cred1',
|
||||
persisted=False,
|
||||
)
|
||||
obj = objects.job_template
|
||||
obj.survey_enabled = True
|
||||
obj.survey_spec = {'spec': [{'default':'my_default', 'type':'password', 'variable':'my_variable'}]}
|
||||
kwargs = obj._update_unified_job_kwargs({}, {'extra_vars': {'my_variable':'$encrypted$'}})
|
||||
assert kwargs['extra_vars'] == '{"my_variable": "my_default"}'
|
||||
|
||||
|
||||
def test_job_template_survey_mixin_length(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'survey_mixin_test',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
credential='cred1',
|
||||
persisted=False,
|
||||
)
|
||||
obj = objects.job_template
|
||||
obj.survey_enabled = True
|
||||
obj.survey_spec = {'spec': [{'default':'my_default', 'type':'password', 'variable':'my_variable'},
|
||||
{'type':'password', 'variable':'my_other_variable'}]}
|
||||
kwargs = obj._update_unified_job_kwargs({}, {'extra_vars': {'my_variable':'$encrypted$'}})
|
||||
assert kwargs['extra_vars'] == '{"my_variable": "my_default"}'
|
||||
|
||||
|
||||
def test_job_template_survey_mixin_survey_runtime_has_highest_priority(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'survey_mixin_test',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
credential='cred1',
|
||||
persisted=False,
|
||||
)
|
||||
obj = objects.job_template
|
||||
obj.survey_enabled = True
|
||||
obj.survey_spec = {'spec': [{'default':'foo', 'type':'password', 'variable':'my_variable'}]}
|
||||
kwargs = obj._update_unified_job_kwargs({}, {'extra_vars': {'my_variable': 'bar'}})
|
||||
assert kwargs['extra_vars'] == '{"my_variable": "bar"}'
|
||||
|
||||
|
||||
def test_job_template_can_start_with_callback_extra_vars_provided(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'callback_extra_vars_test',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
credential='cred1',
|
||||
persisted=False,
|
||||
)
|
||||
obj = objects.job_template
|
||||
obj.ask_variables_on_launch = True
|
||||
with mock.patch.object(obj.__class__, 'passwords_needed_to_start', []):
|
||||
assert obj.can_start_without_user_input(callback_extra_vars='{"foo": "bar"}') is True
|
||||
|
||||
|
||||
def test_ask_mapping_integrity():
|
||||
assert 'credentials' in JobTemplate.get_ask_mapping()
|
||||
assert JobTemplate.get_ask_mapping()['job_tags'] == 'ask_tags_on_launch'
|
||||
@@ -0,0 +1,151 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from awx.main.models import (
|
||||
Job,
|
||||
Inventory,
|
||||
Host,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hosts(inventory):
|
||||
return [
|
||||
Host(name='host1', ansible_facts={"a": 1, "b": 2}, inventory=inventory),
|
||||
Host(name='host2', ansible_facts={"a": 1, "b": 2}, inventory=inventory),
|
||||
Host(name='host3', ansible_facts={"a": 1, "b": 2}, inventory=inventory),
|
||||
Host(name=u'Iñtërnâtiônàlizætiøn', ansible_facts={"a": 1, "b": 2}, inventory=inventory),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def inventory():
|
||||
return Inventory(id=5)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job(mocker, hosts, inventory):
|
||||
j = Job(inventory=inventory, id=2)
|
||||
j._get_inventory_hosts = mocker.Mock(return_value=hosts)
|
||||
return j
|
||||
|
||||
|
||||
def test_start_job_fact_cache(hosts, job, inventory, tmpdir):
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
modified_times = {}
|
||||
job.start_job_fact_cache(fact_cache, modified_times, 0)
|
||||
|
||||
for host in hosts:
|
||||
filepath = os.path.join(fact_cache, host.name)
|
||||
assert os.path.exists(filepath)
|
||||
with open(filepath, 'r') as f:
|
||||
assert f.read() == json.dumps(host.ansible_facts)
|
||||
assert filepath in modified_times
|
||||
|
||||
|
||||
def test_fact_cache_with_invalid_path_traversal(job, inventory, tmpdir, mocker):
|
||||
job._get_inventory_hosts = mocker.Mock(return_value=[
|
||||
Host(name='../foo', ansible_facts={"a": 1, "b": 2},),
|
||||
])
|
||||
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
job.start_job_fact_cache(fact_cache, {}, 0)
|
||||
# a file called "foo" should _not_ be written outside the facts dir
|
||||
assert os.listdir(os.path.join(fact_cache, '..')) == ['facts']
|
||||
|
||||
|
||||
def test_finish_job_fact_cache_with_existing_data(job, hosts, inventory, mocker, tmpdir):
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
modified_times = {}
|
||||
job.start_job_fact_cache(fact_cache, modified_times, 0)
|
||||
|
||||
for h in hosts:
|
||||
h.save = mocker.Mock()
|
||||
|
||||
ansible_facts_new = {"foo": "bar", "insights": {"system_id": "updated_by_scan"}}
|
||||
filepath = os.path.join(fact_cache, hosts[1].name)
|
||||
with open(filepath, 'w') as f:
|
||||
f.write(json.dumps(ansible_facts_new))
|
||||
f.flush()
|
||||
# I feel kind of gross about calling `os.utime` by hand, but I noticed
|
||||
# that in our container-based dev environment, the resolution for
|
||||
# `os.stat()` after a file write was over a second, and I don't want to put
|
||||
# a sleep() in this test
|
||||
new_modification_time = time.time() + 3600
|
||||
os.utime(filepath, (new_modification_time, new_modification_time))
|
||||
|
||||
job.finish_job_fact_cache(fact_cache, modified_times)
|
||||
|
||||
for host in (hosts[0], hosts[2], hosts[3]):
|
||||
host.save.assert_not_called()
|
||||
assert host.ansible_facts == {"a": 1, "b": 2}
|
||||
assert host.ansible_facts_modified is None
|
||||
assert hosts[1].ansible_facts == ansible_facts_new
|
||||
assert hosts[1].insights_system_id == "updated_by_scan"
|
||||
hosts[1].save.assert_called_once_with()
|
||||
|
||||
|
||||
def test_finish_job_fact_cache_with_malformed_fact(job, hosts, inventory, mocker, tmpdir):
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
modified_times = {}
|
||||
job.start_job_fact_cache(fact_cache, modified_times, 0)
|
||||
|
||||
for h in hosts:
|
||||
h.save = mocker.Mock()
|
||||
|
||||
for h in hosts:
|
||||
filepath = os.path.join(fact_cache, h.name)
|
||||
with open(filepath, 'w') as f:
|
||||
json.dump({'ansible_local': {'insights': 'this is an unexpected error from ansible'}}, f)
|
||||
new_modification_time = time.time() + 3600
|
||||
os.utime(filepath, (new_modification_time, new_modification_time))
|
||||
|
||||
job.finish_job_fact_cache(fact_cache, modified_times)
|
||||
|
||||
for h in hosts:
|
||||
assert h.insights_system_id is None
|
||||
|
||||
|
||||
def test_finish_job_fact_cache_with_bad_data(job, hosts, inventory, mocker, tmpdir):
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
modified_times = {}
|
||||
job.start_job_fact_cache(fact_cache, modified_times, 0)
|
||||
|
||||
for h in hosts:
|
||||
h.save = mocker.Mock()
|
||||
|
||||
for h in hosts:
|
||||
filepath = os.path.join(fact_cache, h.name)
|
||||
with open(filepath, 'w') as f:
|
||||
f.write('not valid json!')
|
||||
f.flush()
|
||||
new_modification_time = time.time() + 3600
|
||||
os.utime(filepath, (new_modification_time, new_modification_time))
|
||||
|
||||
job.finish_job_fact_cache(fact_cache, modified_times)
|
||||
|
||||
for h in hosts:
|
||||
h.save.assert_not_called()
|
||||
|
||||
|
||||
def test_finish_job_fact_cache_clear(job, hosts, inventory, mocker, tmpdir):
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
modified_times = {}
|
||||
job.start_job_fact_cache(fact_cache, modified_times, 0)
|
||||
|
||||
for h in hosts:
|
||||
h.save = mocker.Mock()
|
||||
|
||||
os.remove(os.path.join(fact_cache, hosts[1].name))
|
||||
job.finish_job_fact_cache(fact_cache, modified_times)
|
||||
|
||||
for host in (hosts[0], hosts[2], hosts[3]):
|
||||
host.save.assert_not_called()
|
||||
assert host.ansible_facts == {"a": 1, "b": 2}
|
||||
assert host.ansible_facts_modified is None
|
||||
assert hosts[1].ansible_facts == {}
|
||||
hosts[1].save.assert_called_once_with()
|
||||
@@ -0,0 +1,65 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
from awx.main.models.label import Label
|
||||
from awx.main.models.unified_jobs import UnifiedJobTemplate, UnifiedJob
|
||||
|
||||
|
||||
mock_query_set = mock.MagicMock()
|
||||
|
||||
mock_objects = mock.MagicMock(filter=mock.MagicMock(return_value=mock_query_set))
|
||||
|
||||
|
||||
@mock.patch('awx.main.models.label.Label.objects', mock_objects)
|
||||
class TestLabelFilterMocked:
|
||||
def test_get_orphaned_labels(self, mocker):
|
||||
ret = Label.get_orphaned_labels()
|
||||
|
||||
assert mock_query_set == ret
|
||||
Label.objects.filter.assert_called_with(organization=None, unifiedjobtemplate_labels__isnull=True)
|
||||
|
||||
def test_is_detached(self, mocker):
|
||||
mock_query_set.count.return_value = 1
|
||||
|
||||
label = Label(id=37)
|
||||
ret = label.is_detached()
|
||||
|
||||
assert ret is True
|
||||
Label.objects.filter.assert_called_with(id=37, unifiedjob_labels__isnull=True, unifiedjobtemplate_labels__isnull=True)
|
||||
mock_query_set.count.assert_called_with()
|
||||
|
||||
def test_is_detached_not(self, mocker):
|
||||
mock_query_set.count.return_value = 0
|
||||
|
||||
label = Label(id=37)
|
||||
ret = label.is_detached()
|
||||
|
||||
assert ret is False
|
||||
Label.objects.filter.assert_called_with(id=37, unifiedjob_labels__isnull=True, unifiedjobtemplate_labels__isnull=True)
|
||||
mock_query_set.count.assert_called_with()
|
||||
|
||||
@pytest.mark.parametrize("jt_count,j_count,expected", [
|
||||
(1, 0, True),
|
||||
(0, 1, True),
|
||||
(1, 1, False),
|
||||
])
|
||||
def test_is_candidate_for_detach(self, mocker, jt_count, j_count, expected):
|
||||
mock_job_qs = mocker.MagicMock()
|
||||
mock_job_qs.count = mocker.MagicMock(return_value=j_count)
|
||||
mocker.patch.object(UnifiedJob, 'objects', mocker.MagicMock(
|
||||
filter=mocker.MagicMock(return_value=mock_job_qs)))
|
||||
|
||||
mock_jt_qs = mocker.MagicMock()
|
||||
mock_jt_qs.count = mocker.MagicMock(return_value=jt_count)
|
||||
mocker.patch.object(UnifiedJobTemplate, 'objects', mocker.MagicMock(
|
||||
filter=mocker.MagicMock(return_value=mock_jt_qs)))
|
||||
|
||||
label = Label(id=37)
|
||||
ret = label.is_candidate_for_detach()
|
||||
|
||||
UnifiedJob.objects.filter.assert_called_with(labels__in=[label.id])
|
||||
UnifiedJobTemplate.objects.filter.assert_called_with(labels__in=[label.id])
|
||||
mock_job_qs.count.assert_called_with()
|
||||
mock_jt_qs.count.assert_called_with()
|
||||
|
||||
assert ret is expected
|
||||
@@ -0,0 +1,15 @@
|
||||
import pytest
|
||||
import json
|
||||
from awx.main.models import (
|
||||
Project,
|
||||
)
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
|
||||
def test_clean_credential_insights():
|
||||
proj = Project(name="myproj", credential=None, scm_type='insights')
|
||||
with pytest.raises(ValidationError) as e:
|
||||
proj.clean_credential()
|
||||
|
||||
assert json.dumps(str(e.value)) == json.dumps(str([u'Insights Credential is required for an Insights Project.']))
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
import pytest
|
||||
from itertools import count
|
||||
|
||||
from awx.main.utils.encryption import encrypt_value
|
||||
from awx.main.models import (
|
||||
Job,
|
||||
JobTemplate,
|
||||
JobLaunchConfig,
|
||||
WorkflowJobTemplate,
|
||||
Project,
|
||||
Inventory
|
||||
)
|
||||
|
||||
ENCRYPTED_SECRET = encrypt_value('secret')
|
||||
|
||||
|
||||
class DistinctParametrize(object):
|
||||
|
||||
def __init__(self):
|
||||
self._gen = count(0)
|
||||
|
||||
def __call__(self, value):
|
||||
return str(next(self._gen))
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
class SurveyVariableValidation:
|
||||
|
||||
def test_survey_answers_as_string(self, job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'job-template-with-survey',
|
||||
survey=[{'variable': 'var1', 'type': 'text'}],
|
||||
persisted=False)
|
||||
jt = objects.job_template
|
||||
user_extra_vars = json.dumps({'var1': 'asdf'})
|
||||
accepted, ignored, errors = jt._accept_or_ignore_job_kwargs(extra_vars=user_extra_vars)
|
||||
assert ignored.get('extra_vars', {}) == {}, [str(element) for element in errors]
|
||||
assert 'var1' in accepted['extra_vars']
|
||||
|
||||
def test_job_template_survey_variable_validation(self, job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'survey_variable_validation',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
credential='cred1',
|
||||
persisted=False,
|
||||
)
|
||||
obj = objects.job_template
|
||||
obj.survey_spec = {
|
||||
"description": "",
|
||||
"spec": [
|
||||
{
|
||||
"required": True,
|
||||
"min": 0,
|
||||
"default": "5",
|
||||
"max": 1024,
|
||||
"question_description": "",
|
||||
"choices": "",
|
||||
"variable": "a",
|
||||
"question_name": "Whosyourdaddy",
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"name": ""
|
||||
}
|
||||
obj.survey_enabled = True
|
||||
accepted, rejected, errors = obj.accept_or_ignore_variables({"a": 5})
|
||||
assert rejected == {"a": 5}
|
||||
assert accepted == {}
|
||||
assert str(errors[0]) == "Value 5 for 'a' expected to be a string."
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job(mocker):
|
||||
ret = mocker.MagicMock(**{
|
||||
'decrypted_extra_vars.return_value': '{\"secret_key\": \"my_password\"}',
|
||||
'display_extra_vars.return_value': '{\"secret_key\": \"$encrypted$\"}',
|
||||
'extra_vars_dict': {"secret_key": "my_password"},
|
||||
'pk': 1, 'job_template.pk': 1, 'job_template.name': '',
|
||||
'created_by.pk': 1, 'created_by.username': 'admin',
|
||||
'launch_type': 'manual',
|
||||
'verbosity': 1,
|
||||
'awx_meta_vars.return_value': {},
|
||||
'ansible_virtualenv_path': '',
|
||||
'inventory.get_script_data.return_value': {}})
|
||||
ret.project = mocker.MagicMock(scm_revision='asdf1234')
|
||||
return ret
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_with_survey():
|
||||
return Job(
|
||||
name="test-job-with-passwords",
|
||||
extra_vars=json.dumps({
|
||||
'submitter_email': 'foobar@redhat.com',
|
||||
'secret_key': '6kQngg3h8lgiSTvIEb21',
|
||||
'SSN': '123-45-6789'}),
|
||||
survey_passwords={
|
||||
'secret_key': '$encrypted$',
|
||||
'SSN': '$encrypted$'})
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
def test_job_survey_password_redaction(job_with_survey):
|
||||
"""Tests the Job model's funciton to redact passwords from
|
||||
extra_vars - used when displaying job information"""
|
||||
assert json.loads(job_with_survey.display_extra_vars()) == {
|
||||
'submitter_email': 'foobar@redhat.com',
|
||||
'secret_key': '$encrypted$',
|
||||
'SSN': '$encrypted$'}
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
def test_survey_passwords_not_in_extra_vars():
|
||||
"""Tests that survey passwords not included in extra_vars are
|
||||
not included when displaying job information"""
|
||||
job = Job(
|
||||
name="test-survey-not-in",
|
||||
extra_vars=json.dumps({
|
||||
'submitter_email': 'foobar@redhat.com'}),
|
||||
survey_passwords={
|
||||
'secret_key': '$encrypted$',
|
||||
'SSN': '$encrypted$'})
|
||||
assert json.loads(job.display_extra_vars()) == {
|
||||
'submitter_email': 'foobar@redhat.com',
|
||||
}
|
||||
|
||||
|
||||
def test_launch_config_has_unprompted_vars(survey_spec_factory):
|
||||
jt = JobTemplate(
|
||||
survey_enabled = True,
|
||||
survey_spec = survey_spec_factory(['question1', 'question2'])
|
||||
)
|
||||
unprompted_config = JobLaunchConfig(
|
||||
extra_data = {
|
||||
'question1': 'foobar',
|
||||
'question4': 'foobar'
|
||||
}
|
||||
)
|
||||
assert unprompted_config.has_unprompted(jt)
|
||||
allowed_config = JobLaunchConfig(
|
||||
extra_data = {
|
||||
'question1': 'foobar',
|
||||
'question2': 'foobar'
|
||||
}
|
||||
)
|
||||
assert not allowed_config.has_unprompted(jt)
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
def test_update_kwargs_survey_invalid_default(survey_spec_factory):
|
||||
spec = survey_spec_factory('var2')
|
||||
spec['spec'][0]['required'] = False
|
||||
spec['spec'][0]['min'] = 3
|
||||
spec['spec'][0]['default'] = 1
|
||||
jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True, extra_vars="var2: 2")
|
||||
defaulted_extra_vars = jt._update_unified_job_kwargs({}, {})
|
||||
assert 'extra_vars' in defaulted_extra_vars
|
||||
# Make sure we did not set the invalid default of 1
|
||||
assert json.loads(defaulted_extra_vars['extra_vars'])['var2'] == 2
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
def test_display_survey_spec_encrypts_default(survey_spec_factory):
|
||||
spec = survey_spec_factory('var2')
|
||||
spec['spec'][0]['type'] = 'password'
|
||||
spec['spec'][0]['default'] = 'some-default'
|
||||
jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True)
|
||||
assert jt.display_survey_spec()['spec'][0]['default'] == '$encrypted$'
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
@pytest.mark.parametrize("question_type,default,min,max,expect_use,expect_value", [
|
||||
("text", "", 0, 0, True, ''), # default used
|
||||
("text", "", 1, 0, False, 'N/A'), # value less than min length
|
||||
("password", "", 1, 0, False, 'N/A'), # passwords behave the same as text
|
||||
("multiplechoice", "", 0, 0, False, 'N/A'), # historical bug
|
||||
("multiplechoice", "zeb", 0, 0, False, 'N/A'), # zeb not in choices
|
||||
("multiplechoice", "coffee", 0, 0, True, 'coffee'),
|
||||
("multiselect", None, 0, 0, False, 'N/A'), # NOTE: Behavior is arguable, value of [] may be prefered
|
||||
("multiselect", "", 0, 0, False, 'N/A'),
|
||||
("multiselect", ["zeb"], 0, 0, False, 'N/A'),
|
||||
("multiselect", ["milk"], 0, 0, True, ["milk"]),
|
||||
("multiselect", ["orange\nmilk"], 0, 0, False, 'N/A'), # historical bug
|
||||
])
|
||||
def test_optional_survey_question_defaults(
|
||||
survey_spec_factory, question_type, default, min, max, expect_use, expect_value):
|
||||
spec = survey_spec_factory([
|
||||
{
|
||||
"required": False,
|
||||
"default": default,
|
||||
"choices": "orange\nmilk\nchocolate\ncoffee",
|
||||
"variable": "c",
|
||||
"min": min,
|
||||
"max": max,
|
||||
"type": question_type
|
||||
},
|
||||
])
|
||||
jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True)
|
||||
defaulted_extra_vars = jt._update_unified_job_kwargs({}, {})
|
||||
element = spec['spec'][0]
|
||||
if expect_use:
|
||||
assert jt._survey_element_validation(element, {element['variable']: element['default']}) == []
|
||||
else:
|
||||
assert jt._survey_element_validation(element, {element['variable']: element['default']})
|
||||
if expect_use:
|
||||
assert json.loads(defaulted_extra_vars['extra_vars'])['c'] == expect_value
|
||||
else:
|
||||
assert 'c' not in defaulted_extra_vars['extra_vars']
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
@pytest.mark.parametrize("question_type,default,maxlen,kwargs,expected", [
|
||||
('text', None, 5, {}, {}),
|
||||
('text', '', 5, {}, {'x': ''}),
|
||||
('text', 'y', 5, {}, {'x': 'y'}),
|
||||
('text', 'too-long', 5, {}, {}),
|
||||
('password', None, 5, {}, {}),
|
||||
('password', '', 5, {}, {'x': ''}),
|
||||
('password', ENCRYPTED_SECRET, 5, {}, {}), # len(secret) == 6, invalid
|
||||
('password', ENCRYPTED_SECRET, 10, {}, {'x': ENCRYPTED_SECRET}), # len(secret) < 10, valid
|
||||
('password', None, 5, {'extra_vars': {'x': '$encrypted$'}}, {}),
|
||||
('password', '', 5, {'extra_vars': {'x': '$encrypted$'}}, {'x': ''}),
|
||||
('password', None, 5, {'extra_vars': {'x': 'y'}}, {'x': 'y'}),
|
||||
('password', '', 5, {'extra_vars': {'x': 'y'}}, {'x': 'y'}),
|
||||
('password', 'foo', 5, {'extra_vars': {'x': 'y'}}, {'x': 'y'}),
|
||||
('password', None, 5, {'extra_vars': {'x': ''}}, {'x': ''}),
|
||||
('password', '', 5, {'extra_vars': {'x': ''}}, {'x': ''}),
|
||||
('password', 'foo', 5, {'extra_vars': {'x': ''}}, {'x': ''}),
|
||||
('password', ENCRYPTED_SECRET, 5, {'extra_vars': {'x': '$encrypted$'}}, {}),
|
||||
('password', ENCRYPTED_SECRET, 10, {'extra_vars': {'x': '$encrypted$'}}, {'x': ENCRYPTED_SECRET}),
|
||||
], ids=DistinctParametrize())
|
||||
def test_survey_encryption_defaults(survey_spec_factory, question_type, default, maxlen, kwargs, expected):
|
||||
spec = survey_spec_factory([
|
||||
{
|
||||
"required": True,
|
||||
"variable": "x",
|
||||
"min": 0,
|
||||
"max": maxlen,
|
||||
"type": question_type
|
||||
},
|
||||
])
|
||||
if default is not None:
|
||||
spec['spec'][0]['default'] = default
|
||||
else:
|
||||
spec['spec'][0].pop('default', None)
|
||||
jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True)
|
||||
extra_vars = json.loads(jt._update_unified_job_kwargs({}, kwargs).get('extra_vars'))
|
||||
assert extra_vars == expected
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
class TestWorkflowSurveys:
|
||||
def test_update_kwargs_survey_defaults(self, survey_spec_factory):
|
||||
"Assure that the survey default over-rides a JT variable"
|
||||
spec = survey_spec_factory('var1')
|
||||
spec['spec'][0]['default'] = 3
|
||||
spec['spec'][0]['required'] = False
|
||||
wfjt = WorkflowJobTemplate(
|
||||
name="test-wfjt",
|
||||
survey_spec=spec,
|
||||
survey_enabled=True,
|
||||
extra_vars="var1: 5"
|
||||
)
|
||||
updated_extra_vars = wfjt._update_unified_job_kwargs({}, {})
|
||||
assert 'extra_vars' in updated_extra_vars
|
||||
assert json.loads(updated_extra_vars['extra_vars'])['var1'] == 3
|
||||
assert wfjt.can_start_without_user_input()
|
||||
|
||||
def test_variables_needed_to_start(self, survey_spec_factory):
|
||||
"Assure that variables_needed_to_start output contains mandatory vars"
|
||||
spec = survey_spec_factory(['question1', 'question2', 'question3'])
|
||||
spec['spec'][0]['required'] = False
|
||||
spec['spec'][1]['required'] = True
|
||||
spec['spec'][2]['required'] = False
|
||||
wfjt = WorkflowJobTemplate(
|
||||
name="test-wfjt",
|
||||
survey_spec=spec,
|
||||
survey_enabled=True,
|
||||
extra_vars="question2: hiworld"
|
||||
)
|
||||
assert wfjt.variables_needed_to_start == ['question2']
|
||||
assert not wfjt.can_start_without_user_input()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize('provided_vars,valid', [
|
||||
({'tmpl_var': 'bar'}, True), # same as template, not counted as prompts
|
||||
({'tmpl_var': 'bar2'}, False), # different value from template, not okay
|
||||
({'tmpl_var': 'bar', 'a': 2}, False), # extra key, not okay
|
||||
({'tmpl_var': 'bar', False: 2}, False), # Falsy key
|
||||
({'tmpl_var': 'bar', u'🐉': u'🐉'}, False), # dragons
|
||||
])
|
||||
class TestExtraVarsNoPrompt:
|
||||
def process_vars_and_assert(self, tmpl, provided_vars, valid):
|
||||
prompted_fields, ignored_fields, errors = tmpl._accept_or_ignore_job_kwargs(
|
||||
extra_vars=provided_vars
|
||||
)
|
||||
if valid:
|
||||
assert not ignored_fields
|
||||
assert not errors
|
||||
else:
|
||||
assert ignored_fields
|
||||
assert errors
|
||||
|
||||
def test_jt_extra_vars_counting(self, provided_vars, valid):
|
||||
jt = JobTemplate(
|
||||
name='foo',
|
||||
extra_vars={'tmpl_var': 'bar'},
|
||||
project=Project(),
|
||||
project_id=42,
|
||||
playbook='helloworld.yml',
|
||||
inventory=Inventory(),
|
||||
inventory_id=42
|
||||
)
|
||||
prompted_fields, ignored_fields, errors = jt._accept_or_ignore_job_kwargs(
|
||||
extra_vars=provided_vars
|
||||
)
|
||||
self.process_vars_and_assert(jt, provided_vars, valid)
|
||||
|
||||
def test_wfjt_extra_vars_counting(self, provided_vars, valid):
|
||||
wfjt = WorkflowJobTemplate(
|
||||
name='foo',
|
||||
extra_vars={'tmpl_var': 'bar'}
|
||||
)
|
||||
prompted_fields, ignored_fields, errors = wfjt._accept_or_ignore_job_kwargs(
|
||||
extra_vars=provided_vars
|
||||
)
|
||||
self.process_vars_and_assert(wfjt, provided_vars, valid)
|
||||
@@ -0,0 +1,69 @@
|
||||
import pytest
|
||||
|
||||
from awx.main.models import SystemJobTemplate
|
||||
|
||||
|
||||
@pytest.mark.parametrize("extra_data", [
|
||||
'{ "days": 1 }',
|
||||
'{ "days": 100 }',
|
||||
'{ "days": 0 }',
|
||||
{"days": 0},
|
||||
{"days": 1},
|
||||
{"days": 13435},
|
||||
])
|
||||
def test_valid__clean_extra_data_system_jobs(extra_data):
|
||||
accepted, rejected, errors = SystemJobTemplate(
|
||||
job_type='cleanup_jobs'
|
||||
).accept_or_ignore_variables(extra_data)
|
||||
assert not rejected
|
||||
assert not errors
|
||||
|
||||
|
||||
@pytest.mark.parametrize("extra_data", [
|
||||
'{ "days": 1.2 }',
|
||||
'{ "days": -1.2 }',
|
||||
'{ "days": -111 }',
|
||||
'{ "days": "-111" }',
|
||||
'{ "days": false }',
|
||||
'{ "days": "foobar" }',
|
||||
{"days": 1.2},
|
||||
{"days": -1.2},
|
||||
{"days": -111},
|
||||
{"days": "-111"},
|
||||
{"days": False},
|
||||
{"days": "foobar"},
|
||||
])
|
||||
def test_invalid__extra_data_system_jobs(extra_data):
|
||||
accepted, rejected, errors = SystemJobTemplate(
|
||||
job_type='cleanup_jobs'
|
||||
).accept_or_ignore_variables(extra_data)
|
||||
assert str(errors['extra_vars'][0]) == u'days must be a positive integer.'
|
||||
|
||||
|
||||
def test_unallowed_system_job_data():
|
||||
sjt = SystemJobTemplate(job_type='cleanup_jobs')
|
||||
accepted, ignored, errors = sjt.accept_or_ignore_variables({
|
||||
'days': 34,
|
||||
'foobar': 'baz'
|
||||
})
|
||||
assert 'foobar' in ignored
|
||||
assert 'days' in accepted
|
||||
|
||||
|
||||
def test_reject_other_prommpts():
|
||||
sjt = SystemJobTemplate()
|
||||
accepted, ignored, errors = sjt._accept_or_ignore_job_kwargs(limit="")
|
||||
assert accepted == {}
|
||||
assert 'not allowed on launch' in errors['limit'][0]
|
||||
|
||||
|
||||
def test_reject_some_accept_some():
|
||||
sjt = SystemJobTemplate(job_type='cleanup_jobs')
|
||||
accepted, ignored, errors = sjt._accept_or_ignore_job_kwargs(limit="", extra_vars={
|
||||
'days': 34,
|
||||
'foobar': 'baz'
|
||||
})
|
||||
assert accepted == {"extra_vars": {"days": 34}}
|
||||
assert ignored == {"limit": "", "extra_vars": {"foobar": "baz"}}
|
||||
assert 'not allowed on launch' in errors['limit'][0]
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
from awx.main.models import (
|
||||
UnifiedJob,
|
||||
UnifiedJobTemplate,
|
||||
WorkflowJob,
|
||||
WorkflowJobNode,
|
||||
WorkflowApprovalTemplate,
|
||||
Job,
|
||||
User,
|
||||
Project,
|
||||
JobTemplate,
|
||||
Inventory
|
||||
)
|
||||
|
||||
|
||||
def test_incorrectly_formatted_variables():
|
||||
bad_data = '{"bar":"foo'
|
||||
accepted, ignored, errors = UnifiedJobTemplate().accept_or_ignore_variables(bad_data)
|
||||
assert not accepted
|
||||
assert ignored == bad_data
|
||||
assert 'Cannot parse as JSON' in str(errors['extra_vars'][0])
|
||||
|
||||
|
||||
def test_unified_job_workflow_attributes():
|
||||
with mock.patch('django.db.ConnectionRouter.db_for_write'):
|
||||
job = UnifiedJob(id=1, name="job-1", launch_type="workflow")
|
||||
job.unified_job_node = WorkflowJobNode(workflow_job=WorkflowJob(pk=1))
|
||||
|
||||
assert job.spawned_by_workflow is True
|
||||
assert job.workflow_job_id == 1
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def unified_job(mocker):
|
||||
mocker.patch.object(UnifiedJob, 'can_cancel', return_value=True)
|
||||
j = UnifiedJob()
|
||||
j.status = 'pending'
|
||||
j.cancel_flag = None
|
||||
j.save = mocker.MagicMock()
|
||||
j.websocket_emit_status = mocker.MagicMock()
|
||||
return j
|
||||
|
||||
|
||||
def test_cancel(unified_job):
|
||||
|
||||
unified_job.cancel()
|
||||
|
||||
assert unified_job.cancel_flag is True
|
||||
assert unified_job.status == 'canceled'
|
||||
assert unified_job.job_explanation == ''
|
||||
# Note: the websocket emit status check is just reflecting the state of the current code.
|
||||
# Some more thought may want to go into only emitting canceled if/when the job record
|
||||
# status is changed to canceled. Unlike, currently, where it's emitted unconditionally.
|
||||
unified_job.websocket_emit_status.assert_called_with("canceled")
|
||||
unified_job.save.assert_called_with(update_fields=['cancel_flag', 'start_args', 'status'])
|
||||
|
||||
|
||||
def test_cancel_job_explanation(unified_job):
|
||||
job_explanation = 'giggity giggity'
|
||||
|
||||
unified_job.cancel(job_explanation=job_explanation)
|
||||
|
||||
assert unified_job.job_explanation == job_explanation
|
||||
unified_job.save.assert_called_with(update_fields=['cancel_flag', 'start_args', 'status', 'job_explanation'])
|
||||
|
||||
|
||||
def test_organization_copy_to_jobs():
|
||||
'''
|
||||
All unified job types should infer their organization from their template organization
|
||||
'''
|
||||
for cls in UnifiedJobTemplate.__subclasses__():
|
||||
if cls is WorkflowApprovalTemplate:
|
||||
continue # these do not track organization
|
||||
assert 'organization' in cls._get_unified_job_field_names(), cls
|
||||
|
||||
|
||||
def test_log_representation():
|
||||
'''
|
||||
Common representation used inside of log messages
|
||||
'''
|
||||
uj = UnifiedJob(status='running', id=4)
|
||||
job = Job(status='running', id=4)
|
||||
assert job.log_format == 'job 4 (running)'
|
||||
assert uj.log_format == 'unified_job 4 (running)'
|
||||
|
||||
|
||||
class TestMetaVars:
|
||||
'''
|
||||
Corresponding functional test exists for cases with indirect relationships
|
||||
'''
|
||||
|
||||
def test_job_metavars(self):
|
||||
maker = User(username='joe', pk=47, id=47)
|
||||
inv = Inventory(name='example-inv', id=45)
|
||||
assert Job(
|
||||
name='fake-job',
|
||||
pk=42, id=42,
|
||||
launch_type='manual',
|
||||
created_by=maker,
|
||||
inventory=inv
|
||||
).awx_meta_vars() == {
|
||||
'tower_job_id': 42,
|
||||
'awx_job_id': 42,
|
||||
'tower_job_launch_type': 'manual',
|
||||
'awx_job_launch_type': 'manual',
|
||||
'awx_user_name': 'joe',
|
||||
'tower_user_name': 'joe',
|
||||
'awx_user_email': '',
|
||||
'tower_user_email': '',
|
||||
'awx_user_first_name': '',
|
||||
'tower_user_first_name': '',
|
||||
'awx_user_last_name': '',
|
||||
'tower_user_last_name': '',
|
||||
'awx_user_id': 47,
|
||||
'tower_user_id': 47,
|
||||
'tower_inventory_id': 45,
|
||||
'awx_inventory_id': 45,
|
||||
'tower_inventory_name': 'example-inv',
|
||||
'awx_inventory_name': 'example-inv'
|
||||
}
|
||||
|
||||
def test_project_update_metavars(self):
|
||||
data = Job(
|
||||
name='fake-job',
|
||||
pk=40, id=40,
|
||||
launch_type='manual',
|
||||
project=Project(
|
||||
name='jobs-sync',
|
||||
scm_revision='12345444'
|
||||
),
|
||||
job_template=JobTemplate(
|
||||
name='jobs-jt',
|
||||
id=92, pk=92
|
||||
)
|
||||
).awx_meta_vars()
|
||||
assert data['awx_project_revision'] == '12345444'
|
||||
assert 'tower_job_template_id' in data
|
||||
assert data['tower_job_template_id'] == 92
|
||||
assert data['tower_job_template_name'] == 'jobs-jt'
|
||||
@@ -0,0 +1,251 @@
|
||||
import pytest
|
||||
|
||||
from awx.main.models.jobs import JobTemplate
|
||||
from awx.main.models import Inventory, CredentialType, Credential, Project
|
||||
from awx.main.models.workflow import (
|
||||
WorkflowJobTemplate, WorkflowJobTemplateNode,
|
||||
WorkflowJob, WorkflowJobNode
|
||||
)
|
||||
from unittest import mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def credential():
|
||||
ssh_type = CredentialType.defaults['ssh']()
|
||||
return Credential(
|
||||
id=43,
|
||||
name='example-cred',
|
||||
credential_type=ssh_type,
|
||||
inputs={'username': 'asdf', 'password': 'asdf'}
|
||||
)
|
||||
|
||||
|
||||
class TestWorkflowJobInheritNodesMixin():
|
||||
class TestCreateWorkflowJobNodes():
|
||||
@pytest.fixture
|
||||
def job_templates(self):
|
||||
return [JobTemplate() for i in range(0, 10)]
|
||||
|
||||
@pytest.fixture
|
||||
def job_template_nodes(self, job_templates):
|
||||
return [WorkflowJobTemplateNode(unified_job_template=job_templates[i]) for i in range(0, 10)]
|
||||
|
||||
def test__create_workflow_job_nodes(self, mocker, job_template_nodes):
|
||||
workflow_job_node_create = mocker.patch('awx.main.models.WorkflowJobTemplateNode.create_workflow_job_node')
|
||||
|
||||
workflow_job = WorkflowJob()
|
||||
workflow_job._create_workflow_nodes(job_template_nodes)
|
||||
|
||||
for job_template_node in job_template_nodes:
|
||||
workflow_job_node_create.assert_any_call(workflow_job=workflow_job)
|
||||
|
||||
class TestMapWorkflowJobNodes():
|
||||
@pytest.fixture
|
||||
def job_template_nodes(self):
|
||||
return [WorkflowJobTemplateNode(id=i) for i in range(0, 20)]
|
||||
|
||||
@pytest.fixture
|
||||
def job_nodes(self):
|
||||
return [WorkflowJobNode(id=i) for i in range(100, 120)]
|
||||
|
||||
def test__map_workflow_job_nodes(self, job_template_nodes, job_nodes, mocker):
|
||||
mixin = WorkflowJob()
|
||||
wj_node = WorkflowJobNode()
|
||||
mocker.patch('awx.main.models.workflow.WorkflowJobTemplateNode.create_workflow_job_node',
|
||||
return_value=wj_node)
|
||||
|
||||
node_ids_map = mixin._create_workflow_nodes(job_template_nodes, user=None)
|
||||
assert len(node_ids_map) == len(job_template_nodes)
|
||||
|
||||
for i, job_template_node in enumerate(job_template_nodes):
|
||||
assert node_ids_map[job_template_node.id] == wj_node
|
||||
|
||||
class TestInheritRelationship():
|
||||
@pytest.fixture
|
||||
def job_template_nodes(self, mocker):
|
||||
nodes = [mocker.MagicMock(id=i, pk=i) for i in range(0, 10)]
|
||||
|
||||
for i in range(0, 9):
|
||||
nodes[i].success_nodes = mocker.MagicMock(
|
||||
all=mocker.MagicMock(return_value=[mocker.MagicMock(id=i + 1, pk=i + 1)]))
|
||||
nodes[i].always_nodes = mocker.MagicMock(all=mocker.MagicMock(return_value=[]))
|
||||
nodes[i].failure_nodes = mocker.MagicMock(all=mocker.MagicMock(return_value=[]))
|
||||
new_wj_node = mocker.MagicMock(success_nodes=mocker.MagicMock())
|
||||
nodes[i].create_workflow_job_node = mocker.MagicMock(return_value=new_wj_node)
|
||||
|
||||
return nodes
|
||||
|
||||
@pytest.fixture
|
||||
def job_nodes(self, mocker):
|
||||
nodes = [mocker.MagicMock(id=i) for i in range(100, 110)]
|
||||
return nodes
|
||||
|
||||
@pytest.fixture
|
||||
def job_nodes_dict(self, job_nodes):
|
||||
_map = {}
|
||||
for n in job_nodes:
|
||||
_map[n.id] = n
|
||||
return _map
|
||||
|
||||
|
||||
def test__inherit_relationship(self, mocker, job_template_nodes, job_nodes, job_nodes_dict):
|
||||
wj = WorkflowJob()
|
||||
|
||||
node_ids_map = wj._create_workflow_nodes(job_template_nodes)
|
||||
wj._inherit_node_relationships(job_template_nodes, node_ids_map)
|
||||
|
||||
for i in range(0, 8):
|
||||
node_ids_map[i].success_nodes.add.assert_any_call(node_ids_map[i + 1])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_job_unit():
|
||||
return WorkflowJob(name='workflow', status='new')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_job_template_unit():
|
||||
return WorkflowJobTemplate(name='workflow')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def jt_ask(job_template_factory):
|
||||
# note: factory sets ask_xxxx_on_launch to true for inventory & credential
|
||||
jt = job_template_factory(name='example-jt', persisted=False).job_template
|
||||
jt.ask_variables_on_launch = True
|
||||
jt.ask_job_type_on_launch = True
|
||||
jt.ask_skip_tags_on_launch = True
|
||||
jt.ask_limit_on_launch = True
|
||||
jt.ask_tags_on_launch = True
|
||||
jt.ask_verbosity_on_launch = True
|
||||
return jt
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project_unit():
|
||||
return Project(name='example-proj')
|
||||
|
||||
|
||||
example_prompts = dict(job_type='check', job_tags='quack', limit='duck', skip_tags='oink')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_node_no_prompts(workflow_job_unit, jt_ask):
|
||||
return WorkflowJobNode(workflow_job=workflow_job_unit, unified_job_template=jt_ask)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_node_with_prompts(job_node_no_prompts, mocker):
|
||||
job_node_no_prompts.char_prompts = example_prompts
|
||||
job_node_no_prompts.inventory = Inventory(name='example-inv', id=45)
|
||||
job_node_no_prompts.inventory_id = 45
|
||||
return job_node_no_prompts
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def wfjt_node_no_prompts(workflow_job_template_unit, jt_ask):
|
||||
node = WorkflowJobTemplateNode(
|
||||
workflow_job_template=workflow_job_template_unit,
|
||||
unified_job_template=jt_ask
|
||||
)
|
||||
return node
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def wfjt_node_with_prompts(wfjt_node_no_prompts, mocker):
|
||||
wfjt_node_no_prompts.char_prompts = example_prompts
|
||||
wfjt_node_no_prompts.inventory = Inventory(name='example-inv')
|
||||
return wfjt_node_no_prompts
|
||||
|
||||
|
||||
def test_node_getter_and_setters():
|
||||
node = WorkflowJobTemplateNode()
|
||||
node.job_type = 'check'
|
||||
assert node.char_prompts['job_type'] == 'check'
|
||||
assert node.job_type == 'check'
|
||||
|
||||
|
||||
class TestWorkflowJobCreate:
|
||||
def test_create_no_prompts(self, wfjt_node_no_prompts, workflow_job_unit, mocker):
|
||||
mock_create = mocker.MagicMock()
|
||||
with mocker.patch('awx.main.models.WorkflowJobNode.objects.create', mock_create):
|
||||
wfjt_node_no_prompts.create_workflow_job_node(workflow_job=workflow_job_unit)
|
||||
mock_create.assert_called_once_with(
|
||||
all_parents_must_converge=False,
|
||||
extra_data={},
|
||||
survey_passwords={},
|
||||
char_prompts=wfjt_node_no_prompts.char_prompts,
|
||||
inventory=None,
|
||||
unified_job_template=wfjt_node_no_prompts.unified_job_template,
|
||||
workflow_job=workflow_job_unit,
|
||||
identifier=mocker.ANY)
|
||||
|
||||
def test_create_with_prompts(self, wfjt_node_with_prompts, workflow_job_unit, credential, mocker):
|
||||
mock_create = mocker.MagicMock()
|
||||
with mocker.patch('awx.main.models.WorkflowJobNode.objects.create', mock_create):
|
||||
wfjt_node_with_prompts.create_workflow_job_node(
|
||||
workflow_job=workflow_job_unit
|
||||
)
|
||||
mock_create.assert_called_once_with(
|
||||
all_parents_must_converge=False,
|
||||
extra_data={},
|
||||
survey_passwords={},
|
||||
char_prompts=wfjt_node_with_prompts.char_prompts,
|
||||
inventory=wfjt_node_with_prompts.inventory,
|
||||
unified_job_template=wfjt_node_with_prompts.unified_job_template,
|
||||
workflow_job=workflow_job_unit,
|
||||
identifier=mocker.ANY)
|
||||
|
||||
|
||||
@mock.patch('awx.main.models.workflow.WorkflowNodeBase.get_parent_nodes', lambda self: [])
|
||||
class TestWorkflowJobNodeJobKWARGS:
|
||||
"""
|
||||
Tests for building the keyword arguments that go into creating and
|
||||
launching a new job that corresponds to a workflow node.
|
||||
"""
|
||||
kwargs_base = {'_eager_fields': {'launch_type': 'workflow'}}
|
||||
|
||||
def test_null_kwargs(self, job_node_no_prompts):
|
||||
assert job_node_no_prompts.get_job_kwargs() == self.kwargs_base
|
||||
|
||||
def test_inherit_workflow_job_and_node_extra_vars(self, job_node_no_prompts):
|
||||
job_node_no_prompts.extra_data = {"b": 98}
|
||||
workflow_job = job_node_no_prompts.workflow_job
|
||||
workflow_job.extra_vars = '{"a": 84}'
|
||||
assert job_node_no_prompts.get_job_kwargs() == dict(
|
||||
extra_vars={'a': 84, 'b': 98}, **self.kwargs_base)
|
||||
|
||||
def test_char_prompts_and_res_node_prompts(self, job_node_with_prompts):
|
||||
# TBD: properly handle multicred credential assignment
|
||||
expect_kwargs = dict(
|
||||
inventory=job_node_with_prompts.inventory,
|
||||
**example_prompts)
|
||||
expect_kwargs.update(self.kwargs_base)
|
||||
assert job_node_with_prompts.get_job_kwargs() == expect_kwargs
|
||||
|
||||
def test_reject_some_node_prompts(self, job_node_with_prompts):
|
||||
# TBD: properly handle multicred credential assignment
|
||||
job_node_with_prompts.unified_job_template.ask_inventory_on_launch = False
|
||||
job_node_with_prompts.unified_job_template.ask_job_type_on_launch = False
|
||||
expect_kwargs = dict(inventory=job_node_with_prompts.inventory,
|
||||
**example_prompts)
|
||||
expect_kwargs.update(self.kwargs_base)
|
||||
expect_kwargs.pop('inventory')
|
||||
expect_kwargs.pop('job_type')
|
||||
assert job_node_with_prompts.get_job_kwargs() == expect_kwargs
|
||||
|
||||
def test_no_accepted_project_node_prompts(self, job_node_no_prompts, project_unit):
|
||||
job_node_no_prompts.unified_job_template = project_unit
|
||||
assert job_node_no_prompts.get_job_kwargs() == self.kwargs_base
|
||||
|
||||
def test_extra_vars_node_prompts(self, wfjt_node_no_prompts):
|
||||
wfjt_node_no_prompts.extra_vars = {'foo': 'bar'}
|
||||
assert wfjt_node_no_prompts.prompts_dict() == {'extra_vars': {'foo': 'bar'}}
|
||||
|
||||
def test_string_extra_vars_node_prompts(self, wfjt_node_no_prompts):
|
||||
wfjt_node_no_prompts.extra_vars = '{"foo": "bar"}'
|
||||
assert wfjt_node_no_prompts.prompts_dict() == {'extra_vars': {'foo': 'bar'}}
|
||||
|
||||
|
||||
def test_get_ask_mapping_integrity():
|
||||
assert list(WorkflowJobTemplate.get_ask_mapping().keys()) == ['extra_vars', 'inventory', 'limit', 'scm_branch']
|
||||
Reference in New Issue
Block a user