Initial commit
This commit is contained in:
@@ -0,0 +1,311 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
import json
|
||||
|
||||
# AWX models
|
||||
from awx.main.models import (
|
||||
ActivityStream,
|
||||
Organization,
|
||||
JobTemplate,
|
||||
Credential,
|
||||
CredentialType,
|
||||
Inventory,
|
||||
InventorySource,
|
||||
Project,
|
||||
User
|
||||
)
|
||||
|
||||
# other AWX
|
||||
from awx.main.utils import model_to_dict, model_instance_diff
|
||||
from awx.main.utils.common import get_allowed_fields
|
||||
from awx.main.signals import model_serializer_mapping
|
||||
|
||||
# Django
|
||||
from django.contrib.auth.models import AnonymousUser
|
||||
|
||||
# Django-CRUM
|
||||
from crum import impersonate
|
||||
|
||||
|
||||
class TestImplicitRolesOmitted:
|
||||
'''
|
||||
Test that there is exactly 1 "create" entry in the activity stream for
|
||||
common items in the system.
|
||||
These tests will fail if `rbac_activity_stream` creates
|
||||
false-positive entries.
|
||||
'''
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_activity_stream_create_organization(self):
|
||||
Organization.objects.create(name='test-organization2')
|
||||
qs = ActivityStream.objects.filter(organization__isnull=False)
|
||||
assert qs.count() == 1
|
||||
assert qs[0].operation == 'create'
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_activity_stream_delete_organization(self):
|
||||
org = Organization.objects.create(name='gYSlNSOFEW')
|
||||
org.delete()
|
||||
qs = ActivityStream.objects.filter(changes__icontains='gYSlNSOFEW')
|
||||
assert qs.count() == 2
|
||||
assert qs[1].operation == 'delete'
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_activity_stream_create_JT(self, project, inventory):
|
||||
JobTemplate.objects.create(
|
||||
name='test-jt',
|
||||
project=project,
|
||||
inventory=inventory,
|
||||
)
|
||||
qs = ActivityStream.objects.filter(job_template__isnull=False)
|
||||
assert qs.count() == 1
|
||||
assert qs[0].operation == 'create'
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_activity_stream_create_inventory(self, organization):
|
||||
organization.inventories.create(name='test-inv')
|
||||
qs = ActivityStream.objects.filter(inventory__isnull=False)
|
||||
assert qs.count() == 1
|
||||
assert qs[0].operation == 'create'
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_activity_stream_create_credential(self, organization):
|
||||
organization.inventories.create(name='test-inv')
|
||||
qs = ActivityStream.objects.filter(inventory__isnull=False)
|
||||
assert qs.count() == 1
|
||||
assert qs[0].operation == 'create'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestRolesAssociationEntries:
|
||||
'''
|
||||
Test that non-implicit role associations have a corresponding
|
||||
activity stream entry.
|
||||
These tests will fail if `rbac_activity_stream` skipping logic
|
||||
in signals is wrong.
|
||||
'''
|
||||
|
||||
def test_non_implicit_associations_are_recorded(self, project):
|
||||
org2 = Organization.objects.create(name='test-organization2')
|
||||
# check that duplicate adds do not get recorded in 2nd loop
|
||||
for i in range(2):
|
||||
# Not supported, should not be possible via API
|
||||
# org2.admin_role.children.add(project.admin_role)
|
||||
project.admin_role.parents.add(org2.admin_role)
|
||||
assert ActivityStream.objects.filter(
|
||||
role=org2.admin_role,
|
||||
organization=org2,
|
||||
project=project
|
||||
).count() == 1, 'In loop %s' % i
|
||||
|
||||
def test_model_associations_are_recorded(self, organization):
|
||||
proj1 = Project.objects.create(name='proj1', organization=organization)
|
||||
proj2 = Project.objects.create(name='proj2', organization=organization)
|
||||
proj2.use_role.parents.add(proj1.admin_role)
|
||||
assert ActivityStream.objects.filter(role=proj1.admin_role, project=proj2).count() == 1
|
||||
|
||||
@pytest.mark.parametrize('value', [True, False])
|
||||
def test_auditor_is_recorded(self, post, value):
|
||||
u = User.objects.create(username='foouser')
|
||||
assert not u.is_system_auditor
|
||||
u.is_system_auditor = value
|
||||
u = User.objects.get(pk=u.pk) # refresh from db
|
||||
assert u.is_system_auditor == value
|
||||
entry_qs = ActivityStream.objects.filter(user=u)
|
||||
if value:
|
||||
assert len(entry_qs) == 2
|
||||
else:
|
||||
assert len(entry_qs) == 1
|
||||
# unfortunate, the original creation does _not_ set a real is_auditor field
|
||||
assert 'is_system_auditor' not in json.loads(entry_qs[0].changes)
|
||||
if value:
|
||||
auditor_changes = json.loads(entry_qs[1].changes)
|
||||
assert auditor_changes['object2'] == 'user'
|
||||
assert auditor_changes['object2_pk'] == u.pk
|
||||
|
||||
def test_user_no_op_api(self, system_auditor):
|
||||
as_ct = ActivityStream.objects.count()
|
||||
system_auditor.is_system_auditor = True # already auditor
|
||||
assert ActivityStream.objects.count() == as_ct
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def somecloud_type():
|
||||
return CredentialType.objects.create(
|
||||
kind='cloud',
|
||||
name='SomeCloud',
|
||||
managed_by_tower=False,
|
||||
inputs={
|
||||
'fields': [{
|
||||
'id': 'api_token',
|
||||
'label': 'API Token',
|
||||
'type': 'string',
|
||||
'secret': True
|
||||
}]
|
||||
},
|
||||
injectors={
|
||||
'env': {
|
||||
'MY_CLOUD_API_TOKEN': '{{api_token.foo()}}'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestCredentialModels:
|
||||
'''
|
||||
Assure that core elements of activity stream feature are working
|
||||
'''
|
||||
|
||||
def test_create_credential_type(self, somecloud_type):
|
||||
assert ActivityStream.objects.filter(credential_type=somecloud_type).count() == 1
|
||||
entry = ActivityStream.objects.filter(credential_type=somecloud_type)[0]
|
||||
assert entry.operation == 'create'
|
||||
|
||||
def test_credential_hidden_information(self, somecloud_type):
|
||||
cred = Credential.objects.create(
|
||||
credential_type=somecloud_type,
|
||||
inputs = {'api_token': 'ABC123'}
|
||||
)
|
||||
entry = ActivityStream.objects.filter(credential=cred)[0]
|
||||
assert entry.operation == 'create'
|
||||
assert json.loads(entry.changes)['inputs'] == 'hidden'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestUserModels:
|
||||
|
||||
def test_user_hidden_information(self, alice):
|
||||
entry = ActivityStream.objects.filter(user=alice)[0]
|
||||
assert entry.operation == 'create'
|
||||
assert json.loads(entry.changes)['password'] == 'hidden'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_missing_related_on_delete(inventory_source):
|
||||
old_is = InventorySource.objects.get(name=inventory_source.name)
|
||||
inventory_source.inventory.delete()
|
||||
d = model_to_dict(old_is, serializer_mapping=model_serializer_mapping())
|
||||
assert d['inventory'] == '<missing inventory source>-{}'.format(old_is.inventory_id)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_activity_stream_actor(admin_user):
|
||||
with impersonate(admin_user):
|
||||
o = Organization.objects.create(name='test organization')
|
||||
entry = o.activitystream_set.get(operation='create')
|
||||
assert entry.actor == admin_user
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_annon_user_action():
|
||||
with mock.patch('awx.main.signals.get_current_user') as u_mock:
|
||||
u_mock.return_value = AnonymousUser()
|
||||
inv = Inventory.objects.create(name='ainventory')
|
||||
entry = inv.activitystream_set.filter(operation='create').first()
|
||||
assert not entry.actor
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_activity_stream_deleted_actor(alice, bob):
|
||||
alice.first_name = 'Alice'
|
||||
alice.last_name = 'Doe'
|
||||
alice.save()
|
||||
with impersonate(alice):
|
||||
o = Organization.objects.create(name='test organization')
|
||||
entry = o.activitystream_set.get(operation='create')
|
||||
assert entry.actor == alice
|
||||
|
||||
alice.delete()
|
||||
entry = o.activitystream_set.get(operation='create')
|
||||
assert entry.actor is None
|
||||
deleted = entry.deleted_actor
|
||||
assert deleted['username'] == 'alice'
|
||||
assert deleted['first_name'] == 'Alice'
|
||||
assert deleted['last_name'] == 'Doe'
|
||||
|
||||
entry.actor = bob
|
||||
entry.save(update_fields=['actor'])
|
||||
deleted = entry.deleted_actor
|
||||
|
||||
entry = ActivityStream.objects.get(id=entry.pk)
|
||||
assert entry.deleted_actor['username'] == 'bob'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_modified_not_allowed_field(somecloud_type):
|
||||
'''
|
||||
If this test fails, that means that read-only fields are showing
|
||||
up in the activity stream serialization of an instance.
|
||||
|
||||
That _probably_ means that you just connected a new model to the
|
||||
activity_stream_registrar, but did not add its serializer to
|
||||
the model->serializer mapping.
|
||||
'''
|
||||
from awx.main.registrar import activity_stream_registrar
|
||||
|
||||
for Model in activity_stream_registrar.models:
|
||||
assert 'modified' not in get_allowed_fields(Model(), model_serializer_mapping()), Model
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_survey_spec_create_entry(job_template, survey_spec_factory):
|
||||
start_count = job_template.activitystream_set.count()
|
||||
job_template.survey_spec = survey_spec_factory('foo')
|
||||
job_template.save()
|
||||
assert job_template.activitystream_set.count() == start_count + 1
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_survey_create_diff(job_template, survey_spec_factory):
|
||||
old = JobTemplate.objects.get(pk=job_template.pk)
|
||||
job_template.survey_spec = survey_spec_factory('foo')
|
||||
before, after = model_instance_diff(old, job_template, model_serializer_mapping())['survey_spec']
|
||||
assert before == '{}'
|
||||
assert json.loads(after) == survey_spec_factory('foo')
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_saved_passwords_hidden_activity(workflow_job_template, job_template_with_survey_passwords):
|
||||
node_with_passwords = workflow_job_template.workflow_nodes.create(
|
||||
unified_job_template=job_template_with_survey_passwords,
|
||||
extra_data={'bbbb': '$encrypted$fooooo'},
|
||||
survey_passwords={'bbbb': '$encrypted$'}
|
||||
)
|
||||
node_with_passwords.delete()
|
||||
entry = ActivityStream.objects.order_by('timestamp').last()
|
||||
changes = json.loads(entry.changes)
|
||||
assert 'survey_passwords' not in changes
|
||||
assert json.loads(changes['extra_data'])['bbbb'] == '$encrypted$'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_cluster_node_recorded(inventory, project):
|
||||
jt = JobTemplate.objects.create(name='testjt', inventory=inventory, project=project)
|
||||
with mock.patch('awx.main.models.activity_stream.settings.CLUSTER_HOST_ID', 'foo_host'):
|
||||
job = jt.create_unified_job()
|
||||
entry = ActivityStream.objects.filter(job=job).first()
|
||||
assert entry.action_node == 'foo_host'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_cluster_node_long_node_name(inventory, project):
|
||||
jt = JobTemplate.objects.create(name='testjt', inventory=inventory, project=project)
|
||||
with mock.patch('awx.main.models.activity_stream.settings.CLUSTER_HOST_ID', 'f' * 700):
|
||||
job = jt.create_unified_job()
|
||||
# node name is very long, we just want to make sure it does not error
|
||||
entry = ActivityStream.objects.filter(job=job).first()
|
||||
assert entry.action_node.startswith('ffffff')
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_credential_defaults_idempotency():
|
||||
CredentialType.setup_tower_managed_defaults()
|
||||
old_inputs = CredentialType.objects.get(name='Ansible Tower', kind='cloud').inputs
|
||||
prior_count = ActivityStream.objects.count()
|
||||
# this is commonly re-ran in migrations, and no changes should be shown
|
||||
# because inputs and injectors are not actually tracked in the database
|
||||
CredentialType.setup_tower_managed_defaults()
|
||||
assert CredentialType.objects.get(name='Ansible Tower', kind='cloud').inputs == old_inputs
|
||||
assert ActivityStream.objects.count() == prior_count
|
||||
@@ -0,0 +1,49 @@
|
||||
import pytest
|
||||
|
||||
# AWX context managers for testing
|
||||
from awx.main.models.rbac import batch_role_ancestor_rebuilding
|
||||
from awx.main.signals import (
|
||||
disable_activity_stream,
|
||||
disable_computed_fields,
|
||||
update_inventory_computed_fields
|
||||
)
|
||||
|
||||
# AWX models
|
||||
from awx.main.models.organization import Organization
|
||||
from awx.main.models import ActivityStream, Job
|
||||
from awx.main.tests.functional import immediate_on_commit
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_rbac_batch_rebuilding(rando, organization):
|
||||
with batch_role_ancestor_rebuilding():
|
||||
organization.admin_role.members.add(rando)
|
||||
inventory = organization.inventories.create(name='test-inventory')
|
||||
assert rando not in inventory.admin_role
|
||||
assert rando in inventory.admin_role
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_disable_activity_stream():
|
||||
with disable_activity_stream():
|
||||
Organization.objects.create(name='test-organization')
|
||||
assert ActivityStream.objects.filter(organization__isnull=False).count() == 0
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestComputedFields:
|
||||
|
||||
def test_computed_fields_normal_use(self, mocker, inventory):
|
||||
job = Job.objects.create(name='fake-job', inventory=inventory)
|
||||
with immediate_on_commit():
|
||||
with mocker.patch.object(update_inventory_computed_fields, 'delay'):
|
||||
job.delete()
|
||||
update_inventory_computed_fields.delay.assert_called_once_with(inventory.id)
|
||||
|
||||
def test_disable_computed_fields(self, mocker, inventory):
|
||||
job = Job.objects.create(name='fake-job', inventory=inventory)
|
||||
with disable_computed_fields():
|
||||
with mocker.patch.object(update_inventory_computed_fields, 'delay'):
|
||||
job.delete()
|
||||
update_inventory_computed_fields.delay.assert_not_called()
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
from unittest import mock
|
||||
import pytest
|
||||
|
||||
from django.utils.timezone import now
|
||||
|
||||
from awx.main.models import Job, JobEvent, Inventory, Host, JobHostSummary
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@mock.patch('awx.main.models.events.emit_event_detail')
|
||||
def test_parent_changed(emit):
|
||||
j = Job()
|
||||
j.save()
|
||||
JobEvent.create_from_data(job_id=j.pk, uuid='abc123', event='playbook_on_task_start').save()
|
||||
assert JobEvent.objects.count() == 1
|
||||
for e in JobEvent.objects.all():
|
||||
assert e.changed is False
|
||||
|
||||
JobEvent.create_from_data(
|
||||
job_id=j.pk,
|
||||
parent_uuid='abc123',
|
||||
event='runner_on_ok',
|
||||
event_data={
|
||||
'res': {'changed': ['localhost']}
|
||||
}
|
||||
).save()
|
||||
# the `playbook_on_stats` event is where we update the parent changed linkage
|
||||
JobEvent.create_from_data(
|
||||
job_id=j.pk,
|
||||
parent_uuid='abc123',
|
||||
event='playbook_on_stats'
|
||||
).save()
|
||||
events = JobEvent.objects.filter(event__in=['playbook_on_task_start', 'runner_on_ok'])
|
||||
assert events.count() == 2
|
||||
for e in events.all():
|
||||
assert e.changed is True
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize('event', JobEvent.FAILED_EVENTS)
|
||||
@mock.patch('awx.main.models.events.emit_event_detail')
|
||||
def test_parent_failed(emit, event):
|
||||
j = Job()
|
||||
j.save()
|
||||
JobEvent.create_from_data(job_id=j.pk, uuid='abc123', event='playbook_on_task_start').save()
|
||||
assert JobEvent.objects.count() == 1
|
||||
for e in JobEvent.objects.all():
|
||||
assert e.failed is False
|
||||
|
||||
JobEvent.create_from_data(
|
||||
job_id=j.pk,
|
||||
parent_uuid='abc123',
|
||||
event=event
|
||||
).save()
|
||||
|
||||
# the `playbook_on_stats` event is where we update the parent failed linkage
|
||||
JobEvent.create_from_data(
|
||||
job_id=j.pk,
|
||||
parent_uuid='abc123',
|
||||
event='playbook_on_stats'
|
||||
).save()
|
||||
events = JobEvent.objects.filter(event__in=['playbook_on_task_start', event])
|
||||
assert events.count() == 2
|
||||
for e in events.all():
|
||||
assert e.failed is True
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_host_summary_generation():
|
||||
hostnames = [f'Host {i}' for i in range(100)]
|
||||
inv = Inventory()
|
||||
inv.save()
|
||||
Host.objects.bulk_create([
|
||||
Host(created=now(), modified=now(), name=h, inventory_id=inv.id)
|
||||
for h in hostnames
|
||||
])
|
||||
j = Job(inventory=inv)
|
||||
j.save()
|
||||
host_map = dict((host.name, host.id) for host in inv.hosts.all())
|
||||
JobEvent.create_from_data(
|
||||
job_id=j.pk,
|
||||
parent_uuid='abc123',
|
||||
event='playbook_on_stats',
|
||||
event_data={
|
||||
'ok': dict((hostname, len(hostname)) for hostname in hostnames),
|
||||
'changed': {},
|
||||
'dark': {},
|
||||
'failures': {},
|
||||
'ignored': {},
|
||||
'processed': {},
|
||||
'rescued': {},
|
||||
'skipped': {},
|
||||
},
|
||||
host_map=host_map
|
||||
).save()
|
||||
|
||||
assert j.job_host_summaries.count() == len(hostnames)
|
||||
assert sorted([s.host_name for s in j.job_host_summaries.all()]) == sorted(hostnames)
|
||||
|
||||
for s in j.job_host_summaries.all():
|
||||
assert host_map[s.host_name] == s.host_id
|
||||
assert s.ok == len(s.host_name)
|
||||
assert s.changed == 0
|
||||
assert s.dark == 0
|
||||
assert s.failures == 0
|
||||
assert s.ignored == 0
|
||||
assert s.processed == 0
|
||||
assert s.rescued == 0
|
||||
assert s.skipped == 0
|
||||
|
||||
for host in Host.objects.all():
|
||||
assert host.last_job_id == j.id
|
||||
assert host.last_job_host_summary.host == host
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_host_summary_generation_with_deleted_hosts():
|
||||
hostnames = [f'Host {i}' for i in range(10)]
|
||||
inv = Inventory()
|
||||
inv.save()
|
||||
Host.objects.bulk_create([
|
||||
Host(created=now(), modified=now(), name=h, inventory_id=inv.id)
|
||||
for h in hostnames
|
||||
])
|
||||
j = Job(inventory=inv)
|
||||
j.save()
|
||||
host_map = dict((host.name, host.id) for host in inv.hosts.all())
|
||||
|
||||
# delete half of the hosts during the playbook run
|
||||
for h in inv.hosts.all()[:5]:
|
||||
h.delete()
|
||||
|
||||
JobEvent.create_from_data(
|
||||
job_id=j.pk,
|
||||
parent_uuid='abc123',
|
||||
event='playbook_on_stats',
|
||||
event_data={
|
||||
'ok': dict((hostname, len(hostname)) for hostname in hostnames),
|
||||
'changed': {},
|
||||
'dark': {},
|
||||
'failures': {},
|
||||
'ignored': {},
|
||||
'processed': {},
|
||||
'rescued': {},
|
||||
'skipped': {},
|
||||
},
|
||||
host_map=host_map
|
||||
).save()
|
||||
|
||||
|
||||
ids = sorted([s.host_id or -1 for s in j.job_host_summaries.order_by('id').all()])
|
||||
names = sorted([s.host_name for s in j.job_host_summaries.all()])
|
||||
assert ids == [-1, -1, -1, -1, -1, 6, 7, 8, 9, 10]
|
||||
assert names == ['Host 0', 'Host 1', 'Host 2', 'Host 3', 'Host 4', 'Host 5',
|
||||
'Host 6', 'Host 7', 'Host 8', 'Host 9']
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_host_summary_generation_with_limit():
|
||||
# Make an inventory with 10 hosts, run a playbook with a --limit
|
||||
# pointed at *one* host,
|
||||
# Verify that *only* that host has an associated JobHostSummary and that
|
||||
# *only* that host has an updated value for .last_job.
|
||||
hostnames = [f'Host {i}' for i in range(10)]
|
||||
inv = Inventory()
|
||||
inv.save()
|
||||
Host.objects.bulk_create([
|
||||
Host(created=now(), modified=now(), name=h, inventory_id=inv.id)
|
||||
for h in hostnames
|
||||
])
|
||||
j = Job(inventory=inv)
|
||||
j.save()
|
||||
|
||||
# host map is a data structure that tracks a mapping of host name --> ID
|
||||
# for the inventory, _regardless_ of whether or not there's a limit
|
||||
# applied to the actual playbook run
|
||||
host_map = dict((host.name, host.id) for host in inv.hosts.all())
|
||||
|
||||
# by making the playbook_on_stats *only* include Host 1, we're emulating
|
||||
# the behavior of a `--limit=Host 1`
|
||||
matching_host = Host.objects.get(name='Host 1')
|
||||
JobEvent.create_from_data(
|
||||
job_id=j.pk,
|
||||
parent_uuid='abc123',
|
||||
event='playbook_on_stats',
|
||||
event_data={
|
||||
'ok': {matching_host.name: len(matching_host.name)}, # effectively, limit=Host 1
|
||||
'changed': {},
|
||||
'dark': {},
|
||||
'failures': {},
|
||||
'ignored': {},
|
||||
'processed': {},
|
||||
'rescued': {},
|
||||
'skipped': {},
|
||||
},
|
||||
host_map=host_map
|
||||
).save()
|
||||
|
||||
# since the playbook_on_stats only references one host,
|
||||
# there should *only* be on JobHostSummary record (and it should
|
||||
# be related to the appropriate Host)
|
||||
assert JobHostSummary.objects.count() == 1
|
||||
for h in Host.objects.all():
|
||||
if h.name == 'Host 1':
|
||||
assert h.last_job_id == j.id
|
||||
assert h.last_job_host_summary_id == JobHostSummary.objects.first().id
|
||||
else:
|
||||
# all other hosts in the inventory should remain untouched
|
||||
assert h.last_job_id is None
|
||||
assert h.last_job_host_summary_id is None
|
||||
@@ -0,0 +1,376 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
# AWX
|
||||
from awx.main.models import (
|
||||
Host,
|
||||
Inventory,
|
||||
InventorySource,
|
||||
InventoryUpdate,
|
||||
CredentialType,
|
||||
Credential,
|
||||
Job
|
||||
)
|
||||
from awx.main.constants import CLOUD_PROVIDERS
|
||||
from awx.main.utils.filters import SmartFilter
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestInventoryScript:
|
||||
|
||||
def test_hostvars(self, inventory):
|
||||
inventory.hosts.create(name='ahost', variables={"foo": "bar"})
|
||||
assert inventory.get_script_data(
|
||||
hostvars=True
|
||||
)['_meta']['hostvars']['ahost'] == {
|
||||
'foo': 'bar'
|
||||
}
|
||||
|
||||
def test_towervars(self, inventory):
|
||||
host = inventory.hosts.create(name='ahost')
|
||||
assert inventory.get_script_data(
|
||||
hostvars=True,
|
||||
towervars=True
|
||||
)['_meta']['hostvars']['ahost'] == {
|
||||
'remote_tower_enabled': 'true',
|
||||
'remote_tower_id': host.id
|
||||
}
|
||||
|
||||
def test_all_group(self, inventory):
|
||||
inventory.groups.create(name='all', variables={'a1': 'a1'})
|
||||
# make sure we return a1 details in output
|
||||
data = inventory.get_script_data()
|
||||
assert 'all' in data
|
||||
assert data['all'] == {
|
||||
'vars': {
|
||||
'a1': 'a1'
|
||||
}
|
||||
}
|
||||
|
||||
def test_empty_group(self, inventory):
|
||||
inventory.groups.create(name='ghost')
|
||||
data = inventory.get_script_data()
|
||||
# canonical behavior same as ansible-inventory
|
||||
# group not provided top-level to avoid host / group confusion
|
||||
# still list group as a child of the all group
|
||||
assert 'ghost' not in data
|
||||
assert 'ghost' in data['all']['children']
|
||||
|
||||
def test_empty_group_with_vars(self, inventory):
|
||||
inventory.groups.create(name='ghost2', variables={'foo': 'bar'})
|
||||
data = inventory.get_script_data()
|
||||
# must be top-level key so group vars can be provided
|
||||
assert 'ghost2' in data
|
||||
assert data['ghost2']['vars'] == {'foo': 'bar'}
|
||||
assert 'ghost2' in data['all']['children']
|
||||
|
||||
def test_grandparent_group(self, inventory):
|
||||
g1 = inventory.groups.create(name='g1', variables={'v1': 'v1'})
|
||||
g2 = inventory.groups.create(name='g2', variables={'v2': 'v2'})
|
||||
h1 = inventory.hosts.create(name='h1')
|
||||
# h1 becomes indirect member of g1 group
|
||||
g1.children.add(g2)
|
||||
g2.hosts.add(h1)
|
||||
# make sure we return g1 details in output
|
||||
data = inventory.get_script_data(hostvars=1)
|
||||
assert 'g1' in data
|
||||
assert 'g2' in data
|
||||
assert data['g1'] == {
|
||||
'children': ['g2'],
|
||||
'vars': {'v1': 'v1'}
|
||||
}
|
||||
assert data['g2'] == {
|
||||
'hosts': ['h1'],
|
||||
'vars': {'v2': 'v2'}
|
||||
}
|
||||
|
||||
def test_slice_subset(self, inventory):
|
||||
for i in range(3):
|
||||
inventory.hosts.create(name='host{}'.format(i))
|
||||
for i in range(3):
|
||||
assert inventory.get_script_data(slice_number=i + 1, slice_count=3) == {
|
||||
'all': {'hosts': ['host{}'.format(i)]}
|
||||
}
|
||||
|
||||
def test_slice_subset_with_groups(self, inventory):
|
||||
hosts = []
|
||||
for i in range(3):
|
||||
host = inventory.hosts.create(name='host{}'.format(i))
|
||||
hosts.append(host)
|
||||
g1 = inventory.groups.create(name='contains_all_hosts')
|
||||
for host in hosts:
|
||||
g1.hosts.add(host)
|
||||
g2 = inventory.groups.create(name='contains_two_hosts')
|
||||
for host in hosts[:2]:
|
||||
g2.hosts.add(host)
|
||||
for i in range(3):
|
||||
expected_data = {
|
||||
'contains_all_hosts': {'hosts': ['host{}'.format(i)]},
|
||||
}
|
||||
if i < 2:
|
||||
expected_data['contains_two_hosts'] = {'hosts': ['host{}'.format(i)]}
|
||||
data = inventory.get_script_data(slice_number=i + 1, slice_count=3)
|
||||
data.pop('all')
|
||||
assert data == expected_data
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestActiveCount:
|
||||
|
||||
def test_host_active_count(self, organization):
|
||||
inv1 = Inventory.objects.create(name='inv1', organization=organization)
|
||||
inv2 = Inventory.objects.create(name='inv2', organization=organization)
|
||||
assert Host.objects.active_count() == 0
|
||||
inv1.hosts.create(name='host1')
|
||||
inv2.hosts.create(name='host1')
|
||||
assert Host.objects.active_count() == 1
|
||||
inv1.hosts.create(name='host2')
|
||||
assert Host.objects.active_count() == 2
|
||||
|
||||
def test_active_count_minus_tower(self, inventory):
|
||||
inventory.hosts.create(name='locally-managed-host')
|
||||
source = inventory.inventory_sources.create(
|
||||
name='tower-source', source='tower'
|
||||
)
|
||||
source.hosts.create(
|
||||
name='remotely-managed-host', inventory=inventory
|
||||
)
|
||||
assert Host.objects.active_count() == 1
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestSCMUpdateFeatures:
|
||||
|
||||
def test_automatic_project_update_on_create(self, inventory, project):
|
||||
inv_src = InventorySource(
|
||||
source_project=project,
|
||||
source_path='inventory_file',
|
||||
inventory=inventory,
|
||||
update_on_project_update=True,
|
||||
source='scm')
|
||||
with mock.patch.object(inv_src, 'update') as mck_update:
|
||||
inv_src.save()
|
||||
mck_update.assert_called_once_with()
|
||||
|
||||
def test_reset_scm_revision(self, scm_inventory_source):
|
||||
starting_rev = scm_inventory_source.scm_last_revision
|
||||
assert starting_rev != ''
|
||||
scm_inventory_source.source_path = '/newfolder/newfile.ini'
|
||||
scm_inventory_source.save()
|
||||
assert scm_inventory_source.scm_last_revision == ''
|
||||
|
||||
def test_source_location(self, scm_inventory_source):
|
||||
# Combines project directory with the inventory file specified
|
||||
inventory_update = InventoryUpdate(
|
||||
inventory_source=scm_inventory_source,
|
||||
source_path=scm_inventory_source.source_path)
|
||||
p = scm_inventory_source.source_project
|
||||
assert inventory_update.get_actual_source_path().endswith(f'_{p.id}__test_proj/inventory_file')
|
||||
|
||||
def test_no_unwanted_updates(self, scm_inventory_source):
|
||||
# Changing the non-sensitive fields should not trigger update
|
||||
with mock.patch.object(scm_inventory_source.source_project, 'update') as mck_update:
|
||||
scm_inventory_source.name = 'edited_inventory'
|
||||
scm_inventory_source.description = "I'm testing this!"
|
||||
scm_inventory_source.save()
|
||||
assert not mck_update.called
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestRelatedJobs:
|
||||
|
||||
def test_inventory_related(self, inventory):
|
||||
job = Job.objects.create(
|
||||
inventory=inventory
|
||||
)
|
||||
assert job.id in [jerb.id for jerb in inventory._get_related_jobs()]
|
||||
|
||||
def test_related_group_jobs(self, group):
|
||||
job = Job.objects.create(
|
||||
inventory=group.inventory
|
||||
)
|
||||
assert job.id in [jerb.id for jerb in group._get_related_jobs()]
|
||||
|
||||
def test_related_group_update(self, group):
|
||||
src = group.inventory_sources.create(name='foo', source='ec2')
|
||||
job = InventoryUpdate.objects.create(
|
||||
inventory_source=src,
|
||||
source=src.source
|
||||
)
|
||||
assert job.id in [jerb.id for jerb in group._get_related_jobs()]
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestSCMClean:
|
||||
def test_clean_update_on_project_update_multiple(self, inventory):
|
||||
inv_src1 = InventorySource(inventory=inventory,
|
||||
update_on_project_update=True,
|
||||
source='scm')
|
||||
inv_src1.clean_update_on_project_update()
|
||||
inv_src1.save()
|
||||
|
||||
inv_src1.source_vars = '---\nhello: world'
|
||||
inv_src1.clean_update_on_project_update()
|
||||
|
||||
inv_src2 = InventorySource(inventory=inventory,
|
||||
update_on_project_update=True,
|
||||
source='scm')
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
inv_src2.clean_update_on_project_update()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestInventorySourceInjectors:
|
||||
def test_extra_credentials(self, project, credential):
|
||||
inventory_source = InventorySource.objects.create(
|
||||
name='foo', source='custom', source_project=project
|
||||
)
|
||||
inventory_source.credentials.add(credential)
|
||||
assert inventory_source.get_cloud_credential() == credential # for serializer
|
||||
assert inventory_source.get_extra_credentials() == [credential]
|
||||
|
||||
inventory_source.source = 'ec2'
|
||||
assert inventory_source.get_cloud_credential() == credential
|
||||
assert inventory_source.get_extra_credentials() == []
|
||||
|
||||
def test_all_cloud_sources_covered(self):
|
||||
"""Code in several places relies on the fact that the older
|
||||
CLOUD_PROVIDERS constant contains the same names as what are
|
||||
defined within the injectors
|
||||
"""
|
||||
assert set(CLOUD_PROVIDERS) == set(InventorySource.injectors.keys())
|
||||
|
||||
@pytest.mark.parametrize('source,filename', [
|
||||
('ec2', 'aws_ec2.yml'),
|
||||
('openstack', 'openstack.yml'),
|
||||
('gce', 'gcp_compute.yml')
|
||||
])
|
||||
def test_plugin_filenames(self, source, filename):
|
||||
"""It is important that the filenames for inventory plugin files
|
||||
are named correctly, because Ansible will reject files that do
|
||||
not have these exact names
|
||||
"""
|
||||
injector = InventorySource.injectors[source]()
|
||||
assert injector.filename == filename
|
||||
|
||||
@pytest.mark.parametrize('source,proper_name', [
|
||||
('ec2', 'amazon.aws.aws_ec2'),
|
||||
('openstack', 'openstack.cloud.openstack'),
|
||||
('gce', 'google.cloud.gcp_compute'),
|
||||
('azure_rm', 'azure.azcollection.azure_rm'),
|
||||
('vmware', 'community.vmware.vmware_vm_inventory'),
|
||||
('rhv', 'ovirt.ovirt.ovirt'),
|
||||
('satellite6', 'theforeman.foreman.foreman'),
|
||||
('tower', 'awx.awx.tower'),
|
||||
])
|
||||
def test_plugin_proper_names(self, source, proper_name):
|
||||
injector = InventorySource.injectors[source]()
|
||||
assert injector.get_proper_name() == proper_name
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_custom_source_custom_credential(organization):
|
||||
credential_type = CredentialType.objects.create(
|
||||
kind='cloud',
|
||||
name='MyCloud',
|
||||
inputs = {
|
||||
'fields': [{
|
||||
'id': 'api_token',
|
||||
'label': 'API Token',
|
||||
'type': 'string',
|
||||
'secret': True
|
||||
}]
|
||||
}
|
||||
)
|
||||
credential = Credential.objects.create(
|
||||
name='my cred', credential_type=credential_type, organization=organization,
|
||||
inputs={'api_token': 'secret'}
|
||||
)
|
||||
inv_source = InventorySource.objects.create(source='scm')
|
||||
inv_source.credentials.add(credential)
|
||||
assert inv_source.get_cloud_credential() == credential
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup_ec2_gce(organization):
|
||||
ec2_inv = Inventory.objects.create(name='test_ec2', organization=organization)
|
||||
|
||||
ec2_source = ec2_inv.inventory_sources.create(name='test_ec2_source', source='ec2')
|
||||
for i in range(2):
|
||||
ec2_host = ec2_inv.hosts.create(name='test_ec2_{0}'.format(i))
|
||||
ec2_host.inventory_sources.add(ec2_source)
|
||||
ec2_inv.save()
|
||||
|
||||
gce_inv = Inventory.objects.create(name='test_gce', organization=organization)
|
||||
|
||||
gce_source = gce_inv.inventory_sources.create(name='test_gce_source', source='gce')
|
||||
gce_host = gce_inv.hosts.create(name='test_gce_host')
|
||||
gce_host.inventory_sources.add(gce_source)
|
||||
gce_inv.save()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup_inventory_groups(inventory, group_factory):
|
||||
|
||||
groupA = group_factory('test_groupA')
|
||||
groupB = group_factory('test_groupB')
|
||||
|
||||
host = Host.objects.create(name='single_host', inventory=inventory)
|
||||
|
||||
groupA.hosts.add(host)
|
||||
groupA.save()
|
||||
|
||||
groupB.hosts.add(host)
|
||||
groupB.save()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_inventory_update_name(inventory, inventory_source):
|
||||
iu = inventory_source.update()
|
||||
assert inventory_source.name != inventory.name
|
||||
assert iu.name == inventory.name + ' - ' + inventory_source.name
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_inventory_name_with_unicode(inventory, inventory_source):
|
||||
inventory.name = 'オオオ'
|
||||
inventory.save()
|
||||
iu = inventory_source.update()
|
||||
assert iu.name.startswith(inventory.name)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_inventory_update_excessively_long_name(inventory, inventory_source):
|
||||
inventory.name = 'a' * 400 # field max length 512
|
||||
inventory_source.name = 'b' * 400
|
||||
iu = inventory_source.update()
|
||||
assert inventory_source.name != inventory.name
|
||||
assert iu.name.startswith(inventory.name)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestHostManager:
|
||||
def test_host_filter_not_smart(self, setup_ec2_gce, organization):
|
||||
smart_inventory = Inventory(name='smart',
|
||||
organization=organization,
|
||||
host_filter='inventory_sources__source=ec2')
|
||||
assert len(smart_inventory.hosts.all()) == 0
|
||||
|
||||
def test_host_distinctness(self, setup_inventory_groups, organization):
|
||||
"""
|
||||
two criteria would both yield the same host, check that we only get 1 copy here
|
||||
"""
|
||||
assert (
|
||||
list(SmartFilter.query_from_string('name=single_host or name__startswith=single_')) ==
|
||||
[Host.objects.get(name='single_host')]
|
||||
)
|
||||
|
||||
# Things we can not easily test due to SQLite backend:
|
||||
# 2 organizations with host of same name only has 1 entry in smart inventory
|
||||
# smart inventory in 1 organization does not include host from another
|
||||
# smart inventory correctly returns hosts in filter in same organization
|
||||
@@ -0,0 +1,128 @@
|
||||
import pytest
|
||||
|
||||
from awx.main.models import (
|
||||
JobTemplate, Job, JobHostSummary,
|
||||
WorkflowJob, Inventory, Project, Organization
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_awx_virtualenv_from_settings(inventory, project, machine_credential):
|
||||
jt = JobTemplate.objects.create(
|
||||
name='my-jt',
|
||||
inventory=inventory,
|
||||
project=project,
|
||||
playbook='helloworld.yml'
|
||||
)
|
||||
jt.credentials.add(machine_credential)
|
||||
job = jt.create_unified_job()
|
||||
assert job.ansible_virtualenv_path == '/var/lib/awx/venv/ansible'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_prevent_slicing():
|
||||
jt = JobTemplate.objects.create(
|
||||
name='foo',
|
||||
job_slice_count=4
|
||||
)
|
||||
job = jt.create_unified_job(_prevent_slicing=True)
|
||||
assert job.job_slice_count == 1
|
||||
assert job.job_slice_number == 0
|
||||
assert isinstance(job, Job)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_awx_custom_virtualenv(inventory, project, machine_credential, organization):
|
||||
jt = JobTemplate.objects.create(
|
||||
name='my-jt',
|
||||
inventory=inventory,
|
||||
project=project,
|
||||
playbook='helloworld.yml',
|
||||
organization=organization
|
||||
)
|
||||
jt.credentials.add(machine_credential)
|
||||
job = jt.create_unified_job()
|
||||
|
||||
job.organization.custom_virtualenv = '/var/lib/awx/venv/fancy-org'
|
||||
job.organization.save()
|
||||
assert job.ansible_virtualenv_path == '/var/lib/awx/venv/fancy-org'
|
||||
|
||||
job.project.custom_virtualenv = '/var/lib/awx/venv/fancy-proj'
|
||||
job.project.save()
|
||||
assert job.ansible_virtualenv_path == '/var/lib/awx/venv/fancy-proj'
|
||||
|
||||
job.job_template.custom_virtualenv = '/var/lib/awx/venv/fancy-jt'
|
||||
job.job_template.save()
|
||||
assert job.ansible_virtualenv_path == '/var/lib/awx/venv/fancy-jt'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_awx_custom_virtualenv_without_jt(project):
|
||||
project.custom_virtualenv = '/var/lib/awx/venv/fancy-proj'
|
||||
project.save()
|
||||
job = Job(project=project)
|
||||
job.save()
|
||||
|
||||
job = Job.objects.get(pk=job.id)
|
||||
assert job.ansible_virtualenv_path == '/var/lib/awx/venv/fancy-proj'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_job_host_summary_representation(host):
|
||||
job = Job.objects.create(name='foo')
|
||||
jhs = JobHostSummary.objects.create(
|
||||
host=host, job=job,
|
||||
changed=1, dark=2, failures=3, ignored=4, ok=5, processed=6, rescued=7, skipped=8
|
||||
)
|
||||
assert 'single-host changed=1 dark=2 failures=3 ignored=4 ok=5 processed=6 rescued=7 skipped=8' == str(jhs)
|
||||
|
||||
# Representation should be robust to deleted related items
|
||||
jhs = JobHostSummary.objects.get(pk=jhs.id)
|
||||
host.delete()
|
||||
assert 'N/A changed=1 dark=2 failures=3 ignored=4 ok=5 processed=6 rescued=7 skipped=8' == str(jhs)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_jt_organization_follows_project():
|
||||
org1 = Organization.objects.create(name='foo1')
|
||||
org2 = Organization.objects.create(name='foo2')
|
||||
project1 = Project.objects.create(name='proj1', organization=org1)
|
||||
project2 = Project.objects.create(name='proj2', organization=org2)
|
||||
jt = JobTemplate.objects.create(
|
||||
name='foo', playbook='helloworld.yml',
|
||||
project=project1
|
||||
)
|
||||
assert jt.organization == org1
|
||||
jt.project = project2
|
||||
jt.save()
|
||||
assert JobTemplate.objects.get(pk=jt.id).organization == org2
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestSlicingModels:
|
||||
|
||||
def test_slice_workflow_spawn(self, slice_jt_factory):
|
||||
slice_jt = slice_jt_factory(3)
|
||||
job = slice_jt.create_unified_job()
|
||||
assert isinstance(job, WorkflowJob)
|
||||
assert job.job_template == slice_jt
|
||||
assert job.unified_job_template == slice_jt
|
||||
assert job.workflow_nodes.count() == 3
|
||||
|
||||
def test_slices_with_JT_and_prompts(self, slice_job_factory):
|
||||
job = slice_job_factory(3, jt_kwargs={'ask_limit_on_launch': True}, prompts={'limit': 'foobar'}, spawn=True)
|
||||
assert job.launch_config.prompts_dict() == {'limit': 'foobar'}
|
||||
for node in job.workflow_nodes.all():
|
||||
assert node.limit is None # data not saved in node prompts
|
||||
job = node.job
|
||||
assert job.limit == 'foobar'
|
||||
|
||||
def test_effective_slice_count(self, job_template, inventory, organization):
|
||||
job_template.inventory = inventory
|
||||
assert job_template.inventory.hosts.count() == 0
|
||||
job_template.job_slice_count = 2
|
||||
job_template.inventory.hosts.create(name='foo1')
|
||||
assert job_template.get_effective_slice_ct({})
|
||||
inventory2 = Inventory.objects.create(organization=organization, name='fooinv')
|
||||
[inventory2.hosts.create(name='foo{}'.format(i)) for i in range(3)]
|
||||
assert job_template.get_effective_slice_ct({'inventory': inventory2})
|
||||
@@ -0,0 +1,75 @@
|
||||
import pytest
|
||||
|
||||
# AWX
|
||||
from awx.main.models import JobTemplate, JobLaunchConfig
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def full_jt(inventory, project, machine_credential):
|
||||
jt = JobTemplate.objects.create(
|
||||
name='my-jt',
|
||||
inventory=inventory,
|
||||
project=project,
|
||||
playbook='helloworld.yml'
|
||||
)
|
||||
jt.credentials.add(machine_credential)
|
||||
return jt
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def config_factory(full_jt):
|
||||
def return_config(data):
|
||||
job = full_jt.create_unified_job(**data)
|
||||
try:
|
||||
return job.launch_config
|
||||
except JobLaunchConfig.DoesNotExist:
|
||||
return None
|
||||
return return_config
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestConfigCreation:
|
||||
'''
|
||||
Checks cases for the auto-creation of a job configuration with the
|
||||
creation of a unified job
|
||||
'''
|
||||
def test_null_configuration(self, full_jt):
|
||||
job = full_jt.create_unified_job()
|
||||
assert job.launch_config.prompts_dict() == {}
|
||||
|
||||
def test_char_field_change(self, full_jt):
|
||||
job = full_jt.create_unified_job(limit='foobar')
|
||||
config = job.launch_config
|
||||
assert config.limit == 'foobar'
|
||||
assert config.char_prompts == {'limit': 'foobar'}
|
||||
|
||||
def test_added_credential(self, full_jt, credential):
|
||||
job = full_jt.create_unified_job(credentials=[credential])
|
||||
config = job.launch_config
|
||||
assert set(config.credentials.all()) == set([credential])
|
||||
|
||||
def test_survey_passwords_ignored(self, inventory_source):
|
||||
iu = inventory_source.create_unified_job(
|
||||
survey_passwords={'foo': '$encrypted$'}
|
||||
)
|
||||
assert iu.launch_config.prompts_dict() == {}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestConfigReversibility:
|
||||
'''
|
||||
Checks that a blob of saved prompts will be re-created in the
|
||||
prompts_dict for launching new jobs
|
||||
'''
|
||||
def test_char_field_only(self, config_factory):
|
||||
config = config_factory({'limit': 'foobar'})
|
||||
assert config.prompts_dict() == {'limit': 'foobar'}
|
||||
|
||||
def test_related_objects(self, config_factory, inventory, credential):
|
||||
prompts = {
|
||||
'limit': 'foobar',
|
||||
'inventory': inventory,
|
||||
'credentials': set([credential])
|
||||
}
|
||||
config = config_factory(prompts)
|
||||
assert config.prompts_dict() == prompts
|
||||
@@ -0,0 +1,33 @@
|
||||
import pytest
|
||||
|
||||
from awx.main.models import Credential
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_clean_credential_with_ssh_type(credentialtype_ssh, job_template):
|
||||
credential = Credential(
|
||||
name='My Credential',
|
||||
credential_type=credentialtype_ssh
|
||||
)
|
||||
credential.save()
|
||||
|
||||
job_template.credentials.add(credential)
|
||||
job_template.full_clean()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_clean_credential_with_custom_types(credentialtype_aws, credentialtype_net, job_template):
|
||||
aws = Credential(
|
||||
name='AWS Credential',
|
||||
credential_type=credentialtype_aws
|
||||
)
|
||||
aws.save()
|
||||
net = Credential(
|
||||
name='Net Credential',
|
||||
credential_type=credentialtype_net
|
||||
)
|
||||
net.save()
|
||||
|
||||
job_template.credentials.add(aws)
|
||||
job_template.credentials.add(net)
|
||||
job_template.full_clean()
|
||||
@@ -0,0 +1,180 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from copy import deepcopy
|
||||
import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
#from awx.main.models import NotificationTemplates, Notifications, JobNotificationMixin
|
||||
from awx.main.models import (AdHocCommand, InventoryUpdate, Job, JobNotificationMixin, ProjectUpdate,
|
||||
Schedule, SystemJob, WorkflowJob)
|
||||
from awx.api.serializers import UnifiedJobSerializer
|
||||
|
||||
|
||||
class TestJobNotificationMixin(object):
|
||||
CONTEXT_STRUCTURE = {'job': {'allow_simultaneous': bool,
|
||||
'artifacts': {},
|
||||
'custom_virtualenv': str,
|
||||
'controller_node': str,
|
||||
'created': datetime.datetime,
|
||||
'description': str,
|
||||
'diff_mode': bool,
|
||||
'elapsed': float,
|
||||
'execution_node': str,
|
||||
'failed': bool,
|
||||
'finished': bool,
|
||||
'force_handlers': bool,
|
||||
'forks': int,
|
||||
'host_status_counts': {
|
||||
'skipped': int, 'ok': int, 'changed': int,
|
||||
'failures': int, 'dark': int, 'processed': int,
|
||||
'rescued': int, 'failed': bool
|
||||
},
|
||||
'id': int,
|
||||
'job_explanation': str,
|
||||
'job_slice_count': int,
|
||||
'job_slice_number': int,
|
||||
'job_tags': str,
|
||||
'job_type': str,
|
||||
'launch_type': str,
|
||||
'limit': str,
|
||||
'modified': datetime.datetime,
|
||||
'name': str,
|
||||
'playbook': str,
|
||||
'scm_branch': str,
|
||||
'scm_revision': str,
|
||||
'skip_tags': str,
|
||||
'start_at_task': str,
|
||||
'started': str,
|
||||
'status': str,
|
||||
'summary_fields': {'created_by': {'first_name': str,
|
||||
'id': int,
|
||||
'last_name': str,
|
||||
'username': str},
|
||||
'instance_group': {'id': int, 'name': str},
|
||||
'inventory': {'description': str,
|
||||
'has_active_failures': bool,
|
||||
'has_inventory_sources': bool,
|
||||
'hosts_with_active_failures': int,
|
||||
'id': int,
|
||||
'inventory_sources_with_failures': int,
|
||||
'kind': str,
|
||||
'name': str,
|
||||
'organization_id': int,
|
||||
'total_groups': int,
|
||||
'total_hosts': int,
|
||||
'total_inventory_sources': int},
|
||||
'job_template': {'description': str,
|
||||
'id': int,
|
||||
'name': str},
|
||||
'labels': {'count': int, 'results': list},
|
||||
'project': {'description': str,
|
||||
'id': int,
|
||||
'name': str,
|
||||
'scm_type': str,
|
||||
'status': str},
|
||||
'schedule': {'description': str,
|
||||
'id': int,
|
||||
'name': str,
|
||||
'next_run': datetime.datetime},
|
||||
'unified_job_template': {'description': str,
|
||||
'id': int,
|
||||
'name': str,
|
||||
'unified_job_type': str}},
|
||||
|
||||
'timeout': int,
|
||||
'type': str,
|
||||
'url': str,
|
||||
'use_fact_cache': bool,
|
||||
'verbosity': int},
|
||||
'job_friendly_name': str,
|
||||
'job_metadata': str,
|
||||
'approval_status': str,
|
||||
'approval_node_name': str,
|
||||
'workflow_url': str,
|
||||
'url': str}
|
||||
|
||||
def check_structure(self, expected_structure, obj):
|
||||
if isinstance(expected_structure, dict):
|
||||
assert isinstance(obj, dict)
|
||||
for key in obj:
|
||||
assert key in expected_structure
|
||||
if obj[key] is None:
|
||||
continue
|
||||
if isinstance(expected_structure[key], dict):
|
||||
assert isinstance(obj[key], dict)
|
||||
self.check_structure(expected_structure[key], obj[key])
|
||||
else:
|
||||
if key == 'job_explanation':
|
||||
assert isinstance(str(obj[key]), expected_structure[key])
|
||||
else:
|
||||
assert isinstance(obj[key], expected_structure[key])
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize('JobClass', [AdHocCommand, InventoryUpdate, Job, ProjectUpdate, SystemJob, WorkflowJob])
|
||||
def test_context(self, JobClass, sqlite_copy_expert, project, inventory_source):
|
||||
"""The Jinja context defines all of the fields that can be used by a template. Ensure that the context generated
|
||||
for each job type has the expected structure."""
|
||||
kwargs = {}
|
||||
if JobClass is InventoryUpdate:
|
||||
kwargs['inventory_source'] = inventory_source
|
||||
kwargs['source'] = inventory_source.source
|
||||
elif JobClass is ProjectUpdate:
|
||||
kwargs['project'] = project
|
||||
|
||||
job = JobClass.objects.create(name='foo', **kwargs)
|
||||
job_serialization = UnifiedJobSerializer(job).to_representation(job)
|
||||
|
||||
context = job.context(job_serialization)
|
||||
self.check_structure(TestJobNotificationMixin.CONTEXT_STRUCTURE, context)
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_schedule_context(self, job_template, admin_user):
|
||||
schedule = Schedule.objects.create(
|
||||
name='job-schedule',
|
||||
rrule='DTSTART:20171129T155939z\nFREQ=MONTHLY',
|
||||
unified_job_template=job_template
|
||||
)
|
||||
job = Job.objects.create(
|
||||
name='fake-job',
|
||||
launch_type='workflow',
|
||||
schedule=schedule,
|
||||
job_template=job_template
|
||||
)
|
||||
|
||||
job_serialization = UnifiedJobSerializer(job).to_representation(job)
|
||||
|
||||
context = job.context(job_serialization)
|
||||
self.check_structure(TestJobNotificationMixin.CONTEXT_STRUCTURE, context)
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_context_job_metadata_with_unicode(self):
|
||||
job = Job.objects.create(name='批量安装项目')
|
||||
job_serialization = UnifiedJobSerializer(job).to_representation(job)
|
||||
context = job.context(job_serialization)
|
||||
assert '批量安装项目' in context['job_metadata']
|
||||
|
||||
|
||||
def test_context_stub(self):
|
||||
"""The context stub is a fake context used to validate custom notification messages. Ensure that
|
||||
this also has the expected structure. Furthermore, ensure that the stub context contains
|
||||
*all* fields that could possibly be included in a context."""
|
||||
def check_structure_and_completeness(expected_structure, obj):
|
||||
expected_structure = deepcopy(expected_structure)
|
||||
if isinstance(expected_structure, dict):
|
||||
assert isinstance(obj, dict)
|
||||
for key in obj:
|
||||
assert key in expected_structure
|
||||
# Context stub should not have any undefined fields
|
||||
assert obj[key] is not None
|
||||
if isinstance(expected_structure[key], dict):
|
||||
assert isinstance(obj[key], dict)
|
||||
check_structure_and_completeness(expected_structure[key], obj[key])
|
||||
expected_structure.pop(key)
|
||||
else:
|
||||
assert isinstance(obj[key], expected_structure[key])
|
||||
expected_structure.pop(key)
|
||||
# Ensure all items in expected structure were present
|
||||
assert not len(expected_structure)
|
||||
|
||||
context_stub = JobNotificationMixin.context_stub()
|
||||
check_structure_and_completeness(TestJobNotificationMixin.CONTEXT_STRUCTURE, context_stub)
|
||||
@@ -0,0 +1,87 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
from awx.main.models import Project, Credential, CredentialType
|
||||
from awx.main.models.organization import Organization
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_project_initial_update():
|
||||
with mock.patch.object(Project, "update") as mock_update:
|
||||
Project.objects.create(name='foo', scm_type='git')
|
||||
mock_update.assert_called_once_with()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_does_not_update_nonsensitive_change(project):
|
||||
with mock.patch.object(Project, "update") as mock_update:
|
||||
project.scm_update_on_launch = not project.scm_update_on_launch
|
||||
project.save()
|
||||
mock_update.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_sensitive_change_triggers_update(project):
|
||||
with mock.patch.object(Project, "update") as mock_update:
|
||||
project.scm_url = 'https://foo.invalid'
|
||||
project.save()
|
||||
mock_update.assert_called_once_with()
|
||||
# test other means of initialization
|
||||
project = Project.objects.get(pk=project.pk)
|
||||
with mock.patch.object(Project, "update") as mock_update:
|
||||
project.scm_url = 'https://foo2.invalid'
|
||||
project.save()
|
||||
mock_update.assert_called_once_with()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_local_path_autoset(organization):
|
||||
with mock.patch.object(Project, "update"):
|
||||
p = Project.objects.create(
|
||||
name="test-proj",
|
||||
organization=organization,
|
||||
scm_url='localhost',
|
||||
scm_type='git'
|
||||
)
|
||||
assert p.local_path == f'_{p.id}__test_proj'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_foreign_key_change_changes_modified_by(project, organization):
|
||||
assert project._get_fields_snapshot()['organization_id'] == organization.id
|
||||
project.organization = Organization(name='foo', pk=41)
|
||||
assert project._get_fields_snapshot()['organization_id'] == 41
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_project_related_jobs(project):
|
||||
update = project.create_unified_job()
|
||||
assert update.id in [u.id for u in project._get_related_jobs()]
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_galaxy_credentials(project):
|
||||
org = project.organization
|
||||
galaxy = CredentialType.defaults['galaxy_api_token']()
|
||||
galaxy.save()
|
||||
for i in range(5):
|
||||
cred = Credential.objects.create(
|
||||
name=f'Ansible Galaxy {i + 1}',
|
||||
organization=org,
|
||||
credential_type=galaxy,
|
||||
inputs={
|
||||
'url': 'https://galaxy.ansible.com/'
|
||||
}
|
||||
)
|
||||
cred.save()
|
||||
org.galaxy_credentials.add(cred)
|
||||
|
||||
assert [
|
||||
cred.name for cred in org.galaxy_credentials.all()
|
||||
] == [
|
||||
'Ansible Galaxy 1',
|
||||
'Ansible Galaxy 2',
|
||||
'Ansible Galaxy 3',
|
||||
'Ansible Galaxy 4',
|
||||
'Ansible Galaxy 5',
|
||||
]
|
||||
@@ -0,0 +1,517 @@
|
||||
from datetime import datetime, timedelta
|
||||
from contextlib import contextmanager
|
||||
|
||||
from django.utils.timezone import now
|
||||
from django.db.utils import IntegrityError
|
||||
from unittest import mock
|
||||
import pytest
|
||||
import pytz
|
||||
|
||||
from awx.main.models import JobTemplate, Schedule, ActivityStream
|
||||
|
||||
from crum import impersonate
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_template(inventory, project):
|
||||
# need related resources set for these tests
|
||||
return JobTemplate.objects.create(
|
||||
name='test-job_template',
|
||||
inventory=inventory,
|
||||
project=project
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestComputedFields:
|
||||
|
||||
# expired in 2015, so next_run should not be populated
|
||||
dead_rrule = "DTSTART;TZID=UTC:20140520T190000 RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=1;BYMONTHDAY=1;UNTIL=20150530T000000Z"
|
||||
continuing_rrule = "DTSTART;TZID=UTC:20140520T190000 RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=1;BYMONTHDAY=1"
|
||||
|
||||
@property
|
||||
def distant_rrule(self):
|
||||
# this rule should produce a next_run, but it should not overlap with test run time
|
||||
this_year = now().year
|
||||
return "DTSTART;TZID=UTC:{}0520T190000 RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=1;BYMONTHDAY=1;UNTIL={}0530T000000Z".format(
|
||||
this_year + 1, this_year + 2
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def assert_no_unwanted_stuff(self, schedule, act_stream=True, sch_assert=True):
|
||||
"""These changes are not wanted for any computed fields update
|
||||
of schedules, so we make the assertions for all of the tests here
|
||||
"""
|
||||
original_sch_modified = schedule.modified
|
||||
original_sch_modified_by = schedule.modified_by
|
||||
original_ujt_modified = schedule.unified_job_template.modified
|
||||
original_ujt_modified_by = schedule.unified_job_template.modified_by
|
||||
original_AS_entries = ActivityStream.objects.count()
|
||||
yield None
|
||||
if sch_assert:
|
||||
schedule.refresh_from_db()
|
||||
assert schedule.modified == original_sch_modified
|
||||
assert schedule.modified_by == original_sch_modified_by
|
||||
# a related schedule update should not change JT modified time
|
||||
schedule.unified_job_template.refresh_from_db()
|
||||
assert schedule.unified_job_template.modified == original_ujt_modified
|
||||
assert schedule.unified_job_template.modified_by == original_ujt_modified_by
|
||||
if act_stream:
|
||||
assert ActivityStream.objects.count() == original_AS_entries, (
|
||||
ActivityStream.objects.order_by('-timestamp').first().changes
|
||||
)
|
||||
|
||||
def test_computed_fields_modified_by_retained(self, job_template, admin_user):
|
||||
with impersonate(admin_user):
|
||||
s = Schedule.objects.create(
|
||||
name='Some Schedule',
|
||||
rrule='DTSTART:20300112T210000Z RRULE:FREQ=DAILY;INTERVAL=1',
|
||||
unified_job_template=job_template
|
||||
)
|
||||
assert s.created_by == admin_user
|
||||
with self.assert_no_unwanted_stuff(s):
|
||||
s.update_computed_fields() # modification done by system here
|
||||
s.save()
|
||||
assert s.modified_by == admin_user
|
||||
|
||||
def test_computed_fields_no_op(self, job_template):
|
||||
s = Schedule.objects.create(
|
||||
name='Some Schedule',
|
||||
rrule=self.dead_rrule,
|
||||
unified_job_template=job_template,
|
||||
enabled=True
|
||||
)
|
||||
with self.assert_no_unwanted_stuff(s):
|
||||
assert s.next_run is None
|
||||
assert s.dtend is not None
|
||||
prior_dtend = s.dtend
|
||||
s.update_computed_fields()
|
||||
assert s.next_run is None
|
||||
assert s.dtend == prior_dtend
|
||||
|
||||
def test_computed_fields_time_change(self, job_template):
|
||||
s = Schedule.objects.create(
|
||||
name='Some Schedule',
|
||||
rrule=self.continuing_rrule,
|
||||
unified_job_template=job_template,
|
||||
enabled=True
|
||||
)
|
||||
with self.assert_no_unwanted_stuff(s):
|
||||
# force update of next_run, as if schedule re-calculation had not happened
|
||||
# since this time
|
||||
old_next_run = datetime(2009, 3, 13, tzinfo=pytz.utc)
|
||||
Schedule.objects.filter(pk=s.pk).update(next_run=old_next_run)
|
||||
s.next_run = old_next_run
|
||||
prior_modified = s.modified
|
||||
with mock.patch('awx.main.models.schedules.emit_channel_notification'):
|
||||
s.update_computed_fields()
|
||||
assert s.next_run != old_next_run
|
||||
assert s.modified == prior_modified
|
||||
|
||||
def test_computed_fields_turning_on(self, job_template):
|
||||
s = Schedule.objects.create(
|
||||
name='Some Schedule',
|
||||
rrule=self.distant_rrule,
|
||||
unified_job_template=job_template,
|
||||
enabled=False
|
||||
)
|
||||
# we expect 1 activity stream entry for changing enabled field
|
||||
with self.assert_no_unwanted_stuff(s, act_stream=False):
|
||||
assert s.next_run is None
|
||||
assert job_template.next_schedule is None
|
||||
s.enabled = True
|
||||
s.save(update_fields=['enabled'])
|
||||
assert s.next_run is not None
|
||||
assert job_template.next_schedule == s
|
||||
|
||||
def test_computed_fields_turning_on_via_rrule(self, job_template):
|
||||
s = Schedule.objects.create(
|
||||
name='Some Schedule',
|
||||
rrule=self.dead_rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
with self.assert_no_unwanted_stuff(s, act_stream=False):
|
||||
assert s.next_run is None
|
||||
assert job_template.next_schedule is None
|
||||
s.rrule = self.distant_rrule
|
||||
with mock.patch('awx.main.models.schedules.emit_channel_notification'):
|
||||
s.update_computed_fields()
|
||||
assert s.next_run is not None
|
||||
assert job_template.next_schedule == s
|
||||
|
||||
def test_computed_fields_turning_off_by_deleting(self, job_template):
|
||||
s1 = Schedule.objects.create(
|
||||
name='first schedule',
|
||||
rrule=self.distant_rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s2 = Schedule.objects.create(
|
||||
name='second schedule',
|
||||
rrule=self.distant_rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
assert job_template.next_schedule in [s1, s2]
|
||||
if job_template.next_schedule == s1:
|
||||
expected_schedule = s2
|
||||
else:
|
||||
expected_schedule = s1
|
||||
with self.assert_no_unwanted_stuff(expected_schedule, act_stream=False, sch_assert=False):
|
||||
job_template.next_schedule.delete()
|
||||
job_template.refresh_from_db()
|
||||
assert job_template.next_schedule == expected_schedule
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize('freq, delta', (
|
||||
('MINUTELY', 1),
|
||||
('HOURLY', 1)
|
||||
))
|
||||
def test_past_week_rrule(job_template, freq, delta):
|
||||
# see: https://github.com/ansible/awx/issues/8071
|
||||
recent = (datetime.utcnow() - timedelta(days=3))
|
||||
recent = recent.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
recent_dt = recent.strftime('%Y%m%d')
|
||||
rrule = f'DTSTART;TZID=America/New_York:{recent_dt}T000000 RRULE:FREQ={freq};INTERVAL={delta};COUNT=5' # noqa
|
||||
sched = Schedule.objects.create(
|
||||
name='example schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
first_event = sched.rrulestr(sched.rrule)[0]
|
||||
assert first_event.replace(tzinfo=None) == recent
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize('freq, delta', (
|
||||
('MINUTELY', 1),
|
||||
('HOURLY', 1)
|
||||
))
|
||||
def test_really_old_dtstart(job_template, freq, delta):
|
||||
# see: https://github.com/ansible/awx/issues/8071
|
||||
# If an event is per-minute/per-hour and was created a *really long*
|
||||
# time ago, we should just bump forward to start counting "in the last week"
|
||||
rrule = f'DTSTART;TZID=America/New_York:20150101T000000 RRULE:FREQ={freq};INTERVAL={delta}' # noqa
|
||||
sched = Schedule.objects.create(
|
||||
name='example schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
last_week = (datetime.utcnow() - timedelta(days=7)).date()
|
||||
first_event = sched.rrulestr(sched.rrule)[0]
|
||||
assert last_week == first_event.date()
|
||||
|
||||
# the next few scheduled events should be the next minute/hour incremented
|
||||
next_five_events = list(sched.rrulestr(sched.rrule).xafter(now(), count=5))
|
||||
|
||||
assert next_five_events[0] > now()
|
||||
last = None
|
||||
for event in next_five_events:
|
||||
if last:
|
||||
assert event == last + (
|
||||
timedelta(minutes=1) if freq == 'MINUTELY' else timedelta(hours=1)
|
||||
)
|
||||
last = event
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_repeats_forever(job_template):
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule='DTSTART:20300112T210000Z RRULE:FREQ=DAILY;INTERVAL=1',
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
assert str(s.next_run) == str(s.dtstart) == '2030-01-12 21:00:00+00:00'
|
||||
assert s.dtend is None
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_no_recurrence_utc(job_template):
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule='DTSTART:20300112T210000Z RRULE:FREQ=DAILY;INTERVAL=1;COUNT=1',
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
assert str(s.next_run) == str(s.dtstart) == str(s.dtend) == '2030-01-12 21:00:00+00:00'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_no_recurrence_est(job_template):
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule='DTSTART;TZID=America/New_York:20300112T210000 RRULE:FREQ=DAILY;INTERVAL=1;COUNT=1',
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
assert str(s.next_run) == str(s.dtstart) == str(s.dtend) == '2030-01-13 02:00:00+00:00'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_next_run_utc(job_template):
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule='DTSTART:20300112T210000Z RRULE:FREQ=MONTHLY;INTERVAL=1;BYDAY=SA;BYSETPOS=1;COUNT=4',
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
assert str(s.next_run) == '2030-02-02 21:00:00+00:00'
|
||||
assert str(s.next_run) == str(s.dtstart)
|
||||
assert str(s.dtend) == '2030-05-04 21:00:00+00:00'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_next_run_est(job_template):
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule='DTSTART;TZID=America/New_York:20300112T210000 RRULE:FREQ=MONTHLY;INTERVAL=1;BYDAY=SA;BYSETPOS=1;COUNT=4',
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
|
||||
assert str(s.next_run) == '2030-02-03 02:00:00+00:00'
|
||||
assert str(s.next_run) == str(s.dtstart)
|
||||
|
||||
# March 10, 2030 is when DST takes effect in NYC
|
||||
assert str(s.dtend) == '2030-05-05 01:00:00+00:00'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_year_boundary(job_template):
|
||||
rrule = 'DTSTART;TZID=America/New_York:20301231T230000 RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=12;BYMONTHDAY=31;COUNT=4' # noqa
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
|
||||
assert str(s.next_run) == '2031-01-01 04:00:00+00:00' # UTC = +5 EST
|
||||
assert str(s.next_run) == str(s.dtstart)
|
||||
assert str(s.dtend) == '2034-01-01 04:00:00+00:00' # UTC = +5 EST
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_leap_year_day(job_template):
|
||||
rrule = 'DTSTART;TZID=America/New_York:20320229T050000 RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=02;BYMONTHDAY=29;COUNT=2' # noqa
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
|
||||
assert str(s.next_run) == '2032-02-29 10:00:00+00:00' # UTC = +5 EST
|
||||
assert str(s.next_run) == str(s.dtstart)
|
||||
assert str(s.dtend) == '2036-02-29 10:00:00+00:00' # UTC = +5 EST
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize('until, dtend', [
|
||||
['20300602T170000Z', '2030-06-02 12:00:00+00:00'],
|
||||
['20300602T000000Z', '2030-06-01 12:00:00+00:00'],
|
||||
])
|
||||
def test_utc_until(job_template, until, dtend):
|
||||
rrule = 'DTSTART:20300601T120000Z RRULE:FREQ=DAILY;INTERVAL=1;UNTIL={}'.format(until)
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
|
||||
assert str(s.next_run) == '2030-06-01 12:00:00+00:00'
|
||||
assert str(s.next_run) == str(s.dtstart)
|
||||
assert str(s.dtend) == dtend
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize('dtstart, until', [
|
||||
['DTSTART:20380601T120000Z', '20380601T170000'], # noon UTC to 5PM UTC
|
||||
['DTSTART;TZID=America/New_York:20380601T120000', '20380601T170000'], # noon EST to 5PM EST
|
||||
])
|
||||
def test_tzinfo_naive_until(job_template, dtstart, until):
|
||||
rrule = '{} RRULE:FREQ=HOURLY;INTERVAL=1;UNTIL={}'.format(dtstart, until) # noqa
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
gen = Schedule.rrulestr(s.rrule).xafter(now(), count=20)
|
||||
assert len(list(gen)) == 6 # noon, 1PM, 2, 3, 4, 5PM
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_utc_until_in_the_past(job_template):
|
||||
rrule = 'DTSTART:20180601T120000Z RRULE:FREQ=DAILY;INTERVAL=1;UNTIL=20150101T100000Z'
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
|
||||
assert s.next_run is s.dtstart is s.dtend is None
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@mock.patch('awx.main.models.schedules.now', lambda: datetime(2030, 3, 5, tzinfo=pytz.utc))
|
||||
def test_dst_phantom_hour(job_template):
|
||||
# The DST period in the United States begins at 02:00 (2 am) local time, so
|
||||
# the hour from 2:00:00 to 2:59:59 does not exist in the night of the
|
||||
# switch.
|
||||
|
||||
# Three Sundays, starting 2:30AM America/New_York, starting Mar 3, 2030,
|
||||
# (which doesn't exist)
|
||||
rrule = 'DTSTART;TZID=America/New_York:20300303T023000 RRULE:FREQ=WEEKLY;BYDAY=SU;INTERVAL=1;COUNT=3'
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
|
||||
# 3/10/30 @ 2:30AM is skipped because it _doesn't exist_ <cue twilight zone music>
|
||||
assert str(s.next_run) == '2030-03-17 06:30:00+00:00'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.timeout(3)
|
||||
def test_beginning_of_time(job_template):
|
||||
# ensure that really large generators don't have performance issues
|
||||
start = now()
|
||||
rrule = 'DTSTART:19700101T000000Z RRULE:FREQ=MINUTELY;INTERVAL=1'
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
assert s.next_run > start
|
||||
assert (s.next_run - start).total_seconds() < 60
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize('rrule, tz', [
|
||||
['DTSTART:20300112T210000Z RRULE:FREQ=DAILY;INTERVAL=1', 'UTC'],
|
||||
['DTSTART;TZID=America/New_York:20300112T210000 RRULE:FREQ=DAILY;INTERVAL=1', 'America/New_York']
|
||||
])
|
||||
def test_timezone_property(job_template, rrule, tz):
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
assert s.timezone == tz
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_utc_until_property(job_template):
|
||||
rrule = 'DTSTART:20380601T120000Z RRULE:FREQ=HOURLY;INTERVAL=1;UNTIL=20380601T170000Z'
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
|
||||
assert s.rrule.endswith('20380601T170000Z')
|
||||
assert s.until == '2038-06-01T17:00:00'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_localized_until_property(job_template):
|
||||
rrule = 'DTSTART;TZID=America/New_York:20380601T120000 RRULE:FREQ=HOURLY;INTERVAL=1;UNTIL=20380601T220000Z'
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
|
||||
assert s.rrule.endswith('20380601T220000Z')
|
||||
assert s.until == '2038-06-01T17:00:00'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_utc_naive_coercion(job_template):
|
||||
rrule = 'DTSTART:20380601T120000Z RRULE:FREQ=HOURLY;INTERVAL=1;UNTIL=20380601T170000'
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
|
||||
assert s.rrule.endswith('20380601T170000Z')
|
||||
assert s.until == '2038-06-01T17:00:00'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_est_naive_coercion(job_template):
|
||||
rrule = 'DTSTART;TZID=America/New_York:20380601T120000 RRULE:FREQ=HOURLY;INTERVAL=1;UNTIL=20380601T170000'
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
|
||||
assert s.rrule.endswith('20380601T220000Z') # 5PM EDT = 10PM UTC
|
||||
assert s.until == '2038-06-01T17:00:00'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_empty_until_property(job_template):
|
||||
rrule = 'DTSTART;TZID=America/New_York:20380601T120000 RRULE:FREQ=HOURLY;INTERVAL=1'
|
||||
s = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s.save()
|
||||
assert s.until == ''
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_duplicate_name_across_templates(job_template):
|
||||
# Assert that duplicate name is allowed for different unified job templates.
|
||||
rrule = 'DTSTART;TZID=America/New_York:20380601T120000 RRULE:FREQ=HOURLY;INTERVAL=1'
|
||||
job_template_2 = JobTemplate.objects.create(name='test-job_template_2')
|
||||
s1 = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s2 = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template_2
|
||||
)
|
||||
s1.save()
|
||||
s2.save()
|
||||
|
||||
assert s1.name == s2.name
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_duplicate_name_within_template(job_template):
|
||||
# Assert that duplicate name is not allowed for the same unified job templates.
|
||||
rrule = 'DTSTART;TZID=America/New_York:20380601T120000 RRULE:FREQ=HOURLY;INTERVAL=1'
|
||||
s1 = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
s2 = Schedule(
|
||||
name='Some Schedule',
|
||||
rrule=rrule,
|
||||
unified_job_template=job_template
|
||||
)
|
||||
|
||||
s1.save()
|
||||
with pytest.raises(IntegrityError) as ierror:
|
||||
s2.save()
|
||||
|
||||
assert str(ierror.value) == "UNIQUE constraint failed: main_schedule.unified_job_template_id, main_schedule.name"
|
||||
@@ -0,0 +1,343 @@
|
||||
import itertools
|
||||
import pytest
|
||||
|
||||
# CRUM
|
||||
from crum import impersonate
|
||||
|
||||
# Django
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
|
||||
# AWX
|
||||
from awx.main.models import (
|
||||
UnifiedJobTemplate, Job, JobTemplate, WorkflowJobTemplate,
|
||||
WorkflowApprovalTemplate, Project, WorkflowJob, Schedule,
|
||||
Credential
|
||||
)
|
||||
from awx.api.versioning import reverse
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_subclass_types(rando):
|
||||
assert set(UnifiedJobTemplate._submodels_with_roles()) == set([
|
||||
ContentType.objects.get_for_model(JobTemplate).id,
|
||||
ContentType.objects.get_for_model(Project).id,
|
||||
ContentType.objects.get_for_model(WorkflowJobTemplate).id,
|
||||
ContentType.objects.get_for_model(WorkflowApprovalTemplate).id
|
||||
|
||||
])
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_soft_unique_together(post, project, admin_user):
|
||||
"""This tests that SOFT_UNIQUE_TOGETHER restrictions are applied correctly.
|
||||
"""
|
||||
jt1 = JobTemplate.objects.create(
|
||||
name='foo_jt',
|
||||
project=project
|
||||
)
|
||||
assert jt1.organization == project.organization
|
||||
r = post(
|
||||
url=reverse('api:job_template_list'),
|
||||
data=dict(
|
||||
name='foo_jt', # same as first
|
||||
project=project.id,
|
||||
ask_inventory_on_launch=True,
|
||||
playbook='helloworld.yml'
|
||||
),
|
||||
user=admin_user,
|
||||
expect=400
|
||||
)
|
||||
assert 'combination already exists' in str(r.data)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestCreateUnifiedJob:
|
||||
'''
|
||||
Ensure that copying a job template to a job handles many to many field copy
|
||||
'''
|
||||
def test_many_to_many(self, mocker, job_template_labels):
|
||||
jt = job_template_labels
|
||||
_get_unified_job_field_names = mocker.patch('awx.main.models.jobs.JobTemplate._get_unified_job_field_names', return_value=['labels'])
|
||||
j = jt.create_unified_job()
|
||||
|
||||
_get_unified_job_field_names.assert_called_with()
|
||||
assert j.labels.all().count() == 2
|
||||
assert j.labels.all()[0] == jt.labels.all()[0]
|
||||
assert j.labels.all()[1] == jt.labels.all()[1]
|
||||
|
||||
'''
|
||||
Ensure that data is looked for in parameter list before looking at the object
|
||||
'''
|
||||
def test_many_to_many_kwargs(self, mocker, job_template_labels):
|
||||
jt = job_template_labels
|
||||
_get_unified_job_field_names = mocker.patch('awx.main.models.jobs.JobTemplate._get_unified_job_field_names', return_value=['labels'])
|
||||
jt.create_unified_job()
|
||||
|
||||
_get_unified_job_field_names.assert_called_with()
|
||||
|
||||
'''
|
||||
Ensure that credentials m2m field is copied to new relaunched job
|
||||
'''
|
||||
def test_job_relaunch_copy_vars(self, machine_credential, inventory,
|
||||
deploy_jobtemplate, post, mocker, net_credential):
|
||||
job_with_links = Job(name='existing-job', inventory=inventory)
|
||||
job_with_links.job_template = deploy_jobtemplate
|
||||
job_with_links.limit = "my_server"
|
||||
job_with_links.save()
|
||||
job_with_links.credentials.add(machine_credential)
|
||||
job_with_links.credentials.add(net_credential)
|
||||
second_job = job_with_links.copy_unified_job()
|
||||
|
||||
# Check that job data matches the original variables
|
||||
assert [c.pk for c in second_job.credentials.all()] == [
|
||||
machine_credential.pk,
|
||||
net_credential.pk
|
||||
]
|
||||
assert second_job.inventory == job_with_links.inventory
|
||||
assert second_job.limit == 'my_server'
|
||||
assert net_credential in second_job.credentials.all()
|
||||
|
||||
def test_job_relaunch_modifed_jt(self, jt_linked):
|
||||
# Replace all credentials with a new one of same type
|
||||
new_creds = []
|
||||
for cred in jt_linked.credentials.all():
|
||||
new_creds.append(Credential.objects.create(
|
||||
name=str(cred.name) + '_new',
|
||||
credential_type=cred.credential_type,
|
||||
inputs=cred.inputs
|
||||
))
|
||||
job = jt_linked.create_unified_job()
|
||||
jt_linked.credentials.clear()
|
||||
jt_linked.credentials.add(*new_creds)
|
||||
relaunched_job = job.copy_unified_job()
|
||||
assert set(relaunched_job.credentials.all()) == set(new_creds)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestMetaVars:
|
||||
'''
|
||||
Extension of unit tests with same class name
|
||||
'''
|
||||
|
||||
def test_deleted_user(self, admin_user):
|
||||
job = Job.objects.create(
|
||||
name='job',
|
||||
created_by=admin_user
|
||||
)
|
||||
job.save()
|
||||
|
||||
user_vars = ['_'.join(x) for x in itertools.product(
|
||||
['tower', 'awx'],
|
||||
['user_name', 'user_id', 'user_email', 'user_first_name', 'user_last_name']
|
||||
)]
|
||||
|
||||
for key in user_vars:
|
||||
assert key in job.awx_meta_vars()
|
||||
|
||||
# deleted user is hard to simulate as this test occurs within one transaction
|
||||
job = Job.objects.get(pk=job.id)
|
||||
job.created_by_id = 999999999
|
||||
for key in user_vars:
|
||||
assert key not in job.awx_meta_vars()
|
||||
|
||||
def test_workflow_job_metavars(self, admin_user, job_template):
|
||||
workflow_job = WorkflowJob.objects.create(
|
||||
name='workflow-job',
|
||||
created_by=admin_user
|
||||
)
|
||||
node = workflow_job.workflow_nodes.create(unified_job_template=job_template)
|
||||
job_kv = node.get_job_kwargs()
|
||||
job = node.unified_job_template.create_unified_job(**job_kv)
|
||||
|
||||
workflow_job.workflow_nodes.create(job=job)
|
||||
data = job.awx_meta_vars()
|
||||
assert data['awx_user_id'] == admin_user.id
|
||||
assert data['awx_user_name'] == admin_user.username
|
||||
assert data['awx_workflow_job_id'] == workflow_job.pk
|
||||
assert data['awx_workflow_job_launch_type'] == workflow_job.launch_type
|
||||
|
||||
def test_scheduled_job_metavars(self, job_template, admin_user):
|
||||
schedule = Schedule.objects.create(
|
||||
name='job-schedule',
|
||||
rrule='DTSTART:20171129T155939z\nFREQ=MONTHLY',
|
||||
unified_job_template=job_template
|
||||
)
|
||||
job = Job.objects.create(
|
||||
name='fake-job',
|
||||
launch_type='workflow',
|
||||
schedule=schedule,
|
||||
job_template=job_template
|
||||
)
|
||||
data = job.awx_meta_vars()
|
||||
assert data['awx_schedule_id'] == schedule.pk
|
||||
assert 'awx_user_name' not in data
|
||||
|
||||
def test_scheduled_workflow_job_node_metavars(self, workflow_job_template):
|
||||
schedule = Schedule.objects.create(
|
||||
name='job-schedule',
|
||||
rrule='DTSTART:20171129T155939z\nFREQ=MONTHLY',
|
||||
unified_job_template=workflow_job_template
|
||||
)
|
||||
|
||||
workflow_job = WorkflowJob.objects.create(
|
||||
name='workflow-job',
|
||||
workflow_job_template=workflow_job_template,
|
||||
schedule=schedule
|
||||
)
|
||||
|
||||
job = Job.objects.create(
|
||||
launch_type='workflow'
|
||||
)
|
||||
workflow_job.workflow_nodes.create(job=job)
|
||||
assert job.awx_meta_vars() == {
|
||||
'awx_job_id': job.id,
|
||||
'tower_job_id': job.id,
|
||||
'awx_job_launch_type': 'workflow',
|
||||
'tower_job_launch_type': 'workflow',
|
||||
'awx_workflow_job_name': 'workflow-job',
|
||||
'tower_workflow_job_name': 'workflow-job',
|
||||
'awx_workflow_job_id': workflow_job.id,
|
||||
'tower_workflow_job_id': workflow_job.id,
|
||||
'awx_workflow_job_launch_type': workflow_job.launch_type,
|
||||
'tower_workflow_job_launch_type': workflow_job.launch_type,
|
||||
'awx_parent_job_schedule_id': schedule.id,
|
||||
'tower_parent_job_schedule_id': schedule.id,
|
||||
'awx_parent_job_schedule_name': 'job-schedule',
|
||||
'tower_parent_job_schedule_name': 'job-schedule',
|
||||
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_event_processing_not_finished():
|
||||
job = Job.objects.create(emitted_events=2, status='finished')
|
||||
job.event_class.objects.create(job=job)
|
||||
assert not job.event_processing_finished
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_event_model_undefined():
|
||||
wj = WorkflowJob.objects.create(name='foobar', status='finished')
|
||||
assert wj.event_processing_finished
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestUpdateParentInstance:
|
||||
|
||||
def test_template_modified_by_not_changed_on_launch(self, job_template, alice):
|
||||
# jobs are launched as a particular user, user not saved as JT modified_by
|
||||
with impersonate(alice):
|
||||
assert job_template.current_job is None
|
||||
assert job_template.status == 'never updated'
|
||||
assert job_template.modified_by is None
|
||||
job = job_template.jobs.create(status='new')
|
||||
job.status = 'pending'
|
||||
job.save()
|
||||
assert job_template.current_job == job
|
||||
assert job_template.status == 'pending'
|
||||
assert job_template.modified_by is None
|
||||
|
||||
def check_update(self, project, status):
|
||||
pu_check = project.project_updates.create(
|
||||
job_type='check', status='new', launch_type='manual'
|
||||
)
|
||||
pu_check.status = 'running'
|
||||
pu_check.save()
|
||||
# these should always be updated for a running check job
|
||||
assert project.current_job == pu_check
|
||||
assert project.status == 'running'
|
||||
|
||||
pu_check.status = status
|
||||
pu_check.save()
|
||||
return pu_check
|
||||
|
||||
def run_update(self, project, status):
|
||||
pu_run = project.project_updates.create(
|
||||
job_type='run', status='new', launch_type='sync'
|
||||
)
|
||||
pu_run.status = 'running'
|
||||
pu_run.save()
|
||||
|
||||
pu_run.status = status
|
||||
pu_run.save()
|
||||
return pu_run
|
||||
|
||||
def test_project_update_fails_project(self, project):
|
||||
# This is the normal server auto-update on create behavior
|
||||
assert project.status == 'never updated'
|
||||
pu_check = self.check_update(project, status='failed')
|
||||
|
||||
assert project.last_job == pu_check
|
||||
assert project.status == 'failed'
|
||||
|
||||
def test_project_sync_with_skip_update(self, project):
|
||||
# syncs may be permitted to change project status
|
||||
# only if prior status is "never updated"
|
||||
assert project.status == 'never updated'
|
||||
pu_run = self.run_update(project, status='successful')
|
||||
|
||||
assert project.last_job == pu_run
|
||||
assert project.status == 'successful'
|
||||
|
||||
def test_project_sync_does_not_fail_project(self, project):
|
||||
# Accurate normal server behavior, creating a project auto-updates
|
||||
# have to create update, otherwise will fight with last_job logic
|
||||
assert project.status == 'never updated'
|
||||
pu_check = self.check_update(project, status='successful')
|
||||
assert project.status == 'successful'
|
||||
|
||||
self.run_update(project, status='failed')
|
||||
assert project.last_job == pu_check
|
||||
assert project.status == 'successful'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestTaskImpact:
|
||||
@pytest.fixture
|
||||
def job_host_limit(self, job_template, inventory):
|
||||
def r(hosts, forks):
|
||||
for i in range(hosts):
|
||||
inventory.hosts.create(name='foo' + str(i))
|
||||
job = Job.objects.create(
|
||||
name='fake-job',
|
||||
launch_type='workflow',
|
||||
job_template=job_template,
|
||||
inventory=inventory,
|
||||
forks=forks
|
||||
)
|
||||
return job
|
||||
return r
|
||||
|
||||
def test_limit_task_impact(self, job_host_limit, run_computed_fields_right_away):
|
||||
job = job_host_limit(5, 2)
|
||||
job.inventory.update_computed_fields()
|
||||
assert job.inventory.total_hosts == 5
|
||||
assert job.task_impact == 2 + 1 # forks becomes constraint
|
||||
|
||||
def test_host_task_impact(self, job_host_limit, run_computed_fields_right_away):
|
||||
job = job_host_limit(3, 5)
|
||||
job.inventory.update_computed_fields()
|
||||
assert job.task_impact == 3 + 1 # hosts becomes constraint
|
||||
|
||||
def test_shard_task_impact(self, slice_job_factory, run_computed_fields_right_away):
|
||||
# factory creates on host per slice
|
||||
workflow_job = slice_job_factory(3, jt_kwargs={'forks': 50}, spawn=True)
|
||||
# arrange the jobs by their number
|
||||
jobs = [None for i in range(3)]
|
||||
for node in workflow_job.workflow_nodes.all():
|
||||
jobs[node.job.job_slice_number - 1] = node.job
|
||||
# Even distribution - all jobs run on 1 host
|
||||
assert [
|
||||
len(jobs[0].inventory.get_script_data(slice_number=i + 1, slice_count=3)['all']['hosts'])
|
||||
for i in range(3)
|
||||
] == [1, 1, 1]
|
||||
jobs[0].inventory.update_computed_fields()
|
||||
assert [job.task_impact for job in jobs] == [2, 2, 2] # plus one base task impact
|
||||
# Uneven distribution - first job takes the extra host
|
||||
jobs[0].inventory.hosts.create(name='remainder_foo')
|
||||
assert [
|
||||
len(jobs[0].inventory.get_script_data(slice_number=i + 1, slice_count=3)['all']['hosts'])
|
||||
for i in range(3)
|
||||
] == [2, 1, 1]
|
||||
jobs[0].inventory.update_computed_fields()
|
||||
assert [job.task_impact for job in jobs] == [3, 2, 2]
|
||||
@@ -0,0 +1,420 @@
|
||||
|
||||
# Python
|
||||
import pytest
|
||||
from unittest import mock
|
||||
import json
|
||||
|
||||
# AWX
|
||||
from awx.main.models.workflow import (
|
||||
WorkflowJob,
|
||||
WorkflowJobNode,
|
||||
WorkflowJobTemplateNode,
|
||||
WorkflowJobTemplate,
|
||||
)
|
||||
from awx.main.models.jobs import JobTemplate, Job
|
||||
from awx.main.models.projects import ProjectUpdate
|
||||
from awx.main.scheduler.dag_workflow import WorkflowDAG
|
||||
from awx.api.versioning import reverse
|
||||
from awx.api.views import WorkflowJobTemplateNodeSuccessNodesList
|
||||
|
||||
# Django
|
||||
from django.test import TransactionTestCase
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
|
||||
class TestWorkflowDAGFunctional(TransactionTestCase):
|
||||
def workflow_job(self, states=['new', 'new', 'new', 'new', 'new']):
|
||||
"""
|
||||
Workflow topology:
|
||||
node[0]
|
||||
/\
|
||||
s/ \f
|
||||
/ \
|
||||
node[1] node[3]
|
||||
/ \
|
||||
s/ \f
|
||||
/ \
|
||||
node[2] node[4]
|
||||
"""
|
||||
wfj = WorkflowJob.objects.create()
|
||||
jt = JobTemplate.objects.create(name='test-jt')
|
||||
nodes = [WorkflowJobNode.objects.create(workflow_job=wfj, unified_job_template=jt) for i in range(0, 5)]
|
||||
for node, state in zip(nodes, states):
|
||||
if state:
|
||||
node.job = jt.create_job()
|
||||
node.job.status = state
|
||||
node.job.save()
|
||||
node.save()
|
||||
nodes[0].success_nodes.add(nodes[1])
|
||||
nodes[1].success_nodes.add(nodes[2])
|
||||
nodes[0].failure_nodes.add(nodes[3])
|
||||
nodes[3].failure_nodes.add(nodes[4])
|
||||
return wfj
|
||||
|
||||
def test_build_WFJT_dag(self):
|
||||
'''
|
||||
Test that building the graph uses 4 queries
|
||||
1 to get the nodes
|
||||
3 to get the related success, failure, and always connections
|
||||
'''
|
||||
dag = WorkflowDAG()
|
||||
wfj = self.workflow_job()
|
||||
with self.assertNumQueries(4):
|
||||
dag._init_graph(wfj)
|
||||
|
||||
def test_workflow_done(self):
|
||||
wfj = self.workflow_job(states=['failed', None, None, 'successful', None])
|
||||
dag = WorkflowDAG(workflow_job=wfj)
|
||||
assert 3 == len(dag.mark_dnr_nodes())
|
||||
is_done = dag.is_workflow_done()
|
||||
has_failed, reason = dag.has_workflow_failed()
|
||||
self.assertTrue(is_done)
|
||||
self.assertFalse(has_failed)
|
||||
assert reason is None
|
||||
|
||||
# verify that relaunched WFJ fails if a JT leaf is deleted
|
||||
for jt in JobTemplate.objects.all():
|
||||
jt.delete()
|
||||
relaunched = wfj.create_relaunch_workflow_job()
|
||||
dag = WorkflowDAG(workflow_job=relaunched)
|
||||
dag.mark_dnr_nodes()
|
||||
is_done = dag.is_workflow_done()
|
||||
has_failed, reason = dag.has_workflow_failed()
|
||||
self.assertTrue(is_done)
|
||||
self.assertTrue(has_failed)
|
||||
assert "Workflow job node {} related unified job template missing".format(wfj.workflow_nodes.all()[0].id)
|
||||
|
||||
def test_workflow_fails_for_no_error_handler(self):
|
||||
wfj = self.workflow_job(states=['successful', 'failed', None, None, None])
|
||||
dag = WorkflowDAG(workflow_job=wfj)
|
||||
dag.mark_dnr_nodes()
|
||||
is_done = dag.is_workflow_done()
|
||||
has_failed = dag.has_workflow_failed()
|
||||
self.assertTrue(is_done)
|
||||
self.assertTrue(has_failed)
|
||||
|
||||
def test_workflow_fails_leaf(self):
|
||||
wfj = self.workflow_job(states=['successful', 'successful', 'failed', None, None])
|
||||
dag = WorkflowDAG(workflow_job=wfj)
|
||||
dag.mark_dnr_nodes()
|
||||
is_done = dag.is_workflow_done()
|
||||
has_failed = dag.has_workflow_failed()
|
||||
self.assertTrue(is_done)
|
||||
self.assertTrue(has_failed)
|
||||
|
||||
def test_workflow_not_finished(self):
|
||||
wfj = self.workflow_job(states=['new', None, None, None, None])
|
||||
dag = WorkflowDAG(workflow_job=wfj)
|
||||
dag.mark_dnr_nodes()
|
||||
is_done = dag.is_workflow_done()
|
||||
has_failed, reason = dag.has_workflow_failed()
|
||||
self.assertFalse(is_done)
|
||||
self.assertFalse(has_failed)
|
||||
assert reason is None
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestWorkflowDNR():
|
||||
@pytest.fixture
|
||||
def workflow_job_fn(self):
|
||||
def fn(states=['new', 'new', 'new', 'new', 'new', 'new']):
|
||||
r"""
|
||||
Workflow topology:
|
||||
node[0]
|
||||
/ |
|
||||
s f
|
||||
/ |
|
||||
node[1] node[3]
|
||||
/ |
|
||||
s f
|
||||
/ |
|
||||
node[2] node[4]
|
||||
\ |
|
||||
s f
|
||||
\ |
|
||||
node[5]
|
||||
"""
|
||||
wfj = WorkflowJob.objects.create()
|
||||
jt = JobTemplate.objects.create(name='test-jt')
|
||||
nodes = [WorkflowJobNode.objects.create(workflow_job=wfj, unified_job_template=jt) for i in range(0, 6)]
|
||||
for node, state in zip(nodes, states):
|
||||
if state:
|
||||
node.job = jt.create_job()
|
||||
node.job.status = state
|
||||
node.job.save()
|
||||
node.save()
|
||||
nodes[0].success_nodes.add(nodes[1])
|
||||
nodes[1].success_nodes.add(nodes[2])
|
||||
nodes[0].failure_nodes.add(nodes[3])
|
||||
nodes[3].failure_nodes.add(nodes[4])
|
||||
nodes[2].success_nodes.add(nodes[5])
|
||||
nodes[4].failure_nodes.add(nodes[5])
|
||||
return wfj, nodes
|
||||
return fn
|
||||
|
||||
def test_workflow_dnr_because_parent(self, workflow_job_fn):
|
||||
wfj, nodes = workflow_job_fn(states=['successful', None, None, None, None, None,])
|
||||
dag = WorkflowDAG(workflow_job=wfj)
|
||||
workflow_nodes = dag.mark_dnr_nodes()
|
||||
assert 2 == len(workflow_nodes)
|
||||
assert nodes[3] in workflow_nodes
|
||||
assert nodes[4] in workflow_nodes
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestWorkflowJob:
|
||||
@pytest.fixture
|
||||
def workflow_job(self, workflow_job_template_factory):
|
||||
wfjt = workflow_job_template_factory('blah').workflow_job_template
|
||||
wfj = WorkflowJob.objects.create(workflow_job_template=wfjt)
|
||||
|
||||
nodes = [WorkflowJobTemplateNode.objects.create(workflow_job_template=wfjt) for i in range(0, 5)]
|
||||
|
||||
nodes[0].success_nodes.add(nodes[1])
|
||||
nodes[1].success_nodes.add(nodes[2])
|
||||
|
||||
nodes[0].failure_nodes.add(nodes[3])
|
||||
nodes[3].failure_nodes.add(nodes[4])
|
||||
|
||||
return wfj
|
||||
|
||||
def test_inherit_job_template_workflow_nodes(self, mocker, workflow_job):
|
||||
workflow_job.copy_nodes_from_original(original=workflow_job.workflow_job_template)
|
||||
|
||||
nodes = WorkflowJob.objects.get(id=workflow_job.id).workflow_job_nodes.all().order_by('created')
|
||||
assert nodes[0].success_nodes.filter(id=nodes[1].id).exists()
|
||||
assert nodes[1].success_nodes.filter(id=nodes[2].id).exists()
|
||||
assert nodes[0].failure_nodes.filter(id=nodes[3].id).exists()
|
||||
assert nodes[3].failure_nodes.filter(id=nodes[4].id).exists()
|
||||
|
||||
def test_inherit_ancestor_artifacts_from_job(self, job_template, mocker):
|
||||
"""
|
||||
Assure that nodes along the line of execution inherit artifacts
|
||||
from both jobs ran, and from the accumulation of old jobs
|
||||
"""
|
||||
# Related resources
|
||||
wfj = WorkflowJob.objects.create(name='test-wf-job')
|
||||
job = Job.objects.create(name='test-job', artifacts={'b': 43})
|
||||
# Workflow job nodes
|
||||
job_node = WorkflowJobNode.objects.create(workflow_job=wfj, job=job,
|
||||
ancestor_artifacts={'a': 42})
|
||||
queued_node = WorkflowJobNode.objects.create(workflow_job=wfj, unified_job_template=job_template)
|
||||
# Connect old job -> new job
|
||||
mocker.patch.object(queued_node, 'get_parent_nodes', lambda: [job_node])
|
||||
assert queued_node.get_job_kwargs()['extra_vars'] == {'a': 42, 'b': 43}
|
||||
assert queued_node.ancestor_artifacts == {'a': 42, 'b': 43}
|
||||
|
||||
def test_inherit_ancestor_artifacts_from_project_update(self, project, job_template, mocker):
|
||||
"""
|
||||
Test that the existence of a project update (no artifacts) does
|
||||
not break the flow of ancestor_artifacts
|
||||
"""
|
||||
# Related resources
|
||||
wfj = WorkflowJob.objects.create(name='test-wf-job')
|
||||
update = ProjectUpdate.objects.create(name='test-update', project=project)
|
||||
# Workflow job nodes
|
||||
project_node = WorkflowJobNode.objects.create(workflow_job=wfj, job=update,
|
||||
ancestor_artifacts={'a': 42, 'b': 43})
|
||||
queued_node = WorkflowJobNode.objects.create(workflow_job=wfj, unified_job_template=job_template)
|
||||
# Connect project update -> new job
|
||||
mocker.patch.object(queued_node, 'get_parent_nodes', lambda: [project_node])
|
||||
assert queued_node.get_job_kwargs()['extra_vars'] == {'a': 42, 'b': 43}
|
||||
assert queued_node.ancestor_artifacts == {'a': 42, 'b': 43}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestWorkflowJobTemplate:
|
||||
@pytest.fixture
|
||||
def wfjt(self, workflow_job_template_factory, organization):
|
||||
wfjt = workflow_job_template_factory(
|
||||
'test', organization=organization).workflow_job_template
|
||||
wfjt.organization = organization
|
||||
nodes = [WorkflowJobTemplateNode.objects.create(workflow_job_template=wfjt) for i in range(0, 3)]
|
||||
nodes[0].success_nodes.add(nodes[1])
|
||||
nodes[1].failure_nodes.add(nodes[2])
|
||||
return wfjt
|
||||
|
||||
def test_node_parentage(self, wfjt):
|
||||
# test success parent
|
||||
wfjt_node = wfjt.workflow_job_template_nodes.all()[1]
|
||||
parent_qs = wfjt_node.get_parent_nodes()
|
||||
assert len(parent_qs) == 1
|
||||
assert parent_qs[0] == wfjt.workflow_job_template_nodes.all()[0]
|
||||
# test failure parent
|
||||
wfjt_node = wfjt.workflow_job_template_nodes.all()[2]
|
||||
parent_qs = wfjt_node.get_parent_nodes()
|
||||
assert len(parent_qs) == 1
|
||||
assert parent_qs[0] == wfjt.workflow_job_template_nodes.all()[1]
|
||||
|
||||
def test_topology_validator(self, wfjt):
|
||||
test_view = WorkflowJobTemplateNodeSuccessNodesList()
|
||||
nodes = wfjt.workflow_job_template_nodes.all()
|
||||
# test cycle validation
|
||||
assert test_view.is_valid_relation(nodes[2], nodes[0]) == {'Error': 'Cycle detected.'}
|
||||
|
||||
def test_always_success_failure_creation(self, wfjt, admin, get):
|
||||
wfjt_node = wfjt.workflow_job_template_nodes.all()[1]
|
||||
node = WorkflowJobTemplateNode.objects.create(workflow_job_template=wfjt)
|
||||
wfjt_node.always_nodes.add(node)
|
||||
assert len(node.get_parent_nodes()) == 1
|
||||
url = reverse('api:workflow_job_template_node_list') + str(wfjt_node.id) + '/'
|
||||
resp = get(url, admin)
|
||||
assert node.id in resp.data['always_nodes']
|
||||
|
||||
def test_wfjt_unique_together_with_org(self, organization):
|
||||
wfjt1 = WorkflowJobTemplate(name='foo', organization=organization)
|
||||
wfjt1.save()
|
||||
wfjt2 = WorkflowJobTemplate(name='foo', organization=organization)
|
||||
with pytest.raises(ValidationError):
|
||||
wfjt2.validate_unique()
|
||||
wfjt2 = WorkflowJobTemplate(name='foo', organization=None)
|
||||
wfjt2.validate_unique()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestWorkflowJobTemplatePrompts:
|
||||
"""These are tests for prompts that live on the workflow job template model
|
||||
not the node, prompts apply for entire workflow
|
||||
"""
|
||||
@pytest.fixture
|
||||
def wfjt_prompts(self):
|
||||
return WorkflowJobTemplate.objects.create(
|
||||
ask_inventory_on_launch=True,
|
||||
ask_variables_on_launch=True,
|
||||
ask_limit_on_launch=True,
|
||||
ask_scm_branch_on_launch=True
|
||||
)
|
||||
|
||||
@pytest.fixture
|
||||
def prompts_data(self, inventory):
|
||||
return dict(
|
||||
inventory=inventory,
|
||||
extra_vars={'foo': 'bar'},
|
||||
limit='webservers',
|
||||
scm_branch='release-3.3'
|
||||
)
|
||||
|
||||
def test_apply_workflow_job_prompts(self, workflow_job_template, wfjt_prompts, prompts_data, inventory):
|
||||
# null or empty fields used
|
||||
workflow_job = workflow_job_template.create_unified_job()
|
||||
assert workflow_job.limit is None
|
||||
assert workflow_job.inventory is None
|
||||
assert workflow_job.scm_branch is None
|
||||
|
||||
# fields from prompts used
|
||||
workflow_job = workflow_job_template.create_unified_job(**prompts_data)
|
||||
assert json.loads(workflow_job.extra_vars) == {'foo': 'bar'}
|
||||
assert workflow_job.limit == 'webservers'
|
||||
assert workflow_job.inventory == inventory
|
||||
assert workflow_job.scm_branch == 'release-3.3'
|
||||
|
||||
# non-null fields from WFJT used
|
||||
workflow_job_template.inventory = inventory
|
||||
workflow_job_template.limit = 'fooo'
|
||||
workflow_job_template.scm_branch = 'bar'
|
||||
workflow_job = workflow_job_template.create_unified_job()
|
||||
assert workflow_job.limit == 'fooo'
|
||||
assert workflow_job.inventory == inventory
|
||||
assert workflow_job.scm_branch == 'bar'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_process_workflow_job_prompts(self, inventory, workflow_job_template, wfjt_prompts, prompts_data):
|
||||
accepted, rejected, errors = workflow_job_template._accept_or_ignore_job_kwargs(**prompts_data)
|
||||
assert accepted == {}
|
||||
assert rejected == prompts_data
|
||||
assert errors
|
||||
accepted, rejected, errors = wfjt_prompts._accept_or_ignore_job_kwargs(**prompts_data)
|
||||
assert accepted == prompts_data
|
||||
assert rejected == {}
|
||||
assert not errors
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_set_all_the_prompts(self, post, organization, inventory, org_admin):
|
||||
r = post(
|
||||
url = reverse('api:workflow_job_template_list'),
|
||||
data = dict(
|
||||
name='My new workflow',
|
||||
organization=organization.id,
|
||||
inventory=inventory.id,
|
||||
limit='foooo',
|
||||
ask_limit_on_launch=True,
|
||||
scm_branch='bar',
|
||||
ask_scm_branch_on_launch=True
|
||||
),
|
||||
user = org_admin,
|
||||
expect = 201
|
||||
)
|
||||
wfjt = WorkflowJobTemplate.objects.get(id=r.data['id'])
|
||||
assert wfjt.char_prompts == {
|
||||
'limit': 'foooo', 'scm_branch': 'bar'
|
||||
}
|
||||
assert wfjt.ask_scm_branch_on_launch is True
|
||||
assert wfjt.ask_limit_on_launch is True
|
||||
|
||||
launch_url = r.data['related']['launch']
|
||||
with mock.patch('awx.main.queue.CallbackQueueDispatcher.dispatch', lambda self, obj: None):
|
||||
r = post(
|
||||
url = launch_url,
|
||||
data = dict(
|
||||
scm_branch = 'prompt_branch',
|
||||
limit = 'prompt_limit'
|
||||
),
|
||||
user = org_admin,
|
||||
expect=201
|
||||
)
|
||||
assert r.data['limit'] == 'prompt_limit'
|
||||
assert r.data['scm_branch'] == 'prompt_branch'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_workflow_ancestors(organization):
|
||||
# Spawn order of templates grandparent -> parent -> child
|
||||
# create child WFJT and workflow job
|
||||
child = WorkflowJobTemplate.objects.create(organization=organization, name='child')
|
||||
child_job = WorkflowJob.objects.create(
|
||||
workflow_job_template=child,
|
||||
launch_type='workflow'
|
||||
)
|
||||
# create parent WFJT and workflow job, and link it up
|
||||
parent = WorkflowJobTemplate.objects.create(organization=organization, name='parent')
|
||||
parent_job = WorkflowJob.objects.create(
|
||||
workflow_job_template=parent,
|
||||
launch_type='workflow'
|
||||
)
|
||||
WorkflowJobNode.objects.create(
|
||||
workflow_job=parent_job,
|
||||
unified_job_template=child,
|
||||
job=child_job
|
||||
)
|
||||
# create grandparent WFJT and workflow job and link it up
|
||||
grandparent = WorkflowJobTemplate.objects.create(organization=organization, name='grandparent')
|
||||
grandparent_job = WorkflowJob.objects.create(
|
||||
workflow_job_template=grandparent,
|
||||
launch_type='schedule'
|
||||
)
|
||||
WorkflowJobNode.objects.create(
|
||||
workflow_job=grandparent_job,
|
||||
unified_job_template=parent,
|
||||
job=parent_job
|
||||
)
|
||||
# ancestors method gives a list of WFJT ids
|
||||
assert child_job.get_ancestor_workflows() == [parent, grandparent]
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_workflow_ancestors_recursion_prevention(organization):
|
||||
# This is toxic database data, this tests that it doesn't create an infinite loop
|
||||
wfjt = WorkflowJobTemplate.objects.create(organization=organization, name='child')
|
||||
wfj = WorkflowJob.objects.create(
|
||||
workflow_job_template=wfjt,
|
||||
launch_type='workflow'
|
||||
)
|
||||
WorkflowJobNode.objects.create(
|
||||
workflow_job=wfj,
|
||||
unified_job_template=wfjt,
|
||||
job=wfj # well, this is a problem
|
||||
)
|
||||
# mostly, we just care that this assertion finishes in finite time
|
||||
assert wfj.get_ancestor_workflows() == []
|
||||
Reference in New Issue
Block a user