Initial commit
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
import datetime
|
||||
|
||||
from awx.main.analytics.broadcast_websocket import FixedSlidingWindow
|
||||
from awx.main.analytics.broadcast_websocket import dt_to_seconds
|
||||
|
||||
|
||||
class TestFixedSlidingWindow():
|
||||
|
||||
def ts(self, **kwargs):
|
||||
e = {
|
||||
'year': 1985,
|
||||
'month': 1,
|
||||
'day': 1,
|
||||
'hour': 1,
|
||||
}
|
||||
return dt_to_seconds(datetime.datetime(**kwargs, **e))
|
||||
|
||||
def test_record_same_minute(self):
|
||||
"""
|
||||
Legend:
|
||||
- = record()
|
||||
^ = render()
|
||||
|---| = 1 minute, 60 seconds
|
||||
|
||||
....................
|
||||
|------------------------------------------------------------|
|
||||
^^^^^^^^^^^^^^^^^^^^
|
||||
"""
|
||||
|
||||
fsw = FixedSlidingWindow(self.ts(minute=0, second=0, microsecond=0))
|
||||
for i in range(20):
|
||||
fsw.record(self.ts(minute=0, second=i, microsecond=0))
|
||||
assert (i + 1) == fsw.render(self.ts(minute=0, second=i, microsecond=0))
|
||||
|
||||
|
||||
def test_record_same_minute_render_diff_minute(self):
|
||||
"""
|
||||
Legend:
|
||||
- = record()
|
||||
^ = render()
|
||||
|---| = 1 minute, 60 seconds
|
||||
|
||||
....................
|
||||
|------------------------------------------------------------|
|
||||
^^ ^
|
||||
AB C
|
||||
|------------------------------------------------------------|
|
||||
^^^^^^^^^^^^^^^^^^^^^
|
||||
DEEEEEEEEEEEEEEEEEEEF
|
||||
"""
|
||||
|
||||
fsw = FixedSlidingWindow(self.ts(minute=0, second=0, microsecond=0))
|
||||
for i in range(20):
|
||||
fsw.record(self.ts(minute=0, second=i, microsecond=0))
|
||||
|
||||
assert 20 == fsw.render(self.ts(minute=0, second=19, microsecond=0)), \
|
||||
"A. The second of the last record() call"
|
||||
assert 20 == fsw.render(self.ts(minute=0, second=20, microsecond=0)), \
|
||||
"B. The second after the last record() call"
|
||||
assert 20 == fsw.render(self.ts(minute=0, second=59, microsecond=0)), \
|
||||
"C. Last second in the same minute that all record() called in"
|
||||
assert 20 == fsw.render(self.ts(minute=1, second=0, microsecond=0)), \
|
||||
"D. First second of the minute following the minute that all record() calls in"
|
||||
for i in range(20):
|
||||
assert 20 - i == fsw.render(self.ts(minute=1, second=i, microsecond=0)), \
|
||||
"E. Sliding window where 1 record() should drop from the results each time"
|
||||
|
||||
assert 0 == fsw.render(self.ts(minute=1, second=20, microsecond=0)), \
|
||||
"F. First second one minute after all record() calls"
|
||||
@@ -0,0 +1,54 @@
|
||||
from unittest import mock
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def get_related_assert():
|
||||
def fn(model_obj, related, resource_name, related_resource_name):
|
||||
assert related_resource_name in related
|
||||
assert related[related_resource_name] == '/api/v2/%s/%d/%s/' % (resource_name, model_obj.pk, related_resource_name)
|
||||
return fn
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def get_related_mock_and_run():
|
||||
def fn(serializer_class, model_obj):
|
||||
serializer = serializer_class()
|
||||
related = serializer.get_related(model_obj)
|
||||
return related
|
||||
return fn
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_get_related(get_related_assert, get_related_mock_and_run):
|
||||
def fn(serializer_class, model_obj, resource_name, related_resource_name):
|
||||
related = get_related_mock_and_run(serializer_class, model_obj)
|
||||
get_related_assert(model_obj, related, resource_name, related_resource_name)
|
||||
return related
|
||||
return fn
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def get_summary_fields_assert():
|
||||
def fn(summary, summary_field_name):
|
||||
assert summary_field_name in summary
|
||||
return fn
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def get_summary_fields_mock_and_run():
|
||||
def fn(serializer_class, model_obj):
|
||||
serializer = serializer_class()
|
||||
serializer.show_capabilities = []
|
||||
serializer.context['view'] = mock.Mock(kwargs={})
|
||||
return serializer.get_summary_fields(model_obj)
|
||||
return fn
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_get_summary_fields(get_summary_fields_mock_and_run, get_summary_fields_assert):
|
||||
def fn(serializer_class, model_obj, summary_field_name):
|
||||
summary = get_summary_fields_mock_and_run(serializer_class, model_obj)
|
||||
get_summary_fields_assert(summary, summary_field_name)
|
||||
return summary
|
||||
return fn
|
||||
@@ -0,0 +1,31 @@
|
||||
from awx.api.serializers import ActivityStreamSerializer
|
||||
from awx.main.registrar import activity_stream_registrar
|
||||
from awx.main.models import ActivityStream
|
||||
|
||||
from awx.conf.models import Setting
|
||||
|
||||
|
||||
def test_activity_stream_related():
|
||||
'''
|
||||
If this test failed with content in `missing_models`, that means that a
|
||||
model has been connected to the activity stream, but the model has not
|
||||
been added to the activity stream serializer.
|
||||
|
||||
How to fix this:
|
||||
Ideally, all models should be in awx.api.serializers.SUMMARIZABLE_FK_FIELDS
|
||||
|
||||
If, for whatever reason, the missing model should not generally be
|
||||
summarized from related resources, then a special case can be carved out in
|
||||
ActivityStreamSerializer._local_summarizable_fk_fields
|
||||
'''
|
||||
serializer_related = set(
|
||||
ActivityStream._meta.get_field(field_name).related_model for field_name, stuff in
|
||||
ActivityStreamSerializer()._local_summarizable_fk_fields
|
||||
if hasattr(ActivityStream, field_name)
|
||||
)
|
||||
|
||||
models = set(activity_stream_registrar.models)
|
||||
models.remove(Setting)
|
||||
|
||||
missing_models = models - serializer_related
|
||||
assert not missing_models
|
||||
@@ -0,0 +1,86 @@
|
||||
# Python
|
||||
import pytest
|
||||
from unittest import mock
|
||||
from unittest.mock import PropertyMock
|
||||
|
||||
# AWX
|
||||
from awx.api.serializers import (
|
||||
CustomInventoryScriptSerializer,
|
||||
InventorySourceSerializer,
|
||||
)
|
||||
from awx.main.models import (
|
||||
CustomInventoryScript,
|
||||
InventorySource,
|
||||
User,
|
||||
)
|
||||
|
||||
#DRF
|
||||
from rest_framework.request import Request
|
||||
from rest_framework.test import (
|
||||
APIRequestFactory,
|
||||
force_authenticate,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def inventory_source(mocker):
|
||||
obj = mocker.MagicMock(
|
||||
pk=22,
|
||||
inventory=mocker.MagicMock(pk=23),
|
||||
update=mocker.MagicMock(),
|
||||
source_project_id=None,
|
||||
current_update=None,
|
||||
last_update=None,
|
||||
spec=InventorySource
|
||||
)
|
||||
return obj
|
||||
|
||||
|
||||
class TestCustomInventoryScriptSerializer(object):
|
||||
@pytest.mark.parametrize("superuser,sysaudit,admin_role,value",
|
||||
((True, False, False, '#!/python'),
|
||||
(False, True, False, '#!/python'),
|
||||
(False, False, True, '#!/python'),
|
||||
(False, False, False, None)))
|
||||
def test_to_representation_orphan(self, superuser, sysaudit, admin_role, value):
|
||||
with mock.patch.object(CustomInventoryScriptSerializer, 'get_summary_fields', return_value={}):
|
||||
with mock.patch.object(User, 'is_system_auditor', return_value=sysaudit):
|
||||
user = User(username="root", is_superuser=superuser)
|
||||
roles = [user] if admin_role else []
|
||||
|
||||
with mock.patch('awx.main.models.CustomInventoryScript.admin_role', new_callable=PropertyMock, return_value=roles),\
|
||||
mock.patch('awx.api.serializers.settings'):
|
||||
cis = CustomInventoryScript(pk=1, script=value)
|
||||
serializer = CustomInventoryScriptSerializer()
|
||||
|
||||
factory = APIRequestFactory()
|
||||
wsgi_request = factory.post("/inventory_script/1", {'id':1}, format="json")
|
||||
force_authenticate(wsgi_request, user)
|
||||
|
||||
request = Request(wsgi_request)
|
||||
serializer.context['request'] = request
|
||||
|
||||
representation = serializer.to_representation(cis)
|
||||
assert representation['script'] == value
|
||||
|
||||
|
||||
@mock.patch('awx.api.serializers.UnifiedJobTemplateSerializer.get_related', lambda x,y: {})
|
||||
@mock.patch('awx.api.serializers.InventorySourceOptionsSerializer.get_related', lambda x,y: {})
|
||||
class TestInventorySourceSerializerGetRelated(object):
|
||||
@pytest.mark.parametrize('related_resource_name', [
|
||||
'activity_stream',
|
||||
'notification_templates_error',
|
||||
'notification_templates_success',
|
||||
'notification_templates_started',
|
||||
'inventory_updates',
|
||||
'update',
|
||||
'hosts',
|
||||
'groups',
|
||||
])
|
||||
def test_get_related(self, test_get_related, inventory_source, related_resource_name):
|
||||
test_get_related(
|
||||
InventorySourceSerializer,
|
||||
inventory_source,
|
||||
'inventory_sources',
|
||||
related_resource_name
|
||||
)
|
||||
@@ -0,0 +1,193 @@
|
||||
# Python
|
||||
from collections import namedtuple
|
||||
import pytest
|
||||
from unittest import mock
|
||||
import json
|
||||
|
||||
# AWX
|
||||
from awx.api.serializers import (
|
||||
JobDetailSerializer,
|
||||
JobSerializer,
|
||||
JobOptionsSerializer,
|
||||
ProjectUpdateDetailSerializer,
|
||||
)
|
||||
|
||||
from awx.main.models import (
|
||||
Label,
|
||||
Job,
|
||||
JobEvent,
|
||||
ProjectUpdateEvent,
|
||||
)
|
||||
|
||||
|
||||
def mock_JT_resource_data():
|
||||
return {}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_template(mocker):
|
||||
mock_jt = mocker.MagicMock(pk=5)
|
||||
mock_jt.validation_errors = mock_JT_resource_data
|
||||
return mock_jt
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project_update(mocker):
|
||||
mock_pu = mocker.MagicMock(pk=1)
|
||||
return mock_pu
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job(mocker, job_template, project_update):
|
||||
return mocker.MagicMock(pk=5, job_template=job_template, project_update=project_update,
|
||||
workflow_job_id=None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def labels(mocker):
|
||||
return [Label(id=x, name='label-%d' % x) for x in range(0, 25)]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def jobs(mocker):
|
||||
return [Job(id=x, name='job-%d' % x) for x in range(0, 25)]
|
||||
|
||||
|
||||
@mock.patch('awx.api.serializers.UnifiedJobTemplateSerializer.get_related', lambda x,y: {})
|
||||
@mock.patch('awx.api.serializers.JobOptionsSerializer.get_related', lambda x,y: {})
|
||||
class TestJobSerializerGetRelated():
|
||||
|
||||
@pytest.mark.parametrize("related_resource_name", [
|
||||
'job_events',
|
||||
'relaunch',
|
||||
'labels',
|
||||
])
|
||||
def test_get_related(self, test_get_related, job, related_resource_name):
|
||||
test_get_related(JobSerializer, job, 'jobs', related_resource_name)
|
||||
|
||||
def test_job_template_absent(self, job):
|
||||
job.job_template = None
|
||||
serializer = JobSerializer()
|
||||
related = serializer.get_related(job)
|
||||
assert 'job_template' not in related
|
||||
|
||||
def test_job_template_present(self, get_related_mock_and_run, job):
|
||||
related = get_related_mock_and_run(JobSerializer, job)
|
||||
assert 'job_template' in related
|
||||
assert related['job_template'] == '/api/v2/%s/%d/' % ('job_templates', job.job_template.pk)
|
||||
|
||||
|
||||
@mock.patch('awx.api.serializers.BaseSerializer.to_representation', lambda self,obj: {
|
||||
'extra_vars': obj.extra_vars})
|
||||
class TestJobSerializerSubstitution():
|
||||
|
||||
def test_survey_password_hide(self, mocker):
|
||||
job = mocker.MagicMock(**{
|
||||
'display_extra_vars.return_value': '{\"secret_key\": \"$encrypted$\"}',
|
||||
'extra_vars.return_value': '{\"secret_key\": \"my_password\"}'})
|
||||
serializer = JobSerializer(job)
|
||||
rep = serializer.to_representation(job)
|
||||
extra_vars = json.loads(rep['extra_vars'])
|
||||
assert extra_vars['secret_key'] == '$encrypted$'
|
||||
job.display_extra_vars.assert_called_once_with()
|
||||
assert 'my_password' not in extra_vars
|
||||
|
||||
|
||||
@mock.patch('awx.api.serializers.BaseSerializer.get_summary_fields', lambda x,y: {})
|
||||
class TestJobOptionsSerializerGetSummaryFields():
|
||||
|
||||
def test__summary_field_labels_10_max(self, mocker, job_template, labels):
|
||||
job_template.labels.all = mocker.MagicMock(**{'return_value': labels})
|
||||
|
||||
serializer = JobOptionsSerializer()
|
||||
summary_labels = serializer._summary_field_labels(job_template)
|
||||
|
||||
assert len(summary_labels['results']) == 10
|
||||
assert summary_labels['results'] == [{'id': x.id, 'name': x.name} for x in labels[:10]]
|
||||
|
||||
def test_labels_exists(self, test_get_summary_fields, job_template):
|
||||
test_get_summary_fields(JobOptionsSerializer, job_template, 'labels')
|
||||
|
||||
|
||||
class TestJobDetailSerializerGetHostStatusCountFields(object):
|
||||
|
||||
def test_hosts_are_counted_once(self, job, mocker):
|
||||
mock_event = JobEvent(**{
|
||||
'event': 'playbook_on_stats',
|
||||
'event_data': {
|
||||
'skipped': {
|
||||
'localhost': 2,
|
||||
'fiz': 1,
|
||||
},
|
||||
'ok': {
|
||||
'localhost': 1,
|
||||
'foo': 2,
|
||||
},
|
||||
'changed': {
|
||||
'localhost': 1,
|
||||
'bar': 3,
|
||||
},
|
||||
'dark': {
|
||||
'localhost': 2,
|
||||
'fiz': 2,
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
mock_qs = namedtuple('mock_qs', ['get'])(mocker.MagicMock(return_value=mock_event))
|
||||
job.job_events.only = mocker.MagicMock(return_value=mock_qs)
|
||||
|
||||
serializer = JobDetailSerializer()
|
||||
host_status_counts = serializer.get_host_status_counts(job)
|
||||
|
||||
assert host_status_counts == {'ok': 1, 'changed': 1, 'dark': 2}
|
||||
|
||||
def test_host_status_counts_is_empty_dict_without_stats_event(self, job):
|
||||
job.job_events = JobEvent.objects.none()
|
||||
|
||||
serializer = JobDetailSerializer()
|
||||
host_status_counts = serializer.get_host_status_counts(job)
|
||||
|
||||
assert host_status_counts == {}
|
||||
|
||||
|
||||
class TestProjectUpdateDetailSerializerGetHostStatusCountFields(object):
|
||||
|
||||
def test_hosts_are_counted_once(self, project_update, mocker):
|
||||
mock_event = ProjectUpdateEvent(**{
|
||||
'event': 'playbook_on_stats',
|
||||
'event_data': {
|
||||
'skipped': {
|
||||
'localhost': 2,
|
||||
'fiz': 1,
|
||||
},
|
||||
'ok': {
|
||||
'localhost': 1,
|
||||
'foo': 2,
|
||||
},
|
||||
'changed': {
|
||||
'localhost': 1,
|
||||
'bar': 3,
|
||||
},
|
||||
'dark': {
|
||||
'localhost': 2,
|
||||
'fiz': 2,
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
mock_qs = namedtuple('mock_qs', ['get'])(mocker.MagicMock(return_value=mock_event))
|
||||
project_update.project_update_events.only = mocker.MagicMock(return_value=mock_qs)
|
||||
|
||||
serializer = ProjectUpdateDetailSerializer()
|
||||
host_status_counts = serializer.get_host_status_counts(project_update)
|
||||
|
||||
assert host_status_counts == {'ok': 1, 'changed': 1, 'dark': 2}
|
||||
|
||||
def test_host_status_counts_is_empty_dict_without_stats_event(self, project_update):
|
||||
project_update.project_update_events = ProjectUpdateEvent.objects.none()
|
||||
|
||||
serializer = ProjectUpdateDetailSerializer()
|
||||
host_status_counts = serializer.get_host_status_counts(project_update)
|
||||
|
||||
assert host_status_counts == {}
|
||||
@@ -0,0 +1,126 @@
|
||||
# Python
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
# AWX
|
||||
from awx.api.serializers import (
|
||||
JobTemplateSerializer,
|
||||
)
|
||||
from awx.api.views import JobTemplateDetail
|
||||
from awx.main.models import (
|
||||
Role,
|
||||
User,
|
||||
Job,
|
||||
JobTemplate,
|
||||
)
|
||||
from rest_framework.test import APIRequestFactory
|
||||
|
||||
#DRF
|
||||
from rest_framework import serializers
|
||||
|
||||
|
||||
def mock_JT_resource_data():
|
||||
return {}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_template(mocker):
|
||||
mock_jt = mocker.MagicMock(spec=JobTemplate)
|
||||
mock_jt.pk = 5
|
||||
mock_jt.host_config_key = '9283920492'
|
||||
mock_jt.validation_errors = mock_JT_resource_data
|
||||
mock_jt.webhook_service = ''
|
||||
mock_jt.organization_id = None
|
||||
mock_jt.webhook_credential_id = None
|
||||
return mock_jt
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job(mocker, job_template):
|
||||
return mocker.MagicMock(pk=5, job_template=job_template)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def jobs(mocker):
|
||||
return [Job(id=x, name='job-%d' % x) for x in range(0, 25)]
|
||||
|
||||
|
||||
@mock.patch('awx.api.serializers.UnifiedJobTemplateSerializer.get_related', lambda x,y: {})
|
||||
@mock.patch('awx.api.serializers.JobOptionsSerializer.get_related', lambda x,y: {})
|
||||
class TestJobTemplateSerializerGetRelated():
|
||||
@pytest.mark.parametrize("related_resource_name", [
|
||||
'jobs',
|
||||
'schedules',
|
||||
'activity_stream',
|
||||
'launch',
|
||||
'webhook_key',
|
||||
'notification_templates_started',
|
||||
'notification_templates_success',
|
||||
'notification_templates_error',
|
||||
'survey_spec',
|
||||
'labels',
|
||||
'callback',
|
||||
])
|
||||
def test_get_related(self, test_get_related, job_template, related_resource_name):
|
||||
test_get_related(JobTemplateSerializer, job_template, 'job_templates', related_resource_name)
|
||||
|
||||
def test_callback_absent(self, get_related_mock_and_run, job_template):
|
||||
job_template.host_config_key = None
|
||||
related = get_related_mock_and_run(JobTemplateSerializer, job_template)
|
||||
assert 'callback' not in related
|
||||
|
||||
|
||||
class TestJobTemplateSerializerGetSummaryFields():
|
||||
def test_survey_spec_exists(self, test_get_summary_fields, mocker, job_template):
|
||||
job_template.survey_spec = {'name': 'blah', 'description': 'blah blah'}
|
||||
with mocker.patch.object(JobTemplateSerializer, '_recent_jobs') as mock_rj:
|
||||
mock_rj.return_value = []
|
||||
test_get_summary_fields(JobTemplateSerializer, job_template, 'survey')
|
||||
|
||||
def test_survey_spec_absent(self, get_summary_fields_mock_and_run, mocker, job_template):
|
||||
job_template.survey_spec = None
|
||||
with mocker.patch.object(JobTemplateSerializer, '_recent_jobs') as mock_rj:
|
||||
mock_rj.return_value = []
|
||||
summary = get_summary_fields_mock_and_run(JobTemplateSerializer, job_template)
|
||||
assert 'survey' not in summary
|
||||
|
||||
def test_copy_edit_standard(self, mocker, job_template_factory):
|
||||
"""Verify that the exact output of the access.py methods
|
||||
are put into the serializer user_capabilities"""
|
||||
|
||||
jt_obj = job_template_factory('testJT', project='proj1', persisted=False).job_template
|
||||
jt_obj.admin_role = Role(id=9, role_field='admin_role')
|
||||
jt_obj.execute_role = Role(id=8, role_field='execute_role')
|
||||
jt_obj.read_role = Role(id=7, role_field='execute_role')
|
||||
user = User(username="auser")
|
||||
serializer = JobTemplateSerializer(job_template)
|
||||
serializer.show_capabilities = ['copy', 'edit']
|
||||
serializer._summary_field_labels = lambda self: []
|
||||
serializer._recent_jobs = lambda self: []
|
||||
request = APIRequestFactory().get('/api/v2/job_templates/42/')
|
||||
request.user = user
|
||||
view = JobTemplateDetail()
|
||||
view.request = request
|
||||
view.kwargs = {}
|
||||
serializer.context['view'] = view
|
||||
|
||||
with mocker.patch("awx.api.serializers.role_summary_fields_generator", return_value='Can eat pie'):
|
||||
with mocker.patch("awx.main.access.JobTemplateAccess.can_change", return_value='foobar'):
|
||||
with mocker.patch("awx.main.access.JobTemplateAccess.can_copy", return_value='foo'):
|
||||
response = serializer.get_summary_fields(jt_obj)
|
||||
|
||||
assert response['user_capabilities']['copy'] == 'foo'
|
||||
assert response['user_capabilities']['edit'] == 'foobar'
|
||||
|
||||
|
||||
class TestJobTemplateSerializerValidation(object):
|
||||
good_extra_vars = ["{\"test\": \"keys\"}", "---\ntest: key"]
|
||||
bad_extra_vars = ["{\"test\": \"keys\"", "---\ntest: [2"]
|
||||
|
||||
def test_validate_extra_vars(self):
|
||||
serializer = JobTemplateSerializer()
|
||||
for ev in self.good_extra_vars:
|
||||
serializer.validate_extra_vars(ev)
|
||||
for ev in self.bad_extra_vars:
|
||||
with pytest.raises(serializers.ValidationError):
|
||||
serializer.validate_extra_vars(ev)
|
||||
@@ -0,0 +1,59 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import pytest
|
||||
from rest_framework.serializers import ValidationError
|
||||
|
||||
# AWX
|
||||
from awx.api.serializers import NotificationTemplateSerializer
|
||||
|
||||
|
||||
class StubNotificationTemplate():
|
||||
notification_type = 'email'
|
||||
|
||||
|
||||
class TestNotificationTemplateSerializer():
|
||||
|
||||
@pytest.mark.parametrize('valid_messages',
|
||||
[None,
|
||||
{'started': None},
|
||||
{'started': {'message': None}},
|
||||
{'started': {'message': 'valid'}},
|
||||
{'started': {'body': 'valid'}},
|
||||
{'started': {'message': 'valid', 'body': 'valid'}},
|
||||
{'started': None, 'success': None, 'error': None},
|
||||
{'started': {'message': None, 'body': None},
|
||||
'success': {'message': None, 'body': None},
|
||||
'error': {'message': None, 'body': None}},
|
||||
{'started': {'message': '{{ job.id }}', 'body': '{{ job.status }}'},
|
||||
'success': {'message': None, 'body': '{{ job_friendly_name }}'},
|
||||
'error': {'message': '{{ url }}', 'body': None}},
|
||||
{'started': {'body': '{{ job_metadata }}'}},
|
||||
{'started': {'body': '{{ job.summary_fields.inventory.total_hosts }}'}},
|
||||
{'started': {'body': u'Iñtërnâtiônàlizætiøn'}}
|
||||
])
|
||||
def test_valid_messages(self, valid_messages):
|
||||
serializer = NotificationTemplateSerializer()
|
||||
serializer.instance = StubNotificationTemplate()
|
||||
serializer.validate_messages(valid_messages)
|
||||
|
||||
@pytest.mark.parametrize('invalid_messages',
|
||||
[1,
|
||||
[],
|
||||
'',
|
||||
{'invalid_event': ''},
|
||||
{'started': 'should_be_dict'},
|
||||
{'started': {'bad_message_type': ''}},
|
||||
{'started': {'message': 1}},
|
||||
{'started': {'message': []}},
|
||||
{'started': {'message': {}}},
|
||||
{'started': {'message': '{{ unclosed_braces'}},
|
||||
{'started': {'message': '{{ undefined }}'}},
|
||||
{'started': {'message': '{{ job.undefined }}'}},
|
||||
{'started': {'message': '{{ job.id | bad_filter }}'}},
|
||||
{'started': {'message': '{{ job.__class__ }}'}},
|
||||
{'started': {'message': 'Newlines \n not allowed\n'}},
|
||||
])
|
||||
def test_invalid__messages(self, invalid_messages):
|
||||
serializer = NotificationTemplateSerializer()
|
||||
serializer.instance = StubNotificationTemplate()
|
||||
with pytest.raises(ValidationError):
|
||||
serializer.validate_messages(invalid_messages)
|
||||
@@ -0,0 +1,16 @@
|
||||
# Python
|
||||
import pytest
|
||||
|
||||
# Django Rest Framework
|
||||
from rest_framework.exceptions import ValidationError
|
||||
|
||||
# AWX
|
||||
from awx.api.serializers import JobLaunchSerializer
|
||||
|
||||
|
||||
def test_primary_key_related_field():
|
||||
# We are testing if the PrimaryKeyRelatedField in this serializer can take dictionary.
|
||||
# PrimaryKeyRelatedField should not be able to take dictionary as input, and should raise a ValidationError.
|
||||
data = {'credentials' : {'1': '2', '3':'4'}}
|
||||
with pytest.raises(ValidationError):
|
||||
JobLaunchSerializer(data=data)
|
||||
@@ -0,0 +1,14 @@
|
||||
import pytest
|
||||
|
||||
from awx.api.serializers import OAuth2TokenSerializer
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scope, expect', [
|
||||
('', False),
|
||||
('read', True),
|
||||
('read read', False),
|
||||
('write read', True),
|
||||
('read rainbow', False)
|
||||
])
|
||||
def test_invalid_scopes(scope, expect):
|
||||
assert OAuth2TokenSerializer()._is_valid_scope(scope) is expect
|
||||
@@ -0,0 +1,69 @@
|
||||
# AWX
|
||||
from awx.api import serializers
|
||||
from awx.main.models import UnifiedJob, UnifiedJobTemplate
|
||||
|
||||
# DRF
|
||||
from rest_framework.generics import ListAPIView
|
||||
|
||||
|
||||
def test_unified_template_field_consistency():
|
||||
'''
|
||||
Example of what is being tested:
|
||||
The endpoints /projects/N/ and /projects/ should have the same fields as
|
||||
that same project when it is serialized by the unified job template serializer
|
||||
in /unified_job_templates/
|
||||
'''
|
||||
for cls in UnifiedJobTemplate.__subclasses__():
|
||||
detail_serializer = getattr(serializers, '{}Serializer'.format(cls.__name__))
|
||||
unified_serializer = serializers.UnifiedJobTemplateSerializer().get_sub_serializer(cls())
|
||||
assert set(detail_serializer().fields.keys()) == set(unified_serializer().fields.keys())
|
||||
|
||||
|
||||
def test_unified_job_list_field_consistency():
|
||||
'''
|
||||
Example of what is being tested:
|
||||
The endpoint /project_updates/ should have the same fields as that
|
||||
project update when it is serialized by the unified job template serializer
|
||||
in /unified_jobs/
|
||||
'''
|
||||
for cls in UnifiedJob.__subclasses__():
|
||||
list_serializer = getattr(serializers, '{}ListSerializer'.format(cls.__name__))
|
||||
unified_serializer = serializers.UnifiedJobListSerializer().get_sub_serializer(cls())
|
||||
assert set(list_serializer().fields.keys()) == set(unified_serializer().fields.keys()), (
|
||||
'Mismatch between {} list serializer & unified list serializer'.format(cls)
|
||||
)
|
||||
|
||||
|
||||
def test_unified_job_detail_exclusive_fields():
|
||||
'''
|
||||
For each type, assert that the only fields allowed to be exclusive to
|
||||
detail view are the allowed types
|
||||
'''
|
||||
allowed_detail_fields = frozenset(
|
||||
('result_traceback', 'job_args', 'job_cwd', 'job_env', 'event_processing_finished')
|
||||
)
|
||||
for cls in UnifiedJob.__subclasses__():
|
||||
list_serializer = getattr(serializers, '{}ListSerializer'.format(cls.__name__))
|
||||
detail_serializer = getattr(serializers, '{}Serializer'.format(cls.__name__))
|
||||
list_fields = set(list_serializer().fields.keys())
|
||||
detail_fields = set(detail_serializer().fields.keys()) - allowed_detail_fields
|
||||
assert list_fields == detail_fields, 'List / detail mismatch for serializers of {}'.format(cls)
|
||||
|
||||
|
||||
def test_list_views_use_list_serializers(all_views):
|
||||
'''
|
||||
Check that the list serializers are only used for list views,
|
||||
and vice versa
|
||||
'''
|
||||
list_serializers = tuple(
|
||||
getattr(serializers, '{}ListSerializer'.format(cls.__name__)) for
|
||||
cls in (UnifiedJob.__subclasses__() + [UnifiedJob])
|
||||
)
|
||||
for View in all_views:
|
||||
if hasattr(View, 'model') and issubclass(getattr(View, 'model'), UnifiedJob):
|
||||
if issubclass(View, ListAPIView):
|
||||
assert issubclass(View.serializer_class, list_serializers), (
|
||||
'View {} serializer {} is not a list serializer'.format(View, View.serializer_class)
|
||||
)
|
||||
else:
|
||||
assert not issubclass(View.model, list_serializers)
|
||||
@@ -0,0 +1,285 @@
|
||||
# Python
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
# AWX
|
||||
from awx.api.serializers import (
|
||||
WorkflowJobTemplateSerializer,
|
||||
WorkflowJobTemplateNodeSerializer,
|
||||
WorkflowJobNodeSerializer,
|
||||
)
|
||||
from awx.main.models import (
|
||||
Job,
|
||||
WorkflowJobTemplateNode,
|
||||
WorkflowJob,
|
||||
WorkflowJobNode,
|
||||
WorkflowJobTemplate,
|
||||
Project,
|
||||
Inventory,
|
||||
JobTemplate
|
||||
)
|
||||
|
||||
|
||||
@mock.patch('awx.api.serializers.UnifiedJobTemplateSerializer.get_related', lambda x,y: {})
|
||||
class TestWorkflowJobTemplateSerializerGetRelated():
|
||||
@pytest.fixture
|
||||
def workflow_job_template(self, workflow_job_template_factory):
|
||||
wfjt = workflow_job_template_factory('hello world', persisted=False).workflow_job_template
|
||||
wfjt.pk = 3
|
||||
return wfjt
|
||||
|
||||
@pytest.mark.parametrize("related_resource_name", [
|
||||
'workflow_jobs',
|
||||
'launch',
|
||||
'workflow_nodes',
|
||||
'webhook_key',
|
||||
])
|
||||
def test_get_related(self, mocker, test_get_related, workflow_job_template, related_resource_name):
|
||||
test_get_related(WorkflowJobTemplateSerializer,
|
||||
workflow_job_template,
|
||||
'workflow_job_templates',
|
||||
related_resource_name)
|
||||
|
||||
|
||||
@mock.patch('awx.api.serializers.BaseSerializer.get_related', lambda x,y: {})
|
||||
class TestWorkflowNodeBaseSerializerGetRelated():
|
||||
@pytest.fixture
|
||||
def job_template(self, job_template_factory):
|
||||
jt = job_template_factory(name="blah", persisted=False).job_template
|
||||
jt.pk = 1
|
||||
return jt
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_job_template_node_related(self, job_template):
|
||||
return WorkflowJobTemplateNode(pk=1, unified_job_template=job_template)
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_job_template_node(self):
|
||||
return WorkflowJobTemplateNode(pk=1)
|
||||
|
||||
def test_workflow_unified_job_template_present(self, get_related_mock_and_run, workflow_job_template_node_related):
|
||||
related = get_related_mock_and_run(WorkflowJobTemplateNodeSerializer, workflow_job_template_node_related)
|
||||
assert 'unified_job_template' in related
|
||||
assert related['unified_job_template'] == '/api/v2/%s/%d/' % ('job_templates', workflow_job_template_node_related.unified_job_template.pk)
|
||||
|
||||
def test_workflow_unified_job_template_absent(self, workflow_job_template_node):
|
||||
related = WorkflowJobTemplateNodeSerializer().get_related(workflow_job_template_node)
|
||||
assert 'unified_job_template' not in related
|
||||
|
||||
|
||||
@mock.patch('awx.api.serializers.BaseSerializer.get_related', lambda x,y: {})
|
||||
class TestWorkflowJobTemplateNodeSerializerGetRelated():
|
||||
@pytest.fixture
|
||||
def workflow_job_template_node(self):
|
||||
return WorkflowJobTemplateNode(pk=1)
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_job_template(self, workflow_job_template_factory):
|
||||
wfjt = workflow_job_template_factory("bliggity", persisted=False).workflow_job_template
|
||||
wfjt.pk = 1
|
||||
return wfjt
|
||||
|
||||
@pytest.fixture
|
||||
def job_template(self, job_template_factory):
|
||||
jt = job_template_factory(name="blah", persisted=False).job_template
|
||||
jt.pk = 1
|
||||
return jt
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_job_template_node_related(self, workflow_job_template_node, workflow_job_template):
|
||||
workflow_job_template_node.workflow_job_template = workflow_job_template
|
||||
return workflow_job_template_node
|
||||
|
||||
@pytest.mark.parametrize("related_resource_name", [
|
||||
'success_nodes',
|
||||
'failure_nodes',
|
||||
'always_nodes',
|
||||
])
|
||||
def test_get_related(self, test_get_related, workflow_job_template_node, related_resource_name):
|
||||
test_get_related(WorkflowJobTemplateNodeSerializer,
|
||||
workflow_job_template_node,
|
||||
'workflow_job_template_nodes',
|
||||
related_resource_name)
|
||||
|
||||
def test_workflow_job_template_present(self, get_related_mock_and_run, workflow_job_template_node_related):
|
||||
related = get_related_mock_and_run(WorkflowJobTemplateNodeSerializer, workflow_job_template_node_related)
|
||||
assert 'workflow_job_template' in related
|
||||
assert related['workflow_job_template'] == '/api/v2/%s/%d/' % ('workflow_job_templates', workflow_job_template_node_related.workflow_job_template.pk)
|
||||
|
||||
def test_workflow_job_template_absent(self, workflow_job_template_node):
|
||||
related = WorkflowJobTemplateNodeSerializer().get_related(workflow_job_template_node)
|
||||
assert 'workflow_job_template' not in related
|
||||
|
||||
|
||||
class FakeView:
|
||||
def __init__(self, obj):
|
||||
self.obj = obj
|
||||
|
||||
def get_object(self):
|
||||
return self.obj
|
||||
|
||||
|
||||
class FakeRequest:
|
||||
pass
|
||||
|
||||
|
||||
class TestWorkflowJobTemplateNodeSerializerCharPrompts():
|
||||
@pytest.fixture
|
||||
def WFJT_serializer(self):
|
||||
serializer = WorkflowJobTemplateNodeSerializer()
|
||||
node = WorkflowJobTemplateNode(pk=1)
|
||||
node.char_prompts = {'limit': 'webservers'}
|
||||
|
||||
view = FakeView(node)
|
||||
view.request = FakeRequest()
|
||||
view.request.method = "PATCH"
|
||||
|
||||
serializer = WorkflowJobTemplateNodeSerializer()
|
||||
serializer = WorkflowJobTemplateNodeSerializer(context={'view':view})
|
||||
serializer.instance = node
|
||||
|
||||
return serializer
|
||||
|
||||
def test_change_single_field(self, WFJT_serializer):
|
||||
"Test that a single prompt field can be changed without affecting other fields"
|
||||
internal_value = WFJT_serializer.to_internal_value({'job_type': 'check'})
|
||||
assert internal_value['job_type'] == 'check'
|
||||
WFJT_serializer.instance.job_type = 'check'
|
||||
assert WFJT_serializer.instance.limit == 'webservers'
|
||||
|
||||
def test_null_single_field(self, WFJT_serializer):
|
||||
"Test that a single prompt field can be removed without affecting other fields"
|
||||
internal_value = WFJT_serializer.to_internal_value({'job_type': None})
|
||||
assert internal_value['job_type'] is None
|
||||
WFJT_serializer.instance.job_type = None
|
||||
assert WFJT_serializer.instance.limit == 'webservers'
|
||||
|
||||
|
||||
@mock.patch('awx.api.serializers.BaseSerializer.validate', lambda self, attrs: attrs)
|
||||
class TestWorkflowJobTemplateNodeSerializerSurveyPasswords():
|
||||
|
||||
@pytest.fixture
|
||||
def jt(self, survey_spec_factory):
|
||||
return JobTemplate(
|
||||
name='fake-jt',
|
||||
survey_enabled=True,
|
||||
survey_spec=survey_spec_factory(variables='var1', default_type='password'),
|
||||
project=Project('fake-proj'), project_id=42,
|
||||
inventory=Inventory('fake-inv'), inventory_id=42
|
||||
)
|
||||
|
||||
def test_set_survey_passwords_create(self, jt):
|
||||
serializer = WorkflowJobTemplateNodeSerializer()
|
||||
wfjt = WorkflowJobTemplate(name='fake-wfjt')
|
||||
attrs = serializer.validate({
|
||||
'unified_job_template': jt,
|
||||
'workflow_job_template': wfjt,
|
||||
'extra_data': {'var1': 'secret_answer'}
|
||||
})
|
||||
assert 'survey_passwords' in attrs
|
||||
assert 'var1' in attrs['survey_passwords']
|
||||
assert attrs['extra_data']['var1'].startswith('$encrypted$')
|
||||
assert len(attrs['extra_data']['var1']) > len('$encrypted$')
|
||||
|
||||
def test_set_survey_passwords_modify(self, jt):
|
||||
serializer = WorkflowJobTemplateNodeSerializer()
|
||||
wfjt = WorkflowJobTemplate(name='fake-wfjt')
|
||||
serializer.instance = WorkflowJobTemplateNode(
|
||||
workflow_job_template=wfjt,
|
||||
unified_job_template=jt
|
||||
)
|
||||
attrs = serializer.validate({
|
||||
'unified_job_template': jt,
|
||||
'workflow_job_template': wfjt,
|
||||
'extra_data': {'var1': 'secret_answer'}
|
||||
})
|
||||
assert 'survey_passwords' in attrs
|
||||
assert 'var1' in attrs['survey_passwords']
|
||||
assert attrs['extra_data']['var1'].startswith('$encrypted$')
|
||||
assert len(attrs['extra_data']['var1']) > len('$encrypted$')
|
||||
|
||||
def test_use_db_answer(self, jt, mocker):
|
||||
serializer = WorkflowJobTemplateNodeSerializer()
|
||||
wfjt = WorkflowJobTemplate(name='fake-wfjt')
|
||||
serializer.instance = WorkflowJobTemplateNode(
|
||||
workflow_job_template=wfjt,
|
||||
unified_job_template=jt,
|
||||
extra_data={'var1': '$encrypted$foooooo'}
|
||||
)
|
||||
with mocker.patch('awx.main.models.mixins.decrypt_value', return_value='foo'):
|
||||
attrs = serializer.validate({
|
||||
'unified_job_template': jt,
|
||||
'workflow_job_template': wfjt,
|
||||
'extra_data': {'var1': '$encrypted$'}
|
||||
})
|
||||
assert 'survey_passwords' in attrs
|
||||
assert 'var1' in attrs['survey_passwords']
|
||||
assert attrs['extra_data']['var1'] == '$encrypted$foooooo'
|
||||
|
||||
def test_accept_password_default(self, jt, mocker):
|
||||
'''
|
||||
If user provides "$encrypted$" without a corresponding DB value for the
|
||||
node, but survey question has a default, then variables are accepted
|
||||
with that particular var omitted so on launch time the default takes effect
|
||||
'''
|
||||
serializer = WorkflowJobTemplateNodeSerializer()
|
||||
wfjt = WorkflowJobTemplate(name='fake-wfjt')
|
||||
jt.survey_spec['spec'][0]['default'] = '$encrypted$bar'
|
||||
attrs = serializer.validate({
|
||||
'unified_job_template': jt,
|
||||
'workflow_job_template': wfjt,
|
||||
'extra_data': {'var1': '$encrypted$'}
|
||||
})
|
||||
assert 'survey_passwords' in attrs
|
||||
assert attrs['survey_passwords'] == {}
|
||||
assert attrs['extra_data'] == {}
|
||||
|
||||
|
||||
@mock.patch('awx.api.serializers.WorkflowJobTemplateNodeSerializer.get_related', lambda x,y: {})
|
||||
class TestWorkflowJobNodeSerializerGetRelated():
|
||||
@pytest.fixture
|
||||
def workflow_job_node(self):
|
||||
return WorkflowJobNode(pk=1)
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_job(self):
|
||||
return WorkflowJob(pk=1)
|
||||
|
||||
@pytest.fixture
|
||||
def job(self):
|
||||
return Job(name="blah", pk=1)
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_job_node_related(self, workflow_job_node, workflow_job, job):
|
||||
workflow_job_node.workflow_job = workflow_job
|
||||
workflow_job_node.job = job
|
||||
return workflow_job_node
|
||||
|
||||
@pytest.mark.parametrize("related_resource_name", [
|
||||
'success_nodes',
|
||||
'failure_nodes',
|
||||
'always_nodes',
|
||||
])
|
||||
def test_get_related(self, test_get_related, workflow_job_node, related_resource_name):
|
||||
test_get_related(WorkflowJobNodeSerializer,
|
||||
workflow_job_node,
|
||||
'workflow_job_nodes',
|
||||
related_resource_name)
|
||||
|
||||
def test_workflow_job_present(self, get_related_mock_and_run, workflow_job_node_related):
|
||||
related = get_related_mock_and_run(WorkflowJobNodeSerializer, workflow_job_node_related)
|
||||
assert 'workflow_job' in related
|
||||
assert related['workflow_job'] == '/api/v2/%s/%d/' % ('workflow_jobs', workflow_job_node_related.workflow_job.pk)
|
||||
|
||||
def test_workflow_job_absent(self, workflow_job_node):
|
||||
related = WorkflowJobNodeSerializer().get_related(workflow_job_node)
|
||||
assert 'workflow_job' not in related
|
||||
|
||||
def test_job_present(self, get_related_mock_and_run, workflow_job_node_related):
|
||||
related = get_related_mock_and_run(WorkflowJobNodeSerializer, workflow_job_node_related)
|
||||
assert 'job' in related
|
||||
assert related['job'] == '/api/v2/%s/%d/' % ('jobs', workflow_job_node_related.job.pk)
|
||||
|
||||
def test_job_absent(self, workflow_job_node):
|
||||
related = WorkflowJobNodeSerializer().get_related(workflow_job_node)
|
||||
assert 'job' not in related
|
||||
@@ -0,0 +1,112 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import pytest
|
||||
|
||||
from rest_framework.exceptions import PermissionDenied, ParseError
|
||||
from awx.api.filters import FieldLookupBackend, OrderByBackend, get_field_from_path
|
||||
from awx.main.models import (AdHocCommand, ActivityStream,
|
||||
CustomInventoryScript, Credential, Job,
|
||||
JobTemplate, SystemJob, UnifiedJob, User,
|
||||
WorkflowJob, WorkflowJobTemplate,
|
||||
WorkflowJobOptions, InventorySource,
|
||||
JobEvent)
|
||||
from awx.main.models.oauth import OAuth2Application
|
||||
from awx.main.models.jobs import JobOptions
|
||||
|
||||
# Django
|
||||
from django.db.models.fields import FieldDoesNotExist
|
||||
|
||||
|
||||
def test_related():
|
||||
field_lookup = FieldLookupBackend()
|
||||
lookup = '__'.join(['inventory', 'organization', 'pk'])
|
||||
field, new_lookup = field_lookup.get_field_from_lookup(InventorySource, lookup)
|
||||
print(field)
|
||||
print(new_lookup)
|
||||
|
||||
|
||||
def test_invalid_filter_key():
|
||||
field_lookup = FieldLookupBackend()
|
||||
# FieldDoesNotExist is caught and converted to ParseError by filter_queryset
|
||||
with pytest.raises(FieldDoesNotExist) as excinfo:
|
||||
field_lookup.value_to_python(JobEvent, 'event_data.task_action', 'foo')
|
||||
assert 'has no field named' in str(excinfo)
|
||||
|
||||
|
||||
def test_invalid_field_hop():
|
||||
with pytest.raises(ParseError) as excinfo:
|
||||
get_field_from_path(Credential, 'organization__description__user')
|
||||
assert 'No related model for' in str(excinfo)
|
||||
|
||||
|
||||
def test_invalid_order_by_key():
|
||||
field_order_by = OrderByBackend()
|
||||
with pytest.raises(ParseError) as excinfo:
|
||||
[f for f in field_order_by._validate_ordering_fields(JobEvent, ('event_data.task_action',))]
|
||||
assert 'has no field named' in str(excinfo)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(u"empty_value", [u'', ''])
|
||||
def test_empty_in(empty_value):
|
||||
field_lookup = FieldLookupBackend()
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
field_lookup.value_to_python(JobTemplate, 'project__name__in', empty_value)
|
||||
assert 'empty value for __in' in str(excinfo.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(u"valid_value", [u'foo', u'foo,'])
|
||||
def test_valid_in(valid_value):
|
||||
field_lookup = FieldLookupBackend()
|
||||
value, new_lookup, _ = field_lookup.value_to_python(JobTemplate, 'project__name__in', valid_value)
|
||||
assert 'foo' in value
|
||||
|
||||
|
||||
def test_invalid_field():
|
||||
invalid_field = u"ヽヾ"
|
||||
field_lookup = FieldLookupBackend()
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
field_lookup.value_to_python(WorkflowJobTemplate, invalid_field, 'foo')
|
||||
assert 'is not an allowed field name. Must be ascii encodable.' in str(excinfo.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('lookup_suffix', ['', 'contains', 'startswith', 'in'])
|
||||
@pytest.mark.parametrize('password_field', Credential.PASSWORD_FIELDS)
|
||||
def test_filter_on_password_field(password_field, lookup_suffix):
|
||||
field_lookup = FieldLookupBackend()
|
||||
lookup = '__'.join(filter(None, [password_field, lookup_suffix]))
|
||||
with pytest.raises(PermissionDenied) as excinfo:
|
||||
field, new_lookup = field_lookup.get_field_from_lookup(Credential, lookup)
|
||||
assert 'not allowed' in str(excinfo.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('model, query', [
|
||||
(User, 'password__icontains'),
|
||||
(User, 'settings__value__icontains'),
|
||||
(User, 'main_oauth2accesstoken__token__gt'),
|
||||
(UnifiedJob, 'job_args__icontains'),
|
||||
(UnifiedJob, 'job_env__icontains'),
|
||||
(UnifiedJob, 'start_args__icontains'),
|
||||
(AdHocCommand, 'extra_vars__icontains'),
|
||||
(JobOptions, 'extra_vars__icontains'),
|
||||
(SystemJob, 'extra_vars__icontains'),
|
||||
(WorkflowJobOptions, 'extra_vars__icontains'),
|
||||
(Job, 'survey_passwords__icontains'),
|
||||
(WorkflowJob, 'survey_passwords__icontains'),
|
||||
(JobTemplate, 'survey_spec__icontains'),
|
||||
(WorkflowJobTemplate, 'survey_spec__icontains'),
|
||||
(CustomInventoryScript, 'script__icontains'),
|
||||
(ActivityStream, 'o_auth2_application__client_secret__gt'),
|
||||
(OAuth2Application, 'grant__code__gt')
|
||||
])
|
||||
def test_filter_sensitive_fields_and_relations(model, query):
|
||||
field_lookup = FieldLookupBackend()
|
||||
with pytest.raises(PermissionDenied) as excinfo:
|
||||
field, new_lookup = field_lookup.get_field_from_lookup(model, query)
|
||||
assert 'not allowed' in str(excinfo.value)
|
||||
|
||||
|
||||
def test_looping_filters_prohibited():
|
||||
field_lookup = FieldLookupBackend()
|
||||
with pytest.raises(ParseError) as loop_exc:
|
||||
field_lookup.get_field_from_lookup(Job, 'job_events__job__job_events')
|
||||
assert 'job_events' in str(loop_exc.value)
|
||||
@@ -0,0 +1,217 @@
|
||||
|
||||
# Python
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
# DRF
|
||||
from rest_framework import status
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.exceptions import PermissionDenied
|
||||
|
||||
# AWX
|
||||
from awx.api.generics import (
|
||||
ParentMixin,
|
||||
SubListCreateAttachDetachAPIView, SubListAttachDetachAPIView,
|
||||
ResourceAccessList,
|
||||
ListAPIView
|
||||
)
|
||||
from awx.main.models import Organization, Credential
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def get_object_or_404(mocker):
|
||||
# pytest patch without return_value generates a random value, we are counting on this
|
||||
return mocker.patch('awx.api.generics.get_object_or_404')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def get_object_or_400(mocker):
|
||||
return mocker.patch('awx.api.generics.get_object_or_400')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_organization():
|
||||
return Organization(pk=4, name="Unsaved Org")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def parent_relationship_factory(mocker):
|
||||
def rf(serializer_class, relationship_name, relationship_value=mocker.Mock()):
|
||||
mock_parent_relationship = mocker.MagicMock(**{'%s.add.return_value' % relationship_name: relationship_value})
|
||||
mocker.patch('awx.api.generics.ParentMixin.get_parent_object', return_value=mock_parent_relationship)
|
||||
|
||||
serializer = serializer_class()
|
||||
[setattr(serializer, x, '') for x in ['relationship', 'model', 'parent_model']]
|
||||
serializer.relationship = relationship_name
|
||||
|
||||
return (serializer, mock_parent_relationship)
|
||||
return rf
|
||||
|
||||
|
||||
# TODO: Test create and associate failure (i.e. id doesn't exist, record already exists, permission denied)
|
||||
# TODO: Mock and check return (Response)
|
||||
class TestSubListCreateAttachDetachAPIView:
|
||||
def test_attach_validate_ok(self, mocker):
|
||||
mock_request = mocker.MagicMock(data=dict(id=1))
|
||||
serializer = SubListCreateAttachDetachAPIView()
|
||||
|
||||
(sub_id, res) = serializer.attach_validate(mock_request)
|
||||
|
||||
assert sub_id == 1
|
||||
assert res is None
|
||||
|
||||
def test_attach_validate_invalid_type(self, mocker):
|
||||
mock_request = mocker.MagicMock(data=dict(id='foobar'))
|
||||
serializer = SubListCreateAttachDetachAPIView()
|
||||
|
||||
(sub_id, res) = serializer.attach_validate(mock_request)
|
||||
|
||||
assert type(res) is Response
|
||||
|
||||
def test_attach_create_and_associate(self, mocker, get_object_or_400, parent_relationship_factory):
|
||||
(serializer, mock_parent_relationship) = parent_relationship_factory(SubListCreateAttachDetachAPIView, 'wife')
|
||||
create_return_value = mocker.MagicMock(status_code=status.HTTP_201_CREATED)
|
||||
serializer.create = mocker.Mock(return_value=create_return_value)
|
||||
|
||||
mock_request = mocker.MagicMock(data=dict())
|
||||
serializer.attach(mock_request, None, None)
|
||||
|
||||
serializer.create.assert_called_with(mock_request, None, None)
|
||||
mock_parent_relationship.wife.add.assert_called_with(get_object_or_400.return_value)
|
||||
|
||||
def test_attach_associate_only(self, mocker, get_object_or_400, parent_relationship_factory):
|
||||
(serializer, mock_parent_relationship) = parent_relationship_factory(SubListCreateAttachDetachAPIView, 'wife')
|
||||
serializer.create = mocker.Mock(return_value=mocker.MagicMock())
|
||||
|
||||
mock_request = mocker.MagicMock(data=dict(id=1))
|
||||
serializer.attach(mock_request, None, None)
|
||||
|
||||
serializer.create.assert_not_called()
|
||||
mock_parent_relationship.wife.add.assert_called_with(get_object_or_400.return_value)
|
||||
|
||||
def test_unattach_validate_ok(self, mocker):
|
||||
mock_request = mocker.MagicMock(data=dict(id=1))
|
||||
serializer = SubListCreateAttachDetachAPIView()
|
||||
|
||||
(sub_id, res) = serializer.unattach_validate(mock_request)
|
||||
|
||||
assert sub_id == 1
|
||||
assert res is None
|
||||
|
||||
def test_unattach_validate_invalid_type(self, mocker):
|
||||
mock_request = mocker.MagicMock(data=dict(id='foobar'))
|
||||
serializer = SubListCreateAttachDetachAPIView()
|
||||
|
||||
(sub_id, res) = serializer.unattach_validate(mock_request)
|
||||
|
||||
assert type(res) is Response
|
||||
|
||||
def test_unattach_validate_missing_id(self, mocker):
|
||||
mock_request = mocker.MagicMock(data=dict())
|
||||
serializer = SubListCreateAttachDetachAPIView()
|
||||
|
||||
(sub_id, res) = serializer.unattach_validate(mock_request)
|
||||
|
||||
assert sub_id is None
|
||||
assert type(res) is Response
|
||||
|
||||
def test_unattach_by_id_ok(self, mocker, parent_relationship_factory, get_object_or_400):
|
||||
(serializer, mock_parent_relationship) = parent_relationship_factory(SubListCreateAttachDetachAPIView, 'wife')
|
||||
mock_request = mocker.MagicMock()
|
||||
mock_sub = mocker.MagicMock(name="object to unattach")
|
||||
get_object_or_400.return_value = mock_sub
|
||||
|
||||
res = serializer.unattach_by_id(mock_request, 1)
|
||||
|
||||
assert type(res) is Response
|
||||
assert res.status_code == status.HTTP_204_NO_CONTENT
|
||||
mock_parent_relationship.wife.remove.assert_called_with(mock_sub)
|
||||
|
||||
def test_unattach_ok(self, mocker):
|
||||
mock_request = mocker.MagicMock()
|
||||
mock_sub_id = mocker.MagicMock()
|
||||
view = SubListCreateAttachDetachAPIView()
|
||||
view.unattach_validate = mocker.MagicMock()
|
||||
view.unattach_by_id = mocker.MagicMock()
|
||||
view.unattach_validate.return_value = (mock_sub_id, None)
|
||||
|
||||
view.unattach(mock_request)
|
||||
|
||||
view.unattach_validate.assert_called_with(mock_request)
|
||||
view.unattach_by_id.assert_called_with(mock_request, mock_sub_id)
|
||||
|
||||
def test_unattach_invalid(self, mocker):
|
||||
mock_request = mocker.MagicMock()
|
||||
mock_res = mocker.MagicMock()
|
||||
view = SubListCreateAttachDetachAPIView()
|
||||
view.unattach_validate = mocker.MagicMock()
|
||||
view.unattach_by_id = mocker.MagicMock()
|
||||
view.unattach_validate.return_value = (None, mock_res)
|
||||
|
||||
view.unattach(mock_request)
|
||||
|
||||
view.unattach_validate.assert_called_with(mock_request)
|
||||
view.unattach_by_id.assert_not_called()
|
||||
|
||||
|
||||
def test_attach_detatch_only(mocker):
|
||||
mock_request = mocker.MagicMock()
|
||||
mock_request.data = {'name': 'name for my new model'}
|
||||
view = SubListAttachDetachAPIView()
|
||||
view.model = mocker.MagicMock()
|
||||
view.model._meta = mocker.MagicMock()
|
||||
view.model._meta.verbose_name = "Foo Bar"
|
||||
|
||||
resp = view.post(mock_request)
|
||||
|
||||
assert 'Foo Bar' in resp.data['msg']
|
||||
assert 'field is missing' in resp.data['msg']
|
||||
|
||||
|
||||
class TestParentMixin:
|
||||
def test_get_parent_object(self, mocker, get_object_or_404):
|
||||
parent_mixin = ParentMixin()
|
||||
parent_mixin.lookup_field = 'foo'
|
||||
parent_mixin.kwargs = dict(foo='bar')
|
||||
parent_mixin.parent_model = 'parent_model'
|
||||
mock_parent_mixin = mocker.MagicMock(wraps=parent_mixin)
|
||||
|
||||
return_value = mock_parent_mixin.get_parent_object()
|
||||
|
||||
get_object_or_404.assert_called_with(parent_mixin.parent_model, **parent_mixin.kwargs)
|
||||
assert get_object_or_404.return_value == return_value
|
||||
|
||||
|
||||
class TestResourceAccessList:
|
||||
|
||||
def mock_request(self):
|
||||
return mock.MagicMock(
|
||||
user=mock.MagicMock(is_anonymous=False, is_superuser=False),
|
||||
method='GET')
|
||||
|
||||
def mock_view(self, parent=None):
|
||||
view = ResourceAccessList()
|
||||
view.parent_model = Organization
|
||||
view.kwargs = {'pk': 4}
|
||||
if parent:
|
||||
view.get_parent_object = lambda: parent
|
||||
return view
|
||||
|
||||
def test_parent_access_check_failed(self, mocker, mock_organization):
|
||||
mock_access = mocker.MagicMock(__name__='for logger', return_value=False)
|
||||
with mocker.patch('awx.main.access.BaseAccess.can_read', mock_access):
|
||||
with pytest.raises(PermissionDenied):
|
||||
self.mock_view(parent=mock_organization).check_permissions(self.mock_request())
|
||||
mock_access.assert_called_once_with(mock_organization)
|
||||
|
||||
def test_parent_access_check_worked(self, mocker, mock_organization):
|
||||
mock_access = mocker.MagicMock(__name__='for logger', return_value=True)
|
||||
with mocker.patch('awx.main.access.BaseAccess.can_read', mock_access):
|
||||
self.mock_view(parent=mock_organization).check_permissions(self.mock_request())
|
||||
mock_access.assert_called_once_with(mock_organization)
|
||||
|
||||
|
||||
def test_related_search_reverse_FK_field():
|
||||
view = ListAPIView()
|
||||
view.model = Credential
|
||||
assert 'unifiedjobtemplates__search' in view.related_search_fields
|
||||
@@ -0,0 +1,196 @@
|
||||
import pytest
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
from awx.main.utils.external_logging import construct_rsyslog_conf_template
|
||||
from awx.main.tests.functional.api.test_settings import _mock_logging_defaults
|
||||
|
||||
'''
|
||||
# Example User Data
|
||||
data_logstash = {
|
||||
"LOG_AGGREGATOR_TYPE": "logstash",
|
||||
"LOG_AGGREGATOR_HOST": "localhost",
|
||||
"LOG_AGGREGATOR_PORT": 8080,
|
||||
"LOG_AGGREGATOR_PROTOCOL": "tcp",
|
||||
"LOG_AGGREGATOR_USERNAME": "logger",
|
||||
"LOG_AGGREGATOR_PASSWORD": "mcstash"
|
||||
}
|
||||
|
||||
data_netcat = {
|
||||
"LOG_AGGREGATOR_TYPE": "other",
|
||||
"LOG_AGGREGATOR_HOST": "localhost",
|
||||
"LOG_AGGREGATOR_PORT": 9000,
|
||||
"LOG_AGGREGATOR_PROTOCOL": "udp",
|
||||
}
|
||||
|
||||
data_loggly = {
|
||||
"LOG_AGGREGATOR_TYPE": "loggly",
|
||||
"LOG_AGGREGATOR_HOST": "http://logs-01.loggly.com/inputs/1fd38090-2af1-4e1e-8d80-492899da0f71/tag/http/",
|
||||
"LOG_AGGREGATOR_PORT": 8080,
|
||||
"LOG_AGGREGATOR_PROTOCOL": "https"
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
# Test reconfigure logging settings function
|
||||
# name this whatever you want
|
||||
@pytest.mark.parametrize(
|
||||
'enabled, log_type, host, port, protocol, errorfile, expected_config', [
|
||||
(
|
||||
True,
|
||||
'loggly',
|
||||
'http://logs-01.loggly.com/inputs/1fd38090-2af1-4e1e-8d80-492899da0f71/tag/http/',
|
||||
None,
|
||||
'https',
|
||||
'/var/log/tower/rsyslog.err',
|
||||
'\n'.join([
|
||||
'template(name="awx" type="string" string="%rawmsg-after-pri%")\nmodule(load="omhttp")',
|
||||
'action(type="omhttp" server="logs-01.loggly.com" serverport="80" usehttps="off" allowunsignedcerts="off" skipverifyhost="off" action.resumeRetryCount="-1" template="awx" action.resumeInterval="5" errorfile="/var/log/tower/rsyslog.err" restpath="inputs/1fd38090-2af1-4e1e-8d80-492899da0f71/tag/http/")', # noqa
|
||||
])
|
||||
),
|
||||
(
|
||||
True, # localhost w/ custom UDP port
|
||||
'other',
|
||||
'localhost',
|
||||
9000,
|
||||
'udp',
|
||||
'', # empty errorfile
|
||||
'\n'.join([
|
||||
'template(name="awx" type="string" string="%rawmsg-after-pri%")',
|
||||
'action(type="omfwd" target="localhost" port="9000" protocol="udp" action.resumeRetryCount="-1" action.resumeInterval="5" template="awx")', # noqa
|
||||
])
|
||||
),
|
||||
(
|
||||
True, # localhost w/ custom TCP port
|
||||
'other',
|
||||
'localhost',
|
||||
9000,
|
||||
'tcp',
|
||||
'/var/log/tower/rsyslog.err',
|
||||
'\n'.join([
|
||||
'template(name="awx" type="string" string="%rawmsg-after-pri%")',
|
||||
'action(type="omfwd" target="localhost" port="9000" protocol="tcp" action.resumeRetryCount="-1" action.resumeInterval="5" template="awx")', # noqa
|
||||
])
|
||||
),
|
||||
(
|
||||
True, # https, default port 443
|
||||
'splunk',
|
||||
'https://yoursplunk/services/collector/event',
|
||||
None,
|
||||
None,
|
||||
'/var/log/tower/rsyslog.err',
|
||||
'\n'.join([
|
||||
'template(name="awx" type="string" string="%rawmsg-after-pri%")\nmodule(load="omhttp")',
|
||||
'action(type="omhttp" server="yoursplunk" serverport="443" usehttps="on" allowunsignedcerts="off" skipverifyhost="off" action.resumeRetryCount="-1" template="awx" action.resumeInterval="5" errorfile="/var/log/tower/rsyslog.err" restpath="services/collector/event")', # noqa
|
||||
])
|
||||
),
|
||||
(
|
||||
True, # http, default port 80
|
||||
'splunk',
|
||||
'http://yoursplunk/services/collector/event',
|
||||
None,
|
||||
None,
|
||||
'/var/log/tower/rsyslog.err',
|
||||
'\n'.join([
|
||||
'template(name="awx" type="string" string="%rawmsg-after-pri%")\nmodule(load="omhttp")',
|
||||
'action(type="omhttp" server="yoursplunk" serverport="80" usehttps="off" allowunsignedcerts="off" skipverifyhost="off" action.resumeRetryCount="-1" template="awx" action.resumeInterval="5" errorfile="/var/log/tower/rsyslog.err" restpath="services/collector/event")', # noqa
|
||||
])
|
||||
),
|
||||
(
|
||||
True, # https, custom port in URL string
|
||||
'splunk',
|
||||
'https://yoursplunk:8088/services/collector/event',
|
||||
None,
|
||||
None,
|
||||
'/var/log/tower/rsyslog.err',
|
||||
'\n'.join([
|
||||
'template(name="awx" type="string" string="%rawmsg-after-pri%")\nmodule(load="omhttp")',
|
||||
'action(type="omhttp" server="yoursplunk" serverport="8088" usehttps="on" allowunsignedcerts="off" skipverifyhost="off" action.resumeRetryCount="-1" template="awx" action.resumeInterval="5" errorfile="/var/log/tower/rsyslog.err" restpath="services/collector/event")', # noqa
|
||||
])
|
||||
),
|
||||
(
|
||||
True, # https, custom port explicitly specified
|
||||
'splunk',
|
||||
'https://yoursplunk/services/collector/event',
|
||||
8088,
|
||||
None,
|
||||
'/var/log/tower/rsyslog.err',
|
||||
'\n'.join([
|
||||
'template(name="awx" type="string" string="%rawmsg-after-pri%")\nmodule(load="omhttp")',
|
||||
'action(type="omhttp" server="yoursplunk" serverport="8088" usehttps="on" allowunsignedcerts="off" skipverifyhost="off" action.resumeRetryCount="-1" template="awx" action.resumeInterval="5" errorfile="/var/log/tower/rsyslog.err" restpath="services/collector/event")', # noqa
|
||||
])
|
||||
),
|
||||
(
|
||||
True, # no scheme specified in URL, default to https, respect custom port
|
||||
'splunk',
|
||||
'yoursplunk.org/services/collector/event',
|
||||
8088,
|
||||
'https',
|
||||
'/var/log/tower/rsyslog.err',
|
||||
'\n'.join([
|
||||
'template(name="awx" type="string" string="%rawmsg-after-pri%")\nmodule(load="omhttp")',
|
||||
'action(type="omhttp" server="yoursplunk.org" serverport="8088" usehttps="on" allowunsignedcerts="off" skipverifyhost="off" action.resumeRetryCount="-1" template="awx" action.resumeInterval="5" errorfile="/var/log/tower/rsyslog.err" restpath="services/collector/event")', # noqa
|
||||
])
|
||||
),
|
||||
(
|
||||
True, # respect custom http-only port
|
||||
'splunk',
|
||||
'http://yoursplunk.org/services/collector/event',
|
||||
8088,
|
||||
None,
|
||||
'/var/log/tower/rsyslog.err',
|
||||
'\n'.join([
|
||||
'template(name="awx" type="string" string="%rawmsg-after-pri%")\nmodule(load="omhttp")',
|
||||
'action(type="omhttp" server="yoursplunk.org" serverport="8088" usehttps="off" allowunsignedcerts="off" skipverifyhost="off" action.resumeRetryCount="-1" template="awx" action.resumeInterval="5" errorfile="/var/log/tower/rsyslog.err" restpath="services/collector/event")', # noqa
|
||||
])
|
||||
),
|
||||
(
|
||||
True, # valid sumologic config
|
||||
'sumologic',
|
||||
'https://endpoint5.collection.us2.sumologic.com/receiver/v1/http/ZaVnC4dhaV0qoiETY0MrM3wwLoDgO1jFgjOxE6-39qokkj3LGtOroZ8wNaN2M6DtgYrJZsmSi4-36_Up5TbbN_8hosYonLKHSSOSKY845LuLZBCBwStrHQ==', # noqa
|
||||
None,
|
||||
'https',
|
||||
'/var/log/tower/rsyslog.err',
|
||||
'\n'.join([
|
||||
'template(name="awx" type="string" string="%rawmsg-after-pri%")\nmodule(load="omhttp")',
|
||||
'action(type="omhttp" server="endpoint5.collection.us2.sumologic.com" serverport="443" usehttps="on" allowunsignedcerts="off" skipverifyhost="off" action.resumeRetryCount="-1" template="awx" action.resumeInterval="5" errorfile="/var/log/tower/rsyslog.err" restpath="receiver/v1/http/ZaVnC4dhaV0qoiETY0MrM3wwLoDgO1jFgjOxE6-39qokkj3LGtOroZ8wNaN2M6DtgYrJZsmSi4-36_Up5TbbN_8hosYonLKHSSOSKY845LuLZBCBwStrHQ==")', # noqa
|
||||
])
|
||||
),
|
||||
]
|
||||
)
|
||||
def test_rsyslog_conf_template(enabled, log_type, host, port, protocol, errorfile, expected_config):
|
||||
|
||||
mock_settings, _ = _mock_logging_defaults()
|
||||
|
||||
# Set test settings
|
||||
logging_defaults = getattr(settings, 'LOGGING')
|
||||
setattr(mock_settings, 'LOGGING', logging_defaults)
|
||||
setattr(mock_settings, 'LOGGING["handlers"]["external_logger"]["address"]', '/var/run/awx-rsyslog/rsyslog.sock')
|
||||
setattr(mock_settings, 'LOG_AGGREGATOR_ENABLED', enabled)
|
||||
setattr(mock_settings, 'LOG_AGGREGATOR_TYPE', log_type)
|
||||
setattr(mock_settings, 'LOG_AGGREGATOR_HOST', host)
|
||||
setattr(mock_settings, 'LOG_AGGREGATOR_RSYSLOGD_ERROR_LOG_FILE', errorfile)
|
||||
if port:
|
||||
setattr(mock_settings, 'LOG_AGGREGATOR_PORT', port)
|
||||
if protocol:
|
||||
setattr(mock_settings, 'LOG_AGGREGATOR_PROTOCOL', protocol)
|
||||
|
||||
# create rsyslog conf template
|
||||
tmpl = construct_rsyslog_conf_template(mock_settings)
|
||||
|
||||
# check validity of created template
|
||||
assert expected_config in tmpl
|
||||
|
||||
|
||||
def test_splunk_auth():
|
||||
mock_settings, _ = _mock_logging_defaults()
|
||||
# Set test settings
|
||||
logging_defaults = getattr(settings, 'LOGGING')
|
||||
setattr(mock_settings, 'LOGGING', logging_defaults)
|
||||
setattr(mock_settings, 'LOG_AGGREGATOR_ENABLED', True)
|
||||
setattr(mock_settings, 'LOG_AGGREGATOR_TYPE', 'splunk')
|
||||
setattr(mock_settings, 'LOG_AGGREGATOR_HOST', 'example.org')
|
||||
setattr(mock_settings, 'LOG_AGGREGATOR_PASSWORD', 'SECRET-TOKEN')
|
||||
|
||||
tmpl = construct_rsyslog_conf_template(mock_settings)
|
||||
assert 'httpheaderkey="Authorization" httpheadervalue="Splunk SECRET-TOKEN"' in tmpl
|
||||
@@ -0,0 +1,29 @@
|
||||
import pytest
|
||||
from io import StringIO
|
||||
|
||||
# AWX
|
||||
from awx.api.parsers import JSONParser
|
||||
|
||||
# Django REST Framework
|
||||
from rest_framework.exceptions import ParseError
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'input_, output', [
|
||||
('{"foo": "bar"}', {'foo': 'bar'}),
|
||||
('null', None),
|
||||
('', {}),
|
||||
]
|
||||
)
|
||||
def test_jsonparser_valid_input(input_, output):
|
||||
input_stream = StringIO(input_)
|
||||
assert JSONParser().parse(input_stream) == output
|
||||
input_stream.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('invalid_input', ['1', '"foobar"', '3.14', '{"foo": "bar",}'])
|
||||
def test_json_parser_invalid_input(invalid_input):
|
||||
input_stream = StringIO(invalid_input)
|
||||
with pytest.raises(ParseError):
|
||||
JSONParser().parse(input_stream)
|
||||
input_stream.close()
|
||||
@@ -0,0 +1,320 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import pytest
|
||||
from copy import deepcopy
|
||||
from unittest import mock
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
from awx.api.views import (
|
||||
ApiVersionRootView,
|
||||
JobTemplateLabelList,
|
||||
InventoryInventorySourcesUpdate,
|
||||
JobTemplateSurveySpec
|
||||
)
|
||||
|
||||
from awx.main.views import handle_error
|
||||
|
||||
from rest_framework.test import APIRequestFactory
|
||||
|
||||
|
||||
def test_handle_error():
|
||||
# Assure that templating of error does not raise errors
|
||||
request = APIRequestFactory().get('/fooooo/')
|
||||
handle_error(request)
|
||||
|
||||
|
||||
class TestApiRootView:
|
||||
def test_get_endpoints(self, mocker):
|
||||
endpoints = [
|
||||
'ping',
|
||||
'config',
|
||||
#'settings',
|
||||
'me',
|
||||
'dashboard',
|
||||
'organizations',
|
||||
'users',
|
||||
'projects',
|
||||
'teams',
|
||||
'credentials',
|
||||
'inventory',
|
||||
'inventory_scripts',
|
||||
'inventory_sources',
|
||||
'groups',
|
||||
'hosts',
|
||||
'job_templates',
|
||||
'jobs',
|
||||
'ad_hoc_commands',
|
||||
'system_job_templates',
|
||||
'system_jobs',
|
||||
'schedules',
|
||||
'notification_templates',
|
||||
'notifications',
|
||||
'labels',
|
||||
'unified_job_templates',
|
||||
'unified_jobs',
|
||||
'activity_stream',
|
||||
'workflow_job_templates',
|
||||
'workflow_jobs',
|
||||
]
|
||||
view = ApiVersionRootView()
|
||||
ret = view.get(mocker.MagicMock())
|
||||
assert ret.status_code == 200
|
||||
for endpoint in endpoints:
|
||||
assert endpoint in ret.data
|
||||
|
||||
|
||||
class TestJobTemplateLabelList:
|
||||
def test_inherited_mixin_unattach(self):
|
||||
with mock.patch('awx.api.generics.DeleteLastUnattachLabelMixin.unattach') as mixin_unattach:
|
||||
view = JobTemplateLabelList()
|
||||
mock_request = mock.MagicMock()
|
||||
|
||||
super(JobTemplateLabelList, view).unattach(mock_request, None, None)
|
||||
assert mixin_unattach.called_with(mock_request, None, None)
|
||||
|
||||
|
||||
class TestInventoryInventorySourcesUpdate:
|
||||
|
||||
@pytest.mark.parametrize("can_update, can_access, is_source, is_up_on_proj, expected", [
|
||||
(True, True, "ec2", False, [{'status': 'started', 'inventory_update': 1, 'inventory_source': 1}]),
|
||||
(False, True, "gce", False, [{'status': 'Could not start because `can_update` returned False', 'inventory_source': 1}]),
|
||||
(True, False, "scm", True, [{'status': 'started', 'inventory_update': 1, 'inventory_source': 1}]),
|
||||
])
|
||||
def test_post(self, mocker, can_update, can_access, is_source, is_up_on_proj, expected):
|
||||
class InventoryUpdate:
|
||||
id = 1
|
||||
|
||||
class Project:
|
||||
name = 'project'
|
||||
|
||||
InventorySource = namedtuple('InventorySource', ['source', 'update_on_project_update', 'pk', 'can_update',
|
||||
'update', 'source_project'])
|
||||
|
||||
class InventorySources(object):
|
||||
def all(self):
|
||||
return [InventorySource(pk=1, source=is_source, source_project=Project,
|
||||
update_on_project_update=is_up_on_proj,
|
||||
can_update=can_update, update=lambda:InventoryUpdate)]
|
||||
|
||||
def exclude(self, **kwargs):
|
||||
return self.all()
|
||||
|
||||
Inventory = namedtuple('Inventory', ['inventory_sources', 'kind'])
|
||||
obj = Inventory(inventory_sources=InventorySources(), kind='')
|
||||
|
||||
mock_request = mocker.MagicMock()
|
||||
mock_request.user.can_access.return_value = can_access
|
||||
|
||||
with mocker.patch.object(InventoryInventorySourcesUpdate, 'get_object', return_value=obj):
|
||||
with mocker.patch.object(InventoryInventorySourcesUpdate, 'get_serializer_context', return_value=None):
|
||||
with mocker.patch('awx.api.serializers.InventoryUpdateDetailSerializer') as serializer_class:
|
||||
serializer = serializer_class.return_value
|
||||
serializer.to_representation.return_value = {}
|
||||
|
||||
view = InventoryInventorySourcesUpdate()
|
||||
response = view.post(mock_request)
|
||||
assert response.data == expected
|
||||
|
||||
|
||||
class TestSurveySpecValidation:
|
||||
|
||||
def test_create_text_encrypted(self):
|
||||
view = JobTemplateSurveySpec()
|
||||
resp = view._validate_spec_data({
|
||||
"name": "new survey",
|
||||
"description": "foobar",
|
||||
"spec": [
|
||||
{
|
||||
"question_description": "",
|
||||
"min": 0,
|
||||
"default": "$encrypted$",
|
||||
"max": 1024,
|
||||
"required": True,
|
||||
"choices": "",
|
||||
"variable": "openshift_username",
|
||||
"question_name": "OpenShift Username",
|
||||
"type": "text"
|
||||
}
|
||||
]
|
||||
}, {})
|
||||
assert resp.status_code == 400
|
||||
assert '$encrypted$ is a reserved keyword for password question defaults' in str(resp.data['error'])
|
||||
|
||||
def test_change_encrypted_var_name(self):
|
||||
view = JobTemplateSurveySpec()
|
||||
old = {
|
||||
"name": "old survey",
|
||||
"description": "foobar",
|
||||
"spec": [
|
||||
{
|
||||
"question_description": "",
|
||||
"min": 0,
|
||||
"default": "$encrypted$foooooooo",
|
||||
"max": 1024,
|
||||
"required": True,
|
||||
"choices": "",
|
||||
"variable": "openshift_username",
|
||||
"question_name": "OpenShift Username",
|
||||
"type": "password"
|
||||
}
|
||||
]
|
||||
}
|
||||
new = deepcopy(old)
|
||||
new['spec'][0]['variable'] = 'openstack_username'
|
||||
resp = view._validate_spec_data(new, old)
|
||||
assert resp.status_code == 400
|
||||
assert 'may not be used for new default' in str(resp.data['error'])
|
||||
|
||||
def test_use_saved_encrypted_default(self):
|
||||
'''
|
||||
Save is allowed, the $encrypted$ replacement is done
|
||||
'''
|
||||
view = JobTemplateSurveySpec()
|
||||
old = {
|
||||
"name": "old survey",
|
||||
"description": "foobar",
|
||||
"spec": [
|
||||
{
|
||||
"question_description": "",
|
||||
"min": 0,
|
||||
"default": "$encrypted$foooooooo",
|
||||
"max": 1024,
|
||||
"required": True,
|
||||
"choices": "",
|
||||
"variable": "openshift_username",
|
||||
"question_name": "OpenShift Username",
|
||||
"type": "password"
|
||||
}
|
||||
]
|
||||
}
|
||||
new = deepcopy(old)
|
||||
new['spec'][0]['default'] = '$encrypted$'
|
||||
new['spec'][0]['required'] = False
|
||||
resp = view._validate_spec_data(new, old)
|
||||
assert resp is None, resp.data
|
||||
assert new == {
|
||||
"name": "old survey",
|
||||
"description": "foobar",
|
||||
"spec": [
|
||||
{
|
||||
"question_description": "",
|
||||
"min": 0,
|
||||
"default": "$encrypted$foooooooo", # default remained the same
|
||||
"max": 1024,
|
||||
"required": False, # only thing changed
|
||||
"choices": "",
|
||||
"variable": "openshift_username",
|
||||
"question_name": "OpenShift Username",
|
||||
"type": "password"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
def test_use_saved_empty_string_default(self):
|
||||
'''
|
||||
Save is allowed, the $encrypted$ replacement is done with empty string
|
||||
The empty string value for default is unencrypted,
|
||||
unlike all other password questions
|
||||
'''
|
||||
view = JobTemplateSurveySpec()
|
||||
old = {
|
||||
"name": "old survey",
|
||||
"description": "foobar",
|
||||
"spec": [
|
||||
{
|
||||
"question_description": "",
|
||||
"min": 0,
|
||||
"default": "",
|
||||
"max": 1024,
|
||||
"required": True,
|
||||
"choices": "",
|
||||
"variable": "openshift_username",
|
||||
"question_name": "OpenShift Username",
|
||||
"type": "password"
|
||||
}
|
||||
]
|
||||
}
|
||||
new = deepcopy(old)
|
||||
new['spec'][0]['default'] = '$encrypted$'
|
||||
resp = view._validate_spec_data(new, old)
|
||||
assert resp is None
|
||||
assert new == {
|
||||
"name": "old survey",
|
||||
"description": "foobar",
|
||||
"spec": [
|
||||
{
|
||||
"question_description": "",
|
||||
"min": 0,
|
||||
"default": "", # still has old unencrypted default
|
||||
"max": 1024,
|
||||
"required": True,
|
||||
"choices": "",
|
||||
"variable": "openshift_username",
|
||||
"question_name": "OpenShift Username",
|
||||
"type": "password"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@staticmethod
|
||||
def spec_from_element(survey_item):
|
||||
survey_item.setdefault('name', 'foo')
|
||||
survey_item.setdefault('variable', 'foo')
|
||||
survey_item.setdefault('required', False)
|
||||
survey_item.setdefault('question_name', 'foo')
|
||||
survey_item.setdefault('type', 'text')
|
||||
spec = {
|
||||
'name': 'test survey',
|
||||
'description': 'foo',
|
||||
'spec': [survey_item]
|
||||
}
|
||||
return spec
|
||||
|
||||
|
||||
@pytest.mark.parametrize("survey_item, error_text", [
|
||||
({'type': 'password', 'default': ['some', 'invalid', 'list']}, 'expected to be string'),
|
||||
({'type': 'password', 'default': False}, 'expected to be string'),
|
||||
({'type': 'integer', 'default': 'foo'}, 'expected to be int'),
|
||||
({'type': 'integer', 'default': u'🐉'}, 'expected to be int'),
|
||||
({'type': 'foo'}, 'allowed question types'),
|
||||
({'type': u'🐉'}, 'allowed question types'),
|
||||
({'type': 'multiplechoice'}, 'multiplechoice must specify choices'),
|
||||
({'type': 'integer', 'min': 'foo'}, 'min limit in survey question 0 expected to be integer'),
|
||||
({'question_name': 42}, "'question_name' in survey question 0 expected to be string.")
|
||||
])
|
||||
def test_survey_question_element_validation(self, survey_item, error_text):
|
||||
spec = self.spec_from_element(survey_item)
|
||||
r = JobTemplateSurveySpec._validate_spec_data(spec, {})
|
||||
assert r is not None, (spec, error_text)
|
||||
assert 'error' in r.data
|
||||
assert error_text in r.data['error']
|
||||
|
||||
|
||||
def test_survey_spec_non_dict_error(self):
|
||||
spec = self.spec_from_element({})
|
||||
spec['spec'][0] = 'foo'
|
||||
r = JobTemplateSurveySpec._validate_spec_data(spec, {})
|
||||
assert 'Survey question 0 is not a json object' in r.data['error']
|
||||
|
||||
|
||||
def test_survey_spec_dual_names_error(self):
|
||||
spec = self.spec_from_element({})
|
||||
spec['spec'].append(spec['spec'][0].copy())
|
||||
r = JobTemplateSurveySpec._validate_spec_data(spec, {})
|
||||
assert "'variable' 'foo' duplicated in survey question 1." in r.data['error']
|
||||
|
||||
|
||||
def test_survey_spec_element_missing_property(self):
|
||||
spec = self.spec_from_element({})
|
||||
spec['spec'][0].pop('type')
|
||||
r = JobTemplateSurveySpec._validate_spec_data(spec, {})
|
||||
assert "'type' missing from survey question 0" in r.data['error']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('_type', ['integer', 'float'])
|
||||
def test_survey_spec_element_number_empty_default(self, _type):
|
||||
""" Assert that empty default is allowed for answer. """
|
||||
spec = self.spec_from_element({'type': _type, 'default': ''})
|
||||
r = JobTemplateSurveySpec._validate_spec_data(spec, {})
|
||||
assert r is None
|
||||
@@ -0,0 +1,42 @@
|
||||
# Copyright (c) 2017 Ansible by Red Hat
|
||||
# All Rights Reserved
|
||||
|
||||
# Python
|
||||
import pytest
|
||||
|
||||
# Django
|
||||
from django.core.management.base import CommandError
|
||||
|
||||
# AWX
|
||||
from awx.main.management.commands.inventory_import import (
|
||||
Command
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
class TestInvalidOptions:
|
||||
|
||||
def test_invalid_options_no_options_specified(self):
|
||||
cmd = Command()
|
||||
with pytest.raises(CommandError) as err:
|
||||
cmd.handle()
|
||||
assert 'inventory-id' in str(err.value)
|
||||
assert 'required' in str(err.value)
|
||||
|
||||
def test_invalid_options_name_and_id(self):
|
||||
# You can not specify both name and if of the inventory
|
||||
cmd = Command()
|
||||
with pytest.raises(CommandError) as err:
|
||||
cmd.handle(
|
||||
inventory_id=42, inventory_name='my-inventory'
|
||||
)
|
||||
assert 'inventory-id' in str(err.value)
|
||||
assert 'exclusive' in str(err.value)
|
||||
|
||||
def test_invalid_options_missing_source(self):
|
||||
cmd = Command()
|
||||
with pytest.raises(CommandError) as err:
|
||||
cmd.handle(inventory_id=42)
|
||||
assert '--source' in str(err.value)
|
||||
assert 'required' in str(err.value)
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
# Copyright (c) 2017 Ansible by Red Hat
|
||||
# All Rights Reserved
|
||||
|
||||
# Python
|
||||
import pytest
|
||||
from unittest import mock
|
||||
from datetime import timedelta
|
||||
|
||||
# Django
|
||||
from django.utils import timezone
|
||||
|
||||
# AWX
|
||||
from awx.main.models import (
|
||||
Job,
|
||||
JobEvent,
|
||||
)
|
||||
from awx.main.management.commands.replay_job_events import (
|
||||
ReplayJobEvents,
|
||||
)
|
||||
|
||||
|
||||
class TestReplayJobEvents():
|
||||
|
||||
@pytest.fixture
|
||||
def epoch(self):
|
||||
return timezone.now()
|
||||
|
||||
@pytest.fixture
|
||||
def job_events(self, epoch):
|
||||
return [
|
||||
JobEvent(created=epoch),
|
||||
JobEvent(created=epoch + timedelta(seconds=10)),
|
||||
JobEvent(created=epoch + timedelta(seconds=20)),
|
||||
JobEvent(created=epoch + timedelta(seconds=30)),
|
||||
JobEvent(created=epoch + timedelta(seconds=31)),
|
||||
JobEvent(created=epoch + timedelta(seconds=31, milliseconds=1)),
|
||||
JobEvent(created=epoch + timedelta(seconds=31, microseconds=1, milliseconds=1)),
|
||||
]
|
||||
|
||||
@pytest.fixture
|
||||
def mock_serializer_fn(self):
|
||||
class MockSerializer():
|
||||
data = dict()
|
||||
|
||||
|
||||
def fn(job_event):
|
||||
serialized = MockSerializer()
|
||||
serialized.data['group_name'] = 'foobar'
|
||||
return serialized
|
||||
return fn
|
||||
|
||||
@pytest.fixture
|
||||
def replayer(self, mocker, job_events, mock_serializer_fn):
|
||||
r = ReplayJobEvents()
|
||||
r.get_serializer = lambda self: mock_serializer_fn
|
||||
r.get_job = mocker.MagicMock(return_value=Job(id=3))
|
||||
r.sleep = mocker.MagicMock()
|
||||
r.get_job_events = lambda self: (job_events, len(job_events))
|
||||
r.replay_offset = lambda *args, **kwarg: 0
|
||||
r.emit_job_status = lambda job, status: True
|
||||
return r
|
||||
|
||||
@mock.patch('awx.main.management.commands.replay_job_events.emit_event_detail', lambda *a, **kw: None)
|
||||
def test_sleep(self, mocker, replayer):
|
||||
replayer.run(3, 1)
|
||||
|
||||
assert replayer.sleep.call_count == 6
|
||||
replayer.sleep.assert_has_calls([
|
||||
mock.call(10.0),
|
||||
mock.call(10.0),
|
||||
mock.call(10.0),
|
||||
mock.call(1.0),
|
||||
mock.call(0.001),
|
||||
mock.call(0.000001),
|
||||
])
|
||||
|
||||
@mock.patch('awx.main.management.commands.replay_job_events.emit_event_detail', lambda *a, **kw: None)
|
||||
def test_speed(self, mocker, replayer):
|
||||
replayer.run(3, 2)
|
||||
|
||||
assert replayer.sleep.call_count == 6
|
||||
replayer.sleep.assert_has_calls([
|
||||
mock.call(5.0),
|
||||
mock.call(5.0),
|
||||
mock.call(5.0),
|
||||
mock.call(0.5),
|
||||
mock.call(0.0005),
|
||||
mock.call(0.0000005),
|
||||
])
|
||||
|
||||
# TODO: Test replay_offset()
|
||||
# TODO: Test stat generation
|
||||
@@ -0,0 +1,55 @@
|
||||
import pytest
|
||||
import logging
|
||||
|
||||
from unittest.mock import PropertyMock
|
||||
|
||||
from awx.api.urls import urlpatterns as api_patterns
|
||||
|
||||
# Django
|
||||
from django.urls import URLResolver, URLPattern
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _disable_database_settings(mocker):
|
||||
m = mocker.patch('awx.conf.settings.SettingsWrapper.all_supported_settings', new_callable=PropertyMock)
|
||||
m.return_value = []
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def all_views():
|
||||
'''
|
||||
returns a set of all views in the app
|
||||
'''
|
||||
patterns = set()
|
||||
url_views = set()
|
||||
# Add recursive URL patterns
|
||||
unprocessed = set(api_patterns)
|
||||
while unprocessed:
|
||||
to_process = unprocessed.copy()
|
||||
unprocessed = set()
|
||||
for pattern in to_process:
|
||||
if hasattr(pattern, 'lookup_str') and not pattern.lookup_str.startswith('awx.api'):
|
||||
continue
|
||||
patterns.add(pattern)
|
||||
if isinstance(pattern, URLResolver):
|
||||
for sub_pattern in pattern.url_patterns:
|
||||
if sub_pattern not in patterns:
|
||||
unprocessed.add(sub_pattern)
|
||||
# Get view classes
|
||||
for pattern in patterns:
|
||||
if isinstance(pattern, URLPattern) and hasattr(pattern.callback, 'view_class'):
|
||||
url_views.add(pattern.callback.view_class)
|
||||
return url_views
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def dummy_log_record():
|
||||
return logging.LogRecord(
|
||||
'awx', # logger name
|
||||
20, # loglevel INFO
|
||||
'./awx/some/module.py', # pathname
|
||||
100, # lineno
|
||||
'User joe logged in', # msg
|
||||
tuple(), # args,
|
||||
None # exc_info
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from awx.main.models import Credential, CredentialType
|
||||
|
||||
|
||||
def test_unique_hash_with_unicode():
|
||||
ct = CredentialType(name=u'Väult', kind='vault')
|
||||
cred = Credential(
|
||||
id=4,
|
||||
name=u'Iñtërnâtiônàlizætiøn',
|
||||
credential_type=ct,
|
||||
inputs={
|
||||
u'vault_id': u'🐉🐉🐉'
|
||||
},
|
||||
credential_type_id=42
|
||||
)
|
||||
assert cred.unique_hash(display=True) == u'Väult (id=🐉🐉🐉)'
|
||||
|
||||
|
||||
def test_custom_cred_with_empty_encrypted_field():
|
||||
ct = CredentialType(
|
||||
name='My Custom Cred',
|
||||
kind='custom',
|
||||
inputs={
|
||||
'fields': [{
|
||||
'id': 'some_field',
|
||||
'label': 'My Field',
|
||||
'secret': True
|
||||
}]
|
||||
}
|
||||
)
|
||||
cred = Credential(
|
||||
id=4,
|
||||
name='Testing 1 2 3',
|
||||
credential_type=ct,
|
||||
inputs={}
|
||||
)
|
||||
assert cred.encrypt_field('some_field', None) is None
|
||||
@@ -0,0 +1,51 @@
|
||||
from datetime import datetime
|
||||
from django.utils.timezone import utc
|
||||
import pytest
|
||||
|
||||
from awx.main.models import (JobEvent, ProjectUpdateEvent, AdHocCommandEvent,
|
||||
InventoryUpdateEvent, SystemJobEvent)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('job_identifier, cls', [
|
||||
['job_id', JobEvent],
|
||||
['project_update_id', ProjectUpdateEvent],
|
||||
['ad_hoc_command_id', AdHocCommandEvent],
|
||||
['inventory_update_id', InventoryUpdateEvent],
|
||||
['system_job_id', SystemJobEvent],
|
||||
])
|
||||
@pytest.mark.parametrize('created', [
|
||||
datetime(2018, 1, 1).isoformat(), datetime(2018, 1, 1)
|
||||
])
|
||||
def test_event_parse_created(job_identifier, cls, created):
|
||||
event = cls.create_from_data(**{
|
||||
job_identifier: 123,
|
||||
'created': created
|
||||
})
|
||||
assert event.created == datetime(2018, 1, 1).replace(tzinfo=utc)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('job_identifier, cls', [
|
||||
['job_id', JobEvent],
|
||||
['project_update_id', ProjectUpdateEvent],
|
||||
['ad_hoc_command_id', AdHocCommandEvent],
|
||||
['inventory_update_id', InventoryUpdateEvent],
|
||||
['system_job_id', SystemJobEvent],
|
||||
])
|
||||
def test_playbook_event_strip_invalid_keys(job_identifier, cls):
|
||||
event = cls.create_from_data(**{
|
||||
job_identifier: 123,
|
||||
'extra_key': 'extra_value'
|
||||
})
|
||||
assert getattr(event, job_identifier) == 123
|
||||
assert not hasattr(event, 'extra_key')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('field', [
|
||||
'play', 'role', 'task', 'playbook'
|
||||
])
|
||||
def test_really_long_event_fields(field):
|
||||
event = JobEvent.create_from_data(**{
|
||||
'job_id': 123,
|
||||
'event_data': {field: 'X' * 4096}
|
||||
})
|
||||
assert event.event_data[field] == 'X' * 1023 + '…'
|
||||
@@ -0,0 +1,76 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
from unittest.mock import Mock
|
||||
|
||||
from awx.main.models import (
|
||||
Job,
|
||||
InstanceGroup,
|
||||
)
|
||||
|
||||
|
||||
def T(impact):
|
||||
j = mock.Mock(Job())
|
||||
j.task_impact = impact
|
||||
return j
|
||||
|
||||
|
||||
def Is(param):
|
||||
'''
|
||||
param:
|
||||
[remaining_capacity1, remaining_capacity2, remaining_capacity3, ...]
|
||||
[(jobs_running1, capacity1), (jobs_running2, capacity2), (jobs_running3, capacity3), ...]
|
||||
'''
|
||||
|
||||
instances = []
|
||||
if isinstance(param[0], tuple):
|
||||
for (jobs_running, capacity) in param:
|
||||
inst = Mock()
|
||||
inst.capacity = capacity
|
||||
inst.jobs_running = jobs_running
|
||||
instances.append(inst)
|
||||
else:
|
||||
for i in param:
|
||||
inst = Mock()
|
||||
inst.remaining_capacity = i
|
||||
instances.append(inst)
|
||||
return instances
|
||||
|
||||
|
||||
class TestInstanceGroup(object):
|
||||
@pytest.mark.parametrize('task,instances,instance_fit_index,reason', [
|
||||
(T(100), Is([100]), 0, "Only one, pick it"),
|
||||
(T(100), Is([100, 100]), 0, "Two equally good fits, pick the first"),
|
||||
(T(100), Is([50, 100]), 1, "First instance not as good as second instance"),
|
||||
(T(100), Is([50, 0, 20, 100, 100, 100, 30, 20]), 3, "Pick Instance [3] as it is the first that the task fits in."),
|
||||
(T(100), Is([50, 0, 20, 99, 11, 1, 5, 99]), None, "The task don't a fit, you must a quit!"),
|
||||
])
|
||||
def test_fit_task_to_most_remaining_capacity_instance(self, task, instances, instance_fit_index, reason):
|
||||
ig = InstanceGroup(id=10)
|
||||
|
||||
instance_picked = ig.fit_task_to_most_remaining_capacity_instance(task, instances)
|
||||
|
||||
if instance_fit_index is None:
|
||||
assert instance_picked is None, reason
|
||||
else:
|
||||
assert instance_picked == instances[instance_fit_index], reason
|
||||
|
||||
@pytest.mark.parametrize('instances,instance_fit_index,reason', [
|
||||
(Is([(0, 100)]), 0, "One idle instance, pick it"),
|
||||
(Is([(1, 100)]), None, "One un-idle instance, pick nothing"),
|
||||
(Is([(0, 100), (0, 200), (1, 500), (0, 700)]), 3, "Pick the largest idle instance"),
|
||||
(Is([(0, 100), (0, 200), (1, 10000), (0, 700), (0, 699)]), 3, "Pick the largest idle instance"),
|
||||
(Is([(0, 0)]), None, "One idle but down instance, don't pick it"),
|
||||
])
|
||||
def test_find_largest_idle_instance(self, instances, instance_fit_index, reason):
|
||||
def filter_offline_instances(*args):
|
||||
return filter(lambda i: i.capacity > 0, instances)
|
||||
|
||||
ig = InstanceGroup(id=10)
|
||||
instances_online_only = filter_offline_instances(instances)
|
||||
|
||||
if instance_fit_index is None:
|
||||
assert ig.find_largest_idle_instance(instances_online_only) is None, reason
|
||||
else:
|
||||
assert ig.find_largest_idle_instance(instances_online_only) == \
|
||||
instances[instance_fit_index], reason
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
import json
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
from awx.main.models import (
|
||||
UnifiedJob,
|
||||
InventoryUpdate,
|
||||
Inventory,
|
||||
Credential,
|
||||
CredentialType,
|
||||
InventorySource,
|
||||
)
|
||||
|
||||
|
||||
def test_cancel(mocker):
|
||||
with mock.patch.object(UnifiedJob, 'cancel', return_value=True) as parent_cancel:
|
||||
iu = InventoryUpdate()
|
||||
|
||||
iu.save = mocker.MagicMock()
|
||||
build_job_explanation_mock = mocker.MagicMock()
|
||||
iu._build_job_explanation = mocker.MagicMock(return_value=build_job_explanation_mock)
|
||||
|
||||
iu.cancel()
|
||||
|
||||
parent_cancel.assert_called_with(is_chain=False, job_explanation=None)
|
||||
|
||||
|
||||
def test__build_job_explanation():
|
||||
iu = InventoryUpdate(id=3, name='I_am_an_Inventory_Update')
|
||||
|
||||
job_explanation = iu._build_job_explanation()
|
||||
|
||||
assert job_explanation == 'Previous Task Canceled: {"job_type": "%s", "job_name": "%s", "job_id": "%s"}' % \
|
||||
('inventory_update', 'I_am_an_Inventory_Update', 3)
|
||||
|
||||
|
||||
def test_valid_clean_insights_credential():
|
||||
cred_type = CredentialType.defaults['insights']()
|
||||
insights_cred = Credential(credential_type=cred_type)
|
||||
inv = Inventory(insights_credential=insights_cred)
|
||||
|
||||
inv.clean_insights_credential()
|
||||
|
||||
|
||||
def test_invalid_clean_insights_credential():
|
||||
cred_type = CredentialType.defaults['scm']()
|
||||
cred = Credential(credential_type=cred_type)
|
||||
inv = Inventory(insights_credential=cred)
|
||||
|
||||
with pytest.raises(ValidationError) as e:
|
||||
inv.clean_insights_credential()
|
||||
|
||||
assert json.dumps(str(e.value)) == json.dumps(str([u"Credential kind must be 'insights'."]))
|
||||
|
||||
|
||||
def test_valid_kind_clean_insights_credential():
|
||||
inv = Inventory(kind='smart')
|
||||
|
||||
inv.clean_insights_credential()
|
||||
|
||||
|
||||
def test_invalid_kind_clean_insights_credential():
|
||||
cred_type = CredentialType.defaults['insights']()
|
||||
insights_cred = Credential(credential_type=cred_type)
|
||||
inv = Inventory(kind='smart', insights_credential=insights_cred)
|
||||
|
||||
with pytest.raises(ValidationError) as e:
|
||||
inv.clean_insights_credential()
|
||||
|
||||
assert json.dumps(str(e.value)) == json.dumps(str([u'Assignment not allowed for Smart Inventory']))
|
||||
|
||||
|
||||
class TestControlledBySCM():
|
||||
def test_clean_source_path_valid(self):
|
||||
inv_src = InventorySource(source_path='/not_real/',
|
||||
source='scm')
|
||||
|
||||
inv_src.clean_source_path()
|
||||
|
||||
@pytest.mark.parametrize('source', [
|
||||
'ec2',
|
||||
'manual',
|
||||
])
|
||||
def test_clean_source_path_invalid(self, source):
|
||||
inv_src = InventorySource(source_path='/not_real/',
|
||||
source=source)
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
inv_src.clean_source_path()
|
||||
|
||||
def test_clean_update_on_launch_update_on_project_update(self):
|
||||
inv_src = InventorySource(update_on_project_update=True,
|
||||
update_on_launch=True,
|
||||
source='scm')
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
inv_src.clean_update_on_launch()
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import pytest
|
||||
|
||||
# AWX
|
||||
from awx.main.models.jobs import JobTemplate
|
||||
|
||||
from unittest import mock
|
||||
|
||||
|
||||
def test_missing_project_error(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'missing-project-jt',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
persisted=False)
|
||||
obj = objects.job_template
|
||||
assert 'project' in obj.resources_needed_to_start
|
||||
assert 'project' in obj.validation_errors
|
||||
|
||||
|
||||
def test_inventory_need_to_start(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'job-template-few-resources',
|
||||
project='project1',
|
||||
persisted=False)
|
||||
obj = objects.job_template
|
||||
assert 'inventory' in obj.resources_needed_to_start
|
||||
|
||||
|
||||
def test_inventory_contradictions(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'job-template-paradox',
|
||||
project='project1',
|
||||
persisted=False)
|
||||
obj = objects.job_template
|
||||
obj.ask_inventory_on_launch = False
|
||||
assert 'inventory' in obj.validation_errors
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
def test_job_template_survey_password_redaction(job_template_with_survey_passwords_unit):
|
||||
"""Tests the JobTemplate model's funciton to redact passwords from
|
||||
extra_vars - used when creating a new job"""
|
||||
assert job_template_with_survey_passwords_unit.survey_password_variables() == ['secret_key', 'SSN']
|
||||
|
||||
|
||||
def test_job_template_survey_mixin(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'survey_mixin_test',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
credential='cred1',
|
||||
persisted=False,
|
||||
)
|
||||
obj = objects.job_template
|
||||
obj.survey_enabled = True
|
||||
obj.survey_spec = {'spec': [{'default':'my_default', 'type':'password', 'variable':'my_variable'}]}
|
||||
kwargs = obj._update_unified_job_kwargs({}, {'extra_vars': {'my_variable':'$encrypted$'}})
|
||||
assert kwargs['extra_vars'] == '{"my_variable": "my_default"}'
|
||||
|
||||
|
||||
def test_job_template_survey_mixin_length(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'survey_mixin_test',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
credential='cred1',
|
||||
persisted=False,
|
||||
)
|
||||
obj = objects.job_template
|
||||
obj.survey_enabled = True
|
||||
obj.survey_spec = {'spec': [{'default':'my_default', 'type':'password', 'variable':'my_variable'},
|
||||
{'type':'password', 'variable':'my_other_variable'}]}
|
||||
kwargs = obj._update_unified_job_kwargs({}, {'extra_vars': {'my_variable':'$encrypted$'}})
|
||||
assert kwargs['extra_vars'] == '{"my_variable": "my_default"}'
|
||||
|
||||
|
||||
def test_job_template_survey_mixin_survey_runtime_has_highest_priority(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'survey_mixin_test',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
credential='cred1',
|
||||
persisted=False,
|
||||
)
|
||||
obj = objects.job_template
|
||||
obj.survey_enabled = True
|
||||
obj.survey_spec = {'spec': [{'default':'foo', 'type':'password', 'variable':'my_variable'}]}
|
||||
kwargs = obj._update_unified_job_kwargs({}, {'extra_vars': {'my_variable': 'bar'}})
|
||||
assert kwargs['extra_vars'] == '{"my_variable": "bar"}'
|
||||
|
||||
|
||||
def test_job_template_can_start_with_callback_extra_vars_provided(job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'callback_extra_vars_test',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
credential='cred1',
|
||||
persisted=False,
|
||||
)
|
||||
obj = objects.job_template
|
||||
obj.ask_variables_on_launch = True
|
||||
with mock.patch.object(obj.__class__, 'passwords_needed_to_start', []):
|
||||
assert obj.can_start_without_user_input(callback_extra_vars='{"foo": "bar"}') is True
|
||||
|
||||
|
||||
def test_ask_mapping_integrity():
|
||||
assert 'credentials' in JobTemplate.get_ask_mapping()
|
||||
assert JobTemplate.get_ask_mapping()['job_tags'] == 'ask_tags_on_launch'
|
||||
@@ -0,0 +1,151 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from awx.main.models import (
|
||||
Job,
|
||||
Inventory,
|
||||
Host,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hosts(inventory):
|
||||
return [
|
||||
Host(name='host1', ansible_facts={"a": 1, "b": 2}, inventory=inventory),
|
||||
Host(name='host2', ansible_facts={"a": 1, "b": 2}, inventory=inventory),
|
||||
Host(name='host3', ansible_facts={"a": 1, "b": 2}, inventory=inventory),
|
||||
Host(name=u'Iñtërnâtiônàlizætiøn', ansible_facts={"a": 1, "b": 2}, inventory=inventory),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def inventory():
|
||||
return Inventory(id=5)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job(mocker, hosts, inventory):
|
||||
j = Job(inventory=inventory, id=2)
|
||||
j._get_inventory_hosts = mocker.Mock(return_value=hosts)
|
||||
return j
|
||||
|
||||
|
||||
def test_start_job_fact_cache(hosts, job, inventory, tmpdir):
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
modified_times = {}
|
||||
job.start_job_fact_cache(fact_cache, modified_times, 0)
|
||||
|
||||
for host in hosts:
|
||||
filepath = os.path.join(fact_cache, host.name)
|
||||
assert os.path.exists(filepath)
|
||||
with open(filepath, 'r') as f:
|
||||
assert f.read() == json.dumps(host.ansible_facts)
|
||||
assert filepath in modified_times
|
||||
|
||||
|
||||
def test_fact_cache_with_invalid_path_traversal(job, inventory, tmpdir, mocker):
|
||||
job._get_inventory_hosts = mocker.Mock(return_value=[
|
||||
Host(name='../foo', ansible_facts={"a": 1, "b": 2},),
|
||||
])
|
||||
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
job.start_job_fact_cache(fact_cache, {}, 0)
|
||||
# a file called "foo" should _not_ be written outside the facts dir
|
||||
assert os.listdir(os.path.join(fact_cache, '..')) == ['facts']
|
||||
|
||||
|
||||
def test_finish_job_fact_cache_with_existing_data(job, hosts, inventory, mocker, tmpdir):
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
modified_times = {}
|
||||
job.start_job_fact_cache(fact_cache, modified_times, 0)
|
||||
|
||||
for h in hosts:
|
||||
h.save = mocker.Mock()
|
||||
|
||||
ansible_facts_new = {"foo": "bar", "insights": {"system_id": "updated_by_scan"}}
|
||||
filepath = os.path.join(fact_cache, hosts[1].name)
|
||||
with open(filepath, 'w') as f:
|
||||
f.write(json.dumps(ansible_facts_new))
|
||||
f.flush()
|
||||
# I feel kind of gross about calling `os.utime` by hand, but I noticed
|
||||
# that in our container-based dev environment, the resolution for
|
||||
# `os.stat()` after a file write was over a second, and I don't want to put
|
||||
# a sleep() in this test
|
||||
new_modification_time = time.time() + 3600
|
||||
os.utime(filepath, (new_modification_time, new_modification_time))
|
||||
|
||||
job.finish_job_fact_cache(fact_cache, modified_times)
|
||||
|
||||
for host in (hosts[0], hosts[2], hosts[3]):
|
||||
host.save.assert_not_called()
|
||||
assert host.ansible_facts == {"a": 1, "b": 2}
|
||||
assert host.ansible_facts_modified is None
|
||||
assert hosts[1].ansible_facts == ansible_facts_new
|
||||
assert hosts[1].insights_system_id == "updated_by_scan"
|
||||
hosts[1].save.assert_called_once_with()
|
||||
|
||||
|
||||
def test_finish_job_fact_cache_with_malformed_fact(job, hosts, inventory, mocker, tmpdir):
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
modified_times = {}
|
||||
job.start_job_fact_cache(fact_cache, modified_times, 0)
|
||||
|
||||
for h in hosts:
|
||||
h.save = mocker.Mock()
|
||||
|
||||
for h in hosts:
|
||||
filepath = os.path.join(fact_cache, h.name)
|
||||
with open(filepath, 'w') as f:
|
||||
json.dump({'ansible_local': {'insights': 'this is an unexpected error from ansible'}}, f)
|
||||
new_modification_time = time.time() + 3600
|
||||
os.utime(filepath, (new_modification_time, new_modification_time))
|
||||
|
||||
job.finish_job_fact_cache(fact_cache, modified_times)
|
||||
|
||||
for h in hosts:
|
||||
assert h.insights_system_id is None
|
||||
|
||||
|
||||
def test_finish_job_fact_cache_with_bad_data(job, hosts, inventory, mocker, tmpdir):
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
modified_times = {}
|
||||
job.start_job_fact_cache(fact_cache, modified_times, 0)
|
||||
|
||||
for h in hosts:
|
||||
h.save = mocker.Mock()
|
||||
|
||||
for h in hosts:
|
||||
filepath = os.path.join(fact_cache, h.name)
|
||||
with open(filepath, 'w') as f:
|
||||
f.write('not valid json!')
|
||||
f.flush()
|
||||
new_modification_time = time.time() + 3600
|
||||
os.utime(filepath, (new_modification_time, new_modification_time))
|
||||
|
||||
job.finish_job_fact_cache(fact_cache, modified_times)
|
||||
|
||||
for h in hosts:
|
||||
h.save.assert_not_called()
|
||||
|
||||
|
||||
def test_finish_job_fact_cache_clear(job, hosts, inventory, mocker, tmpdir):
|
||||
fact_cache = os.path.join(tmpdir, 'facts')
|
||||
modified_times = {}
|
||||
job.start_job_fact_cache(fact_cache, modified_times, 0)
|
||||
|
||||
for h in hosts:
|
||||
h.save = mocker.Mock()
|
||||
|
||||
os.remove(os.path.join(fact_cache, hosts[1].name))
|
||||
job.finish_job_fact_cache(fact_cache, modified_times)
|
||||
|
||||
for host in (hosts[0], hosts[2], hosts[3]):
|
||||
host.save.assert_not_called()
|
||||
assert host.ansible_facts == {"a": 1, "b": 2}
|
||||
assert host.ansible_facts_modified is None
|
||||
assert hosts[1].ansible_facts == {}
|
||||
hosts[1].save.assert_called_once_with()
|
||||
@@ -0,0 +1,65 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
from awx.main.models.label import Label
|
||||
from awx.main.models.unified_jobs import UnifiedJobTemplate, UnifiedJob
|
||||
|
||||
|
||||
mock_query_set = mock.MagicMock()
|
||||
|
||||
mock_objects = mock.MagicMock(filter=mock.MagicMock(return_value=mock_query_set))
|
||||
|
||||
|
||||
@mock.patch('awx.main.models.label.Label.objects', mock_objects)
|
||||
class TestLabelFilterMocked:
|
||||
def test_get_orphaned_labels(self, mocker):
|
||||
ret = Label.get_orphaned_labels()
|
||||
|
||||
assert mock_query_set == ret
|
||||
Label.objects.filter.assert_called_with(organization=None, unifiedjobtemplate_labels__isnull=True)
|
||||
|
||||
def test_is_detached(self, mocker):
|
||||
mock_query_set.count.return_value = 1
|
||||
|
||||
label = Label(id=37)
|
||||
ret = label.is_detached()
|
||||
|
||||
assert ret is True
|
||||
Label.objects.filter.assert_called_with(id=37, unifiedjob_labels__isnull=True, unifiedjobtemplate_labels__isnull=True)
|
||||
mock_query_set.count.assert_called_with()
|
||||
|
||||
def test_is_detached_not(self, mocker):
|
||||
mock_query_set.count.return_value = 0
|
||||
|
||||
label = Label(id=37)
|
||||
ret = label.is_detached()
|
||||
|
||||
assert ret is False
|
||||
Label.objects.filter.assert_called_with(id=37, unifiedjob_labels__isnull=True, unifiedjobtemplate_labels__isnull=True)
|
||||
mock_query_set.count.assert_called_with()
|
||||
|
||||
@pytest.mark.parametrize("jt_count,j_count,expected", [
|
||||
(1, 0, True),
|
||||
(0, 1, True),
|
||||
(1, 1, False),
|
||||
])
|
||||
def test_is_candidate_for_detach(self, mocker, jt_count, j_count, expected):
|
||||
mock_job_qs = mocker.MagicMock()
|
||||
mock_job_qs.count = mocker.MagicMock(return_value=j_count)
|
||||
mocker.patch.object(UnifiedJob, 'objects', mocker.MagicMock(
|
||||
filter=mocker.MagicMock(return_value=mock_job_qs)))
|
||||
|
||||
mock_jt_qs = mocker.MagicMock()
|
||||
mock_jt_qs.count = mocker.MagicMock(return_value=jt_count)
|
||||
mocker.patch.object(UnifiedJobTemplate, 'objects', mocker.MagicMock(
|
||||
filter=mocker.MagicMock(return_value=mock_jt_qs)))
|
||||
|
||||
label = Label(id=37)
|
||||
ret = label.is_candidate_for_detach()
|
||||
|
||||
UnifiedJob.objects.filter.assert_called_with(labels__in=[label.id])
|
||||
UnifiedJobTemplate.objects.filter.assert_called_with(labels__in=[label.id])
|
||||
mock_job_qs.count.assert_called_with()
|
||||
mock_jt_qs.count.assert_called_with()
|
||||
|
||||
assert ret is expected
|
||||
@@ -0,0 +1,15 @@
|
||||
import pytest
|
||||
import json
|
||||
from awx.main.models import (
|
||||
Project,
|
||||
)
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
|
||||
def test_clean_credential_insights():
|
||||
proj = Project(name="myproj", credential=None, scm_type='insights')
|
||||
with pytest.raises(ValidationError) as e:
|
||||
proj.clean_credential()
|
||||
|
||||
assert json.dumps(str(e.value)) == json.dumps(str([u'Insights Credential is required for an Insights Project.']))
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
import pytest
|
||||
from itertools import count
|
||||
|
||||
from awx.main.utils.encryption import encrypt_value
|
||||
from awx.main.models import (
|
||||
Job,
|
||||
JobTemplate,
|
||||
JobLaunchConfig,
|
||||
WorkflowJobTemplate,
|
||||
Project,
|
||||
Inventory
|
||||
)
|
||||
|
||||
ENCRYPTED_SECRET = encrypt_value('secret')
|
||||
|
||||
|
||||
class DistinctParametrize(object):
|
||||
|
||||
def __init__(self):
|
||||
self._gen = count(0)
|
||||
|
||||
def __call__(self, value):
|
||||
return str(next(self._gen))
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
class SurveyVariableValidation:
|
||||
|
||||
def test_survey_answers_as_string(self, job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'job-template-with-survey',
|
||||
survey=[{'variable': 'var1', 'type': 'text'}],
|
||||
persisted=False)
|
||||
jt = objects.job_template
|
||||
user_extra_vars = json.dumps({'var1': 'asdf'})
|
||||
accepted, ignored, errors = jt._accept_or_ignore_job_kwargs(extra_vars=user_extra_vars)
|
||||
assert ignored.get('extra_vars', {}) == {}, [str(element) for element in errors]
|
||||
assert 'var1' in accepted['extra_vars']
|
||||
|
||||
def test_job_template_survey_variable_validation(self, job_template_factory):
|
||||
objects = job_template_factory(
|
||||
'survey_variable_validation',
|
||||
organization='org1',
|
||||
inventory='inventory1',
|
||||
credential='cred1',
|
||||
persisted=False,
|
||||
)
|
||||
obj = objects.job_template
|
||||
obj.survey_spec = {
|
||||
"description": "",
|
||||
"spec": [
|
||||
{
|
||||
"required": True,
|
||||
"min": 0,
|
||||
"default": "5",
|
||||
"max": 1024,
|
||||
"question_description": "",
|
||||
"choices": "",
|
||||
"variable": "a",
|
||||
"question_name": "Whosyourdaddy",
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"name": ""
|
||||
}
|
||||
obj.survey_enabled = True
|
||||
accepted, rejected, errors = obj.accept_or_ignore_variables({"a": 5})
|
||||
assert rejected == {"a": 5}
|
||||
assert accepted == {}
|
||||
assert str(errors[0]) == "Value 5 for 'a' expected to be a string."
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job(mocker):
|
||||
ret = mocker.MagicMock(**{
|
||||
'decrypted_extra_vars.return_value': '{\"secret_key\": \"my_password\"}',
|
||||
'display_extra_vars.return_value': '{\"secret_key\": \"$encrypted$\"}',
|
||||
'extra_vars_dict': {"secret_key": "my_password"},
|
||||
'pk': 1, 'job_template.pk': 1, 'job_template.name': '',
|
||||
'created_by.pk': 1, 'created_by.username': 'admin',
|
||||
'launch_type': 'manual',
|
||||
'verbosity': 1,
|
||||
'awx_meta_vars.return_value': {},
|
||||
'ansible_virtualenv_path': '',
|
||||
'inventory.get_script_data.return_value': {}})
|
||||
ret.project = mocker.MagicMock(scm_revision='asdf1234')
|
||||
return ret
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_with_survey():
|
||||
return Job(
|
||||
name="test-job-with-passwords",
|
||||
extra_vars=json.dumps({
|
||||
'submitter_email': 'foobar@redhat.com',
|
||||
'secret_key': '6kQngg3h8lgiSTvIEb21',
|
||||
'SSN': '123-45-6789'}),
|
||||
survey_passwords={
|
||||
'secret_key': '$encrypted$',
|
||||
'SSN': '$encrypted$'})
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
def test_job_survey_password_redaction(job_with_survey):
|
||||
"""Tests the Job model's funciton to redact passwords from
|
||||
extra_vars - used when displaying job information"""
|
||||
assert json.loads(job_with_survey.display_extra_vars()) == {
|
||||
'submitter_email': 'foobar@redhat.com',
|
||||
'secret_key': '$encrypted$',
|
||||
'SSN': '$encrypted$'}
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
def test_survey_passwords_not_in_extra_vars():
|
||||
"""Tests that survey passwords not included in extra_vars are
|
||||
not included when displaying job information"""
|
||||
job = Job(
|
||||
name="test-survey-not-in",
|
||||
extra_vars=json.dumps({
|
||||
'submitter_email': 'foobar@redhat.com'}),
|
||||
survey_passwords={
|
||||
'secret_key': '$encrypted$',
|
||||
'SSN': '$encrypted$'})
|
||||
assert json.loads(job.display_extra_vars()) == {
|
||||
'submitter_email': 'foobar@redhat.com',
|
||||
}
|
||||
|
||||
|
||||
def test_launch_config_has_unprompted_vars(survey_spec_factory):
|
||||
jt = JobTemplate(
|
||||
survey_enabled = True,
|
||||
survey_spec = survey_spec_factory(['question1', 'question2'])
|
||||
)
|
||||
unprompted_config = JobLaunchConfig(
|
||||
extra_data = {
|
||||
'question1': 'foobar',
|
||||
'question4': 'foobar'
|
||||
}
|
||||
)
|
||||
assert unprompted_config.has_unprompted(jt)
|
||||
allowed_config = JobLaunchConfig(
|
||||
extra_data = {
|
||||
'question1': 'foobar',
|
||||
'question2': 'foobar'
|
||||
}
|
||||
)
|
||||
assert not allowed_config.has_unprompted(jt)
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
def test_update_kwargs_survey_invalid_default(survey_spec_factory):
|
||||
spec = survey_spec_factory('var2')
|
||||
spec['spec'][0]['required'] = False
|
||||
spec['spec'][0]['min'] = 3
|
||||
spec['spec'][0]['default'] = 1
|
||||
jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True, extra_vars="var2: 2")
|
||||
defaulted_extra_vars = jt._update_unified_job_kwargs({}, {})
|
||||
assert 'extra_vars' in defaulted_extra_vars
|
||||
# Make sure we did not set the invalid default of 1
|
||||
assert json.loads(defaulted_extra_vars['extra_vars'])['var2'] == 2
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
def test_display_survey_spec_encrypts_default(survey_spec_factory):
|
||||
spec = survey_spec_factory('var2')
|
||||
spec['spec'][0]['type'] = 'password'
|
||||
spec['spec'][0]['default'] = 'some-default'
|
||||
jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True)
|
||||
assert jt.display_survey_spec()['spec'][0]['default'] == '$encrypted$'
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
@pytest.mark.parametrize("question_type,default,min,max,expect_use,expect_value", [
|
||||
("text", "", 0, 0, True, ''), # default used
|
||||
("text", "", 1, 0, False, 'N/A'), # value less than min length
|
||||
("password", "", 1, 0, False, 'N/A'), # passwords behave the same as text
|
||||
("multiplechoice", "", 0, 0, False, 'N/A'), # historical bug
|
||||
("multiplechoice", "zeb", 0, 0, False, 'N/A'), # zeb not in choices
|
||||
("multiplechoice", "coffee", 0, 0, True, 'coffee'),
|
||||
("multiselect", None, 0, 0, False, 'N/A'), # NOTE: Behavior is arguable, value of [] may be prefered
|
||||
("multiselect", "", 0, 0, False, 'N/A'),
|
||||
("multiselect", ["zeb"], 0, 0, False, 'N/A'),
|
||||
("multiselect", ["milk"], 0, 0, True, ["milk"]),
|
||||
("multiselect", ["orange\nmilk"], 0, 0, False, 'N/A'), # historical bug
|
||||
])
|
||||
def test_optional_survey_question_defaults(
|
||||
survey_spec_factory, question_type, default, min, max, expect_use, expect_value):
|
||||
spec = survey_spec_factory([
|
||||
{
|
||||
"required": False,
|
||||
"default": default,
|
||||
"choices": "orange\nmilk\nchocolate\ncoffee",
|
||||
"variable": "c",
|
||||
"min": min,
|
||||
"max": max,
|
||||
"type": question_type
|
||||
},
|
||||
])
|
||||
jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True)
|
||||
defaulted_extra_vars = jt._update_unified_job_kwargs({}, {})
|
||||
element = spec['spec'][0]
|
||||
if expect_use:
|
||||
assert jt._survey_element_validation(element, {element['variable']: element['default']}) == []
|
||||
else:
|
||||
assert jt._survey_element_validation(element, {element['variable']: element['default']})
|
||||
if expect_use:
|
||||
assert json.loads(defaulted_extra_vars['extra_vars'])['c'] == expect_value
|
||||
else:
|
||||
assert 'c' not in defaulted_extra_vars['extra_vars']
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
@pytest.mark.parametrize("question_type,default,maxlen,kwargs,expected", [
|
||||
('text', None, 5, {}, {}),
|
||||
('text', '', 5, {}, {'x': ''}),
|
||||
('text', 'y', 5, {}, {'x': 'y'}),
|
||||
('text', 'too-long', 5, {}, {}),
|
||||
('password', None, 5, {}, {}),
|
||||
('password', '', 5, {}, {'x': ''}),
|
||||
('password', ENCRYPTED_SECRET, 5, {}, {}), # len(secret) == 6, invalid
|
||||
('password', ENCRYPTED_SECRET, 10, {}, {'x': ENCRYPTED_SECRET}), # len(secret) < 10, valid
|
||||
('password', None, 5, {'extra_vars': {'x': '$encrypted$'}}, {}),
|
||||
('password', '', 5, {'extra_vars': {'x': '$encrypted$'}}, {'x': ''}),
|
||||
('password', None, 5, {'extra_vars': {'x': 'y'}}, {'x': 'y'}),
|
||||
('password', '', 5, {'extra_vars': {'x': 'y'}}, {'x': 'y'}),
|
||||
('password', 'foo', 5, {'extra_vars': {'x': 'y'}}, {'x': 'y'}),
|
||||
('password', None, 5, {'extra_vars': {'x': ''}}, {'x': ''}),
|
||||
('password', '', 5, {'extra_vars': {'x': ''}}, {'x': ''}),
|
||||
('password', 'foo', 5, {'extra_vars': {'x': ''}}, {'x': ''}),
|
||||
('password', ENCRYPTED_SECRET, 5, {'extra_vars': {'x': '$encrypted$'}}, {}),
|
||||
('password', ENCRYPTED_SECRET, 10, {'extra_vars': {'x': '$encrypted$'}}, {'x': ENCRYPTED_SECRET}),
|
||||
], ids=DistinctParametrize())
|
||||
def test_survey_encryption_defaults(survey_spec_factory, question_type, default, maxlen, kwargs, expected):
|
||||
spec = survey_spec_factory([
|
||||
{
|
||||
"required": True,
|
||||
"variable": "x",
|
||||
"min": 0,
|
||||
"max": maxlen,
|
||||
"type": question_type
|
||||
},
|
||||
])
|
||||
if default is not None:
|
||||
spec['spec'][0]['default'] = default
|
||||
else:
|
||||
spec['spec'][0].pop('default', None)
|
||||
jt = JobTemplate(name="test-jt", survey_spec=spec, survey_enabled=True)
|
||||
extra_vars = json.loads(jt._update_unified_job_kwargs({}, kwargs).get('extra_vars'))
|
||||
assert extra_vars == expected
|
||||
|
||||
|
||||
@pytest.mark.survey
|
||||
class TestWorkflowSurveys:
|
||||
def test_update_kwargs_survey_defaults(self, survey_spec_factory):
|
||||
"Assure that the survey default over-rides a JT variable"
|
||||
spec = survey_spec_factory('var1')
|
||||
spec['spec'][0]['default'] = 3
|
||||
spec['spec'][0]['required'] = False
|
||||
wfjt = WorkflowJobTemplate(
|
||||
name="test-wfjt",
|
||||
survey_spec=spec,
|
||||
survey_enabled=True,
|
||||
extra_vars="var1: 5"
|
||||
)
|
||||
updated_extra_vars = wfjt._update_unified_job_kwargs({}, {})
|
||||
assert 'extra_vars' in updated_extra_vars
|
||||
assert json.loads(updated_extra_vars['extra_vars'])['var1'] == 3
|
||||
assert wfjt.can_start_without_user_input()
|
||||
|
||||
def test_variables_needed_to_start(self, survey_spec_factory):
|
||||
"Assure that variables_needed_to_start output contains mandatory vars"
|
||||
spec = survey_spec_factory(['question1', 'question2', 'question3'])
|
||||
spec['spec'][0]['required'] = False
|
||||
spec['spec'][1]['required'] = True
|
||||
spec['spec'][2]['required'] = False
|
||||
wfjt = WorkflowJobTemplate(
|
||||
name="test-wfjt",
|
||||
survey_spec=spec,
|
||||
survey_enabled=True,
|
||||
extra_vars="question2: hiworld"
|
||||
)
|
||||
assert wfjt.variables_needed_to_start == ['question2']
|
||||
assert not wfjt.can_start_without_user_input()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize('provided_vars,valid', [
|
||||
({'tmpl_var': 'bar'}, True), # same as template, not counted as prompts
|
||||
({'tmpl_var': 'bar2'}, False), # different value from template, not okay
|
||||
({'tmpl_var': 'bar', 'a': 2}, False), # extra key, not okay
|
||||
({'tmpl_var': 'bar', False: 2}, False), # Falsy key
|
||||
({'tmpl_var': 'bar', u'🐉': u'🐉'}, False), # dragons
|
||||
])
|
||||
class TestExtraVarsNoPrompt:
|
||||
def process_vars_and_assert(self, tmpl, provided_vars, valid):
|
||||
prompted_fields, ignored_fields, errors = tmpl._accept_or_ignore_job_kwargs(
|
||||
extra_vars=provided_vars
|
||||
)
|
||||
if valid:
|
||||
assert not ignored_fields
|
||||
assert not errors
|
||||
else:
|
||||
assert ignored_fields
|
||||
assert errors
|
||||
|
||||
def test_jt_extra_vars_counting(self, provided_vars, valid):
|
||||
jt = JobTemplate(
|
||||
name='foo',
|
||||
extra_vars={'tmpl_var': 'bar'},
|
||||
project=Project(),
|
||||
project_id=42,
|
||||
playbook='helloworld.yml',
|
||||
inventory=Inventory(),
|
||||
inventory_id=42
|
||||
)
|
||||
prompted_fields, ignored_fields, errors = jt._accept_or_ignore_job_kwargs(
|
||||
extra_vars=provided_vars
|
||||
)
|
||||
self.process_vars_and_assert(jt, provided_vars, valid)
|
||||
|
||||
def test_wfjt_extra_vars_counting(self, provided_vars, valid):
|
||||
wfjt = WorkflowJobTemplate(
|
||||
name='foo',
|
||||
extra_vars={'tmpl_var': 'bar'}
|
||||
)
|
||||
prompted_fields, ignored_fields, errors = wfjt._accept_or_ignore_job_kwargs(
|
||||
extra_vars=provided_vars
|
||||
)
|
||||
self.process_vars_and_assert(wfjt, provided_vars, valid)
|
||||
@@ -0,0 +1,69 @@
|
||||
import pytest
|
||||
|
||||
from awx.main.models import SystemJobTemplate
|
||||
|
||||
|
||||
@pytest.mark.parametrize("extra_data", [
|
||||
'{ "days": 1 }',
|
||||
'{ "days": 100 }',
|
||||
'{ "days": 0 }',
|
||||
{"days": 0},
|
||||
{"days": 1},
|
||||
{"days": 13435},
|
||||
])
|
||||
def test_valid__clean_extra_data_system_jobs(extra_data):
|
||||
accepted, rejected, errors = SystemJobTemplate(
|
||||
job_type='cleanup_jobs'
|
||||
).accept_or_ignore_variables(extra_data)
|
||||
assert not rejected
|
||||
assert not errors
|
||||
|
||||
|
||||
@pytest.mark.parametrize("extra_data", [
|
||||
'{ "days": 1.2 }',
|
||||
'{ "days": -1.2 }',
|
||||
'{ "days": -111 }',
|
||||
'{ "days": "-111" }',
|
||||
'{ "days": false }',
|
||||
'{ "days": "foobar" }',
|
||||
{"days": 1.2},
|
||||
{"days": -1.2},
|
||||
{"days": -111},
|
||||
{"days": "-111"},
|
||||
{"days": False},
|
||||
{"days": "foobar"},
|
||||
])
|
||||
def test_invalid__extra_data_system_jobs(extra_data):
|
||||
accepted, rejected, errors = SystemJobTemplate(
|
||||
job_type='cleanup_jobs'
|
||||
).accept_or_ignore_variables(extra_data)
|
||||
assert str(errors['extra_vars'][0]) == u'days must be a positive integer.'
|
||||
|
||||
|
||||
def test_unallowed_system_job_data():
|
||||
sjt = SystemJobTemplate(job_type='cleanup_jobs')
|
||||
accepted, ignored, errors = sjt.accept_or_ignore_variables({
|
||||
'days': 34,
|
||||
'foobar': 'baz'
|
||||
})
|
||||
assert 'foobar' in ignored
|
||||
assert 'days' in accepted
|
||||
|
||||
|
||||
def test_reject_other_prommpts():
|
||||
sjt = SystemJobTemplate()
|
||||
accepted, ignored, errors = sjt._accept_or_ignore_job_kwargs(limit="")
|
||||
assert accepted == {}
|
||||
assert 'not allowed on launch' in errors['limit'][0]
|
||||
|
||||
|
||||
def test_reject_some_accept_some():
|
||||
sjt = SystemJobTemplate(job_type='cleanup_jobs')
|
||||
accepted, ignored, errors = sjt._accept_or_ignore_job_kwargs(limit="", extra_vars={
|
||||
'days': 34,
|
||||
'foobar': 'baz'
|
||||
})
|
||||
assert accepted == {"extra_vars": {"days": 34}}
|
||||
assert ignored == {"limit": "", "extra_vars": {"foobar": "baz"}}
|
||||
assert 'not allowed on launch' in errors['limit'][0]
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
from awx.main.models import (
|
||||
UnifiedJob,
|
||||
UnifiedJobTemplate,
|
||||
WorkflowJob,
|
||||
WorkflowJobNode,
|
||||
WorkflowApprovalTemplate,
|
||||
Job,
|
||||
User,
|
||||
Project,
|
||||
JobTemplate,
|
||||
Inventory
|
||||
)
|
||||
|
||||
|
||||
def test_incorrectly_formatted_variables():
|
||||
bad_data = '{"bar":"foo'
|
||||
accepted, ignored, errors = UnifiedJobTemplate().accept_or_ignore_variables(bad_data)
|
||||
assert not accepted
|
||||
assert ignored == bad_data
|
||||
assert 'Cannot parse as JSON' in str(errors['extra_vars'][0])
|
||||
|
||||
|
||||
def test_unified_job_workflow_attributes():
|
||||
with mock.patch('django.db.ConnectionRouter.db_for_write'):
|
||||
job = UnifiedJob(id=1, name="job-1", launch_type="workflow")
|
||||
job.unified_job_node = WorkflowJobNode(workflow_job=WorkflowJob(pk=1))
|
||||
|
||||
assert job.spawned_by_workflow is True
|
||||
assert job.workflow_job_id == 1
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def unified_job(mocker):
|
||||
mocker.patch.object(UnifiedJob, 'can_cancel', return_value=True)
|
||||
j = UnifiedJob()
|
||||
j.status = 'pending'
|
||||
j.cancel_flag = None
|
||||
j.save = mocker.MagicMock()
|
||||
j.websocket_emit_status = mocker.MagicMock()
|
||||
return j
|
||||
|
||||
|
||||
def test_cancel(unified_job):
|
||||
|
||||
unified_job.cancel()
|
||||
|
||||
assert unified_job.cancel_flag is True
|
||||
assert unified_job.status == 'canceled'
|
||||
assert unified_job.job_explanation == ''
|
||||
# Note: the websocket emit status check is just reflecting the state of the current code.
|
||||
# Some more thought may want to go into only emitting canceled if/when the job record
|
||||
# status is changed to canceled. Unlike, currently, where it's emitted unconditionally.
|
||||
unified_job.websocket_emit_status.assert_called_with("canceled")
|
||||
unified_job.save.assert_called_with(update_fields=['cancel_flag', 'start_args', 'status'])
|
||||
|
||||
|
||||
def test_cancel_job_explanation(unified_job):
|
||||
job_explanation = 'giggity giggity'
|
||||
|
||||
unified_job.cancel(job_explanation=job_explanation)
|
||||
|
||||
assert unified_job.job_explanation == job_explanation
|
||||
unified_job.save.assert_called_with(update_fields=['cancel_flag', 'start_args', 'status', 'job_explanation'])
|
||||
|
||||
|
||||
def test_organization_copy_to_jobs():
|
||||
'''
|
||||
All unified job types should infer their organization from their template organization
|
||||
'''
|
||||
for cls in UnifiedJobTemplate.__subclasses__():
|
||||
if cls is WorkflowApprovalTemplate:
|
||||
continue # these do not track organization
|
||||
assert 'organization' in cls._get_unified_job_field_names(), cls
|
||||
|
||||
|
||||
def test_log_representation():
|
||||
'''
|
||||
Common representation used inside of log messages
|
||||
'''
|
||||
uj = UnifiedJob(status='running', id=4)
|
||||
job = Job(status='running', id=4)
|
||||
assert job.log_format == 'job 4 (running)'
|
||||
assert uj.log_format == 'unified_job 4 (running)'
|
||||
|
||||
|
||||
class TestMetaVars:
|
||||
'''
|
||||
Corresponding functional test exists for cases with indirect relationships
|
||||
'''
|
||||
|
||||
def test_job_metavars(self):
|
||||
maker = User(username='joe', pk=47, id=47)
|
||||
inv = Inventory(name='example-inv', id=45)
|
||||
assert Job(
|
||||
name='fake-job',
|
||||
pk=42, id=42,
|
||||
launch_type='manual',
|
||||
created_by=maker,
|
||||
inventory=inv
|
||||
).awx_meta_vars() == {
|
||||
'tower_job_id': 42,
|
||||
'awx_job_id': 42,
|
||||
'tower_job_launch_type': 'manual',
|
||||
'awx_job_launch_type': 'manual',
|
||||
'awx_user_name': 'joe',
|
||||
'tower_user_name': 'joe',
|
||||
'awx_user_email': '',
|
||||
'tower_user_email': '',
|
||||
'awx_user_first_name': '',
|
||||
'tower_user_first_name': '',
|
||||
'awx_user_last_name': '',
|
||||
'tower_user_last_name': '',
|
||||
'awx_user_id': 47,
|
||||
'tower_user_id': 47,
|
||||
'tower_inventory_id': 45,
|
||||
'awx_inventory_id': 45,
|
||||
'tower_inventory_name': 'example-inv',
|
||||
'awx_inventory_name': 'example-inv'
|
||||
}
|
||||
|
||||
def test_project_update_metavars(self):
|
||||
data = Job(
|
||||
name='fake-job',
|
||||
pk=40, id=40,
|
||||
launch_type='manual',
|
||||
project=Project(
|
||||
name='jobs-sync',
|
||||
scm_revision='12345444'
|
||||
),
|
||||
job_template=JobTemplate(
|
||||
name='jobs-jt',
|
||||
id=92, pk=92
|
||||
)
|
||||
).awx_meta_vars()
|
||||
assert data['awx_project_revision'] == '12345444'
|
||||
assert 'tower_job_template_id' in data
|
||||
assert data['tower_job_template_id'] == 92
|
||||
assert data['tower_job_template_name'] == 'jobs-jt'
|
||||
@@ -0,0 +1,251 @@
|
||||
import pytest
|
||||
|
||||
from awx.main.models.jobs import JobTemplate
|
||||
from awx.main.models import Inventory, CredentialType, Credential, Project
|
||||
from awx.main.models.workflow import (
|
||||
WorkflowJobTemplate, WorkflowJobTemplateNode,
|
||||
WorkflowJob, WorkflowJobNode
|
||||
)
|
||||
from unittest import mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def credential():
|
||||
ssh_type = CredentialType.defaults['ssh']()
|
||||
return Credential(
|
||||
id=43,
|
||||
name='example-cred',
|
||||
credential_type=ssh_type,
|
||||
inputs={'username': 'asdf', 'password': 'asdf'}
|
||||
)
|
||||
|
||||
|
||||
class TestWorkflowJobInheritNodesMixin():
|
||||
class TestCreateWorkflowJobNodes():
|
||||
@pytest.fixture
|
||||
def job_templates(self):
|
||||
return [JobTemplate() for i in range(0, 10)]
|
||||
|
||||
@pytest.fixture
|
||||
def job_template_nodes(self, job_templates):
|
||||
return [WorkflowJobTemplateNode(unified_job_template=job_templates[i]) for i in range(0, 10)]
|
||||
|
||||
def test__create_workflow_job_nodes(self, mocker, job_template_nodes):
|
||||
workflow_job_node_create = mocker.patch('awx.main.models.WorkflowJobTemplateNode.create_workflow_job_node')
|
||||
|
||||
workflow_job = WorkflowJob()
|
||||
workflow_job._create_workflow_nodes(job_template_nodes)
|
||||
|
||||
for job_template_node in job_template_nodes:
|
||||
workflow_job_node_create.assert_any_call(workflow_job=workflow_job)
|
||||
|
||||
class TestMapWorkflowJobNodes():
|
||||
@pytest.fixture
|
||||
def job_template_nodes(self):
|
||||
return [WorkflowJobTemplateNode(id=i) for i in range(0, 20)]
|
||||
|
||||
@pytest.fixture
|
||||
def job_nodes(self):
|
||||
return [WorkflowJobNode(id=i) for i in range(100, 120)]
|
||||
|
||||
def test__map_workflow_job_nodes(self, job_template_nodes, job_nodes, mocker):
|
||||
mixin = WorkflowJob()
|
||||
wj_node = WorkflowJobNode()
|
||||
mocker.patch('awx.main.models.workflow.WorkflowJobTemplateNode.create_workflow_job_node',
|
||||
return_value=wj_node)
|
||||
|
||||
node_ids_map = mixin._create_workflow_nodes(job_template_nodes, user=None)
|
||||
assert len(node_ids_map) == len(job_template_nodes)
|
||||
|
||||
for i, job_template_node in enumerate(job_template_nodes):
|
||||
assert node_ids_map[job_template_node.id] == wj_node
|
||||
|
||||
class TestInheritRelationship():
|
||||
@pytest.fixture
|
||||
def job_template_nodes(self, mocker):
|
||||
nodes = [mocker.MagicMock(id=i, pk=i) for i in range(0, 10)]
|
||||
|
||||
for i in range(0, 9):
|
||||
nodes[i].success_nodes = mocker.MagicMock(
|
||||
all=mocker.MagicMock(return_value=[mocker.MagicMock(id=i + 1, pk=i + 1)]))
|
||||
nodes[i].always_nodes = mocker.MagicMock(all=mocker.MagicMock(return_value=[]))
|
||||
nodes[i].failure_nodes = mocker.MagicMock(all=mocker.MagicMock(return_value=[]))
|
||||
new_wj_node = mocker.MagicMock(success_nodes=mocker.MagicMock())
|
||||
nodes[i].create_workflow_job_node = mocker.MagicMock(return_value=new_wj_node)
|
||||
|
||||
return nodes
|
||||
|
||||
@pytest.fixture
|
||||
def job_nodes(self, mocker):
|
||||
nodes = [mocker.MagicMock(id=i) for i in range(100, 110)]
|
||||
return nodes
|
||||
|
||||
@pytest.fixture
|
||||
def job_nodes_dict(self, job_nodes):
|
||||
_map = {}
|
||||
for n in job_nodes:
|
||||
_map[n.id] = n
|
||||
return _map
|
||||
|
||||
|
||||
def test__inherit_relationship(self, mocker, job_template_nodes, job_nodes, job_nodes_dict):
|
||||
wj = WorkflowJob()
|
||||
|
||||
node_ids_map = wj._create_workflow_nodes(job_template_nodes)
|
||||
wj._inherit_node_relationships(job_template_nodes, node_ids_map)
|
||||
|
||||
for i in range(0, 8):
|
||||
node_ids_map[i].success_nodes.add.assert_any_call(node_ids_map[i + 1])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_job_unit():
|
||||
return WorkflowJob(name='workflow', status='new')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_job_template_unit():
|
||||
return WorkflowJobTemplate(name='workflow')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def jt_ask(job_template_factory):
|
||||
# note: factory sets ask_xxxx_on_launch to true for inventory & credential
|
||||
jt = job_template_factory(name='example-jt', persisted=False).job_template
|
||||
jt.ask_variables_on_launch = True
|
||||
jt.ask_job_type_on_launch = True
|
||||
jt.ask_skip_tags_on_launch = True
|
||||
jt.ask_limit_on_launch = True
|
||||
jt.ask_tags_on_launch = True
|
||||
jt.ask_verbosity_on_launch = True
|
||||
return jt
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project_unit():
|
||||
return Project(name='example-proj')
|
||||
|
||||
|
||||
example_prompts = dict(job_type='check', job_tags='quack', limit='duck', skip_tags='oink')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_node_no_prompts(workflow_job_unit, jt_ask):
|
||||
return WorkflowJobNode(workflow_job=workflow_job_unit, unified_job_template=jt_ask)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_node_with_prompts(job_node_no_prompts, mocker):
|
||||
job_node_no_prompts.char_prompts = example_prompts
|
||||
job_node_no_prompts.inventory = Inventory(name='example-inv', id=45)
|
||||
job_node_no_prompts.inventory_id = 45
|
||||
return job_node_no_prompts
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def wfjt_node_no_prompts(workflow_job_template_unit, jt_ask):
|
||||
node = WorkflowJobTemplateNode(
|
||||
workflow_job_template=workflow_job_template_unit,
|
||||
unified_job_template=jt_ask
|
||||
)
|
||||
return node
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def wfjt_node_with_prompts(wfjt_node_no_prompts, mocker):
|
||||
wfjt_node_no_prompts.char_prompts = example_prompts
|
||||
wfjt_node_no_prompts.inventory = Inventory(name='example-inv')
|
||||
return wfjt_node_no_prompts
|
||||
|
||||
|
||||
def test_node_getter_and_setters():
|
||||
node = WorkflowJobTemplateNode()
|
||||
node.job_type = 'check'
|
||||
assert node.char_prompts['job_type'] == 'check'
|
||||
assert node.job_type == 'check'
|
||||
|
||||
|
||||
class TestWorkflowJobCreate:
|
||||
def test_create_no_prompts(self, wfjt_node_no_prompts, workflow_job_unit, mocker):
|
||||
mock_create = mocker.MagicMock()
|
||||
with mocker.patch('awx.main.models.WorkflowJobNode.objects.create', mock_create):
|
||||
wfjt_node_no_prompts.create_workflow_job_node(workflow_job=workflow_job_unit)
|
||||
mock_create.assert_called_once_with(
|
||||
all_parents_must_converge=False,
|
||||
extra_data={},
|
||||
survey_passwords={},
|
||||
char_prompts=wfjt_node_no_prompts.char_prompts,
|
||||
inventory=None,
|
||||
unified_job_template=wfjt_node_no_prompts.unified_job_template,
|
||||
workflow_job=workflow_job_unit,
|
||||
identifier=mocker.ANY)
|
||||
|
||||
def test_create_with_prompts(self, wfjt_node_with_prompts, workflow_job_unit, credential, mocker):
|
||||
mock_create = mocker.MagicMock()
|
||||
with mocker.patch('awx.main.models.WorkflowJobNode.objects.create', mock_create):
|
||||
wfjt_node_with_prompts.create_workflow_job_node(
|
||||
workflow_job=workflow_job_unit
|
||||
)
|
||||
mock_create.assert_called_once_with(
|
||||
all_parents_must_converge=False,
|
||||
extra_data={},
|
||||
survey_passwords={},
|
||||
char_prompts=wfjt_node_with_prompts.char_prompts,
|
||||
inventory=wfjt_node_with_prompts.inventory,
|
||||
unified_job_template=wfjt_node_with_prompts.unified_job_template,
|
||||
workflow_job=workflow_job_unit,
|
||||
identifier=mocker.ANY)
|
||||
|
||||
|
||||
@mock.patch('awx.main.models.workflow.WorkflowNodeBase.get_parent_nodes', lambda self: [])
|
||||
class TestWorkflowJobNodeJobKWARGS:
|
||||
"""
|
||||
Tests for building the keyword arguments that go into creating and
|
||||
launching a new job that corresponds to a workflow node.
|
||||
"""
|
||||
kwargs_base = {'_eager_fields': {'launch_type': 'workflow'}}
|
||||
|
||||
def test_null_kwargs(self, job_node_no_prompts):
|
||||
assert job_node_no_prompts.get_job_kwargs() == self.kwargs_base
|
||||
|
||||
def test_inherit_workflow_job_and_node_extra_vars(self, job_node_no_prompts):
|
||||
job_node_no_prompts.extra_data = {"b": 98}
|
||||
workflow_job = job_node_no_prompts.workflow_job
|
||||
workflow_job.extra_vars = '{"a": 84}'
|
||||
assert job_node_no_prompts.get_job_kwargs() == dict(
|
||||
extra_vars={'a': 84, 'b': 98}, **self.kwargs_base)
|
||||
|
||||
def test_char_prompts_and_res_node_prompts(self, job_node_with_prompts):
|
||||
# TBD: properly handle multicred credential assignment
|
||||
expect_kwargs = dict(
|
||||
inventory=job_node_with_prompts.inventory,
|
||||
**example_prompts)
|
||||
expect_kwargs.update(self.kwargs_base)
|
||||
assert job_node_with_prompts.get_job_kwargs() == expect_kwargs
|
||||
|
||||
def test_reject_some_node_prompts(self, job_node_with_prompts):
|
||||
# TBD: properly handle multicred credential assignment
|
||||
job_node_with_prompts.unified_job_template.ask_inventory_on_launch = False
|
||||
job_node_with_prompts.unified_job_template.ask_job_type_on_launch = False
|
||||
expect_kwargs = dict(inventory=job_node_with_prompts.inventory,
|
||||
**example_prompts)
|
||||
expect_kwargs.update(self.kwargs_base)
|
||||
expect_kwargs.pop('inventory')
|
||||
expect_kwargs.pop('job_type')
|
||||
assert job_node_with_prompts.get_job_kwargs() == expect_kwargs
|
||||
|
||||
def test_no_accepted_project_node_prompts(self, job_node_no_prompts, project_unit):
|
||||
job_node_no_prompts.unified_job_template = project_unit
|
||||
assert job_node_no_prompts.get_job_kwargs() == self.kwargs_base
|
||||
|
||||
def test_extra_vars_node_prompts(self, wfjt_node_no_prompts):
|
||||
wfjt_node_no_prompts.extra_vars = {'foo': 'bar'}
|
||||
assert wfjt_node_no_prompts.prompts_dict() == {'extra_vars': {'foo': 'bar'}}
|
||||
|
||||
def test_string_extra_vars_node_prompts(self, wfjt_node_no_prompts):
|
||||
wfjt_node_no_prompts.extra_vars = '{"foo": "bar"}'
|
||||
assert wfjt_node_no_prompts.prompts_dict() == {'extra_vars': {'foo': 'bar'}}
|
||||
|
||||
|
||||
def test_get_ask_mapping_integrity():
|
||||
assert list(WorkflowJobTemplate.get_ask_mapping().keys()) == ['extra_vars', 'inventory', 'limit', 'scm_branch']
|
||||
@@ -0,0 +1,113 @@
|
||||
from unittest import mock
|
||||
import datetime as dt
|
||||
from django.core.mail.message import EmailMessage
|
||||
|
||||
import awx.main.notifications.grafana_backend as grafana_backend
|
||||
|
||||
|
||||
def test_send_messages():
|
||||
with mock.patch('awx.main.notifications.grafana_backend.requests') as requests_mock:
|
||||
requests_mock.post.return_value.status_code = 200
|
||||
m={}
|
||||
m['started'] = dt.datetime.utcfromtimestamp(60).isoformat()
|
||||
m['finished'] = dt.datetime.utcfromtimestamp(120).isoformat()
|
||||
m['subject'] = "test subject"
|
||||
backend = grafana_backend.GrafanaBackend("testapikey")
|
||||
message = EmailMessage(m['subject'],{"started":m['started'],"finished":m['finished']}, [], ['https://example.com', ])
|
||||
sent_messages = backend.send_messages([message, ])
|
||||
requests_mock.post.assert_called_once_with(
|
||||
'https://example.com/api/annotations',
|
||||
headers={'Content-Type': 'application/json', 'Authorization': 'Bearer testapikey'},
|
||||
json={'text': 'test subject', 'isRegion': True, 'timeEnd': 120000, 'panelId': None, 'time': 60000, 'dashboardId': None},
|
||||
verify=True)
|
||||
assert sent_messages == 1
|
||||
|
||||
|
||||
def test_send_messages_with_no_verify_ssl():
|
||||
with mock.patch('awx.main.notifications.grafana_backend.requests') as requests_mock:
|
||||
requests_mock.post.return_value.status_code = 200
|
||||
m={}
|
||||
m['started'] = dt.datetime.utcfromtimestamp(60).isoformat()
|
||||
m['finished'] = dt.datetime.utcfromtimestamp(120).isoformat()
|
||||
m['subject'] = "test subject"
|
||||
backend = grafana_backend.GrafanaBackend("testapikey",grafana_no_verify_ssl=True)
|
||||
message = EmailMessage(m['subject'],{"started":m['started'],"finished":m['finished']}, [], ['https://example.com', ])
|
||||
sent_messages = backend.send_messages([message, ])
|
||||
requests_mock.post.assert_called_once_with(
|
||||
'https://example.com/api/annotations',
|
||||
headers={'Content-Type': 'application/json', 'Authorization': 'Bearer testapikey'},
|
||||
json={'text': 'test subject', 'isRegion': True, 'timeEnd': 120000, 'panelId': None,'time': 60000, 'dashboardId': None},
|
||||
verify=False)
|
||||
assert sent_messages == 1
|
||||
|
||||
|
||||
def test_send_messages_with_dashboardid():
|
||||
with mock.patch('awx.main.notifications.grafana_backend.requests') as requests_mock:
|
||||
requests_mock.post.return_value.status_code = 200
|
||||
m={}
|
||||
m['started'] = dt.datetime.utcfromtimestamp(60).isoformat()
|
||||
m['finished'] = dt.datetime.utcfromtimestamp(120).isoformat()
|
||||
m['subject'] = "test subject"
|
||||
backend = grafana_backend.GrafanaBackend("testapikey",dashboardId=42)
|
||||
message = EmailMessage(m['subject'],{"started":m['started'],"finished":m['finished']}, [], ['https://example.com', ])
|
||||
sent_messages = backend.send_messages([message, ])
|
||||
requests_mock.post.assert_called_once_with(
|
||||
'https://example.com/api/annotations',
|
||||
headers={'Content-Type': 'application/json', 'Authorization': 'Bearer testapikey'},
|
||||
json={'text': 'test subject', 'isRegion': True, 'timeEnd': 120000, 'panelId': None, 'time': 60000, 'dashboardId': 42},
|
||||
verify=True)
|
||||
assert sent_messages == 1
|
||||
|
||||
|
||||
def test_send_messages_with_panelid():
|
||||
with mock.patch('awx.main.notifications.grafana_backend.requests') as requests_mock:
|
||||
requests_mock.post.return_value.status_code = 200
|
||||
m={}
|
||||
m['started'] = dt.datetime.utcfromtimestamp(60).isoformat()
|
||||
m['finished'] = dt.datetime.utcfromtimestamp(120).isoformat()
|
||||
m['subject'] = "test subject"
|
||||
backend = grafana_backend.GrafanaBackend("testapikey",dashboardId=None,panelId=42)
|
||||
message = EmailMessage(m['subject'],{"started":m['started'],"finished":m['finished']}, [], ['https://example.com', ])
|
||||
sent_messages = backend.send_messages([message, ])
|
||||
requests_mock.post.assert_called_once_with(
|
||||
'https://example.com/api/annotations',
|
||||
headers={'Content-Type': 'application/json', 'Authorization': 'Bearer testapikey'},
|
||||
json={'text': 'test subject', 'isRegion': True, 'timeEnd': 120000, 'panelId': 42, 'time': 60000, 'dashboardId': None},
|
||||
verify=True)
|
||||
assert sent_messages == 1
|
||||
|
||||
|
||||
def test_send_messages_with_bothids():
|
||||
with mock.patch('awx.main.notifications.grafana_backend.requests') as requests_mock:
|
||||
requests_mock.post.return_value.status_code = 200
|
||||
m={}
|
||||
m['started'] = dt.datetime.utcfromtimestamp(60).isoformat()
|
||||
m['finished'] = dt.datetime.utcfromtimestamp(120).isoformat()
|
||||
m['subject'] = "test subject"
|
||||
backend = grafana_backend.GrafanaBackend("testapikey",dashboardId=42,panelId=42)
|
||||
message = EmailMessage(m['subject'],{"started":m['started'],"finished":m['finished']}, [], ['https://example.com', ])
|
||||
sent_messages = backend.send_messages([message, ])
|
||||
requests_mock.post.assert_called_once_with(
|
||||
'https://example.com/api/annotations',
|
||||
headers={'Content-Type': 'application/json', 'Authorization': 'Bearer testapikey'},
|
||||
json={'text': 'test subject', 'isRegion': True, 'timeEnd': 120000, 'panelId': 42, 'time': 60000, 'dashboardId': 42},
|
||||
verify=True)
|
||||
assert sent_messages == 1
|
||||
|
||||
|
||||
def test_send_messages_with_tags():
|
||||
with mock.patch('awx.main.notifications.grafana_backend.requests') as requests_mock:
|
||||
requests_mock.post.return_value.status_code = 200
|
||||
m={}
|
||||
m['started'] = dt.datetime.utcfromtimestamp(60).isoformat()
|
||||
m['finished'] = dt.datetime.utcfromtimestamp(120).isoformat()
|
||||
m['subject'] = "test subject"
|
||||
backend = grafana_backend.GrafanaBackend("testapikey",dashboardId=None,panelId=None,annotation_tags=["ansible"])
|
||||
message = EmailMessage(m['subject'],{"started":m['started'],"finished":m['finished']}, [], ['https://example.com', ])
|
||||
sent_messages = backend.send_messages([message, ])
|
||||
requests_mock.post.assert_called_once_with(
|
||||
'https://example.com/api/annotations',
|
||||
headers={'Content-Type': 'application/json', 'Authorization': 'Bearer testapikey'},
|
||||
json={'tags': ['ansible'], 'text': 'test subject', 'isRegion': True, 'timeEnd': 120000, 'panelId': None, 'time': 60000, 'dashboardId': None},
|
||||
verify=True)
|
||||
assert sent_messages == 1
|
||||
@@ -0,0 +1,60 @@
|
||||
import json
|
||||
|
||||
from unittest import mock
|
||||
from django.core.mail.message import EmailMessage
|
||||
|
||||
import awx.main.notifications.rocketchat_backend as rocketchat_backend
|
||||
|
||||
|
||||
def test_send_messages():
|
||||
with mock.patch('awx.main.notifications.rocketchat_backend.requests') as requests_mock:
|
||||
requests_mock.post.return_value.status_code = 201
|
||||
backend = rocketchat_backend.RocketChatBackend()
|
||||
message = EmailMessage('test subject', 'test body', [], ['http://example.com', ])
|
||||
sent_messages = backend.send_messages([message, ])
|
||||
requests_mock.post.assert_called_once_with('http://example.com', data='{"text": "test subject"}', verify=True)
|
||||
assert sent_messages == 1
|
||||
|
||||
|
||||
def test_send_messages_with_username():
|
||||
with mock.patch('awx.main.notifications.rocketchat_backend.requests') as requests_mock:
|
||||
requests_mock.post.return_value.status_code = 201
|
||||
backend = rocketchat_backend.RocketChatBackend(rocketchat_username='testuser')
|
||||
message = EmailMessage('test subject', 'test body', [], ['http://example.com', ])
|
||||
sent_messages = backend.send_messages([message, ])
|
||||
|
||||
calls = requests_mock.post.call_args_list
|
||||
assert len(calls) == 1
|
||||
args, kwargs = calls[0]
|
||||
assert args[0] == 'http://example.com'
|
||||
assert json.loads(kwargs['data'])['text'] == 'test subject'
|
||||
assert json.loads(kwargs['data'])['username'] == 'testuser'
|
||||
assert kwargs['verify'] is True
|
||||
assert sent_messages == 1
|
||||
|
||||
|
||||
def test_send_messages_with_icon_url():
|
||||
with mock.patch('awx.main.notifications.rocketchat_backend.requests') as requests_mock:
|
||||
requests_mock.post.return_value.status_code = 201
|
||||
backend = rocketchat_backend.RocketChatBackend(rocketchat_icon_url='http://example.com')
|
||||
message = EmailMessage('test subject', 'test body', [], ['http://example.com', ])
|
||||
sent_messages = backend.send_messages([message, ])
|
||||
|
||||
calls = requests_mock.post.call_args_list
|
||||
assert len(calls) == 1
|
||||
args, kwargs = calls[0]
|
||||
assert args[0] == 'http://example.com'
|
||||
assert json.loads(kwargs['data'])['text'] == 'test subject'
|
||||
assert json.loads(kwargs['data'])['icon_url'] == 'http://example.com'
|
||||
assert kwargs['verify'] is True
|
||||
assert sent_messages == 1
|
||||
|
||||
|
||||
def test_send_messages_with_no_verify_ssl():
|
||||
with mock.patch('awx.main.notifications.rocketchat_backend.requests') as requests_mock:
|
||||
requests_mock.post.return_value.status_code = 201
|
||||
backend = rocketchat_backend.RocketChatBackend(rocketchat_no_verify_ssl=True)
|
||||
message = EmailMessage('test subject', 'test body', [], ['http://example.com', ])
|
||||
sent_messages = backend.send_messages([message, ])
|
||||
requests_mock.post.assert_called_once_with('http://example.com', data='{"text": "test subject"}', verify=False)
|
||||
assert sent_messages == 1
|
||||
@@ -0,0 +1,43 @@
|
||||
import pytest
|
||||
|
||||
from awx.main.scheduler.dag_simple import SimpleDAG
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def node_generator():
|
||||
def fn():
|
||||
return object()
|
||||
return fn
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def simple_cycle_1(node_generator):
|
||||
g = SimpleDAG()
|
||||
nodes = [node_generator() for i in range(4)]
|
||||
for n in nodes:
|
||||
g.add_node(n)
|
||||
|
||||
r'''
|
||||
0
|
||||
/\
|
||||
/ \
|
||||
. .
|
||||
1---.2
|
||||
. |
|
||||
| |
|
||||
-----|
|
||||
.
|
||||
3
|
||||
'''
|
||||
g.add_edge(nodes[0], nodes[1], "success_nodes")
|
||||
g.add_edge(nodes[0], nodes[2], "success_nodes")
|
||||
g.add_edge(nodes[2], nodes[3], "success_nodes")
|
||||
g.add_edge(nodes[2], nodes[1], "success_nodes")
|
||||
g.add_edge(nodes[1], nodes[2], "success_nodes")
|
||||
return (g, nodes)
|
||||
|
||||
|
||||
def test_has_cycle(simple_cycle_1):
|
||||
(g, nodes) = simple_cycle_1
|
||||
|
||||
assert g.has_cycle() is True
|
||||
@@ -0,0 +1,579 @@
|
||||
import pytest
|
||||
import uuid
|
||||
import os
|
||||
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.encoding import smart_text
|
||||
|
||||
from awx.main.scheduler.dag_workflow import WorkflowDAG
|
||||
|
||||
|
||||
class Job():
|
||||
def __init__(self, status='successful'):
|
||||
self.status = status
|
||||
|
||||
|
||||
class WorkflowNode(object):
|
||||
def __init__(self, id=None, job=None, do_not_run=False, unified_job_template=None):
|
||||
self.id = id if id is not None else uuid.uuid4()
|
||||
self.job = job
|
||||
self.do_not_run = do_not_run
|
||||
self.unified_job_template = unified_job_template
|
||||
self.all_parents_must_converge = False
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def wf_node_generator(mocker):
|
||||
pytest.count = 0
|
||||
|
||||
def fn(**kwargs):
|
||||
wfn = WorkflowNode(id=pytest.count, unified_job_template=object(), **kwargs)
|
||||
pytest.count += 1
|
||||
return wfn
|
||||
return fn
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_dag_1(wf_node_generator):
|
||||
g = WorkflowDAG()
|
||||
nodes = [wf_node_generator() for i in range(4)]
|
||||
for n in nodes:
|
||||
g.add_node(n)
|
||||
|
||||
r'''
|
||||
0
|
||||
/\
|
||||
S / \
|
||||
/ \
|
||||
1 |
|
||||
| |
|
||||
F | | S
|
||||
| |
|
||||
3 |
|
||||
\ |
|
||||
F \ |
|
||||
\/
|
||||
2
|
||||
'''
|
||||
g.add_edge(nodes[0], nodes[1], "success_nodes")
|
||||
g.add_edge(nodes[0], nodes[2], "success_nodes")
|
||||
g.add_edge(nodes[1], nodes[3], "failure_nodes")
|
||||
g.add_edge(nodes[3], nodes[2], "failure_nodes")
|
||||
return (g, nodes)
|
||||
|
||||
|
||||
class TestWorkflowDAG():
|
||||
@pytest.fixture
|
||||
def workflow_dag_root_children(self, wf_node_generator):
|
||||
g = WorkflowDAG()
|
||||
wf_root_nodes = [wf_node_generator() for i in range(0, 10)]
|
||||
wf_leaf_nodes = [wf_node_generator() for i in range(0, 10)]
|
||||
|
||||
for n in wf_root_nodes + wf_leaf_nodes:
|
||||
g.add_node(n)
|
||||
|
||||
'''
|
||||
Pair up a root node with a single child via an edge
|
||||
|
||||
R1 R2 ... Rx
|
||||
| | |
|
||||
| | |
|
||||
C1 C2 Cx
|
||||
'''
|
||||
for i, n in enumerate(wf_leaf_nodes):
|
||||
g.add_edge(wf_root_nodes[i], n, 'label')
|
||||
return (g, wf_root_nodes, wf_leaf_nodes)
|
||||
|
||||
|
||||
def test_get_root_nodes(self, workflow_dag_root_children):
|
||||
(g, wf_root_nodes, ignore) = workflow_dag_root_children
|
||||
assert set([n.id for n in wf_root_nodes]) == set([n['node_object'].id for n in g.get_root_nodes()])
|
||||
|
||||
|
||||
class TestDNR():
|
||||
def test_mark_dnr_nodes(self, workflow_dag_1):
|
||||
(g, nodes) = workflow_dag_1
|
||||
|
||||
r'''
|
||||
0
|
||||
/\
|
||||
S / \
|
||||
/ \
|
||||
1 |
|
||||
| |
|
||||
F | | S
|
||||
| |
|
||||
3 |
|
||||
\ |
|
||||
F \ |
|
||||
\/
|
||||
2
|
||||
'''
|
||||
nodes[0].job = Job(status='successful')
|
||||
do_not_run_nodes = g.mark_dnr_nodes()
|
||||
assert 0 == len(do_not_run_nodes)
|
||||
|
||||
r'''
|
||||
0
|
||||
/\
|
||||
S / \
|
||||
/ \
|
||||
S1 |
|
||||
| |
|
||||
F | | S
|
||||
| |
|
||||
DNR 3 |
|
||||
\ |
|
||||
F \ |
|
||||
\/
|
||||
2
|
||||
'''
|
||||
nodes[1].job = Job(status='successful')
|
||||
do_not_run_nodes = g.mark_dnr_nodes()
|
||||
assert 1 == len(do_not_run_nodes)
|
||||
assert nodes[3] == do_not_run_nodes[0]
|
||||
|
||||
|
||||
class TestAllWorkflowNodes():
|
||||
# test workflow convergence is functioning as expected
|
||||
@pytest.fixture
|
||||
def simple_all_convergence(self, wf_node_generator):
|
||||
g = WorkflowDAG()
|
||||
nodes = [wf_node_generator() for i in range(4)]
|
||||
for n in nodes:
|
||||
g.add_node(n)
|
||||
|
||||
r'''
|
||||
0
|
||||
/\
|
||||
S / \ S
|
||||
/ \
|
||||
1 2
|
||||
\ /
|
||||
F \ / S
|
||||
\/
|
||||
3
|
||||
|
||||
'''
|
||||
g.add_edge(nodes[0], nodes[1], "success_nodes")
|
||||
g.add_edge(nodes[0], nodes[2], "success_nodes")
|
||||
g.add_edge(nodes[1], nodes[3], "failure_nodes")
|
||||
g.add_edge(nodes[2], nodes[3], "success_nodes")
|
||||
nodes[3].all_parents_must_converge = True
|
||||
nodes[0].job = Job(status='successful')
|
||||
nodes[1].job = Job(status='failed')
|
||||
nodes[2].job = Job(status='successful')
|
||||
return (g, nodes)
|
||||
|
||||
def test_simple_all_convergence(self, simple_all_convergence):
|
||||
(g, nodes) = simple_all_convergence
|
||||
dnr_nodes = g.mark_dnr_nodes()
|
||||
assert 0 == len(dnr_nodes), "no nodes should be marked DNR"
|
||||
|
||||
nodes_to_run = g.bfs_nodes_to_run()
|
||||
assert 1 == len(nodes_to_run), "Node 3, and only node 3, should be chosen to run"
|
||||
assert nodes[3] == nodes_to_run[0], "Only node 3 should be chosen to run"
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_all_converge_1(self, wf_node_generator):
|
||||
g = WorkflowDAG()
|
||||
nodes = [wf_node_generator() for i in range(3)]
|
||||
for n in nodes:
|
||||
g.add_node(n)
|
||||
r'''
|
||||
0
|
||||
|\ F
|
||||
| \
|
||||
S| 1
|
||||
| /
|
||||
|/ A
|
||||
2
|
||||
'''
|
||||
g.add_edge(nodes[0], nodes[1], "failure_nodes")
|
||||
g.add_edge(nodes[0], nodes[2], "success_nodes")
|
||||
g.add_edge(nodes[1], nodes[2], "always_nodes")
|
||||
nodes[2].all_parents_must_converge = True
|
||||
nodes[0].job = Job(status='successful')
|
||||
return (g, nodes)
|
||||
|
||||
def test_all_converge_edge_case_1(self, workflow_all_converge_1):
|
||||
(g, nodes) = workflow_all_converge_1
|
||||
dnr_nodes = g.mark_dnr_nodes()
|
||||
assert 2 == len(dnr_nodes), "node[1] and node[2] should be marked DNR"
|
||||
assert nodes[1] == dnr_nodes[0], "Node 1 should be marked DNR"
|
||||
assert nodes[2] == dnr_nodes[1], "Node 2 should be marked DNR"
|
||||
|
||||
nodes_to_run = g.bfs_nodes_to_run()
|
||||
assert 0 == len(nodes_to_run), "No nodes should be chosen to run"
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_all_converge_2(self, wf_node_generator):
|
||||
"""The ordering of _1 and this test, _2, is _slightly_ different.
|
||||
The hope is that topological sorting results in 2 being processed before 3
|
||||
and/or 3 before 2.
|
||||
"""
|
||||
g = WorkflowDAG()
|
||||
nodes = [wf_node_generator() for i in range(3)]
|
||||
for n in nodes:
|
||||
g.add_node(n)
|
||||
r'''
|
||||
0
|
||||
|\ S
|
||||
| \
|
||||
F| 1
|
||||
| /
|
||||
|/ A
|
||||
2
|
||||
'''
|
||||
g.add_edge(nodes[0], nodes[1], "success_nodes")
|
||||
g.add_edge(nodes[0], nodes[2], "failure_nodes")
|
||||
g.add_edge(nodes[1], nodes[2], "always_nodes")
|
||||
nodes[2].all_parents_must_converge = True
|
||||
nodes[0].job = Job(status='successful')
|
||||
return (g, nodes)
|
||||
|
||||
def test_all_converge_edge_case_2(self, workflow_all_converge_2):
|
||||
(g, nodes) = workflow_all_converge_2
|
||||
dnr_nodes = g.mark_dnr_nodes()
|
||||
assert 1 == len(dnr_nodes), "1 and only 1 node should be marked DNR"
|
||||
assert nodes[2] == dnr_nodes[0], "Node 3 should be marked DNR"
|
||||
|
||||
nodes_to_run = g.bfs_nodes_to_run()
|
||||
assert 1 == len(nodes_to_run), "Node 2, and only node 2, should be chosen to run"
|
||||
assert nodes[1] == nodes_to_run[0], "Only node 2 should be chosen to run"
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_all_converge_will_run(self, wf_node_generator):
|
||||
g = WorkflowDAG()
|
||||
nodes = [wf_node_generator() for i in range(4)]
|
||||
for n in nodes:
|
||||
g.add_node(n)
|
||||
r'''
|
||||
0 1 2
|
||||
S \ F | / S
|
||||
\ | /
|
||||
\ | /
|
||||
\|/
|
||||
|
|
||||
3
|
||||
'''
|
||||
g.add_edge(nodes[0], nodes[3], "success_nodes")
|
||||
g.add_edge(nodes[1], nodes[3], "failure_nodes")
|
||||
g.add_edge(nodes[2], nodes[3], "success_nodes")
|
||||
nodes[3].all_parents_must_converge = True
|
||||
|
||||
nodes[0].job = Job(status='successful')
|
||||
nodes[1].job = Job(status='failed')
|
||||
nodes[2].job = Job(status='running')
|
||||
return (g, nodes)
|
||||
|
||||
def test_workflow_all_converge_will_run(self, workflow_all_converge_will_run):
|
||||
(g, nodes) = workflow_all_converge_will_run
|
||||
dnr_nodes = g.mark_dnr_nodes()
|
||||
assert 0 == len(dnr_nodes), "No nodes should get marked DNR"
|
||||
|
||||
nodes_to_run = g.bfs_nodes_to_run()
|
||||
assert 0 == len(nodes_to_run), "No nodes should run yet"
|
||||
|
||||
nodes[2].job.status = 'successful'
|
||||
nodes_to_run = g.bfs_nodes_to_run()
|
||||
assert 1 == len(nodes_to_run), "1 and only 1 node should want to run"
|
||||
assert nodes[3] == nodes_to_run[0], "Convergence node should be chosen to run"
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_all_converge_dnr(self, wf_node_generator):
|
||||
g = WorkflowDAG()
|
||||
nodes = [wf_node_generator() for i in range(4)]
|
||||
for n in nodes:
|
||||
g.add_node(n)
|
||||
r'''
|
||||
0 1 2
|
||||
S \ F | / F
|
||||
\ | /
|
||||
\ | /
|
||||
\|/
|
||||
|
|
||||
3
|
||||
'''
|
||||
g.add_edge(nodes[0], nodes[3], "success_nodes")
|
||||
g.add_edge(nodes[1], nodes[3], "failure_nodes")
|
||||
g.add_edge(nodes[2], nodes[3], "failure_nodes")
|
||||
nodes[3].all_parents_must_converge = True
|
||||
|
||||
nodes[0].job = Job(status='successful')
|
||||
nodes[1].job = Job(status='running')
|
||||
nodes[2].job = Job(status='failed')
|
||||
return (g, nodes)
|
||||
|
||||
def test_workflow_all_converge_while_parent_runs(self, workflow_all_converge_dnr):
|
||||
(g, nodes) = workflow_all_converge_dnr
|
||||
dnr_nodes = g.mark_dnr_nodes()
|
||||
assert 0 == len(dnr_nodes), "No nodes should get marked DNR"
|
||||
|
||||
nodes_to_run = g.bfs_nodes_to_run()
|
||||
assert 0 == len(nodes_to_run), "No nodes should run yet"
|
||||
|
||||
def test_workflow_all_converge_with_incorrect_parent(self, workflow_all_converge_dnr):
|
||||
# Another tick of the scheduler
|
||||
(g, nodes) = workflow_all_converge_dnr
|
||||
nodes[1].job.status = 'successful'
|
||||
dnr_nodes = g.mark_dnr_nodes()
|
||||
assert 1 == len(dnr_nodes), "1 and only 1 node should be marked DNR"
|
||||
assert nodes[3] == dnr_nodes[0], "Convergence node should be marked DNR"
|
||||
|
||||
nodes_to_run = g.bfs_nodes_to_run()
|
||||
assert 0 == len(nodes_to_run), "Convergence node should NOT be chosen to run because it is DNR"
|
||||
|
||||
def test_workflow_all_converge_runs(self, workflow_all_converge_dnr):
|
||||
# Trick the scheduler again to make sure the convergence node acutally runs
|
||||
(g, nodes) = workflow_all_converge_dnr
|
||||
nodes[1].job.status = 'failed'
|
||||
dnr_nodes = g.mark_dnr_nodes()
|
||||
assert 0 == len(dnr_nodes), "No nodes should be marked DNR"
|
||||
|
||||
nodes_to_run = g.bfs_nodes_to_run()
|
||||
assert 1 == len(nodes_to_run), "Convergence node should be chosen to run"
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_all_converge_deep_dnr_tree(self, wf_node_generator):
|
||||
g = WorkflowDAG()
|
||||
nodes = [wf_node_generator() for i in range(7)]
|
||||
for n in nodes:
|
||||
g.add_node(n)
|
||||
r'''
|
||||
0 1 2
|
||||
\ | /
|
||||
S \ S| / F
|
||||
\ | /
|
||||
\|/
|
||||
|
|
||||
3
|
||||
/\
|
||||
S / \ S
|
||||
/ \
|
||||
4| | 5
|
||||
\ /
|
||||
S \ / S
|
||||
\/
|
||||
6
|
||||
'''
|
||||
g.add_edge(nodes[0], nodes[3], "success_nodes")
|
||||
g.add_edge(nodes[1], nodes[3], "success_nodes")
|
||||
g.add_edge(nodes[2], nodes[3], "failure_nodes")
|
||||
g.add_edge(nodes[3], nodes[4], "success_nodes")
|
||||
g.add_edge(nodes[3], nodes[5], "success_nodes")
|
||||
g.add_edge(nodes[4], nodes[6], "success_nodes")
|
||||
g.add_edge(nodes[5], nodes[6], "success_nodes")
|
||||
nodes[3].all_parents_must_converge = True
|
||||
nodes[4].all_parents_must_converge = True
|
||||
nodes[5].all_parents_must_converge = True
|
||||
nodes[6].all_parents_must_converge = True
|
||||
|
||||
nodes[0].job = Job(status='successful')
|
||||
nodes[1].job = Job(status='successful')
|
||||
nodes[2].job = Job(status='successful')
|
||||
return (g, nodes)
|
||||
|
||||
def test_workflow_all_converge_deep_dnr_tree(self, workflow_all_converge_deep_dnr_tree):
|
||||
(g, nodes) = workflow_all_converge_deep_dnr_tree
|
||||
dnr_nodes = g.mark_dnr_nodes()
|
||||
|
||||
assert 4 == len(dnr_nodes), "All nodes w/ no jobs should be marked DNR"
|
||||
assert nodes[3] in dnr_nodes
|
||||
assert nodes[4] in dnr_nodes
|
||||
assert nodes[5] in dnr_nodes
|
||||
assert nodes[6] in dnr_nodes
|
||||
|
||||
nodes_to_run = g.bfs_nodes_to_run()
|
||||
assert 0 == len(nodes_to_run), "All non-run nodes should be DNR and NOT candidates to run"
|
||||
|
||||
|
||||
class TestIsWorkflowDone():
|
||||
@pytest.fixture
|
||||
def workflow_dag_2(self, workflow_dag_1):
|
||||
(g, nodes) = workflow_dag_1
|
||||
r'''
|
||||
S0
|
||||
/\
|
||||
S / \
|
||||
/ \
|
||||
S1 |
|
||||
| |
|
||||
F | | S
|
||||
| |
|
||||
DNR 3 |
|
||||
\ |
|
||||
F \ |
|
||||
\/
|
||||
W2
|
||||
'''
|
||||
nodes[0].job = Job(status='successful')
|
||||
g.mark_dnr_nodes()
|
||||
nodes[1].job = Job(status='successful')
|
||||
g.mark_dnr_nodes()
|
||||
nodes[2].job = Job(status='waiting')
|
||||
return (g, nodes)
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_dag_failed(self, workflow_dag_1):
|
||||
(g, nodes) = workflow_dag_1
|
||||
r'''
|
||||
S0
|
||||
/\
|
||||
S / \
|
||||
/ \
|
||||
S1 |
|
||||
| |
|
||||
F | | S
|
||||
| |
|
||||
DNR 3 |
|
||||
\ |
|
||||
F \ |
|
||||
\/
|
||||
F2
|
||||
'''
|
||||
nodes[0].job = Job(status='successful')
|
||||
g.mark_dnr_nodes()
|
||||
nodes[1].job = Job(status='successful')
|
||||
g.mark_dnr_nodes()
|
||||
nodes[2].job = Job(status='failed')
|
||||
return (g, nodes)
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_dag_canceled(self, wf_node_generator):
|
||||
g = WorkflowDAG()
|
||||
nodes = [wf_node_generator() for i in range(1)]
|
||||
for n in nodes:
|
||||
g.add_node(n)
|
||||
r'''
|
||||
F0
|
||||
'''
|
||||
nodes[0].job = Job(status='canceled')
|
||||
return (g, nodes)
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_dag_failure(self, workflow_dag_canceled):
|
||||
(g, nodes) = workflow_dag_canceled
|
||||
nodes[0].job.status = 'failed'
|
||||
return (g, nodes)
|
||||
|
||||
def test_done(self, workflow_dag_2):
|
||||
g = workflow_dag_2[0]
|
||||
|
||||
assert g.is_workflow_done() is False
|
||||
|
||||
def test_workflow_done_and_failed(self, workflow_dag_failed):
|
||||
(g, nodes) = workflow_dag_failed
|
||||
|
||||
assert g.is_workflow_done() is True
|
||||
assert g.has_workflow_failed() == \
|
||||
(True, smart_text(_("No error handling path for workflow job node(s) [({},{})]. Workflow job node(s)"
|
||||
" missing unified job template and error handling path [].").format(nodes[2].id, nodes[2].job.status)))
|
||||
|
||||
def test_is_workflow_done_no_unified_job_tempalte_end(self, workflow_dag_failed):
|
||||
(g, nodes) = workflow_dag_failed
|
||||
|
||||
nodes[2].unified_job_template = None
|
||||
|
||||
assert g.is_workflow_done() is True
|
||||
assert g.has_workflow_failed() == \
|
||||
(True, smart_text(_("No error handling path for workflow job node(s) []. Workflow job node(s) missing"
|
||||
" unified job template and error handling path [{}].").format(nodes[2].id)))
|
||||
|
||||
def test_is_workflow_done_no_unified_job_tempalte_begin(self, workflow_dag_1):
|
||||
(g, nodes) = workflow_dag_1
|
||||
|
||||
nodes[0].unified_job_template = None
|
||||
g.mark_dnr_nodes()
|
||||
|
||||
assert g.is_workflow_done() is True
|
||||
assert g.has_workflow_failed() == \
|
||||
(True, smart_text(_("No error handling path for workflow job node(s) []. Workflow job node(s) missing"
|
||||
" unified job template and error handling path [{}].").format(nodes[0].id)))
|
||||
|
||||
def test_canceled_should_fail(self, workflow_dag_canceled):
|
||||
(g, nodes) = workflow_dag_canceled
|
||||
|
||||
assert g.has_workflow_failed() == \
|
||||
(True, smart_text(_("No error handling path for workflow job node(s) [({},{})]. Workflow job node(s)"
|
||||
" missing unified job template and error handling path [].").format(nodes[0].id, nodes[0].job.status)))
|
||||
|
||||
def test_failure_should_fail(self, workflow_dag_failure):
|
||||
(g, nodes) = workflow_dag_failure
|
||||
|
||||
assert g.has_workflow_failed() == \
|
||||
(True, smart_text(_("No error handling path for workflow job node(s) [({},{})]. Workflow job node(s)"
|
||||
" missing unified job template and error handling path [].").format(nodes[0].id, nodes[0].job.status)))
|
||||
|
||||
|
||||
class TestBFSNodesToRun():
|
||||
@pytest.fixture
|
||||
def workflow_dag_canceled(self, wf_node_generator):
|
||||
g = WorkflowDAG()
|
||||
nodes = [wf_node_generator() for i in range(4)]
|
||||
for n in nodes:
|
||||
g.add_node(n)
|
||||
r'''
|
||||
C0
|
||||
/ | \
|
||||
F / A| \ S
|
||||
/ | \
|
||||
1 2 3
|
||||
'''
|
||||
g.add_edge(nodes[0], nodes[1], "failure_nodes")
|
||||
g.add_edge(nodes[0], nodes[2], "always_nodes")
|
||||
g.add_edge(nodes[0], nodes[3], "success_nodes")
|
||||
nodes[0].job = Job(status='canceled')
|
||||
return (g, nodes)
|
||||
|
||||
def test_cancel_still_runs_children(self, workflow_dag_canceled):
|
||||
(g, nodes) = workflow_dag_canceled
|
||||
g.mark_dnr_nodes()
|
||||
|
||||
assert set([nodes[1], nodes[2]]) == set(g.bfs_nodes_to_run())
|
||||
|
||||
|
||||
@pytest.mark.skip(reason="Run manually to re-generate doc images")
|
||||
class TestDocsExample():
|
||||
@pytest.fixture
|
||||
def complex_dag(self, wf_node_generator):
|
||||
g = WorkflowDAG()
|
||||
nodes = [wf_node_generator() for i in range(10)]
|
||||
for n in nodes:
|
||||
g.add_node(n)
|
||||
|
||||
g.add_edge(nodes[0], nodes[1], "failure_nodes")
|
||||
g.add_edge(nodes[0], nodes[2], "success_nodes")
|
||||
g.add_edge(nodes[0], nodes[3], "always_nodes")
|
||||
g.add_edge(nodes[1], nodes[4], "success_nodes")
|
||||
g.add_edge(nodes[1], nodes[5], "failure_nodes")
|
||||
|
||||
g.add_edge(nodes[2], nodes[6], "failure_nodes")
|
||||
g.add_edge(nodes[3], nodes[6], "success_nodes")
|
||||
g.add_edge(nodes[4], nodes[6], "always_nodes")
|
||||
|
||||
g.add_edge(nodes[6], nodes[7], "always_nodes")
|
||||
g.add_edge(nodes[6], nodes[8], "success_nodes")
|
||||
g.add_edge(nodes[6], nodes[9], "failure_nodes")
|
||||
|
||||
return (g, nodes)
|
||||
|
||||
def test_dnr_step(self, complex_dag):
|
||||
(g, nodes) = complex_dag
|
||||
base_dir = '/awx_devel'
|
||||
|
||||
g.generate_graphviz_plot(file_name=os.path.join(base_dir, "workflow_step0.gv"))
|
||||
nodes[0].job = Job(status='successful')
|
||||
g.mark_dnr_nodes()
|
||||
g.generate_graphviz_plot(file_name=os.path.join(base_dir, "workflow_step1.gv"))
|
||||
nodes[2].job = Job(status='successful')
|
||||
nodes[3].job = Job(status='successful')
|
||||
g.mark_dnr_nodes()
|
||||
g.generate_graphviz_plot(file_name=os.path.join(base_dir, "workflow_step2.gv"))
|
||||
nodes[6].job = Job(status='failed')
|
||||
g.mark_dnr_nodes()
|
||||
g.generate_graphviz_plot(file_name=os.path.join(base_dir, "workflow_step3.gv"))
|
||||
nodes[7].job = Job(status='successful')
|
||||
nodes[9].job = Job(status='successful')
|
||||
g.mark_dnr_nodes()
|
||||
g.generate_graphviz_plot(file_name=os.path.join(base_dir, "workflow_step4.gv"))
|
||||
@@ -0,0 +1,55 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
from django.conf import settings
|
||||
|
||||
from awx.main.models import (
|
||||
InstanceGroup,
|
||||
Job,
|
||||
JobTemplate,
|
||||
Project,
|
||||
Inventory,
|
||||
)
|
||||
from awx.main.scheduler.kubernetes import PodManager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def container_group():
|
||||
instance_group = mock.Mock(InstanceGroup(name='container-group'))
|
||||
|
||||
return instance_group
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job(container_group):
|
||||
return Job(pk=1,
|
||||
id=1,
|
||||
project=Project(),
|
||||
instance_group=container_group,
|
||||
inventory=Inventory(),
|
||||
job_template=JobTemplate(id=1, name='foo'))
|
||||
|
||||
|
||||
def test_default_pod_spec(job):
|
||||
default_image = PodManager(job).pod_definition['spec']['containers'][0]['image']
|
||||
assert default_image == settings.AWX_CONTAINER_GROUP_DEFAULT_IMAGE
|
||||
|
||||
|
||||
def test_custom_pod_spec(job):
|
||||
job.instance_group.pod_spec_override = """
|
||||
spec:
|
||||
containers:
|
||||
- image: my-custom-image
|
||||
"""
|
||||
custom_image = PodManager(job).pod_definition['spec']['containers'][0]['image']
|
||||
assert custom_image == 'my-custom-image'
|
||||
|
||||
|
||||
def test_pod_manager_namespace_property(job):
|
||||
pm = PodManager(job)
|
||||
assert pm.namespace == settings.AWX_CONTAINER_GROUP_DEFAULT_NAMESPACE
|
||||
|
||||
job.instance_group.pod_spec_override = """
|
||||
metadata:
|
||||
namespace: my-namespace
|
||||
"""
|
||||
assert PodManager(job).namespace == 'my-namespace'
|
||||
@@ -0,0 +1,17 @@
|
||||
import pytest
|
||||
|
||||
from django.conf import settings
|
||||
from datetime import timedelta
|
||||
|
||||
|
||||
@pytest.mark.parametrize("job_name,function_path", [
|
||||
('tower_scheduler', 'awx.main.tasks.awx_periodic_scheduler'),
|
||||
])
|
||||
def test_CELERYBEAT_SCHEDULE(mocker, job_name, function_path):
|
||||
assert job_name in settings.CELERYBEAT_SCHEDULE
|
||||
assert 'schedule' in settings.CELERYBEAT_SCHEDULE[job_name]
|
||||
assert type(settings.CELERYBEAT_SCHEDULE[job_name]['schedule']) is timedelta
|
||||
assert settings.CELERYBEAT_SCHEDULE[job_name]['task'] == function_path
|
||||
|
||||
# Ensures that the function exists
|
||||
mocker.patch(function_path)
|
||||
@@ -0,0 +1,274 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.forms.models import model_to_dict
|
||||
from rest_framework.exceptions import ParseError
|
||||
|
||||
from awx.main.access import (
|
||||
BaseAccess,
|
||||
check_superuser,
|
||||
JobTemplateAccess,
|
||||
WorkflowJobTemplateAccess,
|
||||
SystemJobTemplateAccess,
|
||||
vars_are_encrypted
|
||||
)
|
||||
|
||||
from awx.main.models import (
|
||||
Credential,
|
||||
CredentialType,
|
||||
Inventory,
|
||||
Project,
|
||||
Role,
|
||||
Organization,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_unit():
|
||||
return User(username='rando', password='raginrando', email='rando@redhat.com')
|
||||
|
||||
|
||||
class TestRelatedFieldAccess:
|
||||
@pytest.fixture
|
||||
def resource_good(self, mocker):
|
||||
good_role = mocker.MagicMock(__contains__=lambda self, user: True)
|
||||
return mocker.MagicMock(related=mocker.MagicMock(admin_role=good_role),
|
||||
admin_role=good_role)
|
||||
|
||||
@pytest.fixture
|
||||
def resource_bad(self, mocker):
|
||||
bad_role = mocker.MagicMock(__contains__=lambda self, user: False)
|
||||
return mocker.MagicMock(related=mocker.MagicMock(admin_role=bad_role),
|
||||
admin_role=bad_role)
|
||||
|
||||
@pytest.fixture
|
||||
def access(self, user_unit):
|
||||
return BaseAccess(user_unit)
|
||||
|
||||
def test_new_optional_fail(self, access, resource_bad, mocker):
|
||||
"""
|
||||
User tries to create a new resource, but lacks permission
|
||||
to the related resource they provided
|
||||
"""
|
||||
data = {'related': resource_bad}
|
||||
assert not access.check_related('related', mocker.MagicMock, data)
|
||||
|
||||
def test_new_with_bad_data(self, access, mocker):
|
||||
data = {'related': 3.1415}
|
||||
with pytest.raises(ParseError):
|
||||
access.check_related('related', mocker.MagicMock(), data)
|
||||
|
||||
def test_new_mandatory_fail(self, access, mocker):
|
||||
access.user.is_superuser = False
|
||||
assert not access.check_related(
|
||||
'related', mocker.MagicMock, {}, mandatory=True)
|
||||
assert not access.check_related(
|
||||
'related', mocker.MagicMock, {'resource': None}, mandatory=True)
|
||||
|
||||
def test_existing_no_op(self, access, resource_bad, mocker):
|
||||
"""
|
||||
User edits a resource, but does not change related field
|
||||
lack of access to related field does not block action
|
||||
"""
|
||||
data = {'related': resource_bad.related}
|
||||
assert access.check_related(
|
||||
'related', mocker.MagicMock, data, obj=resource_bad)
|
||||
assert access.check_related(
|
||||
'related', mocker.MagicMock, {}, obj=resource_bad)
|
||||
|
||||
def test_existing_required_access(self, access, resource_bad, mocker):
|
||||
# no-op actions, but mandatory kwarg requires check to pass
|
||||
assert not access.check_related(
|
||||
'related', mocker.MagicMock, {}, obj=resource_bad, mandatory=True)
|
||||
assert not access.check_related(
|
||||
'related', mocker.MagicMock, {'related': resource_bad.related},
|
||||
obj=resource_bad, mandatory=True)
|
||||
|
||||
def test_existing_no_access_to_current(
|
||||
self, access, resource_good, resource_bad, mocker):
|
||||
"""
|
||||
User gives a valid related resource (like organization), but does
|
||||
not have access to _existing_ related resource, so deny action
|
||||
"""
|
||||
data = {'related': resource_good}
|
||||
assert not access.check_related(
|
||||
'related', mocker.MagicMock, data, obj=resource_bad)
|
||||
|
||||
def test_existing_no_access_to_new(
|
||||
self, access, resource_good, resource_bad, mocker):
|
||||
data = {'related': resource_bad}
|
||||
assert not access.check_related(
|
||||
'related', mocker.MagicMock, data, obj=resource_good)
|
||||
|
||||
def test_existing_not_allowed_to_remove(self, access, resource_bad, mocker):
|
||||
data = {'related': None}
|
||||
assert not access.check_related(
|
||||
'related', mocker.MagicMock, data, obj=resource_bad)
|
||||
|
||||
def test_existing_not_null_null(self, access, mocker):
|
||||
resource = mocker.MagicMock(related=None)
|
||||
data = {'related': None}
|
||||
# Not changing anything by giving null when it is already-null
|
||||
# important for PUT requests
|
||||
assert access.check_related(
|
||||
'related', mocker.MagicMock, data, obj=resource, mandatory=True)
|
||||
|
||||
|
||||
def test_encrypted_vars_detection():
|
||||
assert vars_are_encrypted({
|
||||
'aaa': {'b': 'c'},
|
||||
'alist': [],
|
||||
'test_var_eight': '$encrypted$UTF8$AESCBC$Z0FBQUF...==',
|
||||
'test_var_five': 'four',
|
||||
})
|
||||
assert not vars_are_encrypted({
|
||||
'aaa': {'b': 'c'},
|
||||
'alist': [],
|
||||
'test_var_five': 'four',
|
||||
})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_template_with_ids(job_template_factory):
|
||||
# Create non-persisted objects with IDs to send to job_template_factory
|
||||
ssh_type = CredentialType(kind='ssh')
|
||||
credential = Credential(id=1, pk=1, name='testcred', credential_type=ssh_type)
|
||||
|
||||
net_type = CredentialType(kind='net')
|
||||
net_cred = Credential(id=2, pk=2, name='testnetcred', credential_type=net_type)
|
||||
|
||||
cloud_type = CredentialType(kind='aws')
|
||||
cloud_cred = Credential(id=3, pk=3, name='testcloudcred', credential_type=cloud_type)
|
||||
|
||||
inv = Inventory(id=11, pk=11, name='testinv')
|
||||
proj = Project(id=14, pk=14, name='testproj')
|
||||
|
||||
jt_objects = job_template_factory(
|
||||
'testJT', project=proj, inventory=inv, credential=credential,
|
||||
cloud_credential=cloud_cred, network_credential=net_cred,
|
||||
persisted=False)
|
||||
jt = jt_objects.job_template
|
||||
jt.organization = Organization(id=1, pk=1, name='fooOrg')
|
||||
return jt
|
||||
|
||||
|
||||
def test_superuser(mocker):
|
||||
user = mocker.MagicMock(spec=User, id=1, is_superuser=True)
|
||||
access = BaseAccess(user)
|
||||
|
||||
can_add = check_superuser(BaseAccess.can_add)
|
||||
assert can_add(access, None) is True
|
||||
|
||||
|
||||
def test_not_superuser(mocker):
|
||||
user = mocker.MagicMock(spec=User, id=1, is_superuser=False)
|
||||
access = BaseAccess(user)
|
||||
|
||||
can_add = check_superuser(BaseAccess.can_add)
|
||||
assert can_add(access, None) is False
|
||||
|
||||
|
||||
def test_jt_existing_values_are_nonsensitive(job_template_with_ids, user_unit):
|
||||
"""Assure that permission checks are not required if submitted data is
|
||||
identical to what the job template already has."""
|
||||
|
||||
data = model_to_dict(job_template_with_ids, exclude=['unifiedjobtemplate_ptr'])
|
||||
access = JobTemplateAccess(user_unit)
|
||||
|
||||
assert access.changes_are_non_sensitive(job_template_with_ids, data)
|
||||
|
||||
|
||||
def test_change_jt_sensitive_data(job_template_with_ids, mocker, user_unit):
|
||||
"""Assure that can_add is called with all ForeignKeys."""
|
||||
|
||||
class RoleReturnsTrue(Role):
|
||||
class Meta:
|
||||
proxy = True
|
||||
|
||||
def __contains__(self, accessor):
|
||||
return True
|
||||
|
||||
job_template_with_ids.admin_role = RoleReturnsTrue()
|
||||
job_template_with_ids.organization.job_template_admin_role = RoleReturnsTrue()
|
||||
|
||||
inv2 = Inventory()
|
||||
inv2.use_role = RoleReturnsTrue()
|
||||
data = {'inventory': inv2}
|
||||
|
||||
access = JobTemplateAccess(user_unit)
|
||||
|
||||
assert not access.changes_are_non_sensitive(job_template_with_ids, data)
|
||||
|
||||
job_template_with_ids.inventory.use_role = RoleReturnsTrue()
|
||||
job_template_with_ids.project.use_role = RoleReturnsTrue()
|
||||
assert access.can_change(job_template_with_ids, data)
|
||||
|
||||
|
||||
def mock_raise_none(self, add_host=False, feature=None, check_expiration=True):
|
||||
return None
|
||||
|
||||
|
||||
def test_jt_can_add_bad_data(user_unit):
|
||||
"Assure that no server errors are returned if we call JT can_add with bad data"
|
||||
access = JobTemplateAccess(user_unit)
|
||||
assert not access.can_add({'asdf': 'asdf'})
|
||||
|
||||
|
||||
class TestWorkflowAccessMethods:
|
||||
@pytest.fixture
|
||||
def workflow(self, workflow_job_template_factory):
|
||||
objects = workflow_job_template_factory('test_workflow', persisted=False)
|
||||
return objects.workflow_job_template
|
||||
|
||||
def test_workflow_can_add(self, workflow, user_unit):
|
||||
organization = Organization(name='test-org')
|
||||
workflow.organization = organization
|
||||
organization.workflow_admin_role = Role()
|
||||
|
||||
def mock_get_object(Class, **kwargs):
|
||||
if Class == Organization:
|
||||
return organization
|
||||
else:
|
||||
raise Exception('Item requested has not been mocked')
|
||||
|
||||
access = WorkflowJobTemplateAccess(user_unit)
|
||||
with mock.patch('awx.main.models.rbac.Role.__contains__', return_value=True):
|
||||
with mock.patch('awx.main.access.get_object_or_400', mock_get_object):
|
||||
assert access.can_add({'organization': 1})
|
||||
|
||||
|
||||
|
||||
def test_user_capabilities_method():
|
||||
"""Unit test to verify that the user_capabilities method will defer
|
||||
to the appropriate sub-class methods of the access classes.
|
||||
Note that normal output is True/False, but a string is returned
|
||||
in these tests to establish uniqueness.
|
||||
"""
|
||||
|
||||
class FooAccess(BaseAccess):
|
||||
def can_change(self, obj, data):
|
||||
return 'bar'
|
||||
|
||||
def can_copy(self, obj):
|
||||
return 'foo'
|
||||
|
||||
user = User(username='auser')
|
||||
foo_access = FooAccess(user)
|
||||
foo = object()
|
||||
foo_capabilities = foo_access.get_user_capabilities(foo, ['edit', 'copy'])
|
||||
assert foo_capabilities == {
|
||||
'edit': 'bar',
|
||||
'copy': 'foo'
|
||||
}
|
||||
|
||||
|
||||
def test_system_job_template_can_start(mocker):
|
||||
user = mocker.MagicMock(spec=User, id=1, is_system_auditor=True, is_superuser=False)
|
||||
assert user.is_system_auditor
|
||||
access = SystemJobTemplateAccess(user)
|
||||
assert not access.can_start(None)
|
||||
|
||||
user.is_superuser = True
|
||||
access = SystemJobTemplateAccess(user)
|
||||
assert access.can_start(None)
|
||||
@@ -0,0 +1,136 @@
|
||||
import pytest
|
||||
|
||||
from awx.main.models import InstanceGroup
|
||||
|
||||
|
||||
class FakeObject(object):
|
||||
def __init__(self, **kwargs):
|
||||
for k, v in kwargs.items():
|
||||
setattr(self, k, v)
|
||||
|
||||
|
||||
class Job(FakeObject):
|
||||
task_impact = 43
|
||||
is_containerized = False
|
||||
|
||||
def log_format(self):
|
||||
return 'job 382 (fake)'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_cluster():
|
||||
def stand_up_cluster():
|
||||
|
||||
class Instances(FakeObject):
|
||||
def add(self, *args):
|
||||
for instance in args:
|
||||
self.obj.instance_list.append(instance)
|
||||
|
||||
def all(self):
|
||||
return self.obj.instance_list
|
||||
|
||||
class InstanceGroup(FakeObject):
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super(InstanceGroup, self).__init__(**kwargs)
|
||||
self.instance_list = []
|
||||
|
||||
@property
|
||||
def instances(self):
|
||||
mgr = Instances(obj=self)
|
||||
return mgr
|
||||
|
||||
|
||||
class Instance(FakeObject):
|
||||
pass
|
||||
|
||||
|
||||
ig_small = InstanceGroup(name='ig_small')
|
||||
ig_large = InstanceGroup(name='ig_large')
|
||||
tower = InstanceGroup(name='tower')
|
||||
i1 = Instance(hostname='i1', capacity=200)
|
||||
i2 = Instance(hostname='i2', capacity=200)
|
||||
i3 = Instance(hostname='i3', capacity=200)
|
||||
ig_small.instances.add(i1)
|
||||
ig_large.instances.add(i2, i3)
|
||||
tower.instances.add(i2)
|
||||
return [tower, ig_large, ig_small]
|
||||
return stand_up_cluster
|
||||
|
||||
|
||||
def test_committed_capacity(sample_cluster):
|
||||
tower, ig_large, ig_small = sample_cluster()
|
||||
tasks = [
|
||||
Job(status='waiting', instance_group=tower),
|
||||
Job(status='waiting', instance_group=ig_large),
|
||||
Job(status='waiting', instance_group=ig_small)
|
||||
]
|
||||
capacities = InstanceGroup.objects.capacity_values(
|
||||
qs=[tower, ig_large, ig_small], tasks=tasks, breakdown=True
|
||||
)
|
||||
# Jobs submitted to either tower or ig_larg must count toward both
|
||||
assert capacities['tower']['committed_capacity'] == 43 * 2
|
||||
assert capacities['ig_large']['committed_capacity'] == 43 * 2
|
||||
assert capacities['ig_small']['committed_capacity'] == 43
|
||||
|
||||
|
||||
def test_running_capacity(sample_cluster):
|
||||
tower, ig_large, ig_small = sample_cluster()
|
||||
tasks = [
|
||||
Job(status='running', execution_node='i1'),
|
||||
Job(status='running', execution_node='i2'),
|
||||
Job(status='running', execution_node='i3')
|
||||
]
|
||||
capacities = InstanceGroup.objects.capacity_values(
|
||||
qs=[tower, ig_large, ig_small], tasks=tasks, breakdown=True
|
||||
)
|
||||
# Tower is only given 1 instance
|
||||
assert capacities['tower']['running_capacity'] == 43
|
||||
# Large IG has 2 instances
|
||||
assert capacities['ig_large']['running_capacity'] == 43 * 2
|
||||
assert capacities['ig_small']['running_capacity'] == 43
|
||||
|
||||
|
||||
def test_offline_node_running(sample_cluster):
|
||||
"""
|
||||
Assure that algorithm doesn't explode if a job is marked running
|
||||
in an offline node
|
||||
"""
|
||||
tower, ig_large, ig_small = sample_cluster()
|
||||
ig_small.instance_list[0].capacity = 0
|
||||
tasks = [Job(status='running', execution_node='i1', instance_group=ig_small)]
|
||||
capacities = InstanceGroup.objects.capacity_values(
|
||||
qs=[tower, ig_large, ig_small], tasks=tasks)
|
||||
assert capacities['ig_small']['consumed_capacity'] == 43
|
||||
|
||||
|
||||
def test_offline_node_waiting(sample_cluster):
|
||||
"""
|
||||
Same but for a waiting job
|
||||
"""
|
||||
tower, ig_large, ig_small = sample_cluster()
|
||||
ig_small.instance_list[0].capacity = 0
|
||||
tasks = [Job(status='waiting', instance_group=ig_small)]
|
||||
capacities = InstanceGroup.objects.capacity_values(
|
||||
qs=[tower, ig_large, ig_small], tasks=tasks)
|
||||
assert capacities['ig_small']['consumed_capacity'] == 43
|
||||
|
||||
|
||||
def test_RBAC_reduced_filter(sample_cluster):
|
||||
"""
|
||||
User can see jobs that are running in `ig_small` and `ig_large` IGs,
|
||||
but user does not have permission to see those actual instance groups.
|
||||
Verify that this does not blow everything up.
|
||||
"""
|
||||
tower, ig_large, ig_small = sample_cluster()
|
||||
tasks = [
|
||||
Job(status='waiting', instance_group=tower),
|
||||
Job(status='waiting', instance_group=ig_large),
|
||||
Job(status='waiting', instance_group=ig_small)
|
||||
]
|
||||
capacities = InstanceGroup.objects.capacity_values(
|
||||
qs=[tower], tasks=tasks, breakdown=True
|
||||
)
|
||||
# Cross-links between groups not visible to current user,
|
||||
# so a naieve accounting of capacities is returned instead
|
||||
assert capacities['tower']['committed_capacity'] == 43
|
||||
@@ -0,0 +1,154 @@
|
||||
import collections
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import pytest
|
||||
|
||||
import awx
|
||||
from awx.main.db.profiled_pg.base import RecordedQueryLog
|
||||
|
||||
|
||||
QUERY = {
|
||||
'sql': 'SELECT * FROM main_job',
|
||||
'time': '.01'
|
||||
}
|
||||
EXPLAIN = 'Seq Scan on public.main_job (cost=0.00..1.18 rows=18 width=86)'
|
||||
|
||||
|
||||
class FakeDatabase():
|
||||
|
||||
def __init__(self):
|
||||
self._cursor = unittest.mock.Mock(spec_sec=['execute', 'fetchall'])
|
||||
self._cursor.fetchall.return_value = [(EXPLAIN,)]
|
||||
|
||||
def cursor(self):
|
||||
return self._cursor
|
||||
|
||||
@property
|
||||
def execute_calls(self):
|
||||
return self._cursor.execute.call_args_list
|
||||
|
||||
|
||||
# all of these should still be valid operations we should proxy through
|
||||
# to the underlying deque object
|
||||
def test_deque_appendleft():
|
||||
log = RecordedQueryLog(collections.deque(), FakeDatabase)
|
||||
log.appendleft(QUERY)
|
||||
assert len(log) == 1
|
||||
|
||||
|
||||
def test_deque_count():
|
||||
log = RecordedQueryLog(collections.deque(), FakeDatabase)
|
||||
log.append(QUERY)
|
||||
assert log.count('x') == 0
|
||||
assert log.count(QUERY) == 1
|
||||
|
||||
|
||||
def test_deque_clear():
|
||||
log = RecordedQueryLog(collections.deque(), FakeDatabase)
|
||||
log.append(QUERY)
|
||||
log.clear()
|
||||
assert len(log) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('method', ['extend', 'extendleft'])
|
||||
def test_deque_extend(method):
|
||||
log = RecordedQueryLog(collections.deque(), FakeDatabase)
|
||||
getattr(log, method)([QUERY])
|
||||
assert len(log) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('method', ['pop', 'popleft'])
|
||||
def test_deque_pop(method):
|
||||
log = RecordedQueryLog(collections.deque(), FakeDatabase)
|
||||
log.append(QUERY)
|
||||
getattr(log, method)()
|
||||
assert len(log) == 0
|
||||
|
||||
|
||||
def test_deque_remove():
|
||||
log = RecordedQueryLog(collections.deque(), FakeDatabase)
|
||||
log.append(QUERY)
|
||||
log.remove(QUERY)
|
||||
assert len(log) == 0
|
||||
|
||||
|
||||
def test_deque_reverse():
|
||||
log = RecordedQueryLog(collections.deque(), FakeDatabase)
|
||||
log.append(QUERY)
|
||||
log.reverse()
|
||||
assert len(log) == 1
|
||||
|
||||
|
||||
def test_sql_not_recorded_by_default():
|
||||
db = FakeDatabase()
|
||||
log = RecordedQueryLog(collections.deque(maxlen=100), db)
|
||||
assert log.maxlen == 100
|
||||
assert log.threshold is None
|
||||
log.append(QUERY)
|
||||
assert len(log) == 1
|
||||
assert [x for x in log] == [QUERY]
|
||||
assert db.execute_calls == []
|
||||
|
||||
|
||||
def test_sql_below_threshold():
|
||||
db = FakeDatabase()
|
||||
log = RecordedQueryLog(collections.deque(maxlen=100), db)
|
||||
log.threshold = 1
|
||||
log.append(QUERY)
|
||||
assert len(log) == 1
|
||||
assert [x for x in log] == [QUERY]
|
||||
assert db.execute_calls == []
|
||||
|
||||
|
||||
def test_sqlite_failure(tmpdir):
|
||||
tmpdir = str(tmpdir)
|
||||
db = FakeDatabase()
|
||||
db._cursor.execute.side_effect = OSError
|
||||
log = RecordedQueryLog(collections.deque(maxlen=100), db, dest=tmpdir)
|
||||
log.threshold = 0.00000001
|
||||
log.append(QUERY)
|
||||
assert len(log) == 1
|
||||
assert os.listdir(tmpdir) == []
|
||||
|
||||
|
||||
def test_sql_above_threshold(tmpdir):
|
||||
tmpdir = str(tmpdir)
|
||||
db = FakeDatabase()
|
||||
log = RecordedQueryLog(collections.deque(maxlen=100), db, dest=tmpdir)
|
||||
log.threshold = 0.00000001
|
||||
|
||||
for _ in range(5):
|
||||
log.append(QUERY)
|
||||
|
||||
assert len(log) == 5
|
||||
assert len(db.execute_calls) == 5
|
||||
for _call in db.execute_calls:
|
||||
args, kw = _call
|
||||
assert args == ('EXPLAIN VERBOSE {}'.format(QUERY['sql']),)
|
||||
|
||||
path = os.path.join(
|
||||
tmpdir,
|
||||
'{}.sqlite'.format(os.path.basename(sys.argv[0]))
|
||||
)
|
||||
assert os.path.exists(path)
|
||||
|
||||
# verify the results
|
||||
def dict_factory(cursor, row):
|
||||
d = {}
|
||||
for idx,col in enumerate(cursor.description):
|
||||
d[col[0]] = row[idx]
|
||||
return d
|
||||
cursor = sqlite3.connect(path)
|
||||
cursor.row_factory = dict_factory
|
||||
queries_logged = cursor.execute('SELECT * FROM queries').fetchall()
|
||||
assert len(queries_logged) == 5
|
||||
for q in queries_logged:
|
||||
assert q['pid'] == os.getpid()
|
||||
assert q['version'] == awx.__version__
|
||||
assert q['time'] == 0.01
|
||||
assert q['sql'] == QUERY['sql']
|
||||
assert EXPLAIN in q['explain']
|
||||
assert 'test_sql_above_threshold' in q['bt']
|
||||
@@ -0,0 +1,257 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import pytest
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.apps import apps
|
||||
from django.db.models.fields.related import ForeignKey
|
||||
from django.db.models.fields.related_descriptors import (
|
||||
ReverseManyToOneDescriptor,
|
||||
ForwardManyToOneDescriptor
|
||||
)
|
||||
|
||||
from rest_framework.serializers import ValidationError as DRFValidationError
|
||||
|
||||
from awx.main.models import Credential, CredentialType, BaseModel
|
||||
from awx.main.fields import JSONSchemaField, ImplicitRoleField, ImplicitRoleDescriptor
|
||||
|
||||
|
||||
@pytest.mark.parametrize('schema, given, message', [
|
||||
(
|
||||
{ # immitates what the CredentialType injectors field is
|
||||
"additionalProperties": False,
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"extra_vars": {
|
||||
"additionalProperties": False,
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{'extra_vars': ['duck', 'horse']},
|
||||
"list provided in relative path ['extra_vars'], expected dict"
|
||||
),
|
||||
(
|
||||
{ # immitates what the CredentialType injectors field is
|
||||
"additionalProperties": False,
|
||||
"type": "object",
|
||||
},
|
||||
['duck', 'horse'],
|
||||
"list provided, expected dict"
|
||||
),
|
||||
])
|
||||
def test_custom_error_messages(schema, given, message):
|
||||
instance = BaseModel()
|
||||
|
||||
class MockFieldSubclass(JSONSchemaField):
|
||||
def schema(self, model_instance):
|
||||
return schema
|
||||
|
||||
field = MockFieldSubclass()
|
||||
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
field.validate(given, instance)
|
||||
|
||||
assert message == exc.value.error_list[0].message
|
||||
|
||||
|
||||
@pytest.mark.parametrize('input_, valid', [
|
||||
({}, True),
|
||||
({'fields': []}, True),
|
||||
({'fields': {}}, False),
|
||||
({'fields': 123}, False),
|
||||
({'fields': [{'id': 'username', 'label': 'Username', 'foo': 'bar'}]}, False),
|
||||
({'fields': [{'id': 'username', 'label': 'Username'}]}, True),
|
||||
({'fields': [{'id': 'username', 'label': 'Username', 'type': 'string'}]}, True),
|
||||
({'fields': [{'id': 'username', 'label': 'Username', 'help_text': 1}]}, False),
|
||||
({'fields': [{'id': 'username', 'label': 'Username', 'help_text': 'Help Text'}]}, True), # noqa
|
||||
({'fields': [{'id': 'username', 'label': 'Username'}, {'id': 'username', 'label': 'Username 2'}]}, False), # noqa
|
||||
({'fields': [{'id': '$invalid$', 'label': 'Invalid', 'type': 'string'}]}, False), # noqa
|
||||
({'fields': [{'id': 'password', 'label': 'Password', 'type': 'invalid-type'}]}, False),
|
||||
({'fields': [{'id': 'ssh_key', 'label': 'SSH Key', 'type': 'string', 'format': 'ssh_private_key'}]}, True), # noqa
|
||||
({'fields': [{'id': 'flag', 'label': 'Some Flag', 'type': 'boolean'}]}, True),
|
||||
({'fields': [{'id': 'flag', 'label': 'Some Flag', 'type': 'boolean', 'choices': ['a', 'b']}]}, False),
|
||||
({'fields': [{'id': 'flag', 'label': 'Some Flag', 'type': 'boolean', 'secret': True}]}, False),
|
||||
({'fields': [{'id': 'certificate', 'label': 'Cert', 'multiline': True}]}, True),
|
||||
({'fields': [{'id': 'certificate', 'label': 'Cert', 'multiline': True, 'type': 'boolean'}]}, False), # noqa
|
||||
({'fields': [{'id': 'certificate', 'label': 'Cert', 'multiline': 'bad'}]}, False), # noqa
|
||||
({'fields': [{'id': 'token', 'label': 'Token', 'secret': True}]}, True),
|
||||
({'fields': [{'id': 'token', 'label': 'Token', 'secret': 'bad'}]}, False),
|
||||
({'fields': [{'id': 'token', 'label': 'Token', 'ask_at_runtime': True}]}, True),
|
||||
({'fields': [{'id': 'token', 'label': 'Token', 'ask_at_runtime': 'bad'}]}, False), # noqa
|
||||
({'fields': [{'id': 'become_method', 'label': 'Become', 'choices': 'not-a-list'}]}, False), # noqa
|
||||
({'fields': [{'id': 'become_method', 'label': 'Become', 'choices': []}]}, False),
|
||||
({'fields': [{'id': 'become_method', 'label': 'Become', 'choices': ['su', 'sudo']}]}, True), # noqa
|
||||
({'fields': [{'id': 'become_method', 'label': 'Become', 'choices': ['dup', 'dup']}]}, False), # noqa
|
||||
({'fields': [{'id': 'tower', 'label': 'Reserved!', }]}, False), # noqa
|
||||
])
|
||||
def test_cred_type_input_schema_validity(input_, valid):
|
||||
type_ = CredentialType(
|
||||
kind='cloud',
|
||||
name='SomeCloud',
|
||||
managed_by_tower=True,
|
||||
inputs=input_
|
||||
)
|
||||
field = CredentialType._meta.get_field('inputs')
|
||||
if valid is False:
|
||||
with pytest.raises(ValidationError):
|
||||
field.clean(input_, type_)
|
||||
else:
|
||||
field.clean(input_, type_)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('injectors, valid', [
|
||||
({}, True),
|
||||
({'invalid-injector': {}}, False),
|
||||
({'file': 123}, False),
|
||||
({'file': {}}, True),
|
||||
# Uses credential inputs inside of unnamed file contents
|
||||
({'file': {'template': '{{username}}'}}, True),
|
||||
# Uses named file
|
||||
({'file': {'template.username': '{{username}}'}}, True),
|
||||
# Uses multiple named files
|
||||
({'file': {'template.username': '{{username}}', 'template.password': '{{pass}}'}}, True),
|
||||
# Use of unnamed file mutually exclusive with use of named files
|
||||
({'file': {'template': '{{username}}', 'template.password': '{{pass}}'}}, False),
|
||||
# References non-existant named file
|
||||
({'env': {'FROM_FILE': "{{tower.filename.cert}}"}}, False),
|
||||
# References unnamed file, but a file was never defined
|
||||
({'env': {'FROM_FILE': "{{tower.filename}}"}}, False),
|
||||
# Cannot reference tower namespace itself (what would this return??)
|
||||
({'env': {'FROM_FILE': "{{tower}}"}}, False),
|
||||
# References filename of a named file
|
||||
({'file': {'template.cert': '{{awx_secret}}'}, 'env': {'FROM_FILE': "{{tower.filename.cert}}"}}, True),
|
||||
# With named files, `tower.filename` is another namespace, so it cannot be referenced
|
||||
({'file': {'template.cert': '{{awx_secret}}'}, 'env': {'FROM_FILE': "{{tower.filename}}"}}, False),
|
||||
# With an unnamed file, `tower.filename` is just the filename
|
||||
({'file': {'template': '{{awx_secret}}'}, 'env': {'THE_FILENAME': "{{tower.filename}}"}}, True),
|
||||
({'file': {'foo': 'bar'}}, False),
|
||||
({'env': 123}, False),
|
||||
({'env': {}}, True),
|
||||
({'env': {'AWX_SECRET': '{{awx_secret}}'}}, True),
|
||||
({'env': {'AWX_SECRET_99': '{{awx_secret}}'}}, True),
|
||||
({'env': {'99': '{{awx_secret}}'}}, False),
|
||||
({'env': {'AWX_SECRET=': '{{awx_secret}}'}}, False),
|
||||
({'env': {'ANSIBLE_SETTING': '{{awx_secret}}'}}, False),
|
||||
({'env': {'DRAGON': u'🐉'}}, False),
|
||||
({'env': {u'🐉': 'DRAGON'}}, False),
|
||||
({'extra_vars': 123}, False),
|
||||
({'extra_vars': {}}, True),
|
||||
({'extra_vars': {'hostname': '{{host}}'}}, True),
|
||||
({'extra_vars': {'hostname_99': '{{host}}'}}, True),
|
||||
({'extra_vars': {'99': '{{host}}'}}, False),
|
||||
({'extra_vars': {'99=': '{{host}}'}}, False),
|
||||
])
|
||||
def test_cred_type_injectors_schema(injectors, valid):
|
||||
type_ = CredentialType(
|
||||
kind='cloud',
|
||||
name='SomeCloud',
|
||||
managed_by_tower=True,
|
||||
inputs={
|
||||
'fields': [
|
||||
{'id': 'username', 'type': 'string', 'label': '_'},
|
||||
{'id': 'pass', 'type': 'string', 'label': '_'},
|
||||
{'id': 'awx_secret', 'type': 'string', 'label': '_'},
|
||||
{'id': 'host', 'type': 'string', 'label': '_'},
|
||||
]
|
||||
},
|
||||
injectors=injectors
|
||||
)
|
||||
field = CredentialType._meta.get_field('injectors')
|
||||
if valid is False:
|
||||
with pytest.raises(ValidationError):
|
||||
field.clean(injectors, type_)
|
||||
else:
|
||||
field.clean(injectors, type_)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('inputs', [
|
||||
['must-be-a-dict'],
|
||||
{'user': 'wrong-key'},
|
||||
{'username': 1},
|
||||
{'username': 1.5},
|
||||
{'username': ['a', 'b', 'c']},
|
||||
{'username': {'a': 'b'}},
|
||||
{'flag': 1},
|
||||
{'flag': 1.5},
|
||||
{'flag': ['a', 'b', 'c']},
|
||||
{'flag': {'a': 'b'}},
|
||||
{'flag': 'some-string'},
|
||||
])
|
||||
def test_credential_creation_validation_failure(inputs):
|
||||
type_ = CredentialType(
|
||||
kind='cloud',
|
||||
name='SomeCloud',
|
||||
managed_by_tower=True,
|
||||
inputs={
|
||||
'fields': [{
|
||||
'id': 'username',
|
||||
'label': 'Username for SomeCloud',
|
||||
'type': 'string'
|
||||
},{
|
||||
'id': 'flag',
|
||||
'label': 'Some Boolean Flag',
|
||||
'type': 'boolean'
|
||||
}]
|
||||
}
|
||||
)
|
||||
cred = Credential(credential_type=type_, name="Bob's Credential",
|
||||
inputs=inputs)
|
||||
field = cred._meta.get_field('inputs')
|
||||
|
||||
with pytest.raises(Exception) as e:
|
||||
field.validate(inputs, cred)
|
||||
assert e.type in (ValidationError, DRFValidationError)
|
||||
|
||||
|
||||
def test_implicit_role_field_parents():
|
||||
"""This assures that every ImplicitRoleField only references parents
|
||||
which are relationships that actually exist
|
||||
"""
|
||||
app_models = apps.get_app_config('main').get_models()
|
||||
for cls in app_models:
|
||||
for field in cls._meta.get_fields():
|
||||
if not isinstance(field, ImplicitRoleField):
|
||||
continue
|
||||
|
||||
if not field.parent_role:
|
||||
continue
|
||||
|
||||
field_names = field.parent_role
|
||||
if type(field_names) is not list:
|
||||
field_names = [field_names]
|
||||
|
||||
for field_name in field_names:
|
||||
# this type of specification appears to have been considered
|
||||
# at some point, but does not exist in the app and would
|
||||
# need support and tests built out for it
|
||||
assert not isinstance(field_name, tuple)
|
||||
# also used to be a thing before py3 upgrade
|
||||
assert not isinstance(field_name, bytes)
|
||||
# this is always coherent
|
||||
if field_name.startswith('singleton:'):
|
||||
continue
|
||||
# separate out parent role syntax
|
||||
field_name, sep, field_attr = field_name.partition('.')
|
||||
# now make primary assertion, that specified paths exist
|
||||
assert hasattr(cls, field_name)
|
||||
|
||||
# inspect in greater depth
|
||||
second_field = cls._meta.get_field(field_name)
|
||||
second_field_descriptor = getattr(cls, field_name)
|
||||
# all supported linkage types
|
||||
assert isinstance(second_field_descriptor, (
|
||||
ReverseManyToOneDescriptor, # not currently used
|
||||
ImplicitRoleDescriptor,
|
||||
ForwardManyToOneDescriptor
|
||||
))
|
||||
# only these links are supported
|
||||
if field_attr:
|
||||
if isinstance(second_field_descriptor, ReverseManyToOneDescriptor):
|
||||
assert type(second_field) is ForeignKey
|
||||
rel_model = cls._meta.get_field(field_name).related_model
|
||||
third_field = getattr(rel_model, field_attr)
|
||||
# expecting for related_model.foo_role, test role field type
|
||||
assert isinstance(third_field, ImplicitRoleDescriptor)
|
||||
else:
|
||||
# expecting simple format of foo_role
|
||||
assert type(second_field) is ImplicitRoleField
|
||||
@@ -0,0 +1,17 @@
|
||||
# Copyright (c) 2016 Ansible, Inc.
|
||||
|
||||
# Python
|
||||
from unittest import mock
|
||||
|
||||
# AWX
|
||||
from awx.main.ha import is_ha_environment
|
||||
|
||||
|
||||
@mock.patch('awx.main.models.Instance.objects.count', lambda: 2)
|
||||
def test_multiple_instances():
|
||||
assert is_ha_environment()
|
||||
|
||||
|
||||
@mock.patch('awx.main.models.Instance.objects.count', lambda: 1)
|
||||
def test_db_localhost():
|
||||
assert is_ha_environment() is False
|
||||
@@ -0,0 +1,161 @@
|
||||
import textwrap
|
||||
import pytest
|
||||
|
||||
# AWX
|
||||
from awx.main.redact import UriCleaner
|
||||
from awx.main.tests.URI import URI
|
||||
|
||||
TEST_URIS = [
|
||||
URI('no host', scheme='https', username='myusername', password='mypass', host=None),
|
||||
URI('no host', scheme='https', username='myusername', password='mypass*********', host=None),
|
||||
URI('http', scheme='http'),
|
||||
URI('https', scheme='https'),
|
||||
URI('no password', password=''),
|
||||
URI('no host', host=''),
|
||||
URI('host with port', host='host.com:22'),
|
||||
URI('host with @', host='host.com:22'),
|
||||
URI('host with @, password with @ at the end', password='mypasswordwith@', host='@host.com'),
|
||||
URI('no host, with space', host=' '),
|
||||
URI('password is a space', password='%20%20'),
|
||||
URI('no password field', password=None),
|
||||
URI('no username no password', username=None, password=None),
|
||||
URI('password with @ at the end', password='mypasswordwitha@'),
|
||||
URI('password with @@ at the end', password='mypasswordwitha@@'),
|
||||
URI('password with @@@ at the end', password='mypasswordwitha@@@'),
|
||||
URI('password with @@@@ at the end', password='mypasswordwitha@@@@'),
|
||||
URI('password with @a@@ at the end', password='mypasswordwitha@a@@'),
|
||||
URI('password with @@@a at the end', password='mypasswordwitha@@@a'),
|
||||
URI('password with a @ in the middle', password='pa@ssword'),
|
||||
URI('url with @', password='pa@ssword', host='googly.com/whatever@#$:stuff@.com/'),
|
||||
]
|
||||
|
||||
TEST_CLEARTEXT = []
|
||||
# Arguably, this is a regression test given the below data.
|
||||
# regression data https://trello.com/c/cdUELgVY/
|
||||
uri = URI(scheme="https", username="myusername", password="mypasswordwith%40", host="nonexistant.ansible.com/ansible.git/")
|
||||
TEST_CLEARTEXT.append({
|
||||
'uri' : uri,
|
||||
'text' : textwrap.dedent("""\
|
||||
PLAY [all] ********************************************************************
|
||||
|
||||
TASK: [delete project directory before update] ********************************
|
||||
skipping: [localhost]
|
||||
|
||||
TASK: [update project using git and accept hostkey] ***************************
|
||||
skipping: [localhost]
|
||||
|
||||
TASK: [update project using git] **********************************************
|
||||
failed: [localhost] => {"cmd": "/usr/bin/git ls-remote https://%s:%s -h refs/heads/HEAD", "failed": true, "rc": 128}
|
||||
stderr: fatal: unable to access '%s': Could not resolve host: nonexistant.ansible.com
|
||||
|
||||
msg: fatal: unable to access '%s': Could not resolve host: nonexistant.ansible.com
|
||||
|
||||
FATAL: all hosts have already failed -- aborting
|
||||
|
||||
PLAY RECAP ********************************************************************
|
||||
to retry, use: --limit @/root/project_update.retry
|
||||
|
||||
localhost : ok=0 changed=0 unreachable=0 failed=1
|
||||
|
||||
""" % (uri.username, uri.password, str(uri), str(uri))),
|
||||
'host_occurrences' : 2
|
||||
})
|
||||
|
||||
uri = URI(scheme="https", username="Dhh3U47nmC26xk9PKscV", password="PXPfWW8YzYrgS@E5NbQ2H@", host="github.ginger.com/theirrepo.git/info/refs")
|
||||
TEST_CLEARTEXT.append({
|
||||
'uri' : uri,
|
||||
'text' : textwrap.dedent("""\
|
||||
TASK: [update project using git] **
|
||||
failed: [localhost] => {"cmd": "/usr/bin/git ls-remote https://REDACTED:********", "failed": true, "rc": 128}
|
||||
stderr: error: Couldn't resolve host '@%s' while accessing %s
|
||||
|
||||
fatal: HTTP request failed
|
||||
|
||||
msg: error: Couldn't resolve host '@%s' while accessing %s
|
||||
|
||||
fatal: HTTP request failed
|
||||
""" % (uri.host, str(uri), uri.host, str(uri))),
|
||||
'host_occurrences' : 4
|
||||
})
|
||||
|
||||
|
||||
@pytest.mark.parametrize('username, password, not_uri, expected', [
|
||||
('', '', 'www.famfamfam.com](http://www.famfamfam.com/fijdlfd', 'www.famfamfam.com](http://www.famfamfam.com/fijdlfd'),
|
||||
('', '', 'https://www.famfamfam.com](http://www.famfamfam.com/fijdlfd', '$encrypted$'),
|
||||
('root', 'gigity', 'https://root@gigity@www.famfamfam.com](http://www.famfamfam.com/fijdlfd', '$encrypted$'),
|
||||
('root', 'gigity@', 'https://root:gigity@@@www.famfamfam.com](http://www.famfamfam.com/fijdlfd', '$encrypted$'),
|
||||
])
|
||||
# should redact sensitive usernames and passwords
|
||||
def test_non_uri_redact(username, password, not_uri, expected):
|
||||
redacted_str = UriCleaner.remove_sensitive(not_uri)
|
||||
if username:
|
||||
assert username not in redacted_str
|
||||
if password:
|
||||
assert password not in redacted_str
|
||||
|
||||
assert redacted_str == expected
|
||||
|
||||
|
||||
def test_multiple_non_uri_redact():
|
||||
non_uri = 'https://www.famfamfam.com](http://www.famfamfam.com/fijdlfd hi '
|
||||
non_uri += 'https://www.famfamfam.com](http://www.famfamfam.com/fijdlfd world '
|
||||
non_uri += 'https://www.famfamfam.com](http://www.famfamfam.com/fijdlfd foo '
|
||||
non_uri += 'https://foo:bar@giggity.com bar'
|
||||
redacted_str = UriCleaner.remove_sensitive(non_uri)
|
||||
assert redacted_str == '$encrypted$ hi $encrypted$ world $encrypted$ foo https://$encrypted$:$encrypted$@giggity.com bar'
|
||||
|
||||
|
||||
# should replace secret data with safe string, UriCleaner.REPLACE_STR
|
||||
@pytest.mark.parametrize('uri', TEST_URIS)
|
||||
def test_uri_scm_simple_replaced(uri):
|
||||
redacted_str = UriCleaner.remove_sensitive(str(uri))
|
||||
assert redacted_str.count(UriCleaner.REPLACE_STR) == uri.get_secret_count()
|
||||
|
||||
|
||||
# should redact multiple uris in text
|
||||
@pytest.mark.parametrize('uri', TEST_URIS)
|
||||
def test_uri_scm_multiple(uri):
|
||||
cleartext = ''
|
||||
cleartext += str(uri) + ' '
|
||||
cleartext += str(uri) + '\n'
|
||||
|
||||
redacted_str = UriCleaner.remove_sensitive(str(uri))
|
||||
if uri.username:
|
||||
assert uri.username not in redacted_str
|
||||
if uri.password:
|
||||
assert uri.password not in redacted_str
|
||||
|
||||
|
||||
# should replace multiple secret data with safe string
|
||||
@pytest.mark.parametrize('uri', TEST_URIS)
|
||||
def test_uri_scm_multiple_replaced(uri):
|
||||
cleartext = ''
|
||||
find_count = 0
|
||||
|
||||
cleartext += str(uri) + ' '
|
||||
find_count += uri.get_secret_count()
|
||||
|
||||
cleartext += str(uri) + '\n'
|
||||
find_count += uri.get_secret_count()
|
||||
|
||||
redacted_str = UriCleaner.remove_sensitive(cleartext)
|
||||
assert redacted_str.count(UriCleaner.REPLACE_STR) == find_count
|
||||
|
||||
|
||||
# should redact and replace multiple secret data within a complex cleartext blob
|
||||
@pytest.mark.parametrize('test_data', TEST_CLEARTEXT)
|
||||
def test_uri_scm_cleartext_redact_and_replace(test_data):
|
||||
uri = test_data['uri']
|
||||
redacted_str = UriCleaner.remove_sensitive(test_data['text'])
|
||||
assert uri.username not in redacted_str
|
||||
assert uri.password not in redacted_str
|
||||
# Ensure the host didn't get redacted
|
||||
assert redacted_str.count(uri.host) == test_data['host_occurrences']
|
||||
|
||||
|
||||
@pytest.mark.timeout(1)
|
||||
def test_large_string_performance():
|
||||
length = 100000
|
||||
redacted = UriCleaner.remove_sensitive('x' * length)
|
||||
assert len(redacted) == length
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
from split_settings.tools import include
|
||||
|
||||
|
||||
def test_postprocess_auth_basic_enabled():
|
||||
locals().update({'__file__': __file__})
|
||||
|
||||
include('../../../settings/defaults.py', scope=locals())
|
||||
assert 'awx.api.authentication.LoggedBasicAuthentication' in locals()['REST_FRAMEWORK']['DEFAULT_AUTHENTICATION_CLASSES']
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
from awx.main import signals
|
||||
|
||||
|
||||
class TestCleanupDetachedLabels:
|
||||
def test_cleanup_detached_labels_on_deleted_parent(self, mocker):
|
||||
mock_labels = [mocker.MagicMock(), mocker.MagicMock()]
|
||||
mock_instance = mocker.MagicMock()
|
||||
mock_instance.labels.all = mocker.MagicMock()
|
||||
mock_instance.labels.all.return_value = mock_labels
|
||||
mock_labels[0].is_candidate_for_detach.return_value = True
|
||||
mock_labels[1].is_candidate_for_detach.return_value = False
|
||||
|
||||
signals.cleanup_detached_labels_on_deleted_parent(None, mock_instance)
|
||||
|
||||
mock_labels[0].is_candidate_for_detach.assert_called_with()
|
||||
mock_labels[1].is_candidate_for_detach.assert_called_with()
|
||||
mock_labels[0].delete.assert_called_with()
|
||||
mock_labels[1].delete.assert_not_called()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,159 @@
|
||||
from django.core.exceptions import ValidationError
|
||||
from awx.main.validators import (
|
||||
validate_private_key,
|
||||
validate_certificate,
|
||||
validate_ssh_private_key,
|
||||
vars_validate_or_raise,
|
||||
)
|
||||
from awx.main.tests.data.ssh import (
|
||||
TEST_SSH_RSA1_KEY_DATA,
|
||||
TEST_SSH_KEY_DATA,
|
||||
TEST_SSH_KEY_DATA_LOCKED,
|
||||
TEST_OPENSSH_KEY_DATA,
|
||||
TEST_OPENSSH_KEY_DATA_LOCKED,
|
||||
TEST_SSH_CERT_KEY,
|
||||
TEST_CATTED_SSH_KEY_DATA,
|
||||
)
|
||||
from rest_framework.serializers import ValidationError as RestValidationError
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_invalid_keys():
|
||||
invalid_keys = [
|
||||
"---BEGIN FOO -----foobar-----END FOO----",
|
||||
"-----BEGIN FOO---foobar-----END FOO----",
|
||||
"-----BEGIN FOO-----foobar---END FOO----",
|
||||
"----- BEGIN FOO ----- foobar ----- FAIL FOO ----",
|
||||
"----- FAIL FOO ----- foobar ----- END FOO ----",
|
||||
"----BEGIN FOO----foobar----END BAR----",
|
||||
]
|
||||
for invalid_key in invalid_keys:
|
||||
with pytest.raises(ValidationError):
|
||||
validate_private_key(invalid_key)
|
||||
with pytest.raises(ValidationError):
|
||||
validate_certificate(invalid_key)
|
||||
with pytest.raises(ValidationError):
|
||||
validate_ssh_private_key(invalid_key)
|
||||
|
||||
|
||||
def test_invalid_rsa_key():
|
||||
invalid_key = TEST_SSH_KEY_DATA.replace('-----END', '----END')
|
||||
with pytest.raises(ValidationError):
|
||||
validate_private_key(invalid_key)
|
||||
with pytest.raises(ValidationError):
|
||||
validate_certificate(invalid_key)
|
||||
with pytest.raises(ValidationError):
|
||||
validate_ssh_private_key(invalid_key)
|
||||
|
||||
|
||||
def test_valid_catted_rsa_key():
|
||||
valid_key = TEST_CATTED_SSH_KEY_DATA
|
||||
pem_objects = validate_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'rsa'
|
||||
assert not pem_objects[0]['key_enc']
|
||||
with pytest.raises(ValidationError):
|
||||
validate_certificate(valid_key)
|
||||
pem_objects = validate_ssh_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'rsa'
|
||||
assert not pem_objects[0]['key_enc']
|
||||
|
||||
|
||||
def test_valid_rsa_key():
|
||||
valid_key = TEST_SSH_KEY_DATA
|
||||
pem_objects = validate_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'rsa'
|
||||
assert not pem_objects[0]['key_enc']
|
||||
with pytest.raises(ValidationError):
|
||||
validate_certificate(valid_key)
|
||||
pem_objects = validate_ssh_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'rsa'
|
||||
assert not pem_objects[0]['key_enc']
|
||||
|
||||
|
||||
def test_valid_locked_rsa_key():
|
||||
valid_key = TEST_SSH_KEY_DATA_LOCKED
|
||||
pem_objects = validate_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'rsa'
|
||||
assert pem_objects[0]['key_enc']
|
||||
with pytest.raises(ValidationError):
|
||||
validate_certificate(valid_key)
|
||||
pem_objects = validate_ssh_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'rsa'
|
||||
assert pem_objects[0]['key_enc']
|
||||
|
||||
|
||||
def test_valid_openssh_key():
|
||||
valid_key = TEST_OPENSSH_KEY_DATA
|
||||
pem_objects = validate_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'ed25519'
|
||||
assert not pem_objects[0]['key_enc']
|
||||
with pytest.raises(ValidationError):
|
||||
validate_certificate(valid_key)
|
||||
pem_objects = validate_ssh_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'ed25519'
|
||||
assert not pem_objects[0]['key_enc']
|
||||
|
||||
|
||||
def test_valid_locked_openssh_key():
|
||||
valid_key = TEST_OPENSSH_KEY_DATA_LOCKED
|
||||
pem_objects = validate_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'ed25519'
|
||||
assert pem_objects[0]['key_enc']
|
||||
with pytest.raises(ValidationError):
|
||||
validate_certificate(valid_key)
|
||||
pem_objects = validate_ssh_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'ed25519'
|
||||
assert pem_objects[0]['key_enc']
|
||||
|
||||
|
||||
def test_valid_rsa1_key():
|
||||
valid_key = TEST_SSH_RSA1_KEY_DATA
|
||||
pem_objects = validate_ssh_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'rsa1'
|
||||
assert not pem_objects[0]['key_enc']
|
||||
with pytest.raises(ValidationError):
|
||||
validate_certificate(valid_key)
|
||||
pem_objects = validate_ssh_private_key(valid_key)
|
||||
assert pem_objects[0]['key_type'] == 'rsa1'
|
||||
assert not pem_objects[0]['key_enc']
|
||||
|
||||
|
||||
def test_cert_with_key():
|
||||
cert_with_key = TEST_SSH_CERT_KEY
|
||||
with pytest.raises(ValidationError):
|
||||
validate_private_key(cert_with_key)
|
||||
with pytest.raises(ValidationError):
|
||||
validate_certificate(cert_with_key)
|
||||
pem_objects = validate_ssh_private_key(cert_with_key)
|
||||
assert pem_objects[0]['type'] == 'CERTIFICATE'
|
||||
assert pem_objects[1]['key_type'] == 'rsa'
|
||||
assert not pem_objects[1]['key_enc']
|
||||
|
||||
|
||||
@pytest.mark.parametrize("var_str", [
|
||||
'{"a": "b"}',
|
||||
'---\na: b\nc: d',
|
||||
'',
|
||||
'""',
|
||||
])
|
||||
def test_valid_vars(var_str):
|
||||
vars_validate_or_raise(var_str)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("var_str", [
|
||||
'["a": "b"]',
|
||||
'["a", "b"]',
|
||||
"('a=4', 'c=5')",
|
||||
'"',
|
||||
"''",
|
||||
"5",
|
||||
"6.74",
|
||||
"hello",
|
||||
"OrderedDict([('a', 'b')])",
|
||||
"True",
|
||||
"False",
|
||||
])
|
||||
def test_invalid_vars(var_str):
|
||||
with pytest.raises(RestValidationError):
|
||||
vars_validate_or_raise(var_str)
|
||||
@@ -0,0 +1,93 @@
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
# Django REST Framework
|
||||
from rest_framework import exceptions
|
||||
from rest_framework.generics import ListAPIView
|
||||
|
||||
# AWX
|
||||
from awx.main.views import ApiErrorView
|
||||
from awx.api.views import JobList
|
||||
from awx.api.generics import ListCreateAPIView, SubListAttachDetachAPIView
|
||||
|
||||
|
||||
HTTP_METHOD_NAMES = [
|
||||
'get',
|
||||
'post',
|
||||
'put',
|
||||
'patch',
|
||||
'delete',
|
||||
'head',
|
||||
'options',
|
||||
'trace',
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api_view_obj_fixture():
|
||||
return ApiErrorView()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('method_name', HTTP_METHOD_NAMES)
|
||||
def test_exception_view_allow_http_methods(method_name):
|
||||
assert hasattr(ApiErrorView, method_name)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('method_name', HTTP_METHOD_NAMES)
|
||||
def test_exception_view_raises_exception(api_view_obj_fixture, method_name):
|
||||
request_mock = mock.MagicMock()
|
||||
with pytest.raises(exceptions.APIException):
|
||||
getattr(api_view_obj_fixture, method_name)(request_mock)
|
||||
|
||||
|
||||
def test_disable_post_on_v2_jobs_list():
|
||||
job_list = JobList()
|
||||
job_list.request = mock.MagicMock()
|
||||
assert ('POST' in job_list.allowed_methods) is False
|
||||
|
||||
|
||||
def test_views_have_search_fields(all_views):
|
||||
# Gather any views that don't have search fields defined
|
||||
views_missing_search = []
|
||||
for View in all_views:
|
||||
if not issubclass(View, ListAPIView):
|
||||
continue
|
||||
view = View()
|
||||
if not hasattr(view, 'search_fields') or len(view.search_fields) == 0:
|
||||
views_missing_search.append(view)
|
||||
|
||||
if views_missing_search:
|
||||
raise Exception('{} views do not have search fields defined:\n{}'.format(
|
||||
len(views_missing_search),
|
||||
'\n'.join([
|
||||
v.__class__.__name__ + ' (model: {})'.format(getattr(v, 'model', type(None)).__name__)
|
||||
for v in views_missing_search
|
||||
]))
|
||||
)
|
||||
|
||||
|
||||
def test_global_creation_always_possible(all_views):
|
||||
"""To not make life very difficult for clients, this test
|
||||
asserts that all creatable resources can be created by
|
||||
POSTing to the global resource list
|
||||
"""
|
||||
views_by_model = {}
|
||||
for View in all_views:
|
||||
if not getattr(View, 'deprecated', False) and issubclass(View, ListAPIView) and hasattr(View, 'model'):
|
||||
views_by_model.setdefault(View.model, []).append(View)
|
||||
for model, views in views_by_model.items():
|
||||
creatable = False
|
||||
global_view = None
|
||||
creatable_view = None
|
||||
for View in views:
|
||||
if '{}ListView'.format(model.__name__) == View.__name__:
|
||||
global_view = View
|
||||
if issubclass(View, ListCreateAPIView) and not issubclass(View, SubListAttachDetachAPIView):
|
||||
creatable = True
|
||||
creatable_view = View
|
||||
if not creatable or not global_view:
|
||||
continue
|
||||
assert 'POST' in global_view().allowed_methods, (
|
||||
'Resource {} should be creatable in global list view {}. '
|
||||
'Can be created now in {}'.format(model, global_view, creatable_view)
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
import os
|
||||
import os.path
|
||||
|
||||
import pytest
|
||||
|
||||
from awx.main.tests import data
|
||||
from awx.main.utils.ansible import could_be_playbook, could_be_inventory
|
||||
|
||||
DATA = os.path.join(os.path.dirname(data.__file__), 'ansible_utils')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename', os.listdir(os.path.join(DATA, 'playbooks', 'valid')))
|
||||
def test_could_be_playbook(filename):
|
||||
path = os.path.join(DATA, 'playbooks', 'valid')
|
||||
assert could_be_playbook(DATA, path, filename).endswith(filename)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename', os.listdir(os.path.join(DATA, 'playbooks', 'invalid')))
|
||||
def test_is_not_playbook(filename):
|
||||
path = os.path.join(DATA, 'playbooks', 'invalid')
|
||||
assert could_be_playbook(DATA, path, filename) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename', os.listdir(os.path.join(DATA, 'inventories', 'valid')))
|
||||
def test_could_be_inventory(filename):
|
||||
path = os.path.join(DATA, 'inventories', 'valid')
|
||||
assert could_be_inventory(DATA, path, filename).endswith(filename)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename', os.listdir(os.path.join(DATA, 'inventories', 'invalid')))
|
||||
def test_is_not_inventory(filename):
|
||||
path = os.path.join(DATA, 'inventories', 'invalid')
|
||||
assert could_be_inventory(DATA, path, filename) is None
|
||||
@@ -0,0 +1,217 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2017 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
import os
|
||||
import pytest
|
||||
from uuid import uuid4
|
||||
import json
|
||||
import yaml
|
||||
from unittest import mock
|
||||
|
||||
from backports.tempfile import TemporaryDirectory
|
||||
from django.conf import settings
|
||||
|
||||
from rest_framework.exceptions import ParseError
|
||||
|
||||
from awx.main.utils import common
|
||||
|
||||
from awx.main.models import (
|
||||
Job,
|
||||
AdHocCommand,
|
||||
InventoryUpdate,
|
||||
ProjectUpdate,
|
||||
SystemJob,
|
||||
WorkflowJob,
|
||||
Inventory,
|
||||
JobTemplate,
|
||||
UnifiedJobTemplate,
|
||||
UnifiedJob
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('input_, output', [
|
||||
({"foo": "bar"}, {"foo": "bar"}),
|
||||
('{"foo": "bar"}', {"foo": "bar"}),
|
||||
('---\nfoo: bar', {"foo": "bar"}),
|
||||
(4399, {}),
|
||||
])
|
||||
def test_parse_yaml_or_json(input_, output):
|
||||
assert common.parse_yaml_or_json(input_) == output
|
||||
|
||||
|
||||
def test_recursive_vars_not_allowed():
|
||||
rdict = {}
|
||||
rdict['a'] = rdict
|
||||
# YAML dumper will use a tag to give recursive data
|
||||
data = yaml.dump(rdict, default_flow_style=False)
|
||||
with pytest.raises(ParseError) as exc:
|
||||
common.parse_yaml_or_json(data, silent_failure=False)
|
||||
assert 'Circular reference detected' in str(exc)
|
||||
|
||||
|
||||
class TestParserExceptions:
|
||||
|
||||
@staticmethod
|
||||
def json_error(data):
|
||||
try:
|
||||
json.loads(data)
|
||||
return None
|
||||
except Exception as e:
|
||||
return str(e)
|
||||
|
||||
@staticmethod
|
||||
def yaml_error(data):
|
||||
try:
|
||||
yaml.safe_load(data)
|
||||
return None
|
||||
except Exception as e:
|
||||
return str(e)
|
||||
|
||||
def test_invalid_JSON_and_YAML(self):
|
||||
data = "{key:val"
|
||||
with pytest.raises(ParseError) as exc:
|
||||
common.parse_yaml_or_json(data, silent_failure=False)
|
||||
message = str(exc.value)
|
||||
assert "Cannot parse as" in message
|
||||
assert self.json_error(data) in message
|
||||
assert self.yaml_error(data) in message
|
||||
|
||||
def test_invalid_vars_type(self):
|
||||
data = "[1, 2, 3]"
|
||||
with pytest.raises(ParseError) as exc:
|
||||
common.parse_yaml_or_json(data, silent_failure=False)
|
||||
message = str(exc.value)
|
||||
assert "Cannot parse as" in message
|
||||
assert "Input type `list` is not a dictionary" in message
|
||||
|
||||
|
||||
def test_set_environ():
|
||||
key = str(uuid4())
|
||||
old_environ = os.environ.copy()
|
||||
with common.set_environ(**{key: 'bar'}):
|
||||
assert os.environ[key] == 'bar'
|
||||
assert set(os.environ.keys()) - set(old_environ.keys()) == set([key])
|
||||
assert os.environ == old_environ
|
||||
assert key not in os.environ
|
||||
|
||||
|
||||
TEST_MODELS = [
|
||||
(Job, 'job'),
|
||||
(AdHocCommand, 'ad_hoc_command'),
|
||||
(InventoryUpdate, 'inventory_update'),
|
||||
(ProjectUpdate, 'project_update'),
|
||||
(SystemJob, 'system_job'),
|
||||
(WorkflowJob, 'workflow_job'),
|
||||
(UnifiedJob, 'unified_job'),
|
||||
(Inventory, 'inventory'),
|
||||
(JobTemplate, 'job_template'),
|
||||
(UnifiedJobTemplate, 'unified_job_template')
|
||||
]
|
||||
|
||||
|
||||
# Cases relied on for scheduler dependent jobs list
|
||||
@pytest.mark.parametrize('model,name', TEST_MODELS)
|
||||
def test_get_type_for_model(model, name):
|
||||
assert common.get_type_for_model(model) == name
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_get_model_for_invalid_type():
|
||||
with pytest.raises(LookupError):
|
||||
common.get_model_for_type('foobar')
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.parametrize("model_type,model_class", [
|
||||
(name, cls) for cls, name in TEST_MODELS
|
||||
])
|
||||
def test_get_model_for_valid_type(model_type, model_class):
|
||||
assert common.get_model_for_type(model_type) == model_class
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def memoized_function(mocker, mock_cache):
|
||||
with mock.patch('awx.main.utils.common.get_memoize_cache', return_value=mock_cache):
|
||||
@common.memoize(track_function=True)
|
||||
def myfunction(key, value):
|
||||
if key not in myfunction.calls:
|
||||
myfunction.calls[key] = 0
|
||||
|
||||
myfunction.calls[key] += 1
|
||||
|
||||
if myfunction.calls[key] == 1:
|
||||
return value
|
||||
else:
|
||||
return '%s called %s times' % (value, myfunction.calls[key])
|
||||
myfunction.calls = dict()
|
||||
return myfunction
|
||||
|
||||
|
||||
def test_memoize_track_function(memoized_function, mock_cache):
|
||||
assert memoized_function('scott', 'scotterson') == 'scotterson'
|
||||
assert mock_cache.get('myfunction') == {u'scott-scotterson': 'scotterson'}
|
||||
assert memoized_function('scott', 'scotterson') == 'scotterson'
|
||||
|
||||
assert memoized_function.calls['scott'] == 1
|
||||
|
||||
assert memoized_function('john', 'smith') == 'smith'
|
||||
assert mock_cache.get('myfunction') == {u'scott-scotterson': 'scotterson', u'john-smith': 'smith'}
|
||||
assert memoized_function('john', 'smith') == 'smith'
|
||||
|
||||
assert memoized_function.calls['john'] == 1
|
||||
|
||||
|
||||
def test_memoize_delete(memoized_function, mock_cache):
|
||||
assert memoized_function('john', 'smith') == 'smith'
|
||||
assert memoized_function('john', 'smith') == 'smith'
|
||||
assert memoized_function.calls['john'] == 1
|
||||
|
||||
assert mock_cache.get('myfunction') == {u'john-smith': 'smith'}
|
||||
|
||||
with mock.patch('awx.main.utils.common.memoize_delete', side_effect=mock_cache.delete):
|
||||
common.memoize_delete('myfunction')
|
||||
|
||||
assert mock_cache.get('myfunction') is None
|
||||
|
||||
assert memoized_function('john', 'smith') == 'smith called 2 times'
|
||||
assert memoized_function.calls['john'] == 2
|
||||
|
||||
|
||||
def test_memoize_parameter_error():
|
||||
|
||||
with pytest.raises(common.IllegalArgumentError):
|
||||
@common.memoize(cache_key='foo', track_function=True)
|
||||
def fn():
|
||||
return
|
||||
|
||||
|
||||
def test_extract_ansible_vars():
|
||||
my_dict = {
|
||||
"foobar": "baz",
|
||||
"ansible_connetion_setting": "1928"
|
||||
}
|
||||
redacted, var_list = common.extract_ansible_vars(json.dumps(my_dict))
|
||||
assert var_list == set(['ansible_connetion_setting'])
|
||||
assert redacted == {"foobar": "baz"}
|
||||
|
||||
|
||||
def test_get_custom_venv_choices():
|
||||
bundled_venv = os.path.join(settings.BASE_VENV_PATH, 'ansible', '')
|
||||
assert sorted(common.get_custom_venv_choices()) == [bundled_venv]
|
||||
|
||||
with TemporaryDirectory(dir=settings.BASE_VENV_PATH, prefix='tmp') as temp_dir:
|
||||
os.makedirs(os.path.join(temp_dir, 'bin', 'activate'))
|
||||
|
||||
custom_venv_dir = os.path.join(temp_dir, 'custom')
|
||||
custom_venv_1 = os.path.join(custom_venv_dir, 'venv-1')
|
||||
custom_venv_awx = os.path.join(custom_venv_dir, 'custom', 'awx')
|
||||
|
||||
os.makedirs(os.path.join(custom_venv_1, 'bin', 'activate'))
|
||||
os.makedirs(os.path.join(custom_venv_awx, 'bin', 'activate'))
|
||||
|
||||
assert sorted(common.get_custom_venv_choices([custom_venv_dir])) == [
|
||||
bundled_venv,
|
||||
os.path.join(temp_dir, ''),
|
||||
os.path.join(custom_venv_1, '')
|
||||
]
|
||||
@@ -0,0 +1,78 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2017 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
import pytest
|
||||
|
||||
from awx.conf.models import Setting
|
||||
from awx.main.utils import encryption
|
||||
|
||||
|
||||
def test_encrypt_field():
|
||||
field = Setting(pk=123, value='ANSIBLE')
|
||||
encrypted = field.value = encryption.encrypt_field(field, 'value')
|
||||
assert encryption.decrypt_field(field, 'value') == 'ANSIBLE'
|
||||
assert encrypted.startswith('$encrypted$UTF8$AESCBC$')
|
||||
|
||||
|
||||
def test_encrypt_field_without_pk():
|
||||
field = Setting(value='ANSIBLE')
|
||||
encrypted = field.value = encryption.encrypt_field(field, 'value')
|
||||
assert encryption.decrypt_field(field, 'value') == 'ANSIBLE'
|
||||
assert encrypted.startswith('$encrypted$UTF8$AESCBC$')
|
||||
|
||||
|
||||
def test_encrypt_field_with_unicode_string():
|
||||
value = u'Iñtërnâtiônàlizætiøn'
|
||||
field = Setting(value=value)
|
||||
encrypted = field.value = encryption.encrypt_field(field, 'value')
|
||||
assert encryption.decrypt_field(field, 'value') == value
|
||||
assert encrypted.startswith('$encrypted$UTF8$AESCBC$')
|
||||
|
||||
|
||||
def test_encrypt_subfield():
|
||||
field = Setting(value={'name': 'ANSIBLE'})
|
||||
encrypted = field.value = encryption.encrypt_field(field, 'value', subfield='name')
|
||||
assert encryption.decrypt_field(field, 'value', subfield='name') == 'ANSIBLE'
|
||||
assert encrypted.startswith('$encrypted$UTF8$AESCBC$')
|
||||
|
||||
|
||||
def test_encrypt_field_with_ask():
|
||||
encrypted = encryption.encrypt_field(Setting(value='ASK'), 'value', ask=True)
|
||||
assert encrypted == 'ASK'
|
||||
|
||||
|
||||
def test_encrypt_field_with_empty_value():
|
||||
encrypted = encryption.encrypt_field(Setting(value=None), 'value')
|
||||
assert encrypted is None
|
||||
|
||||
|
||||
def test_encrypt_field_with_undefined_attr_raises_expected_exception():
|
||||
with pytest.raises(AttributeError):
|
||||
encryption.encrypt_field({}, 'undefined_attr')
|
||||
|
||||
|
||||
def test_decrypt_field_with_undefined_attr_raises_expected_exception():
|
||||
with pytest.raises(AttributeError):
|
||||
encryption.decrypt_field({}, 'undefined_attr')
|
||||
|
||||
|
||||
class TestSurveyReversibilityValue:
|
||||
'''
|
||||
Tests to enforce the contract with survey password question encrypted values
|
||||
'''
|
||||
_key = encryption.get_encryption_key('value', None)
|
||||
|
||||
def test_encrypt_empty_string(self):
|
||||
assert encryption.encrypt_value('') == ''
|
||||
# the reverse, decryption, does not work
|
||||
|
||||
def test_encrypt_encryption_key(self):
|
||||
assert encryption.encrypt_value('$encrypted$') == '$encrypted$'
|
||||
# the reverse, decryption, does not work
|
||||
|
||||
def test_encrypt_empty_string_twice(self):
|
||||
# Encryption is idempotent
|
||||
val = encryption.encrypt_value('foobar')
|
||||
val2 = encryption.encrypt_value(val)
|
||||
assert encryption.decrypt_value(self._key, val2) == 'foobar'
|
||||
@@ -0,0 +1,229 @@
|
||||
|
||||
# Python
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
# AWX
|
||||
from awx.main.utils.filters import SmartFilter, ExternalLoggerEnabled
|
||||
from awx.main.models import Host
|
||||
|
||||
# Django
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
|
||||
@pytest.mark.parametrize('params, logger_name, expected', [
|
||||
# skip all records if enabled_flag = False
|
||||
({'enabled_flag': False}, 'awx.main', False),
|
||||
# skip all records if the host is undefined
|
||||
({'enabled_flag': True}, 'awx.main', False),
|
||||
# skip all records if underlying logger is used by handlers themselves
|
||||
({'enabled_flag': True}, 'awx.main.utils.handlers', False),
|
||||
({'enabled_flag': True, 'enabled_loggers': ['awx']}, 'awx.main', True),
|
||||
({'enabled_flag': True, 'enabled_loggers': ['abc']}, 'awx.analytics.xyz', False),
|
||||
({'enabled_flag': True, 'enabled_loggers': ['xyz']}, 'awx.analytics.xyz', True),
|
||||
])
|
||||
def test_base_logging_handler_skip_log(params, logger_name, expected, dummy_log_record):
|
||||
filter = ExternalLoggerEnabled(**params)
|
||||
dummy_log_record.name = logger_name
|
||||
assert filter.filter(dummy_log_record) is expected, (params, logger_name)
|
||||
|
||||
|
||||
class Field(object):
|
||||
|
||||
def __init__(self, name, related_model=None, __prevent_search__=None):
|
||||
self.name = name
|
||||
self.related_model = related_model
|
||||
self.__prevent_search__ = __prevent_search__
|
||||
|
||||
|
||||
class Meta(object):
|
||||
|
||||
def __init__(self, fields):
|
||||
self._fields = {
|
||||
f.name: f for f in fields
|
||||
}
|
||||
self.object_name = 'Host'
|
||||
self.fields_map = {}
|
||||
self.fields = self._fields.values()
|
||||
|
||||
def get_field(self, f):
|
||||
return self._fields.get(f)
|
||||
|
||||
|
||||
class mockObjects:
|
||||
def filter(self, *args, **kwargs):
|
||||
return Q(*args, **kwargs)
|
||||
|
||||
|
||||
class mockUser:
|
||||
def __init__(self):
|
||||
print("Host user created")
|
||||
self._meta = Meta(fields=[
|
||||
Field(name='password', __prevent_search__=True)
|
||||
])
|
||||
|
||||
|
||||
class mockHost:
|
||||
def __init__(self):
|
||||
print("Host mock created")
|
||||
self.objects = mockObjects()
|
||||
fields = [
|
||||
Field(name='name'),
|
||||
Field(name='description'),
|
||||
Field(name='created_by', related_model=mockUser())
|
||||
]
|
||||
self._meta = Meta(fields=fields)
|
||||
|
||||
|
||||
@mock.patch('awx.main.utils.filters.get_model', return_value=mockHost())
|
||||
class TestSmartFilterQueryFromString():
|
||||
@mock.patch(
|
||||
'awx.api.filters.get_fields_from_path',
|
||||
lambda model, path: ([model], path) # disable field filtering, because a__b isn't a real Host field
|
||||
)
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('facts__facts__blank=""', Q(**{u"facts__facts__blank": u""})),
|
||||
('"facts__facts__ space "="f"', Q(**{u"facts__facts__ space ": u"f"})),
|
||||
('"facts__facts__ e "=no_quotes_here', Q(**{u"facts__facts__ e ": u"no_quotes_here"})),
|
||||
('a__b__c=3', Q(**{u"a__b__c": 3})),
|
||||
('a__b__c=3.14', Q(**{u"a__b__c": 3.14})),
|
||||
('a__b__c=true', Q(**{u"a__b__c": True})),
|
||||
('a__b__c=false', Q(**{u"a__b__c": False})),
|
||||
('a__b__c=null', Q(**{u"a__b__c": None})),
|
||||
('ansible_facts__a="true"', Q(**{u"ansible_facts__contains": {u"a": u"true"}})),
|
||||
('ansible_facts__a__exact="true"', Q(**{u"ansible_facts__contains": {u"a": u"true"}})),
|
||||
#('"a__b\"__c"="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
#('a__b\"__c="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
])
|
||||
def test_query_generated(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
@pytest.mark.parametrize("filter_string", [
|
||||
'ansible_facts__facts__facts__blank='
|
||||
'ansible_facts__a__b__c__ space =ggg',
|
||||
])
|
||||
def test_invalid_filter_strings(self, mock_get_host_model, filter_string):
|
||||
with pytest.raises(RuntimeError) as e:
|
||||
SmartFilter.query_from_string(filter_string)
|
||||
assert str(e.value) == u"Invalid query " + filter_string
|
||||
|
||||
@pytest.mark.parametrize("filter_string", [
|
||||
'created_by__password__icontains=pbkdf2'
|
||||
'search=foo or created_by__password__icontains=pbkdf2',
|
||||
'created_by__password__icontains=pbkdf2 or search=foo',
|
||||
])
|
||||
def test_forbidden_filter_string(self, mock_get_host_model, filter_string):
|
||||
with pytest.raises(Exception) as e:
|
||||
SmartFilter.query_from_string(filter_string)
|
||||
"Filtering on password is not allowed." in str(e)
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
(u'(a=abc\u1F5E3def)', Q(**{u"a": u"abc\u1F5E3def"})),
|
||||
(u'(ansible_facts__a=abc\u1F5E3def)', Q(**{u"ansible_facts__contains": {u"a": u"abc\u1F5E3def"}})),
|
||||
])
|
||||
def test_unicode(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('(a=b)', Q(**{u"a": u"b"})),
|
||||
('a=b and c=d', Q(**{u"a": u"b"}) & Q(**{u"c": u"d"})),
|
||||
('(a=b and c=d)', Q(**{u"a": u"b"}) & Q(**{u"c": u"d"})),
|
||||
('a=b or c=d', Q(**{u"a": u"b"}) | Q(**{u"c": u"d"})),
|
||||
('(a=b and c=d) or (e=f)', (Q(**{u"a": u"b"}) & Q(**{u"c": u"d"})) | (Q(**{u"e": u"f"}))),
|
||||
(
|
||||
'a=b or a=d or a=e or a=z and b=h and b=i and b=j and b=k',
|
||||
Q(**{u"a": u"b"}) | Q(**{u"a": u"d"}) | Q(**{u"a": u"e"}) | Q(**{u"a": u"z"}) &
|
||||
Q(**{u"b": u"h"}) & Q(**{u"b": u"i"}) & Q(**{u"b": u"j"}) & Q(**{u"b": u"k"})
|
||||
)
|
||||
])
|
||||
def test_boolean_parenthesis(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('ansible_facts__a__b__c[]=3', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [3]}}}})),
|
||||
('ansible_facts__a__b__c[]=3.14', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [3.14]}}}})),
|
||||
('ansible_facts__a__b__c[]=true', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [True]}}}})),
|
||||
('ansible_facts__a__b__c[]=false', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [False]}}}})),
|
||||
('ansible_facts__a__b__c[]="true"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [u"true"]}}}})),
|
||||
('ansible_facts__a__b__c[]="hello world"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [u"hello world"]}}}})),
|
||||
('ansible_facts__a__b__c[]__d[]="foobar"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": [u"foobar"]}]}}}})),
|
||||
('ansible_facts__a__b__c[]__d="foobar"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": u"foobar"}]}}}})),
|
||||
('ansible_facts__a__b__c[]__d__e="foobar"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": {u"e": u"foobar"}}]}}}})),
|
||||
('ansible_facts__a__b__c[]__d__e[]="foobar"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": {u"e": [u"foobar"]}}]}}}})),
|
||||
('ansible_facts__a__b__c[]__d__e__f[]="foobar"', Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": {u"e": {u"f": [u"foobar"]}}}]}}}})),
|
||||
(
|
||||
'(ansible_facts__a__b__c[]__d__e__f[]="foobar") and (ansible_facts__a__b__c[]__d__e[]="foobar")',
|
||||
Q(**{ u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": {u"e": {u"f": [u"foobar"]}}}]}}}}) &
|
||||
Q(**{u"ansible_facts__contains": {u"a": {u"b": {u"c": [{u"d": {u"e": [u"foobar"]}}]}}}})),
|
||||
#('"a__b\"__c"="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
#('a__b\"__c="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
])
|
||||
def test_contains_query_generated(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
#('a__b__c[]="true"', Q(**{u"a__b__c__contains": u"\"true\""})),
|
||||
('ansible_facts__a="true"', Q(**{u"ansible_facts__contains": {u"a": u"true"}})),
|
||||
#('"a__b\"__c"="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
#('a__b\"__c="true"', Q(**{u"a__b\"__c": "true"})),
|
||||
])
|
||||
def test_contains_query_generated_unicode(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('ansible_facts__a=null', Q(**{u"ansible_facts__contains": {u"a": None}})),
|
||||
('ansible_facts__c="null"', Q(**{u"ansible_facts__contains": {u"c": u"\"null\""}})),
|
||||
])
|
||||
def test_contains_query_generated_null(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('group__search=foo', Q(Q(**{u"group__name__icontains": u"foo"}) | Q(**{u"group__description__icontains": u"foo"}))),
|
||||
('search=foo and group__search=foo', Q(
|
||||
Q(**{u"name__icontains": u"foo"}) | Q(**{ u"description__icontains": u"foo"}),
|
||||
Q(**{u"group__name__icontains": u"foo"}) | Q(**{u"group__description__icontains": u"foo"}))),
|
||||
('search=foo or ansible_facts__a=null',
|
||||
Q(Q(**{u"name__icontains": u"foo"}) | Q(**{u"description__icontains": u"foo"})) |
|
||||
Q(**{u"ansible_facts__contains": {u"a": None}})),
|
||||
])
|
||||
def test_search_related_fields(self, mock_get_host_model, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q) == str(q_expected)
|
||||
|
||||
|
||||
class TestSmartFilterQueryFromStringNoDB():
|
||||
@pytest.mark.parametrize("filter_string,q_expected", [
|
||||
('ansible_facts__a="true" and ansible_facts__b="true" and ansible_facts__c="true"',
|
||||
(Q(**{u"ansible_facts__contains": {u"a": u"true"}}) &
|
||||
Q(**{u"ansible_facts__contains": {u"b": u"true"}}) &
|
||||
Q(**{u"ansible_facts__contains": {u"c": u"true"}}))),
|
||||
('ansible_facts__a="true" or ansible_facts__b="true" or ansible_facts__c="true"',
|
||||
(Q(**{u"ansible_facts__contains": {u"a": u"true"}}) |
|
||||
Q(**{u"ansible_facts__contains": {u"b": u"true"}}) |
|
||||
Q(**{u"ansible_facts__contains": {u"c": u"true"}}))),
|
||||
('search=foo',
|
||||
Q(Q(**{ u"description__icontains": u"foo"}) | Q(**{u"name__icontains": u"foo"}))),
|
||||
('search=foo and ansible_facts__a="null"',
|
||||
Q(Q(**{u"description__icontains": u"foo"}) | Q(**{u"name__icontains": u"foo"})) &
|
||||
Q(**{u"ansible_facts__contains": {u"a": u"\"null\""}})),
|
||||
('name=foo or name=bar and name=foobar',
|
||||
Q(name="foo") | Q(name="bar") & Q(name="foobar"))
|
||||
])
|
||||
def test_does_not_invoke_db(self, filter_string, q_expected):
|
||||
q = SmartFilter.query_from_string(filter_string)
|
||||
assert str(q.query) == str(Host.objects.filter(q_expected).query)
|
||||
|
||||
|
||||
'''
|
||||
#('"facts__quoted_val"="f\"oo"', 1),
|
||||
#('facts__facts__arr[]="foo"', 1),
|
||||
#('facts__facts__arr_nested[]__a[]="foo"', 1),
|
||||
'''
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
from awx.main.models import Job, JobEvent
|
||||
|
||||
from awx.main.utils.formatters import LogstashFormatter
|
||||
|
||||
|
||||
def test_log_from_job_event_object():
|
||||
job = Job(id=4)
|
||||
event = JobEvent(job_id=job.id)
|
||||
formatter = LogstashFormatter()
|
||||
|
||||
data_for_log = formatter.reformat_data_for_log(
|
||||
dict(python_objects=dict(job_event=event)), kind='job_events')
|
||||
|
||||
# Check entire body of data for any exceptions from getattr on event object
|
||||
for fd in data_for_log:
|
||||
if not isinstance(data_for_log[fd], str):
|
||||
continue
|
||||
assert 'Exception' not in data_for_log[fd], 'Exception delivered in data: {}'.format(data_for_log[fd])
|
||||
|
||||
# Verify existence of certain high-importance fields
|
||||
for fd in ['changed', 'uuid', 'start_line', 'end_line', 'id', 'counter', 'host_name', 'stdout']:
|
||||
assert fd in data_for_log
|
||||
|
||||
assert data_for_log['job'] == 4
|
||||
@@ -0,0 +1,27 @@
|
||||
# Copyright (c) 2017 Ansible Tower by Red Hat
|
||||
# All Rights Reserved.
|
||||
|
||||
|
||||
from awx.main.utils.insights import filter_insights_api_response
|
||||
from awx.main.tests.data.insights import TEST_INSIGHTS_HOSTS, TEST_INSIGHTS_PLANS, TEST_INSIGHTS_REMEDIATIONS
|
||||
|
||||
|
||||
def test_filter_insights_api_response():
|
||||
actual = filter_insights_api_response(
|
||||
TEST_INSIGHTS_HOSTS['results'][0], TEST_INSIGHTS_PLANS, TEST_INSIGHTS_REMEDIATIONS)
|
||||
|
||||
assert actual['last_check_in'] == '2019-03-19T21:59:09.213151-04:00'
|
||||
assert len(actual['reports']) == 5
|
||||
assert len(actual['reports'][0]['maintenance_actions']) == 1
|
||||
assert actual['reports'][0]['maintenance_actions'][0]['name'] == "Fix Critical CVEs"
|
||||
rule = actual['reports'][0]['rule']
|
||||
|
||||
assert rule['severity'] == 'WARN'
|
||||
assert rule['description'] == (
|
||||
"Kernel vulnerable to side-channel attacks in modern microprocessors (CVE-2017-5715/Spectre)")
|
||||
assert rule['category'] == 'Security'
|
||||
assert rule['summary'] == (
|
||||
"A vulnerability was discovered in modern microprocessors supported by the kernel,"
|
||||
" whereby an unprivileged attacker can use this flaw to bypass restrictions to gain read"
|
||||
" access to privileged memory.\nThe issue was reported as [CVE-2017-5715 / Spectre]"
|
||||
"(https://access.redhat.com/security/cve/CVE-2017-5715).\n")
|
||||
@@ -0,0 +1,128 @@
|
||||
# AWX utils
|
||||
from awx.main.utils.mem_inventory import (
|
||||
MemInventory,
|
||||
mem_data_to_dict, dict_to_mem_data
|
||||
)
|
||||
|
||||
import pytest
|
||||
import json
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def memory_inventory():
|
||||
inventory = MemInventory()
|
||||
h = inventory.get_host('my_host')
|
||||
h.variables = {'foo': 'bar'}
|
||||
g = inventory.get_group('my_group')
|
||||
g.variables = {'foobar': 'barfoo'}
|
||||
h2 = inventory.get_host('group_host')
|
||||
g.add_host(h2)
|
||||
return inventory
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def JSON_of_inv():
|
||||
# Implemented as fixture becuase it may be change inside of tests
|
||||
return {
|
||||
"_meta": {
|
||||
"hostvars": {
|
||||
"group_host": {},
|
||||
"my_host": {"foo": "bar"}
|
||||
}
|
||||
},
|
||||
"all": {"children": ["my_group", "ungrouped"]},
|
||||
"my_group": {
|
||||
"hosts": ["group_host"],
|
||||
"vars": {"foobar": "barfoo"}
|
||||
},
|
||||
"ungrouped": {"hosts": ["my_host"]}
|
||||
}
|
||||
|
||||
|
||||
# Structure mentioned in official docs
|
||||
# https://docs.ansible.com/ansible/dev_guide/developing_inventory.html
|
||||
@pytest.fixture
|
||||
def JSON_with_lists():
|
||||
docs_example = '''{
|
||||
"databases" : {
|
||||
"hosts" : [ "host1.example.com", "host2.example.com" ],
|
||||
"vars" : {
|
||||
"a" : true
|
||||
}
|
||||
},
|
||||
"webservers" : [ "host2.example.com", "host3.example.com" ],
|
||||
"atlanta" : {
|
||||
"hosts" : [ "host1.example.com", "host4.example.com", "host5.example.com" ],
|
||||
"vars" : {
|
||||
"b" : false
|
||||
},
|
||||
"children": [ "marietta", "5points" ]
|
||||
},
|
||||
"marietta" : [ "host6.example.com" ],
|
||||
"5points" : [ "host7.example.com" ]
|
||||
}'''
|
||||
return json.loads(docs_example)
|
||||
|
||||
|
||||
# MemObject basic operations tests
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_inventory_create_all_group():
|
||||
inventory = MemInventory()
|
||||
assert inventory.all_group.name == 'all'
|
||||
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_create_child_group():
|
||||
inventory = MemInventory()
|
||||
g1 = inventory.get_group('g1')
|
||||
# Create new group by name as child of g1
|
||||
g2 = inventory.get_group('g2', g1)
|
||||
# Check that child is in the children of the parent group
|
||||
assert g1.children == [g2]
|
||||
# Check that _only_ the parent group is listed as a root group
|
||||
assert inventory.all_group.children == [g1]
|
||||
# Check that _both_ are tracked by the global `all_groups` dict
|
||||
assert set(inventory.all_group.all_groups.values()) == set([g1, g2])
|
||||
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_ungrouped_mechanics():
|
||||
# ansible-inventory returns a group called `ungrouped`
|
||||
# we can safely treat this the same as the `all_group`
|
||||
inventory = MemInventory()
|
||||
ug = inventory.get_group('ungrouped')
|
||||
assert ug is inventory.all_group
|
||||
|
||||
|
||||
# MemObject --> JSON tests
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_convert_memory_to_JSON_with_vars(memory_inventory):
|
||||
data = mem_data_to_dict(memory_inventory)
|
||||
# Assertions about the variables on the objects
|
||||
assert data['_meta']['hostvars']['my_host'] == {'foo': 'bar'}
|
||||
assert data['my_group']['vars'] == {'foobar': 'barfoo'}
|
||||
# Orphan host should be found in ungrouped false group
|
||||
assert data['ungrouped']['hosts'] == ['my_host']
|
||||
|
||||
|
||||
# JSON --> MemObject tests
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_convert_JSON_to_memory_with_vars(JSON_of_inv):
|
||||
inventory = dict_to_mem_data(JSON_of_inv)
|
||||
# Assertions about the variables on the objects
|
||||
assert inventory.get_host('my_host').variables == {'foo': 'bar'}
|
||||
assert inventory.get_group('my_group').variables == {'foobar': 'barfoo'}
|
||||
# Host should be child of group
|
||||
assert inventory.get_host('group_host') in inventory.get_group('my_group').hosts
|
||||
|
||||
|
||||
@pytest.mark.inventory_import
|
||||
def test_host_lists_accepted(JSON_with_lists):
|
||||
inventory = dict_to_mem_data(JSON_with_lists)
|
||||
assert inventory.get_group('marietta').name == 'marietta'
|
||||
# Check that marietta's hosts was saved
|
||||
h = inventory.get_host('host6.example.com')
|
||||
assert h.name == 'host6.example.com'
|
||||
@@ -0,0 +1,15 @@
|
||||
# awx.main.utils.reload
|
||||
from awx.main.utils import reload
|
||||
|
||||
|
||||
def test_produce_supervisor_command(mocker):
|
||||
communicate_mock = mocker.MagicMock(return_value=('Everything is fine', ''))
|
||||
mock_process = mocker.MagicMock()
|
||||
mock_process.communicate = communicate_mock
|
||||
Popen_mock = mocker.MagicMock(return_value=mock_process)
|
||||
with mocker.patch.object(reload.subprocess, 'Popen', Popen_mock):
|
||||
reload.supervisor_service_command("restart")
|
||||
reload.subprocess.Popen.assert_called_once_with(
|
||||
['supervisorctl', 'restart', 'tower-processes:*',],
|
||||
stderr=-1, stdin=-1, stdout=-1)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from copy import deepcopy
|
||||
import pytest
|
||||
import yaml
|
||||
from awx.main.utils.safe_yaml import safe_dump
|
||||
|
||||
|
||||
@pytest.mark.parametrize('value', [None, 1, 1.5, []])
|
||||
def test_native_types(value):
|
||||
# Native non-string types should dump the same way that `yaml.safe_dump` does
|
||||
assert safe_dump(value) == yaml.safe_dump(value)
|
||||
|
||||
|
||||
def test_empty():
|
||||
assert safe_dump({}) == ''
|
||||
|
||||
|
||||
def test_raw_string():
|
||||
assert safe_dump('foo') == "!unsafe 'foo'\n"
|
||||
|
||||
|
||||
def test_kv_null():
|
||||
assert safe_dump({'a': None}) == "!unsafe 'a': null\n"
|
||||
|
||||
|
||||
def test_kv_null_safe():
|
||||
assert safe_dump({'a': None}, {'a': None}) == "a: null\n"
|
||||
|
||||
|
||||
def test_kv_null_unsafe():
|
||||
assert safe_dump({'a': ''}, {'a': None}) == "!unsafe 'a': !unsafe ''\n"
|
||||
|
||||
|
||||
def test_kv_int():
|
||||
assert safe_dump({'a': 1}) == "!unsafe 'a': 1\n"
|
||||
|
||||
|
||||
def test_kv_float():
|
||||
assert safe_dump({'a': 1.5}) == "!unsafe 'a': 1.5\n"
|
||||
|
||||
|
||||
def test_kv_unsafe():
|
||||
assert safe_dump({'a': 'b'}) == "!unsafe 'a': !unsafe 'b'\n"
|
||||
|
||||
|
||||
def test_kv_unsafe_unicode():
|
||||
assert safe_dump({'a': u'🐉'}) == '!unsafe \'a\': !unsafe "\\U0001F409"\n'
|
||||
|
||||
|
||||
def test_kv_unsafe_in_list():
|
||||
assert safe_dump({'a': ['b']}) == "!unsafe 'a':\n- !unsafe 'b'\n"
|
||||
|
||||
|
||||
def test_kv_unsafe_in_mixed_list():
|
||||
assert safe_dump({'a': [1, 'b']}) == "!unsafe 'a':\n- 1\n- !unsafe 'b'\n"
|
||||
|
||||
|
||||
def test_kv_unsafe_deep_nesting():
|
||||
yaml = safe_dump({'a': [1, [{'b': {'c': [{'d': 'e'}]}}]]})
|
||||
for x in ('a', 'b', 'c', 'd', 'e'):
|
||||
assert "!unsafe '{}'".format(x) in yaml
|
||||
|
||||
|
||||
def test_kv_unsafe_multiple():
|
||||
assert safe_dump({'a': 'b', 'c': 'd'}) == '\n'.join([
|
||||
"!unsafe 'a': !unsafe 'b'",
|
||||
"!unsafe 'c': !unsafe 'd'",
|
||||
""
|
||||
])
|
||||
|
||||
|
||||
def test_safe_marking():
|
||||
assert safe_dump({'a': 'b'}, safe_dict={'a': 'b'}) == "a: b\n"
|
||||
|
||||
|
||||
def test_safe_marking_mixed():
|
||||
assert safe_dump({'a': 'b', 'c': 'd'}, safe_dict={'a': 'b'}) == '\n'.join([
|
||||
"a: b",
|
||||
"!unsafe 'c': !unsafe 'd'",
|
||||
""
|
||||
])
|
||||
|
||||
|
||||
def test_safe_marking_deep_nesting():
|
||||
deep = {'a': [1, [{'b': {'c': [{'d': 'e'}]}}]]}
|
||||
yaml = safe_dump(deep, deepcopy(deep))
|
||||
for x in ('a', 'b', 'c', 'd', 'e'):
|
||||
assert "!unsafe '{}'".format(x) not in yaml
|
||||
|
||||
|
||||
def test_deep_diff_unsafe_marking():
|
||||
deep = {'a': [1, [{'b': {'c': [{'d': 'e'}]}}]]}
|
||||
jt_vars = deepcopy(deep)
|
||||
deep['a'][1][0]['b']['z'] = 'not safe'
|
||||
yaml = safe_dump(deep, jt_vars)
|
||||
assert "!unsafe 'z'" in yaml
|
||||
Reference in New Issue
Block a user