[svn] commit: r2864 - in /branches/trac191-rebased/src/bin/stats: Makefile.am b10-stats.8 b10-stats.xml stats.py.in stats_stub.py.in tests/b10-stats_stub_test.py tests/b10-stats_test.py tests/fake_time.py

BIND 10 source code commits bind10-changes at lists.isc.org
Wed Sep 8 13:56:42 UTC 2010


Author: naokikambe
Date: Wed Sep  8 13:56:42 2010
New Revision: 2864

Log:
- add two mock-up classes with packages (r2862)
  + .isc.cc.session
  + .isc.config.ccsession
- add a new mock-up class ''fake_time.py'' which is against the ''time'' class of python standard, which is returns fixed time value.
- aggregates the definitions of ''get_datetime()'' and ''get_timestamp()'' in ''stats.py.in''.
- replace the position of ''tearDown()'' in ''b10-stats_stub_test.py''
- correct some method names
- rewrite document of stats module
- change Makefile which remove unnecessary lines when installed
- add detailed comments
- some editorial changes
- remove unnecessary lines

(#191, [comment:ticket:191:11], [comment:ticket:191:12])

Added:
    branches/trac191-rebased/src/bin/stats/tests/fake_time.py
Modified:
    branches/trac191-rebased/src/bin/stats/Makefile.am
    branches/trac191-rebased/src/bin/stats/b10-stats.8
    branches/trac191-rebased/src/bin/stats/b10-stats.xml
    branches/trac191-rebased/src/bin/stats/stats.py.in
    branches/trac191-rebased/src/bin/stats/stats_stub.py.in
    branches/trac191-rebased/src/bin/stats/tests/b10-stats_stub_test.py
    branches/trac191-rebased/src/bin/stats/tests/b10-stats_test.py

Modified: branches/trac191-rebased/src/bin/stats/Makefile.am
==============================================================================
--- branches/trac191-rebased/src/bin/stats/Makefile.am (original)
+++ branches/trac191-rebased/src/bin/stats/Makefile.am Wed Sep  8 13:56:42 2010
@@ -27,10 +27,11 @@
 # this is done here since configure.ac AC_OUTPUT doesn't expand exec_prefix
 b10-stats: stats.py
 	$(SED) -e "s|@@PYTHONPATH@@|@pyexecdir@|" \
-	       -e "s|@@LOCALSTATEDIR@@|$(localstatedir)|" stats.py >$@
+	       -e "s|@@LOCALSTATEDIR@@|$(localstatedir)|" \
+	       -e "s|.*#@@REMOVED@@$$||"  stats.py >$@
 	chmod a+x $@
 
-b10-stats_stub: stats_stub.py
+b10-stats_stub: stats_stub.py stats.py
 	$(SED) -e "s|@@PYTHONPATH@@|@pyexecdir@|" \
 	       -e "s|@@LOCALSTATEDIR@@|$(localstatedir)|" stats_stub.py >$@
 	chmod a+x $@

Modified: branches/trac191-rebased/src/bin/stats/b10-stats.8
==============================================================================
--- branches/trac191-rebased/src/bin/stats/b10-stats.8 (original)
+++ branches/trac191-rebased/src/bin/stats/b10-stats.8 Wed Sep  8 13:56:42 2010
@@ -2,12 +2,12 @@
 .\"     Title: b10-stats
 .\"    Author: [FIXME: author] [see http://docbook.sf.net/el/author]
 .\" Generator: DocBook XSL Stylesheets v1.75.2 <http://docbook.sf.net/>
-.\"      Date: Jun 10, 2010
+.\"      Date: Sep 17, 2010
 .\"    Manual: BIND10
 .\"    Source: BIND10
 .\"  Language: English
 .\"
-.TH "B10\-STATS" "8" "Jun 10, 2010" "BIND10" "BIND10"
+.TH "B10\-STATS" "8" "Sep 17, 2010" "BIND10" "BIND10"
 .\" -----------------------------------------------------------------
 .\" * set default formatting
 .\" -----------------------------------------------------------------
@@ -19,61 +19,48 @@
 .\" * MAIN CONTENT STARTS HERE *
 .\" -----------------------------------------------------------------
 .SH "NAME"
-b10-stats \- Statistics Module
+b10-stats \- BIND 10 statistics module
 .SH "SYNOPSIS"
-.HP \w'\fBb10\-stats\fR\ 'u
-\fBb10\-stats\fR
+.HP \w'\fBb10\-cmdctl\fR\ 'u
+\fBb10\-cmdctl\fR [\fB\-v\fR] [\fB\-\-verbose\fR]
 .SH "DESCRIPTION"
 .PP
 The
 \fBb10\-stats\fR
-daemon is \&.\&.
-.SH "STATISTICS OF BIND 10"
-.PP
+is a daemon forked by
+\fBbind10\fR\&. Stats module collects stats data from each module and reports statistics information via
+\fBbindctl\fR\&. It communicates by using the Command Channel by
+\fBb10\-msgq\fR
+with other modules like
+\fBbind10\fR,
+\fBb10\-auth\fR
+and so on\&. It waits for coming data from other modules, then other modules send data to stats module periodically\&. Other modules send stats data to stats module independently from implementation of stats module, so the frequency of sending data may not be constant\&. Stats module collects data and aggregates it\&.
 .SH "OPTIONS"
 .PP
 The arguments are as follows:
 .PP
+\fB\-v\fR, \fB\-\-verbose\fR
 .RS 4
-.RE
-.SH "ARGUMENTS"
-.PP
-
-.sp
-.RS 4
-.ie n \{\
-\h'-04' 1.\h'+01'\c
-.\}
-.el \{\
-.sp -1
-.IP "  1." 4.2
-.\}
-.RE
-.sp
-.RS 4
-.ie n \{\
-\h'-04' 2.\h'+01'\c
-.\}
-.el \{\
-.sp -1
-.IP "  2." 4.2
-.\}
-.RE
-.sp
+This
+\fBb10\-stats\fR
+switches to verbose mode\&. It sends verbose messages to STDOUT\&.
 .RE
 .SH "FILES"
 .PP
-FILES are \&.\&.\&.
+/usr/local/share/bind10\-devel/stats\&.spec
+\(em This is a spec file for
+\fBb10\-stats\fR\&. It contains definitions of statistics items of BIND 10 and commands received vi bindctl\&.
 .SH "SEE ALSO"
 .PP
 
+BIND 10 Guide,
 \fBbind10\fR(8),
-BIND 10 Guide\&.
+\fBbindctl\fR(1)\&.
 .SH "HISTORY"
 .PP
 The
 \fBb10\-stats\fR
-daemon was implemented in specification were initially designed and implemented by JPRS\&. Its development began in Jun 2010\&.
+daemon was initially designed and implemented by Naoki Kambe of JPRS\&.
 .SH "COPYRIGHT"
 .br
 Copyright \(co 2010 Internet Systems Consortium, Inc. ("ISC")

Modified: branches/trac191-rebased/src/bin/stats/b10-stats.xml
==============================================================================
--- branches/trac191-rebased/src/bin/stats/b10-stats.xml (original)
+++ branches/trac191-rebased/src/bin/stats/b10-stats.xml Wed Sep  8 13:56:42 2010
@@ -21,7 +21,7 @@
 <refentry>
 
   <refentryinfo>
-    <date>Jun 10, 2010</date>
+    <date>Sep 17, 2010</date>
   </refentryinfo>
 
   <refmeta>
@@ -32,7 +32,7 @@
 
   <refnamediv>
     <refname>b10-stats</refname>
-    <refpurpose>Statistics Module</refpurpose>
+    <refpurpose>BIND 10 statistics module</refpurpose>
   </refnamediv>
 
   <docinfo>
@@ -44,18 +44,29 @@
 
   <refsynopsisdiv>
     <cmdsynopsis>
-      <command>b10-stats</command>
+      <command>b10-cmdctl</command>
+      <arg><option>-v</option></arg>
+      <arg><option>--verbose</option></arg>
     </cmdsynopsis>
   </refsynopsisdiv>
 
   <refsect1>
     <title>DESCRIPTION</title>
-    <para>The <command>b10-stats</command> daemon is ..</para>
-  </refsect1>
-
-  <refsect1>
-    <title>STATISTICS OF BIND 10</title>
-    <para></para>
+    <para>
+      The <command>b10-stats</command> is a daemon forked by
+      <command>bind10</command>. Stats module collects stats data from
+      each module and reports statistics information
+      via <command>bindctl</command>.  It communicates by using the
+      Command Channel by <command>b10-msgq</command> with other
+      modules
+      like <command>bind10</command>, <command>b10-auth</command> and
+      so on. It waits for coming data from other modules, then other
+      modules send data to stats module periodically. Other modules
+      send stats data to stats module independently from
+      implementation of stats module, so the frequency of sending data
+      may not be constant. Stats module collects data and aggregates
+      it.
+    </para>
   </refsect1>
 
   <refsect1>
@@ -63,50 +74,44 @@
     <para>The arguments are as follows:</para>
     <variablelist>
       <varlistentry>
-        <term><option></option></term>
-        <listitem><para></para></listitem>
+        <term><option>-v</option>, <option>--verbose</option></term>
+        <listitem>
+	  <para>
+          This <command>b10-stats</command> switches to verbose
+          mode. It sends verbose messages to STDOUT.
+	  </para>
+        </listitem>
       </varlistentry>
     </variablelist>
   </refsect1>
 
   <refsect1>
-    <title>ARGUMENTS</title>
-    <para>
-      <orderedlist numeration="loweralpha">
-        <listitem>
-          <para>
-          </para>
-        </listitem>
-        <listitem>
-          <para>
-          </para>
-        </listitem>
-      </orderedlist>
+    <title>FILES</title>
+    <para><filename>/usr/local/share/bind10-devel/stats.spec</filename>
+      — This is a spec file for <command>b10-stats</command>. It
+      contains definitions of statistics items of BIND 10 and commands
+      received vi bindctl.
     </para>
-
-  </refsect1>
-
-  <refsect1>
-    <title>FILES</title>
-    <para>FILES are ... </para>
   </refsect1>
 
   <refsect1>
     <title>SEE ALSO</title>
     <para>
+      <citetitle>BIND 10 Guide</citetitle>,
       <citerefentry>
         <refentrytitle>bind10</refentrytitle><manvolnum>8</manvolnum>
       </citerefentry>,
-      <citetitle>BIND 10 Guide</citetitle>.
+      <citerefentry>
+        <refentrytitle>bindctl</refentrytitle><manvolnum>1</manvolnum>
+      </citerefentry>.
     </para>
   </refsect1>
 
   <refsect1>
     <title>HISTORY</title>
     <para>
-      The <command>b10-stats</command> daemon was implemented in 
-      specification were initially designed and implemented by JPRS.
-      Its development began in Jun 2010.
+      The <command>b10-stats</command> daemon was initially designed
+      and implemented by Naoki Kambe of JPRS.
     </para>
   </refsect1>
 </refentry><!--

Modified: branches/trac191-rebased/src/bin/stats/stats.py.in
==============================================================================
--- branches/trac191-rebased/src/bin/stats/stats.py.in (original)
+++ branches/trac191-rebased/src/bin/stats/stats.py.in Wed Sep  8 13:56:42 2010
@@ -22,11 +22,17 @@
 import os
 import signal
 import select
-import time
+from time import time, strftime, gmtime
 from optparse import OptionParser, OptionValueError
 from collections import defaultdict
 from isc.config.ccsession import ModuleCCSession, create_answer
 from isc.cc import Session, SessionError
+# Note: Following lines are removed in b10-stats	#@@REMOVED@@
+if __name__ == 'stats':					#@@REMOVED@@
+    try:						#@@REMOVED@@
+        from fake_time import time, strftime, gmtime	#@@REMOVED@@
+    except ImportError:					#@@REMOVED@@
+        pass						#@@REMOVED@@
 
 # If B10_FROM_SOURCE is set in the environment, we use data files
 # from a directory relative to that, otherwise we use the ones
@@ -42,14 +48,26 @@
     """
     A abstract class of singleton pattern
     """
-    def __init__(self, *args):
-        type.__init__(self, *args)
+    # Because of singleton pattern: 
+    #   At the beginning of coding, one UNIX domain socket is needed
+    #  for config manager, another socket is needed for stats module,
+    #  then stats module might need two sockets. So I adopted the
+    #  singleton pattern because I avoid creating multiple sockets in
+    #  one stats module. But in the initial version stats module
+    #  reports only via bindctl, so just one socket is needed. To use
+    #  the singleton pattern is not important now. :(
+
+    def __init__(self, *args, **kwargs):
+        type.__init__(self, *args, **kwargs)
         self._instances = {}
 
-    def __call__(self, *args):
-        if not args in self._instances:
-            self._instances[args] = type.__call__(self, *args)
-        return self._instances[args]
+    def __call__(self, *args, **kwargs):
+        if args not in self._instances:
+            self._instances[args]={}
+        kw = tuple(kwargs.items())
+        if  kw not in self._instances[args]:
+            self._instances[args][kw] = type.__call__(self, *args, **kwargs)
+        return self._instances[args][kw]
 
 class Callback():
     """
@@ -73,6 +91,20 @@
     """
     A abstract subject class of observer pattern
     """
+    # Because of observer pattern:
+    #   In the initial release, I'm also sure that observer pattern
+    #  isn't definitely needed because the interface between gathering
+    #  and reporting statistics data is single.  However in the future
+    #  release, the interfaces may be multiple, that is, multiple
+    #  listeners may be needed. For example, one interface, which
+    #  stats module has, is for between ''config manager'' and stats
+    #  module, another interface is for between ''HTTP server'' and
+    #  stats module, and one more interface is for between ''SNMP
+    #  server'' and stats module. So by considering that stats module
+    #  needs multiple interfaces in the future release, I adopted the
+    #  observer pattern in stats module. But I don't have concrete
+    #  ideas in case of multiple listener currently.
+
     def __init__(self):
         self._listeners = []
 
@@ -108,18 +140,14 @@
     def add_event(self, event):
         self.events[event.name]=event
 
-class SessionSubject(Subject):
+class SessionSubject(Subject, metaclass=Singleton):
     """
     A concrete subject class which creates CC session object
     """
-    __metaclass__ = Singleton
     def __init__(self, session=None, verbose=False):
         Subject.__init__(self)
         self.verbose = verbose
-        if session is None:
-            self.session = Session()
-        else:
-            self.session = session
+        self.session=session
         self.running = False
 
     def start(self):
@@ -150,6 +178,8 @@
                                           self.config_handler,
                                           self.command_handler,
                                           self.session)
+
+        self.session = self.subject.session = self.cc_session._session
 
         # initialize internal data
         self.config_spec = self.cc_session.get_module_spec().get_config_spec()
@@ -271,7 +301,7 @@
                         data.extend(args[i:])
                         break
             elif type(data) == dict:
-                for k in args.keys():
+                for k in list(args.keys()):
                     if k in data:
                         data[k] = __increase_data(data[k], args[k])
                     else:
@@ -389,21 +419,21 @@
     """
     get current timestamp
     """
-    return time.time()
+    return time()
 
 def get_datetime():
     """
     get current datetime
     """
-    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
-
-def main():
+    return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
+
+def main(session=None):
     try:
         parser = OptionParser()
         parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                       help="display more about what is going on")
         (options, args) = parser.parse_args()
-        subject = SessionSubject(verbose=options.verbose)
+        subject = SessionSubject(session=session, verbose=options.verbose)
         listener = CCSessionListener(subject, verbose=options.verbose)
         subject.start()
         while subject.running:

Modified: branches/trac191-rebased/src/bin/stats/stats_stub.py.in
==============================================================================
--- branches/trac191-rebased/src/bin/stats/stats_stub.py.in (original)
+++ branches/trac191-rebased/src/bin/stats/stats_stub.py.in Wed Sep  8 13:56:42 2010
@@ -24,6 +24,7 @@
 from optparse import OptionParser, OptionValueError
 from isc.config.ccsession import ModuleCCSession, create_command, parse_answer, parse_command, create_answer
 from isc.cc import Session, SessionError
+from stats import get_datetime
 
 # If B10_FROM_SOURCE is set in the environment, we use data files
 # from a directory relative to that, otherwise we use the ones
@@ -79,7 +80,7 @@
     def __init__(self, session=None, verbose=False):
         self.stub = CCSessionStub(session=session, verbose=verbose)
     
-    def send_command(self):
+    def send_boottime(self):
         return self.stub.send_command("set", {"stats_data": {"bind10.boot_time": get_datetime()}})
 
 class AuthModuleStub:
@@ -91,7 +92,7 @@
         self.stub = CCSessionStub(session=session, verbose=verbose)
         self.count = { "udp": 0, "tcp": 0 }
     
-    def send_command_udp(self, cmd="increase", cnt=0):
+    def send_udp_query_count(self, cmd="increase", cnt=0):
         """
         count up udp query count
         """
@@ -104,7 +105,7 @@
                                            {"auth.queries."+prt: self.count[prt]}
                                        })
 
-    def send_command_tcp(self, cmd="set", cnt=0):
+    def send_tcp_query_count(self, cmd="set", cnt=0):
         """
         set udp query count
         """
@@ -117,27 +118,21 @@
                                            {"auth.queries."+prt: self.count[prt]}
                                        })
 
-def get_datetime():
-    """
-    get current datetime
-    """
-    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
-
-def main():
+def main(session=None):
     try:
         parser=OptionParser()
         parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                       help="display more about what is going on")
         (options, args) = parser.parse_args()
-        stub = CCSessionStub(verbose=options.verbose)
+        stub = CCSessionStub(session=session, verbose=options.verbose)
         boss = BossModuleStub(session=stub.session, verbose=options.verbose)
         auth = AuthModuleStub(session=stub.session, verbose=options.verbose)
         stub.send_command("status", None)
-        boss.send_command()
-        auth.send_command_udp(cmd="set", cnt=81120) # This is an example.
+        boss.send_boottime()
+        auth.send_udp_query_count(cmd="set", cnt=81120) # This is an example.
         while True:
-            auth.send_command_udp()
-            auth.send_command_tcp()
+            auth.send_udp_query_count()
+            auth.send_tcp_query_count()
             time.sleep(1)
 
     except OptionValueError:

Modified: branches/trac191-rebased/src/bin/stats/tests/b10-stats_stub_test.py
==============================================================================
--- branches/trac191-rebased/src/bin/stats/tests/b10-stats_stub_test.py (original)
+++ branches/trac191-rebased/src/bin/stats/tests/b10-stats_stub_test.py Wed Sep  8 13:56:42 2010
@@ -23,19 +23,25 @@
 import time
 import os
 import imp
-from unittest_fakesession import FakeModuleCCSession
 import stats_stub
+from isc.cc.session import Session
 from stats_stub import CCSessionStub, BossModuleStub, AuthModuleStub
+from stats import get_datetime
 
 class TestStats(unittest.TestCase):
 
     def setUp(self):
-        self.session = FakeModuleCCSession()
-        self.stub = CCSessionStub(self.session, verbose=True)
-        self.boss = BossModuleStub(self.session, verbose=True)
-        self.auth = AuthModuleStub(self.session, verbose=True)
-        self.env = {'from': None, 'group': 'Stats'}
+        self.session = Session()
+        self.stub = CCSessionStub(session=self.session, verbose=True)
+        self.boss = BossModuleStub(session=self.session, verbose=True)
+        self.auth = AuthModuleStub(session=self.session, verbose=True)
+        self.env = {'from': self.session.lname, 'group': 'Stats',
+                    'instance': '*', 'to':'*',
+                    'type':'send','seq':0}
         self.result_ok = {'result': [0]}
+
+    def tearDown(self):
+        self.session.close()
 
     def test_stub(self):
         """
@@ -56,9 +62,6 @@
                          self.stub.send_command('set', {'atest': 100.0}))
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
 
-    def tearDown(self):
-        self.session.close()
-
     def test_boss_stub(self):
         """
         Test for send_command of BossModuleStub object
@@ -67,7 +70,7 @@
         result_ok = self.result_ok
         self.assertEqual(('set', {"stats_data":
                                       {"bind10.boot_time": get_datetime()}
-                                  }, env), self.boss.send_command())
+                                  }, env), self.boss.send_boottime())
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
 
     def test_auth_stub(self):
@@ -78,23 +81,25 @@
         result_ok = self.result_ok
         self.assertEqual(
             ('increase', {"stats_data": {"auth.queries.udp": 1}}, env),
-            self.auth.send_command_udp())
+            self.auth.send_udp_query_count())
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
         self.assertEqual(
             ('set', {"stats_data": {"auth.queries.tcp": 1}}, env),
-            self.auth.send_command_tcp())
+            self.auth.send_tcp_query_count())
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
         self.assertEqual(
             ('set', {"stats_data": {"auth.queries.udp": 100}}, env),
-            self.auth.send_command_udp(cmd='set', cnt=100))
+            self.auth.send_udp_query_count(cmd='set', cnt=100))
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
         self.assertEqual(
             ('increase', {"stats_data": {"auth.queries.tcp": 99}}, env),
-            self.auth.send_command_tcp(cmd='increase', cnt=99))
+            self.auth.send_tcp_query_count(cmd='increase', cnt=99))
         self.assertEqual(result_ok, self.session.get_message("Stats", None))
 
     def test_func_main(self):
-        stats_stub.main()
+        # explicitly make failed
+        self.session.close()
+        stats_stub.main(session=self.session)
 
     def test_osenv(self):
         """
@@ -107,11 +112,5 @@
             os.environ["B10_FROM_SOURCE"] = path
             imp.reload(stats_stub)
 
-def get_datetime():
-    """
-    get current datetime
-    """
-    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
-
 if __name__ == "__main__":
     unittest.main()

Modified: branches/trac191-rebased/src/bin/stats/tests/b10-stats_test.py
==============================================================================
--- branches/trac191-rebased/src/bin/stats/tests/b10-stats_test.py (original)
+++ branches/trac191-rebased/src/bin/stats/tests/b10-stats_test.py Wed Sep  8 13:56:42 2010
@@ -24,11 +24,11 @@
 import time
 import unittest
 import imp
-from isc.cc.session import SessionError
-from isc.config.ccsession import ModuleCCSessionError
-from unittest_fakesession import FakeModuleCCSession
+from isc.cc.session import Session, SessionError
+from isc.config.ccsession import ModuleCCSession, ModuleCCSessionError
 import stats
-from stats import SessionSubject, CCSessionListener
+from stats import SessionSubject, CCSessionListener, get_timestamp, get_datetime
+from fake_time import _TEST_TIME_SECS, _TEST_TIME_STRF
 
 # setting Constant
 if sys.path[0] == '':
@@ -39,14 +39,15 @@
 class TestStats(unittest.TestCase):
 
     def setUp(self):
-        self.session = FakeModuleCCSession()
+        self.session = Session()
         self.subject = SessionSubject(session=self.session, verbose=True)
         self.listener = CCSessionListener(self.subject, verbose=True)
         self.stats_spec = self.listener.cc_session.get_module_spec().get_config_spec()
+        self.module_name = self.listener.cc_session.get_module_spec().get_module_name()
         self.stats_data = {
                 'report_time' : get_datetime(),
                 'bind10.boot_time' : "1970-01-01T00:00:00Z",
-                'stats.timestamp' : float(int(get_timestamp())),
+                'stats.timestamp' : get_timestamp(),
                 'stats.lname' : self.session.lname,
                 'auth.queries.tcp': 0,
                 'auth.queries.udp': 0,
@@ -54,15 +55,19 @@
                 "stats.start_time": get_datetime(),
                 "stats.last_update_time": get_datetime()
                 }
-
-        try:
-            self.subject.start()
-        except ModuleCCSessionError:
-            pass
-        for i in (0, 1):
-            self.session.get_message("ConfigManager", None)
+        # check starting
+        self.assertFalse(self.subject.running)
+        self.subject.start()
+        self.assertTrue(self.subject.running)
+        self.assertEqual(len(self.session.message_queue), 0)
+        self.assertEqual(self.module_name, 'Stats')
 
     def tearDown(self):
+        # check closing
+        self.subject.stop()
+        self.assertFalse(self.subject.running)
+        self.subject.detach(self.listener)
+        self.listener.stop()
         self.session.close()
 
     def test_local_func(self):
@@ -80,59 +85,10 @@
         self.assertNotEqual(result_ok(), {'RESULT': [0]})
 
         # test for get_timestamp
-        self.assertEqual(type(get_timestamp()), float)
-        self.assertTrue(abs(get_timestamp() - time.time()) < 1.0)
+        self.assertEqual(get_timestamp(), _TEST_TIME_SECS)
 
         # test for get_datetime
-        self.assertNotEqual(type(get_timestamp()), str)
-        self.assertEqual(get_datetime(), time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
-
-    def test_start(self):
-        """
-        Test for start stats module
-        
-        """
-        session = FakeModuleCCSession()
-        subject = SessionSubject(session=session, verbose=False)
-        listener = CCSessionListener(subject, verbose=False)
-
-        self.assertEqual(len(subject.session.message_queue), 0)
-        self.assertFalse(subject.running)
-        self.assertRaises(ModuleCCSessionError, subject.start)
-        self.assertTrue(subject.running)
-        self.assertEqual(len(session.message_queue), 2)
-        self.assertEqual({"command": ["module_spec", listener.cc_session.specification._module_spec]},
-                         session.get_message("ConfigManager", None))
-        self.assertEqual({"command": ["get_config", {"module_name": "Stats"}]},
-                         session.get_message("ConfigManager", None))
-        self.assertEqual(len(session.message_queue), 0)
-        session.group_sendmsg(result_ok(), "Stats")
-        session.group_sendmsg(result_ok(1, "just an error"), "Stats")
-        self.assertEqual(len(session.message_queue), 2)
-        self.assertTrue(subject.running)
-        subject.start()
-        self.assertTrue(subject.running)
-        self.assertEqual(len(session.message_queue), 2)
-        self.assertEqual({"command": ["module_spec", listener.cc_session.specification._module_spec]},
-                         session.get_message("ConfigManager", None))
-        self.assertEqual({"command": ["get_config", {"module_name": "Stats"}]},
-                         session.get_message("ConfigManager", None))
-        self.assertEqual(len(session.message_queue), 0)
-        subject.check()
-        self.assertTrue(subject.running)
-        subject.detach(listener) # detatch test
-
-    def test_stop(self):
-        """
-        Test for stop stats module
-        
-        """
-        self.assertEqual(len(self.session.message_queue), 0)
-        self.assertTrue(self.subject.running)
-        self.subject.stop()
-        self.assertFalse(self.subject.running)
-        self.assertRaises(SessionError, self.subject.check)
-        self.assertRaises(SessionError, self.subject.start)
+        self.assertEqual(get_datetime(), _TEST_TIME_STRF)
 
     def test_show_command(self):
         """
@@ -145,7 +101,6 @@
         self.subject.check()
         result_data = self.session.get_message("Stats", None)
         # ignore under 0.9 seconds
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
         self.assertEqual(result_ok(0, self.stats_data), result_data)
         self.assertEqual(len(self.session.message_queue), 0)
 
@@ -164,7 +119,6 @@
         self.subject.check()
         result_data = self.session.get_message("Stats", None)
         # ignore under 0.9 seconds
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
         self.assertEqual(result_ok(0, self.stats_data), result_data)
         self.assertEqual(len(self.session.message_queue), 0)
 
@@ -191,11 +145,6 @@
         self.assertEqual(len(self.session.message_queue), 1)
         self.subject.check()
         result_data = self.session.get_message("Stats", None)
-        # ignore under 0.9 seconds
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
-        self.stats_data['report_time'] = get_datetime()
-        self.stats_data['stats.last_update_time'] = get_datetime()
-        self.stats_data['stats.timestamp'] = float(int(get_timestamp()))
         self.assertEqual(result_ok(0, self.stats_data), result_data)
         self.assertEqual(len(self.session.message_queue), 0)
 
@@ -214,11 +163,6 @@
         self.assertEqual(len(self.session.message_queue), 1)
         self.subject.check()
         result_data = self.session.get_message("Stats", None)
-        # ignore under 0.9 seconds
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
-        self.stats_data['report_time'] = get_datetime()
-        self.stats_data['stats.last_update_time'] = get_datetime()
-        self.stats_data['stats.timestamp'] = float(int(get_timestamp()))
         self.assertEqual(result_ok(0, self.stats_data), result_data)
         self.assertEqual(len(self.session.message_queue), 0)
 
@@ -243,10 +187,6 @@
         self.assertEqual(len(self.session.message_queue), 1)
         self.subject.check()
         result_data = self.session.get_message("Stats", None)
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
-        self.stats_data['report_time'] = get_datetime()
-        self.stats_data['stats.last_update_time'] = get_datetime()
-        self.stats_data['stats.timestamp'] = float(int(get_timestamp()))
         self.assertEqual(result_ok(0, self.stats_data), result_data)
         self.assertEqual(len(self.session.message_queue), 0)
 
@@ -274,8 +214,6 @@
         self.subject.check()
         result_data = self.session.get_message("Stats", None)
         self.assertFalse('bind10.boot_time' in result_data['result'][1])
-        # ignore under 0.9 seconds
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
         self.assertEqual(result_ok(0, self.stats_data), result_data)
         self.assertEqual(len(self.session.message_queue), 0)
 
@@ -296,8 +234,6 @@
         self.assertEqual(len(self.session.message_queue), 1)
         self.subject.check()
         result_data = self.session.get_message("Stats", None)
-        # ignore under 0.9 seconds
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
         self.assertEqual(result_ok(0, self.stats_data), result_data)
         self.assertEqual(len(self.session.message_queue), 0)
 
@@ -361,11 +297,8 @@
 
         # check its value
         self.session.group_sendmsg({ "command": [
-                                      "show", {
-                        	        'stats_item_name': 'bind10.boot_time'
-				      }
-                                     ]
-                                   }, "Stats")
+                                      "show", { 'stats_item_name': 'bind10.boot_time' }
+                                     ] }, "Stats")
         self.assertEqual(len(self.session.message_queue), 1)
         self.subject.check()
         result_data = self.session.get_message("Stats", None)
@@ -379,14 +312,11 @@
         self.stats_data['auth.queries.udp'] = 98765
         self.assertEqual(self.stats_data['auth.queries.udp'], 98765)
         self.session.group_sendmsg({ "command": [
-                                      "set", {
-                                          'stats_data': {
+                                      "set", { 'stats_data': {
                                             'auth.queries.udp':
                                               self.stats_data['auth.queries.udp']
-                                            }
-                                        } 
-                                     ]
-                                   }, "Stats")
+                                            } } 
+                                     ] }, "Stats")
         self.assertEqual(len(self.session.message_queue), 1)
         self.subject.check()
         self.assertEqual(result_ok(),
@@ -518,11 +448,6 @@
         self.assertEqual(len(self.session.message_queue), 1)
         self.subject.check()
         result_data = self.session.get_message("Stats", None)
-        # ignore under 0.9 seconds
-        result_data['result'][1]['stats.timestamp'] = float(int(result_data['result'][1]['stats.timestamp']))
-        self.stats_data['report_time'] = get_datetime()
-        self.stats_data['stats.last_update_time'] = get_datetime()
-        self.stats_data['stats.timestamp'] = float(int(get_timestamp()))
         self.assertEqual(result_ok(0, self.stats_data), result_data)
         self.assertEqual(len(self.session.message_queue), 0)
 
@@ -568,11 +493,8 @@
 
         # check its value
         self.session.group_sendmsg({ "command": [
-                                      "show", {
-                        	        'stats_item_name': 'listtype'
-				      }
-                                     ]
-                                   }, "Stats")
+                                      "show", { 'stats_item_name': 'listtype' }
+                                     ] }, "Stats")
         self.assertEqual(len(self.session.message_queue), 1)
         self.subject.check()
         result_data = self.session.get_message("Stats", None)
@@ -644,12 +566,23 @@
 class TestStats2(unittest.TestCase):
 
     def setUp(self):
-        self.session = FakeModuleCCSession()
+        self.session = Session(verbose=True)
         self.subject = SessionSubject(session=self.session, verbose=True)
         self.listener = CCSessionListener(self.subject, verbose=True)
+        self.module_name = self.listener.cc_session.get_module_spec().get_module_name()
+        # check starting
+        self.assertFalse(self.subject.running)
+        self.subject.start()
+        self.assertTrue(self.subject.running)
+        self.assertEqual(len(self.session.message_queue), 0)
+        self.assertEqual(self.module_name, 'Stats')
 
     def tearDown(self):
-        self.session.close()
+        # check closing
+        self.subject.stop()
+        self.assertFalse(self.subject.running)
+        self.subject.detach(self.listener)
+        self.listener.stop()
 
     def test_specfile(self):
         """
@@ -663,8 +596,8 @@
         # change path of SPECFILE_LOCATION
         stats.SPECFILE_LOCATION = TEST_SPECFILE_LOCATION
         self.assertEqual(stats.SPECFILE_LOCATION, TEST_SPECFILE_LOCATION)
-        self.session = FakeModuleCCSession()
         self.subject = stats.SessionSubject(session=self.session, verbose=True)
+        self.session = self.subject.session
         self.listener = stats.CCSessionListener(self.subject, verbose=True)
 
         self.assertEqual(self.listener.stats_spec, [])
@@ -746,7 +679,9 @@
         self.assertEqual(self.listener.initialize_data(stats_spec), stats_data)
 
     def test_func_main(self):
-        stats.main()
+        # explicitly make failed
+        self.session.close()
+        stats.main(session=self.session)
 
     def test_osenv(self):
         """
@@ -765,17 +700,5 @@
     else:
         return { 'result': [ 0 ] }
 
-def get_timestamp():
-    """
-    get current timestamp
-    """
-    return time.time()
-
-def get_datetime():
-    """
-    get current datetime
-    """
-    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
-
 if __name__ == "__main__":
     unittest.main()




More information about the bind10-changes mailing list