Move Grafana state tests to pytest

This commit is contained in:
krionbsd 2021-04-06 16:24:50 +02:00 committed by Megan Wilhite
parent 0faa40c29e
commit 4927ea0d82
4 changed files with 221 additions and 253 deletions

View file

@ -0,0 +1,129 @@
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import pytest
import salt.states.grafana as grafana
import salt.utils.json
from salt.exceptions import SaltInvocationError
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {grafana: {}}
def test_dashboard_present():
"""
Test to ensure the grafana dashboard exists and is managed.
"""
name = "myservice"
rows = ["systemhealth", "requests", "title"]
row = [{"panels": [{"id": "a"}], "title": "systemhealth"}]
ret = {"name": name, "result": None, "changes": {}, "comment": ""}
comt1 = (
"Dashboard myservice is set to be updated. The following rows "
"set to be updated: {}".format(["systemhealth"])
)
pytest.raises(SaltInvocationError, grafana.dashboard_present, name, profile=False)
pytest.raises(SaltInvocationError, grafana.dashboard_present, name, True, True)
mock = MagicMock(
side_effect=[
{"hosts": True, "index": False},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
]
)
mock_f = MagicMock(side_effect=[False, False, True, True, True, True])
mock_t = MagicMock(return_value="")
mock_i = MagicMock(return_value=False)
source = {"dashboard": '["rows", {"rows":["baz", null, 1.0, 2]}]'}
mock_dict = MagicMock(return_value={"_source": source})
with patch.dict(
grafana.__salt__,
{
"config.option": mock,
"elasticsearch.exists": mock_f,
"pillar.get": mock_t,
"elasticsearch.get": mock_dict,
"elasticsearch.index": mock_i,
},
):
pytest.raises(SaltInvocationError, grafana.dashboard_present, name)
with patch.dict(grafana.__opts__, {"test": True}):
pytest.raises(SaltInvocationError, grafana.dashboard_present, name)
comt = "Dashboard {} is set to be created.".format(name)
ret.update({"comment": comt})
assert grafana.dashboard_present(name, True) == ret
mock = MagicMock(
return_value={"rows": [{"panels": "b", "title": "systemhealth"}]}
)
with patch.object(salt.utils.json, "loads", mock):
ret.update({"comment": comt1, "result": None})
assert grafana.dashboard_present(name, True, rows=row) == ret
with patch.object(
salt.utils.json, "loads", MagicMock(return_value={"rows": {}})
):
pytest.raises(
SaltInvocationError,
grafana.dashboard_present,
name,
rows_from_pillar=rows,
)
comt = "Dashboard myservice is up to date"
ret.update({"comment": comt, "result": True})
assert grafana.dashboard_present(name, True) == ret
mock = MagicMock(
return_value={"rows": [{"panels": "b", "title": "systemhealth"}]}
)
with patch.dict(grafana.__opts__, {"test": False}):
with patch.object(salt.utils.json, "loads", mock):
comt = "Failed to update dashboard myservice."
ret.update({"comment": comt, "result": False})
assert grafana.dashboard_present(name, True, rows=row) == ret
def test_dashboard_absent():
"""
Test to ensure the named grafana dashboard is deleted.
"""
name = "myservice"
ret = {"name": name, "result": None, "changes": {}, "comment": ""}
mock = MagicMock(
side_effect=[
{"hosts": True, "index": False},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
]
)
mock_f = MagicMock(side_effect=[True, False])
with patch.dict(
grafana.__salt__, {"config.option": mock, "elasticsearch.exists": mock_f}
):
pytest.raises(SaltInvocationError, grafana.dashboard_absent, name)
with patch.dict(grafana.__opts__, {"test": True}):
comt = "Dashboard myservice is set to be removed."
ret.update({"comment": comt, "result": None})
assert grafana.dashboard_absent(name) == ret
comt = "Dashboard myservice does not exist."
ret.update({"comment": comt, "result": True})
assert grafana.dashboard_absent(name) == ret

View file

@ -0,0 +1,92 @@
import pytest
import salt.states.grafana_datasource as grafana_datasource
from tests.support.mock import MagicMock, Mock, patch
profile = {
"grafana_url": "http://grafana",
"grafana_token": "token",
}
def mock_json_response(data):
response = MagicMock()
response.json = MagicMock(return_value=data)
return Mock(return_value=response)
@pytest.fixture
def configure_loader_modules():
return {grafana_datasource: {}}
def test_present():
with patch("requests.get", mock_json_response([])):
with patch("requests.post") as rpost:
ret = grafana_datasource.present("test", "type", "url", profile=profile)
rpost.assert_called_once_with(
"http://grafana/api/datasources",
grafana_datasource._get_json_data("test", "type", "url"),
headers={
"Authorization": "Bearer token",
"Accept": "application/json",
},
timeout=3,
)
assert ret["result"]
assert ret["comment"] == "New data source test added"
data = grafana_datasource._get_json_data("test", "type", "url")
data.update({"id": 1, "orgId": 1})
with patch("requests.get", mock_json_response([data])):
with patch("requests.put") as rput:
ret = grafana_datasource.present("test", "type", "url", profile=profile)
rput.assert_called_once_with(
"http://grafana/api/datasources/1",
grafana_datasource._get_json_data("test", "type", "url"),
headers={
"Authorization": "Bearer token",
"Accept": "application/json",
},
timeout=3,
)
assert ret["result"]
assert ret["comment"] == "Data source test already up-to-date"
assert ret["changes"] == {}
with patch("requests.put") as rput:
ret = grafana_datasource.present("test", "type", "newurl", profile=profile)
rput.assert_called_once_with(
"http://grafana/api/datasources/1",
grafana_datasource._get_json_data("test", "type", "newurl"),
headers={
"Authorization": "Bearer token",
"Accept": "application/json",
},
timeout=3,
)
assert ret["result"]
assert ret["comment"] == "Data source test updated"
assert ret["changes"] == {"old": {"url": "url"}, "new": {"url": "newurl"}}
def test_absent():
with patch("requests.get", mock_json_response([])):
with patch("requests.delete") as rdelete:
ret = grafana_datasource.absent("test", profile=profile)
assert rdelete.call_count == 0
assert ret["result"]
assert ret["comment"] == "Data source test already absent"
with patch("requests.get", mock_json_response([{"name": "test", "id": 1}])):
with patch("requests.delete") as rdelete:
ret = grafana_datasource.absent("test", profile=profile)
rdelete.assert_called_once_with(
"http://grafana/api/datasources/1",
headers={
"Authorization": "Bearer token",
"Accept": "application/json",
},
timeout=3,
)
assert ret["result"]
assert ret["comment"] == "Data source test was deleted"

View file

@ -1,151 +0,0 @@
# -*- coding: utf-8 -*-
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import salt.states.grafana as grafana
# Import Salt Libs
import salt.utils.json
from salt.exceptions import SaltInvocationError
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class GrafanaTestCase(TestCase, LoaderModuleMockMixin):
"""
Test cases for salt.states.grafana
"""
def setup_loader_modules(self):
return {grafana: {}}
# 'dashboard_present' function tests: 1
def test_dashboard_present(self):
"""
Test to ensure the grafana dashboard exists and is managed.
"""
name = "myservice"
rows = ["systemhealth", "requests", "title"]
row = [{"panels": [{"id": "a"}], "title": "systemhealth"}]
ret = {"name": name, "result": None, "changes": {}, "comment": ""}
comt1 = (
"Dashboard myservice is set to be updated. The following rows "
"set to be updated: {0}".format(["systemhealth"])
)
self.assertRaises(
SaltInvocationError, grafana.dashboard_present, name, profile=False
)
self.assertRaises(
SaltInvocationError, grafana.dashboard_present, name, True, True
)
mock = MagicMock(
side_effect=[
{"hosts": True, "index": False},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
]
)
mock_f = MagicMock(side_effect=[False, False, True, True, True, True])
mock_t = MagicMock(return_value="")
mock_i = MagicMock(return_value=False)
source = {"dashboard": '["rows", {"rows":["baz", null, 1.0, 2]}]'}
mock_dict = MagicMock(return_value={"_source": source})
with patch.dict(
grafana.__salt__,
{
"config.option": mock,
"elasticsearch.exists": mock_f,
"pillar.get": mock_t,
"elasticsearch.get": mock_dict,
"elasticsearch.index": mock_i,
},
):
self.assertRaises(SaltInvocationError, grafana.dashboard_present, name)
with patch.dict(grafana.__opts__, {"test": True}):
self.assertRaises(SaltInvocationError, grafana.dashboard_present, name)
comt = "Dashboard {0} is set to be created.".format(name)
ret.update({"comment": comt})
self.assertDictEqual(grafana.dashboard_present(name, True), ret)
mock = MagicMock(
return_value={"rows": [{"panels": "b", "title": "systemhealth"}]}
)
with patch.object(salt.utils.json, "loads", mock):
ret.update({"comment": comt1, "result": None})
self.assertDictEqual(
grafana.dashboard_present(name, True, rows=row), ret
)
with patch.object(
salt.utils.json, "loads", MagicMock(return_value={"rows": {}})
):
self.assertRaises(
SaltInvocationError,
grafana.dashboard_present,
name,
rows_from_pillar=rows,
)
comt = "Dashboard myservice is up to date"
ret.update({"comment": comt, "result": True})
self.assertDictEqual(grafana.dashboard_present(name, True), ret)
mock = MagicMock(
return_value={"rows": [{"panels": "b", "title": "systemhealth"}]}
)
with patch.dict(grafana.__opts__, {"test": False}):
with patch.object(salt.utils.json, "loads", mock):
comt = "Failed to update dashboard myservice."
ret.update({"comment": comt, "result": False})
self.assertDictEqual(
grafana.dashboard_present(name, True, rows=row), ret
)
# 'dashboard_absent' function tests: 1
def test_dashboard_absent(self):
"""
Test to ensure the named grafana dashboard is deleted.
"""
name = "myservice"
ret = {"name": name, "result": None, "changes": {}, "comment": ""}
mock = MagicMock(
side_effect=[
{"hosts": True, "index": False},
{"hosts": True, "index": True},
{"hosts": True, "index": True},
]
)
mock_f = MagicMock(side_effect=[True, False])
with patch.dict(
grafana.__salt__, {"config.option": mock, "elasticsearch.exists": mock_f}
):
self.assertRaises(SaltInvocationError, grafana.dashboard_absent, name)
with patch.dict(grafana.__opts__, {"test": True}):
comt = "Dashboard myservice is set to be removed."
ret.update({"comment": comt, "result": None})
self.assertDictEqual(grafana.dashboard_absent(name), ret)
comt = "Dashboard myservice does not exist."
ret.update({"comment": comt, "result": True})
self.assertDictEqual(grafana.dashboard_absent(name), ret)

View file

@ -1,102 +0,0 @@
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Libs
import salt.states.grafana_datasource as grafana_datasource
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, Mock, patch
from tests.support.unit import TestCase
profile = {
"grafana_url": "http://grafana",
"grafana_token": "token",
}
def mock_json_response(data):
response = MagicMock()
response.json = MagicMock(return_value=data)
return Mock(return_value=response)
class GrafanaDatasourceTestCase(TestCase, LoaderModuleMockMixin):
def setup_loader_modules(self):
return {grafana_datasource: {}}
def test_present(self):
with patch("requests.get", mock_json_response([])):
with patch("requests.post") as rpost:
ret = grafana_datasource.present("test", "type", "url", profile=profile)
rpost.assert_called_once_with(
"http://grafana/api/datasources",
grafana_datasource._get_json_data("test", "type", "url"),
headers={
"Authorization": "Bearer token",
"Accept": "application/json",
},
timeout=3,
)
self.assertTrue(ret["result"])
self.assertEqual(ret["comment"], "New data source test added")
data = grafana_datasource._get_json_data("test", "type", "url")
data.update({"id": 1, "orgId": 1})
with patch("requests.get", mock_json_response([data])):
with patch("requests.put") as rput:
ret = grafana_datasource.present("test", "type", "url", profile=profile)
rput.assert_called_once_with(
"http://grafana/api/datasources/1",
grafana_datasource._get_json_data("test", "type", "url"),
headers={
"Authorization": "Bearer token",
"Accept": "application/json",
},
timeout=3,
)
self.assertTrue(ret["result"])
self.assertEqual(ret["comment"], "Data source test already up-to-date")
self.assertEqual(ret["changes"], {})
with patch("requests.put") as rput:
ret = grafana_datasource.present(
"test", "type", "newurl", profile=profile
)
rput.assert_called_once_with(
"http://grafana/api/datasources/1",
grafana_datasource._get_json_data("test", "type", "newurl"),
headers={
"Authorization": "Bearer token",
"Accept": "application/json",
},
timeout=3,
)
self.assertTrue(ret["result"])
self.assertEqual(ret["comment"], "Data source test updated")
self.assertEqual(
ret["changes"], {"old": {"url": "url"}, "new": {"url": "newurl"}}
)
def test_absent(self):
with patch("requests.get", mock_json_response([])):
with patch("requests.delete") as rdelete:
ret = grafana_datasource.absent("test", profile=profile)
self.assertTrue(rdelete.call_count == 0)
self.assertTrue(ret["result"])
self.assertEqual(ret["comment"], "Data source test already absent")
with patch("requests.get", mock_json_response([{"name": "test", "id": 1}])):
with patch("requests.delete") as rdelete:
ret = grafana_datasource.absent("test", profile=profile)
rdelete.assert_called_once_with(
"http://grafana/api/datasources/1",
headers={
"Authorization": "Bearer token",
"Accept": "application/json",
},
timeout=3,
)
self.assertTrue(ret["result"])
self.assertEqual(ret["comment"], "Data source test was deleted")