stats: add tests for CPUUsageMonitor, modify it a bit to facilitate testing
authorBrian Warner <warner@allmydata.com>
Wed, 30 Apr 2008 18:39:13 +0000 (11:39 -0700)
committerBrian Warner <warner@allmydata.com>
Wed, 30 Apr 2008 18:39:13 +0000 (11:39 -0700)
src/allmydata/stats.py
src/allmydata/test/test_stats.py [new file with mode: 0644]

index 562aff0553113dd0d2a489134b6e9fcdd342a05e..5a50b5716bd77f456c17c6c6d3d5f4fd3e33513c 100644 (file)
@@ -75,7 +75,8 @@ class LoadMonitor(service.MultiService):
 
 class CPUUsageMonitor(service.MultiService):
     implements(IStatsProducer)
-    MINUTES = 15
+    HISTORY_LENGTH = 15
+    POLL_INTERVAL = 60
 
     def __init__(self):
         service.MultiService.__init__(self)
@@ -88,7 +89,7 @@ class CPUUsageMonitor(service.MultiService):
         eventually(self._set_initial_cpu)
         self.samples = []
         # we provide 1min, 5min, and 15min moving averages
-        TimerService(60, self.check).setServiceParent(self)
+        TimerService(self.POLL_INTERVAL, self.check).setServiceParent(self)
 
     def _set_initial_cpu(self):
         self.initial_cpu = time.clock()
@@ -97,7 +98,7 @@ class CPUUsageMonitor(service.MultiService):
         now_wall = time.time()
         now_cpu = time.clock()
         self.samples.append( (now_wall, now_cpu) )
-        while len(self.samples) > self.MINUTES+1:
+        while len(self.samples) > self.HISTORY_LENGTH+1:
             self.samples.pop(0)
 
     def _average_N_minutes(self, size):
diff --git a/src/allmydata/test/test_stats.py b/src/allmydata/test/test_stats.py
new file mode 100644 (file)
index 0000000..6a4434b
--- /dev/null
@@ -0,0 +1,35 @@
+
+from twisted.trial import unittest
+from twisted.application import service
+from allmydata.stats import CPUUsageMonitor
+from allmydata.util import testutil
+
+class FasterMonitor(CPUUsageMonitor):
+    POLL_INTERVAL = 0.1
+
+
+class CPUUsage(unittest.TestCase, testutil.PollMixin):
+    def setUp(self):
+        self.s = service.MultiService()
+        self.s.startService()
+
+    def tearDown(self):
+        return self.s.stopService()
+
+    def test_monitor(self):
+        m = FasterMonitor()
+        s = m.get_stats() # before it has been started
+        self.failIf("cpu_monitor.1min_avg" in s)
+        m.setServiceParent(self.s)
+        def _poller():
+            return bool(len(m.samples) == m.HISTORY_LENGTH+1)
+        d = self.poll(_poller)
+        def _check(res):
+            s = m.get_stats()
+            self.failUnless("cpu_monitor.1min_avg" in s)
+            self.failUnless("cpu_monitor.5min_avg" in s)
+            self.failUnless("cpu_monitor.15min_avg" in s)
+            self.failUnless("cpu_monitor.total" in s)
+        d.addCallback(_check)
+        return d
+