diff --git a/src/charm.py b/src/charm.py index d8b17d0..3d12932 100755 --- a/src/charm.py +++ b/src/charm.py @@ -6,12 +6,12 @@ import logging import secrets import yaml +from charms.prometheus_k8s.v0.prometheus_scrape import MetricsEndpointProvider from ops.charm import CharmBase from ops.framework import StoredState from ops.charm import RelationJoinedEvent, RelationDepartedEvent from ops.main import main from ops.model import ActiveStatus, BlockedStatus, Relation -from charms.prometheus_k8s.v0.prometheus_scrape import MetricsEndpointProvider logger = logging.getLogger(__name__) diff --git a/tests/test_charm.py b/tests/test_charm.py index a854b5c..3301ab1 100644 --- a/tests/test_charm.py +++ b/tests/test_charm.py @@ -3,13 +3,13 @@ import os import unittest -from unittest.mock import mock_open, patch - from charm import JujuControllerCharm from ops.testing import Harness +from unittest.mock import mock_open, patch agent_conf = ''' apiport: 17070 +cacert: fake ''' @@ -51,12 +51,25 @@ def test_website_relation_joined(self, open, ingress_address): self.assertEqual(data["private-address"], "192.168.1.17") self.assertEqual(data["port"], '17070') - def test_metrics_endpoint_relation_created(self): + @patch("builtins.open", new_callable=mock_open, read_data=agent_conf) + def test_metrics_endpoint_relation_created(self, open): harness = Harness(JujuControllerCharm) self.addCleanup(harness.cleanup) harness.begin() - # harness.add_relation('metrics-endpoint', 'prometheus-k8s') + mock_opener = mockOpener(self) + harness.charm.control_socket.opener = mock_opener + + mock_opener.expect( + url='http://localhost/metrics-users', + method='POST', + # TODO: test body + response=mockResponse( + headers=mockHeaders(content_type='application/json'), + body='{"message":"created user \\"juju-metrics-r0\\""}' + ) + ) + harness.add_relation('metrics-endpoint', 'prometheus-k8s') # def test_metrics_endpoint_relation_broken(self): @@ -69,3 +82,41 @@ def __init__(self, address): class mockNetwork: def __init__(self, address): self.ingress_address = address + + +class mockOpener: + def __init__(self, test_case): + self.test = test_case + + def expect(self, url, method, response): + self.url = url + self.method = method + + self.response = response + + def open(self, request, timeout): + self.test.assertEqual(request.full_url, self.url) + self.test.assertEqual(request.method, self.method) + + return self.response + + +class mockResponse(): + def __init__(self, headers, body): + self.headers = headers + self.body = body + + def read(self): + return self.body + + +class mockHeaders(): + def __init__(self, content_type, params=None): + self.content_type = content_type + self.params = params + + def get_content_type(self): + return self.content_type + + def get_params(self): + return self.params