Debian Codegraph @

tests/test_twisted.py

raw symbols SCIP
1 from unittest import skipUnless
2
3 from prometheus_client import CollectorRegistry, Counter, generate_latest
4
5 try:
6 from warnings import filterwarnings
7
8 from twisted.internet import reactor
9 from twisted.trial.unittest import TestCase
10 from twisted.web.client import Agent, readBody
11 from twisted.web.resource import Resource
12 from twisted.web.server import Site
13
14 from prometheus_client.twisted import MetricsResource
15
16 HAVE_TWISTED = True
17 except ImportError:
18 from unittest import TestCase
19
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 = f"http://localhost:{port}/metrics"
43 d = agent.request(b"GET", url.encode("ascii"))
44
45 # Ignore expected DeprecationWarning.
46 filterwarnings("ignore", category=DeprecationWarning, message="Using readBody "
47 "with a transport that does not have an abortConnection method")
48
49 d.addCallback(readBody)
50 d.addCallback(self.assertEqual, generate_latest(self.registry))
51
52 return d