|
| 1 | +from __future__ import absolute_import, unicode_literals |
| 2 | + |
| 3 | +from unittest import skipUnless |
| 4 | + |
| 5 | +from prometheus_client import Counter |
| 6 | +from prometheus_client import CollectorRegistry, generate_latest |
| 7 | + |
| 8 | +try: |
| 9 | + from prometheus_client.twisted import MetricsResource |
| 10 | + |
| 11 | + from twisted.trial.unittest import TestCase |
| 12 | + from twisted.web.server import Site |
| 13 | + from twisted.web.resource import Resource |
| 14 | + from twisted.internet import reactor |
| 15 | + from twisted.web.client import Agent |
| 16 | + from twisted.web.client import readBody |
| 17 | + HAVE_TWISTED = True |
| 18 | +except ImportError: |
| 19 | + from unittest import TestCase |
| 20 | + HAVE_TWISTED = False |
| 21 | + |
| 22 | + |
| 23 | +class MetricsResourceTest(TestCase): |
| 24 | + @skipUnless(HAVE_TWISTED, "Don't have twisted installed.") |
| 25 | + def setUp(self): |
| 26 | + self.registry = CollectorRegistry() |
| 27 | + |
| 28 | + def test_reports_metrics(self): |
| 29 | + """ |
| 30 | + ``MetricsResource`` serves the metrics from the provided registry. |
| 31 | + """ |
| 32 | + c = Counter('cc', 'A counter', registry=self.registry) |
| 33 | + c.inc() |
| 34 | + |
| 35 | + root = Resource() |
| 36 | + root.putChild(b'metrics', MetricsResource(registry=self.registry)) |
| 37 | + server = reactor.listenTCP(0, Site(root)) |
| 38 | + self.addCleanup(server.stopListening) |
| 39 | + |
| 40 | + agent = Agent(reactor) |
| 41 | + port = server.getHost().port |
| 42 | + url = u"http://localhost:{port}/metrics".format(port=port) |
| 43 | + d = agent.request(b"GET", url.encode("ascii")) |
| 44 | + |
| 45 | + d.addCallback(readBody) |
| 46 | + d.addCallback(self.assertEqual, generate_latest(self.registry)) |
| 47 | + |
| 48 | + return d |
0 commit comments