Initial commit
This commit is contained in:
@@ -0,0 +1,167 @@
|
||||
import pytest
|
||||
import tempfile
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import csv
|
||||
|
||||
from django.utils.timezone import now
|
||||
from datetime import timedelta
|
||||
from django.db.backends.sqlite3.base import SQLiteCursorWrapper
|
||||
|
||||
from awx.main.analytics import collectors
|
||||
|
||||
from awx.main.models import (
|
||||
ProjectUpdate,
|
||||
InventorySource,
|
||||
WorkflowJob,
|
||||
WorkflowJobNode,
|
||||
JobTemplate,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_copy_expert(request):
|
||||
# copy_expert is postgres-specific, and SQLite doesn't support it; mock its
|
||||
# behavior to test that it writes a file that contains stdout from events
|
||||
path = tempfile.mkdtemp(prefix="copied_tables")
|
||||
|
||||
def write_stdout(self, sql, fd):
|
||||
# Would be cool if we instead properly disected the SQL query and verified
|
||||
# it that way. But instead, we just take the naive approach here.
|
||||
sql = sql.strip()
|
||||
assert sql.startswith("COPY (")
|
||||
assert sql.endswith(") TO STDOUT WITH CSV HEADER")
|
||||
|
||||
sql = sql.replace("COPY (", "")
|
||||
sql = sql.replace(") TO STDOUT WITH CSV HEADER", "")
|
||||
# sqlite equivalent
|
||||
sql = sql.replace("ARRAY_AGG", "GROUP_CONCAT")
|
||||
# SQLite doesn't support isoformatted dates, because that would be useful
|
||||
sql = sql.replace("+00:00", "")
|
||||
i = re.compile(r'(?P<date>\d\d\d\d-\d\d-\d\d)T')
|
||||
sql = i.sub(r'\g<date> ', sql)
|
||||
|
||||
# Remove JSON style queries
|
||||
# TODO: could replace JSON style queries with sqlite kind of equivalents
|
||||
sql_new = []
|
||||
for line in sql.split("\n"):
|
||||
if line.find("main_jobevent.event_data::") == -1:
|
||||
sql_new.append(line)
|
||||
elif not line.endswith(","):
|
||||
sql_new[-1] = sql_new[-1].rstrip(",")
|
||||
sql = "\n".join(sql_new)
|
||||
|
||||
self.execute(sql)
|
||||
results = self.fetchall()
|
||||
headers = [i[0] for i in self.description]
|
||||
|
||||
csv_handle = csv.writer(
|
||||
fd,
|
||||
delimiter=",",
|
||||
quoting=csv.QUOTE_ALL,
|
||||
escapechar="\\",
|
||||
lineterminator="\n",
|
||||
)
|
||||
csv_handle.writerow(headers)
|
||||
csv_handle.writerows(results)
|
||||
|
||||
setattr(SQLiteCursorWrapper, "copy_expert", write_stdout)
|
||||
request.addfinalizer(lambda: shutil.rmtree(path))
|
||||
request.addfinalizer(lambda: delattr(SQLiteCursorWrapper, "copy_expert"))
|
||||
return path
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_copy_tables_unified_job_query(
|
||||
sqlite_copy_expert, project, inventory, job_template
|
||||
):
|
||||
"""
|
||||
Ensure that various unified job types are in the output of the query.
|
||||
"""
|
||||
|
||||
time_start = now() - timedelta(hours=9)
|
||||
inv_src = InventorySource.objects.create(
|
||||
name="inventory_update1", inventory=inventory, source="gce"
|
||||
)
|
||||
|
||||
project_update_name = ProjectUpdate.objects.create(
|
||||
project=project, name="project_update1"
|
||||
).name
|
||||
inventory_update_name = inv_src.create_unified_job().name
|
||||
job_name = job_template.create_unified_job().name
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
collectors.unified_jobs_table(time_start, tmpdir, until = now() + timedelta(seconds=1))
|
||||
with open(os.path.join(tmpdir, "unified_jobs_table.csv")) as f:
|
||||
lines = "".join([line for line in f])
|
||||
|
||||
assert project_update_name in lines
|
||||
assert inventory_update_name in lines
|
||||
assert job_name in lines
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def workflow_job(states=["new", "new", "new", "new", "new"]):
|
||||
"""
|
||||
Workflow topology:
|
||||
node[0]
|
||||
/\
|
||||
s/ \f
|
||||
/ \
|
||||
node[1,5] node[3]
|
||||
/ \
|
||||
s/ \f
|
||||
/ \
|
||||
node[2] node[4]
|
||||
"""
|
||||
wfj = WorkflowJob.objects.create()
|
||||
jt = JobTemplate.objects.create(name="test-jt")
|
||||
nodes = [
|
||||
WorkflowJobNode.objects.create(workflow_job=wfj, unified_job_template=jt)
|
||||
for i in range(0, 6)
|
||||
]
|
||||
for node, state in zip(nodes, states):
|
||||
if state:
|
||||
node.job = jt.create_job()
|
||||
node.job.status = state
|
||||
node.job.save()
|
||||
node.save()
|
||||
nodes[0].success_nodes.add(nodes[1])
|
||||
nodes[0].success_nodes.add(nodes[5])
|
||||
nodes[1].success_nodes.add(nodes[2])
|
||||
nodes[0].failure_nodes.add(nodes[3])
|
||||
nodes[3].failure_nodes.add(nodes[4])
|
||||
return wfj
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_copy_tables_workflow_job_node_query(sqlite_copy_expert, workflow_job):
|
||||
time_start = now() - timedelta(hours=9)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
collectors.workflow_job_node_table(time_start, tmpdir, until = now() + timedelta(seconds=1))
|
||||
with open(os.path.join(tmpdir, "workflow_job_node_table.csv")) as f:
|
||||
reader = csv.reader(f)
|
||||
# Pop the headers
|
||||
next(reader)
|
||||
lines = [line for line in reader]
|
||||
|
||||
ids = [int(line[0]) for line in lines]
|
||||
|
||||
assert ids == list(
|
||||
workflow_job.workflow_nodes.all().values_list("id", flat=True)
|
||||
)
|
||||
|
||||
for index, relationship in zip(
|
||||
[7, 8, 9], ["success_nodes", "failure_nodes", "always_nodes"]
|
||||
):
|
||||
for i, l in enumerate(lines):
|
||||
related_nodes = (
|
||||
[int(e) for e in l[index].split(",")] if l[index] else []
|
||||
)
|
||||
assert related_nodes == list(
|
||||
getattr(workflow_job.workflow_nodes.all()[i], relationship)
|
||||
.all()
|
||||
.values_list("id", flat=True)
|
||||
), f"(right side) workflow_nodes.all()[{i}].{relationship}.all()"
|
||||
@@ -0,0 +1,60 @@
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import tarfile
|
||||
from unittest import mock
|
||||
import pytest
|
||||
|
||||
from django.conf import settings
|
||||
from awx.main.analytics import gather, register
|
||||
|
||||
|
||||
@register('example', '1.0')
|
||||
def example(since, **kwargs):
|
||||
return {'awx': 123}
|
||||
|
||||
|
||||
@register('bad_json', '1.0')
|
||||
def bad_json(since, **kwargs):
|
||||
return set()
|
||||
|
||||
|
||||
@register('throws_error', '1.0')
|
||||
def throws_error(since, **kwargs):
|
||||
raise ValueError()
|
||||
|
||||
|
||||
def _valid_license():
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_valid_license():
|
||||
with mock.patch('awx.main.analytics.core._valid_license') as license:
|
||||
license.return_value = True
|
||||
yield license
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_gather(mock_valid_license):
|
||||
settings.INSIGHTS_TRACKING_STATE = True
|
||||
|
||||
tgzfiles = gather(module=importlib.import_module(__name__))
|
||||
files = {}
|
||||
with tarfile.open(tgzfiles[0], "r:gz") as archive:
|
||||
for member in archive.getmembers():
|
||||
files[member.name] = archive.extractfile(member)
|
||||
|
||||
# functions that returned valid JSON should show up
|
||||
assert './example.json' in files.keys()
|
||||
assert json.loads(files['./example.json'].read()) == {'awx': 123}
|
||||
|
||||
# functions that don't return serializable objects should not
|
||||
assert './bad_json.json' not in files.keys()
|
||||
assert './throws_error.json' not in files.keys()
|
||||
try:
|
||||
for tgz in tgzfiles:
|
||||
os.remove(tgz)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import pytest
|
||||
|
||||
from awx.main import models
|
||||
from awx.main.analytics import collectors
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_empty():
|
||||
assert collectors.counts(None) == {
|
||||
"active_user_sessions": 0,
|
||||
"active_anonymous_sessions": 0,
|
||||
"active_sessions": 0,
|
||||
"active_host_count": 0,
|
||||
"credential": 0,
|
||||
"custom_inventory_script": 0,
|
||||
"custom_virtualenvs": 0, # dev env ansible3
|
||||
"host": 0,
|
||||
"inventory": 0,
|
||||
"inventories": {"normal": 0, "smart": 0},
|
||||
"job_template": 0,
|
||||
"notification_template": 0,
|
||||
"organization": 0,
|
||||
"project": 0,
|
||||
"running_jobs": 0,
|
||||
"schedule": 0,
|
||||
"team": 0,
|
||||
"user": 0,
|
||||
"workflow_job_template": 0,
|
||||
"unified_job": 0,
|
||||
"pending_jobs": 0,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_database_counts(
|
||||
organization_factory, job_template_factory, workflow_job_template_factory
|
||||
):
|
||||
objs = organization_factory("org", superusers=["admin"])
|
||||
jt = job_template_factory(
|
||||
"test",
|
||||
organization=objs.organization,
|
||||
inventory="test_inv",
|
||||
project="test_project",
|
||||
credential="test_cred",
|
||||
)
|
||||
workflow_job_template_factory("test")
|
||||
models.Team(organization=objs.organization).save()
|
||||
models.Host(inventory=jt.inventory).save()
|
||||
models.Schedule(
|
||||
rrule="DTSTART;TZID=America/New_York:20300504T150000",
|
||||
unified_job_template=jt.job_template,
|
||||
).save()
|
||||
models.CustomInventoryScript(organization=objs.organization).save()
|
||||
|
||||
counts = collectors.counts(None)
|
||||
for key in (
|
||||
"organization",
|
||||
"team",
|
||||
"user",
|
||||
"inventory",
|
||||
"credential",
|
||||
"project",
|
||||
"job_template",
|
||||
"workflow_job_template",
|
||||
"host",
|
||||
"schedule",
|
||||
"custom_inventory_script",
|
||||
):
|
||||
assert counts[key] == 1
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_inventory_counts(organization_factory, inventory_factory):
|
||||
(inv1, inv2, inv3) = [inventory_factory(f"inv-{i}") for i in range(3)]
|
||||
|
||||
s1 = inv1.inventory_sources.create(name="src1", source="ec2")
|
||||
s2 = inv1.inventory_sources.create(name="src2", source="file")
|
||||
s3 = inv1.inventory_sources.create(name="src3", source="gce")
|
||||
|
||||
s1.hosts.create(name="host1", inventory=inv1)
|
||||
s1.hosts.create(name="host2", inventory=inv1)
|
||||
s1.hosts.create(name="host3", inventory=inv1)
|
||||
|
||||
s2.hosts.create(name="host4", inventory=inv1)
|
||||
s2.hosts.create(name="host5", inventory=inv1)
|
||||
|
||||
s3.hosts.create(name="host6", inventory=inv1)
|
||||
|
||||
s1 = inv2.inventory_sources.create(name="src1", source="ec2")
|
||||
|
||||
s1.hosts.create(name="host1", inventory=inv2)
|
||||
s1.hosts.create(name="host2", inventory=inv2)
|
||||
s1.hosts.create(name="host3", inventory=inv2)
|
||||
|
||||
inv_counts = collectors.inventory_counts(None)
|
||||
|
||||
assert {
|
||||
inv1.id: {
|
||||
"name": "inv-0",
|
||||
"kind": "",
|
||||
"hosts": 6,
|
||||
"sources": 3,
|
||||
"source_list": [
|
||||
{"name": "src1", "source": "ec2", "num_hosts": 3},
|
||||
{"name": "src2", "source": "file", "num_hosts": 2},
|
||||
{"name": "src3", "source": "gce", "num_hosts": 1},
|
||||
],
|
||||
},
|
||||
inv2.id: {
|
||||
"name": "inv-1",
|
||||
"kind": "",
|
||||
"hosts": 3,
|
||||
"sources": 1,
|
||||
"source_list": [{"name": "src1", "source": "ec2", "num_hosts": 3}],
|
||||
},
|
||||
inv3.id: {
|
||||
"name": "inv-2",
|
||||
"kind": "",
|
||||
"hosts": 0,
|
||||
"sources": 0,
|
||||
"source_list": [],
|
||||
},
|
||||
} == inv_counts
|
||||
@@ -0,0 +1,88 @@
|
||||
import pytest
|
||||
|
||||
from prometheus_client.parser import text_string_to_metric_families
|
||||
from awx.main import models
|
||||
from awx.main.analytics.metrics import metrics
|
||||
from awx.api.versioning import reverse
|
||||
from awx.main.models.rbac import Role
|
||||
|
||||
EXPECTED_VALUES = {
|
||||
'awx_system_info':1.0,
|
||||
'awx_organizations_total':1.0,
|
||||
'awx_users_total':1.0,
|
||||
'awx_teams_total':1.0,
|
||||
'awx_inventories_total':1.0,
|
||||
'awx_projects_total':1.0,
|
||||
'awx_job_templates_total':1.0,
|
||||
'awx_workflow_job_templates_total':1.0,
|
||||
'awx_hosts_total':1.0,
|
||||
'awx_hosts_total':1.0,
|
||||
'awx_schedules_total':1.0,
|
||||
'awx_inventory_scripts_total':1.0,
|
||||
'awx_sessions_total':0.0,
|
||||
'awx_sessions_total':0.0,
|
||||
'awx_sessions_total':0.0,
|
||||
'awx_custom_virtualenvs_total':0.0,
|
||||
'awx_running_jobs_total':0.0,
|
||||
'awx_instance_capacity':100.0,
|
||||
'awx_instance_consumed_capacity':0.0,
|
||||
'awx_instance_remaining_capacity':100.0,
|
||||
'awx_instance_cpu':0.0,
|
||||
'awx_instance_memory':0.0,
|
||||
'awx_instance_info':1.0,
|
||||
'awx_license_instance_total':0,
|
||||
'awx_license_instance_free':0,
|
||||
'awx_pending_jobs_total':0,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_metrics_counts(organization_factory, job_template_factory, workflow_job_template_factory):
|
||||
objs = organization_factory('org', superusers=['admin'])
|
||||
jt = job_template_factory(
|
||||
'test', organization=objs.organization,
|
||||
inventory='test_inv', project='test_project',
|
||||
credential='test_cred'
|
||||
)
|
||||
workflow_job_template_factory('test')
|
||||
models.Team(organization=objs.organization).save()
|
||||
models.Host(inventory=jt.inventory).save()
|
||||
models.Schedule(
|
||||
rrule='DTSTART;TZID=America/New_York:20300504T150000',
|
||||
unified_job_template=jt.job_template
|
||||
).save()
|
||||
models.CustomInventoryScript(organization=objs.organization).save()
|
||||
|
||||
output = metrics()
|
||||
gauges = text_string_to_metric_families(output.decode('UTF-8'))
|
||||
|
||||
for gauge in gauges:
|
||||
for sample in gauge.samples:
|
||||
# name, label, value, timestamp, exemplar
|
||||
name, _, value, _, _ = sample
|
||||
assert EXPECTED_VALUES[name] == value
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_metrics_permissions(get, admin, org_admin, alice, bob, organization):
|
||||
assert get(reverse('api:metrics_view'), user=admin).status_code == 200
|
||||
assert get(reverse('api:metrics_view'), user=org_admin).status_code == 403
|
||||
assert get(reverse('api:metrics_view'), user=alice).status_code == 403
|
||||
assert get(reverse('api:metrics_view'), user=bob).status_code == 403
|
||||
organization.auditor_role.members.add(bob)
|
||||
assert get(reverse('api:metrics_view'), user=bob).status_code == 403
|
||||
|
||||
Role.singleton('system_auditor').members.add(bob)
|
||||
bob.is_system_auditor = True
|
||||
assert get(reverse('api:metrics_view'), user=bob).status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_metrics_http_methods(get, post, patch, put, options, admin):
|
||||
assert get(reverse('api:metrics_view'), user=admin).status_code == 200
|
||||
assert put(reverse('api:metrics_view'), user=admin).status_code == 405
|
||||
assert patch(reverse('api:metrics_view'), user=admin).status_code == 405
|
||||
assert post(reverse('api:metrics_view'), user=admin).status_code == 405
|
||||
assert options(reverse('api:metrics_view'), user=admin).status_code == 200
|
||||
|
||||
|
||||
Reference in New Issue
Block a user