File: test_twisted.py

package info (click to toggle)
python-prometheus-client 0.0.18-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 296 kB
  • sloc: python: 2,565; makefile: 6
file content (53 lines) | stat: -rw-r--r-- 1,604 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from __future__ import absolute_import, unicode_literals

import sys

if sys.version_info < (2, 7):
    from unittest2 import skipUnless
else:
    from unittest import skipUnless

from prometheus_client import Counter
from prometheus_client import CollectorRegistry, generate_latest

try:
    from prometheus_client.twisted import MetricsResource

    from twisted.trial.unittest import TestCase
    from twisted.web.server import Site
    from twisted.web.resource import Resource
    from twisted.internet import reactor
    from twisted.web.client import Agent
    from twisted.web.client import readBody
    HAVE_TWISTED = True
except ImportError:
    from unittest import TestCase
    HAVE_TWISTED = False


class MetricsResourceTest(TestCase):
    @skipUnless(HAVE_TWISTED, "Don't have twisted installed.")
    def setUp(self):
        self.registry = CollectorRegistry()

    def test_reports_metrics(self):
        """
        ``MetricsResource`` serves the metrics from the provided registry.
        """
        c = Counter('cc', 'A counter', registry=self.registry)
        c.inc()

        root = Resource()
        root.putChild(b'metrics', MetricsResource(registry=self.registry))
        server = reactor.listenTCP(0, Site(root))
        self.addCleanup(server.stopListening)

        agent = Agent(reactor)
        port = server.getHost().port
        url = "http://localhost:{port}/metrics".format(port=port)
        d = agent.request(b"GET", url.encode("ascii"))

        d.addCallback(readBody)
        d.addCallback(self.assertEqual, generate_latest(self.registry))

        return d