Skip to content

Commit

Permalink
#8: Covered influxdb-query with tests
Browse files Browse the repository at this point in the history
  • Loading branch information
blackandred committed Nov 17, 2020
1 parent 1301b21 commit 1ee824c
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 9 deletions.
10 changes: 4 additions & 6 deletions infracheck/checks/influxdb-query
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Queries an InfluxDB database and compares results.
Parameters:

- host
- port
- port (default: 8086)
- user
- password
- database
Expand Down Expand Up @@ -45,12 +45,10 @@ class InfluxDBQueryCheck(object):

def main(self, query: str, expected: str) -> Tuple[bool, str]:
results = self.client.query(query)
mapped = itertools.chain(list(map(lambda result: result['values'], results['series'])))
encoded = json.dumps(list(results))

encoded = json.dumps(mapped)

if encoded != expected:
return False, "Expected '{expectation}', got '{actual}'".format(expectation=expected, actual=encoded)
if expected not in encoded:
return False, "Expected '{actual}' to contain '{expectation}'".format(expectation=expected, actual=encoded)

return True, "Query results are matching"

Expand Down
60 changes: 60 additions & 0 deletions tests/functional_test_influxdb_query_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import os
import inspect
import unittest
import influxdb
from tests.utils.influxdb_test import InfluxDBContainerRequirement, USER, PASSWORD, DB


# import a script with "-" in filename
path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + '/../'
with open(path + '/infracheck/checks/influxdb-query', 'r') as script:
exec(script.read())


class InfluxDBQueryCheckTest(InfluxDBContainerRequirement, unittest.TestCase):
def test_finds_occurrence_in_json_results(self):
client = influxdb.InfluxDBClient(host='localhost', port=8086)
client.switch_database(DB)
client.switch_user(USER, PASSWORD)

for i in range(1, 5):
client.write_points([
{
"measurement": "cpu_load_short",
"tags": {
"host": "server01",
"region": "us-west"
},
"time": "2009-11-10T23:00:{}Z".format(i * 10),
"fields": {
"value": 0.64 + (i * 10)
}
}
])

check = InfluxDBQueryCheck(
host='localhost', port=8086,
user=USER, password=PASSWORD,
database=DB
)

result, message = check.main('select value from cpu_load_short;', '"value": 10.64')

self.assertEqual('Query results are matching', message)
self.assertTrue(result)

def test_will_not_find_occurrence(self):
client = influxdb.InfluxDBClient(host='localhost', port=8086)
client.switch_database(DB)
client.switch_user(USER, PASSWORD)

check = InfluxDBQueryCheck(
host='localhost', port=8086,
user=USER, password=PASSWORD,
database=DB
)

result, message = check.main('select value from this_metrics_does_not_exist;', '"value": 10.64')

self.assertEqual('Expected \'[]\' to contain \'"value": 10.64\'', message)
self.assertFalse(result)
21 changes: 18 additions & 3 deletions tests/utils/base_docker_container_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@

import docker
import docker.errors
import time
from abc import abstractmethod


Expand All @@ -23,7 +24,7 @@ def tearDownClass(cls) -> None:
@classmethod
def _remove_container(cls):
try:
container = cls.docker_client.containers.get('ssh')
container = cls.docker_client.containers.get(cls._get_container_name())

try:
container.kill()
Expand All @@ -35,9 +36,23 @@ def _remove_container(cls):
except docker.errors.NotFound:
pass

@staticmethod
@classmethod
def _wait_for_log_message(cls, message: str, timeout: int = 60):
container = cls.docker_client.containers.get(cls._get_container_name())

for sec in range(0, timeout):
logs = container.logs().decode('utf-8')

if message in logs:
return True

time.sleep(1)

raise Exception('Message "{message}" not found in container logs'.format(message=message))

@classmethod
@abstractmethod
def _wait_for_container_to_be_ready():
def _wait_for_container_to_be_ready(cls):
pass

@staticmethod
Expand Down
35 changes: 35 additions & 0 deletions tests/utils/influxdb_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

import time
from .base_docker_container_test import BaseDockerContainerRequirement

DB = 'test'
USER = 'infracheck'
PASSWORD = 'solidarity_forever'


class InfluxDBContainerRequirement(BaseDockerContainerRequirement):
@staticmethod
def _get_environment() -> dict:
return {
'INFLUXDB_DB': DB,
'INFLUXDB_ADMIN_USER': USER,
'INFLUXDB_ADMIN_PASSWORD': PASSWORD
}

@classmethod
def _wait_for_container_to_be_ready(cls):
time.sleep(1)
cls._wait_for_log_message('Listening on HTTP')
time.sleep(1)

@staticmethod
def _get_container_name() -> str:
return 'influxdb'

@staticmethod
def _get_ports() -> dict:
return {'8086/tcp': '8086'}

@staticmethod
def _get_image_name() -> str:
return 'influxdb:1.8-alpine'

0 comments on commit 1ee824c

Please sign in to comment.