def __call__(self, *args, **kwargs): """Invoke the test. The test is "kicked-off" by calling this. Any arguments are passed to the test implementation (`execute` method). """ self._report.add_heading(self.test_name, 2) if args or kwargs: self._report.add_message("TESTARGUMENTS", ReprArgs(args, kwargs), 2) self.starttime = timelib.now() # saved starttime in case initializer # needs to create the log file. rv = None # in case of exception rv = self._initialize(rv) if rv is not None: # an exception happened return rv # test elapsed time does not include initializer time. teststarttime = timelib.now() # run the execute() method and check for exceptions. try: rv = self.execute(*args, **kwargs) except KeyboardInterrupt: if self._debug: ex, val, tb = sys.exc_info() debugger.post_mortem(tb, ex, val) rv = self.Incomplete("%s: aborted by user." % self.test_name) self._finalize(rv) raise except TestFailError, errval: rv = self.Failed("Caught Fail exception: %s" % (errval, ))
def RunModule(self, mod): """Run a test module. Prepares the configuration with module configuration, sends report messages appropriate for modules, and reports pass or fail. Arguments: mod: A module object with a run() function that takes a configuration object as it's single parameter. Returns: The return value of the module's Run() function, or FAILED if the module raised an exception. """ cf = self.config # merge any test-module specific config files. The config file name is # the same as the module name, with ".conf" appended. Located in the # same directory as the module itself. testconf = os.path.join(os.path.dirname(mod.__file__), "%s.conf" % (mod.__name__.split(".")[-1], )) cf.mergefile(testconf) cf.evalupdate(cf.options_override) # make the module look like a test. mod.test_name = mod.__name__ try: ID = mod.__version__[1:-1] except AttributeError: # should be there, but don't worry if its not. ID = "undefined" cf.report.add_message("MODULEVERSION", ID) cf.report.add_message("MODULESTARTTIME", timelib.now()) try: rv = self.RunObject(mod) except KeyboardInterrupt: cf.report.add_message("MODULEENDTIME", timelib.now()) cf.report.incomplete("Module aborted by user.") raise except: ex, val, tb = sys.exc_info() if cf.flags.DEBUG: debugger.post_mortem(tb, ex, val) rv = constants.FAILED cf.report.add_message("MODULEENDTIME", timelib.now()) cf.report.failed("Module exception: %s (%s)" % (ex, val)) else: cf.report.add_message("MODULEENDTIME", timelib.now()) if rv is None: # If module run() function returns None we take that to mean that # it runs a TestSuite itself. Report nothing. pass # But if the module returns something else we take that to mean that # it is reporting some true/false value to report as pass/fail. elif rv: return cf.report.passed("Return evaluates True.") else: return cf.report.failed("Return evaluates False.") return rv
def time(self, argv): """time <command> [<args>...] Display the time, in ms, a command takes to run. Result also stored in LASTTIME environment variable. """ argv.pop(0) argv = self._expand_aliases(argv) meth = getattr(self, argv[0]) start = timelib.now() rv = meth(argv) end = timelib.now() elapsed = (end - start) * 1000.0 self._environ["LASTTIME"] = elapsed self._ui.printf("%%G%.3f ms%%N" % (elapsed, )) return rv
def time(self, argv): """time <command> [<args>...] Display the time, in ms, a command takes to run. Result also stored in LASTTIME environment variable. """ argv.pop(0) argv = self._expand_aliases(argv) meth = getattr(self, argv[0]) start = timelib.now() rv = meth(argv) end = timelib.now() elapsed = (end-start)*1000.0 self._environ["LASTTIME"] = elapsed self._ui.printf("%%G%.3f ms%%N" % (elapsed,)) return rv
def run_module(self, mod): """Run a test module. Prepares the configuration with module configuration, sends report messages appropriate for modules, and reports pass or fail. Arguments: mod: A module object with a run() function that takes a configuration object as it's single parameter. Returns: The return value of the module's Run() function, or FAILED if the module raised an exception. """ cf = self.config # make the module look like a test. mod.test_name = mod.__name__ ID = get_module_version(mod) cf.report.add_message("MODULEVERSION", ID) cf.report.add_message("USECASESTARTTIME", timelib.now()) try: rv = self.run_object(mod) except KeyboardInterrupt: cf.report.add_message("MODULEENDTIME", timelib.now()) cf.report.incomplete("Module aborted by user.") raise except: ex, val, tb = sys.exc_info() if cf.flags.DEBUG: from pycopia import debugger debugger.post_mortem(tb, ex, val) rv = constants.FAILED cf.report.add_message("MODULEENDTIME", timelib.now()) cf.report.failed("Module exception: %s (%s)" % (ex, val)) else: cf.report.add_message("MODULEENDTIME", timelib.now()) if rv is None: # If module run() function returns None we take that to mean that # it runs a TestSuite itself. Report PASSED value. return 1 elif type(rv) is core.TestResult: return bool(rv) # If the module returns something else we take that to mean that # it is reporting some true/false value to report as pass/fail. elif rv: return cf.report.passed("Return evaluates True.") else: return cf.report.failed("Return evaluates False.")
def run(self, meth, args=(), kwargs={}, argiterator=None): res = FunctionTimerResult(_form_name(meth, args, kwargs)) if argiterator: iterator = itertools.cycle(argiterator) else: iterator = itertools.repeat(args) start = now() for i in xrange(self._iter): args = iterator.next() rv = meth(*args, **kwargs) end = now() res.runtime = ((end - start)/self._iter) - self._overhead res.overhead = self._overhead res.returnvalue = rv return res
def run(self, meth, args=(), kwargs={}, argiterator=None): res = FunctionTimerResult(_form_name(meth, args, kwargs)) if argiterator: iterator = itertools.cycle(argiterator) else: iterator = itertools.repeat(args) start = now() for i in xrange(self._iter): args = iterator.next() rv = meth(*args, **kwargs) end = now() res.runtime = ((end - start) / self._iter) - self._overhead res.overhead = self._overhead res.returnvalue = rv return res
def Execute(self): self.Info("Starting.") cf = self.config env = cf.environment fo = self.GetFile("voltage_batt_lcd", "dat") self.Info("Data file path: %r" % (fo.name, )) fo.write("# Time\tVoltage (V)\tMeasured (V)\tLevel\tLCD Brightness\n") try: for v in aid.frange(4.19, 2.79, -0.01): env.DUT.BackKey() t = timelib.now() batt = env.DUT.GetBatteryInfo() led = env.DUT.GetLEDInfo() self.Info( "Set voltage: %s, level: %s, measured: %s V, LCD: %s" % (v, batt.capacity, batt.voltage, led.lcd_brightness)) fo.write( "%s\t%s\t%s\t%s\t%s\n" % (t, v, batt.voltage, batt.capacity, led.lcd_brightness)) env.powersupply.SetVoltage(v) self.Sleep(10) except adb.AdbError: self.Info("Device powered off.") fo.close() return self.Passed("Done.")
def test_timelib(self): mt = timelib.localtime_mutable() print(mt) mt.add_seconds(3600) print(mt) print(timelib.strftime("%Y-%m-%d", timelib.weekof(timelib.time()))) t = timelib.now() for d in range(1, 60): week = timelib.weekof(t+(d*60*60*24)) print(timelib.MutableTime(week)) print("Local time:") print(timelib.localtimestamp()) p = timespec.TimespecParser() for spec, secs in [ ("0s", 0.0), ("3m", 180.0), ("3.0m", 180.0), ("3minute+2secs", 182.0), ("2h 3minute+2.2secs", 7382.2), ("-3m", -180.0), ("-3.0m", -180.0), ("1h3m", 3780.0), ("1h-3m", 3420.0), ("1d 3m", 86580.0)]: p.parse(spec) self.assert_(p.seconds == secs) self.assertRaises(ValueError, p.parse, "12m -m")
def finalize(self): """Perform any finalization needed by the test runner. Sends runner end messages to report. Finalizes report. """ cf = self.config rpt = cf.report rpt.add_message("RUNNERENDTIME", timelib.now(), 0) rpt.finalize() # force close of report and logfile between objects. these are # `property` objects and deleting them makes them close and clears the # cache. del rpt del cf.report del cf.logfile del cf.UI del cf.environment if cf.has_key("resultsdir"): for fname in cf.reportfilenames: if not fname.startswith("<"): # a real file, not builtin stdio if os.path.isfile(fname): shutil.move(fname, cf.resultsdir) for suffix in ("", ".1", ".2", ".3", ".4", ".5"): # log may have rotated fname = cf.logfilename + suffix if os.path.isfile(fname): if os.path.getsize(fname) > 0: shutil.move(fname, cf.resultsdir) else: os.unlink(fname) # If resultsdir ends up empty, remove it. if not os.listdir(cf.resultsdir): # TODO, stat this instead os.rmdir(cf.resultsdir)
def Finalize(self): """Perform any finalization needed by the test runner. Sends runner end messages to report. Finalizes report. """ cf = self.config rpt = cf.report rpt.add_message("RUNNERENDTIME", timelib.now(), 0) rpt.finalize() # force close of report and logfile between objects. these are # `property` objects and deleting them makes them close and clears the # cache. del rpt del cf.report del cf.logfile del cf.UI if cf.has_key("resultsdir"): for fname in cf.reportfilenames: if not fname.startswith("<"): # a real file, not builtin stdio if os.path.isfile(fname): shutil.move(fname, cf.resultsdir) for suffix in ("", ".1", ".2", ".3", ".4", ".5"): # log may have rotated fname = cf.logfilename + suffix if os.path.isfile(fname) and os.path.getsize(fname) > 0: shutil.move(fname, cf.resultsdir) # If resultsdir ends up empty, remove it. if not os.listdir(cf.resultsdir): # TODO(dart), stat this instead os.rmdir(cf.resultsdir)
def test_timelib(self): mt = timelib.localtime_mutable() print mt mt.add_seconds(3600) print mt print timelib.strftime("%Y-%m-%d", timelib.weekof(timelib.time())) t = timelib.now() for d in range(1, 60): week = timelib.weekof(t+(d*60*60*24)) print timelib.MutableTime(week) print "Local time:" print timelib.localtimestamp() p = timelib.TimespecParser() for spec, secs in [ ("0s", 0.0), ("3m", 180.0), ("3.0m", 180.0), ("3minute+2secs", 182.0), ("2h 3minute+2.2secs", 7382.2), ("-3m", -180.0), ("-3.0m", -180.0), ("1h3m", 3780.0), ("1h-3m", 3420.0), ("1d 3m", 86580.0)]: p.parse(spec) self.assert_(p.seconds == secs) self.assertRaises(ValueError, p.parse, "12m -m")
def run_module(self, mod): """run_module(module) Runs the module. The parameter should be a module object, but if it is a string then a module object with that name will be imported. """ cf = self._config if type(mod) is str: mod = self.get_module(mod) if not mod: raise ValueError, "Unable to locate test module" try: cf.module_ID = mod._ID except AttributeError: cf.module_ID = "<unknown>" cf.reportbasename = mod.__name__.replace(".", "_") cf.logbasename = "%s.log" % (cf.reportbasename,) # merge any test-module specific config files. testconf = os.path.join(os.path.dirname(mod.__file__) , "%s.conf" % (mod.__name__.split(".")[-1],)) cf.mergefile(testconf) # resultsdir is where you would place any resulting data files. starttime = timelib.now() cf.resultsdir = os.path.join( os.path.expandvars(cf.get("resultsdirbase", "/var/tmp")), "%s-%s" % (cf.reportbasename, timelib.strftime("%Y%m%d%H%M", timelib.localtime(starttime))) ) # make results dir, don't worry if it already exists try: os.mkdir(cf.resultsdir) except OSError, errno: if errno[0] == EEXIST: pass else: raise
def formatdate(timeval=None): if timeval is None: timeval = timelib.now() timeval = timelib.gmtime(timeval) return "%s, %02d %s %04d %02d:%02d:%02d GMT" % ( ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][timeval[6]], timeval[2], ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][timeval[1]-1], timeval[0], timeval[3], timeval[4], timeval[5])
def __call__(self): last_timestamp = timelib.now() data = sock.recv(20) try: while data: timestamp, evtype, evcode, evvalue = _ConvertEvent(data) if handler(timestamp - last_timestamp, evtype, evcode, evvalue) is None: last_timestamp = timestamp data = sock.recv(20) finally: sock.close()
def read_handler(self): count, irq = self.read() if irq & rtc.RTC_PF: while count > 0: # in case we missed an interrupt self._ticks += 1 for rate in self._rates.copy(): if self._ticks % rate == 0: for callback, oneshot in self._sets[rate]: self._lastvalue = callback(timelib.now(), self._lastvalue) if oneshot: self.DeleteJob((callback, rate, oneshot)) count -= 1
def __call__(self, *args, **kwargs): """Invoke the test suite. This is the primary way to invoke a suite of tests. call the instance. Any supplied parameters are passed onto the suite's initialize() method. The method name is consistent with other methods of a similiar nature on other objects (e.g. app.run()). """ self.starttime = timelib.now() try: self._initialize(*args, **kwargs) except TestSuiteAbort: self._finalize() rv = constants.INCOMPLETE else: self._runTests() rv = self._finalize() endtime = timelib.now() self.report.add_message("STARTTIME", self.starttime, 1) self.report.add_message("ENDTIME", endtime, 1) return rv
def run_class(self, cls): """Run a container class inside a module. The class is run as if it were a module, using the classes containing module. The class is just a container, and the run method should be a static method or class method. Arguments: class with run method: A class object with a run() method that takes a configuration object as it's single parameter. Returns: The return value of the class's run() method, or FAILED if the module raised an exception. """ rpt = self.config.report cls.test_name = ".".join([cls.__module__, cls.__name__]) ID = get_module_version(sys.modules[cls.__module__]) rpt.add_message("MODULEVERSION", ID) rpt.add_message("USECASESTARTTIME", timelib.now()) try: rv = self.run_object(cls) except KeyboardInterrupt: rpt.add_message("MODULEENDTIME", timelib.now()) rpt.incomplete("Module aborted by user.") raise except: ex, val, tb = sys.exc_info() if self.config.flags.DEBUG: from pycopia import debugger debugger.post_mortem(tb, ex, val) rpt.add_message("MODULEENDTIME", timelib.now()) rpt.incomplete("Test container exception: %s (%s)" % (ex, val)) return constants.INCOMPLETE else: rpt.add_message("MODULEENDTIME", timelib.now()) return rv
def send(self, smtp, mail_options=None, rcpt_options=None): """send off this message using the supplied SMTP sender object.""" mopts = mail_options or [] rcptopts = rcpt_options or [] if not self.mail_from or not self.rcpt_to: raise RuntimeError, "AutoMessage: cannot send. no From or recipients." if self.has_key("Bcc"): del self["Bcc"] now = timelib.now() self["Date"] = formatdate(now) self["Message-ID"] = "<%s.%x@%s>" % (timelib.localtimestamp( now, fmt="%Y%m%d%H%M%S"), id(self) % 0x7fffffff, _get_hostname()) return smtp.sendmail(self.mail_from, self.rcpt_to, self.as_string(0), mopts, rcptopts)
def __call__(self, *args, **kw): # this heading displays the test name just as a PREREQUISITES entry needs. self._report.add_heading(repr_test(self.test_name, args, kw), 2) self.starttime = timelib.now() self.info("STARTTIME: %s" % (timelib.strftime("%a, %d %b %Y %H:%M:%S %Z", timelib.localtime(self.starttime)),)) rv = None # in case of exception rv = self._initialize(rv) if rv is not None: # an exception happened return rv # test elapsed time does not include initializer time. teststarttime = timelib.now() # run execute try: rv = apply(self.execute, args, kw) except KeyboardInterrupt: if self._debug: ex, val, tb = sys.exc_info() debugger.post_mortem(tb, ex, val) rv = self.incomplete("%s: aborted by user." % self.test_name) self._finalize(rv) raise except TestFailError, errval: rv = self.failed("Caught Fail exception: %s" % (errval,))
def __call__(self, *args, **kw): # this heading displays the test name just as a PREREQUISITES entry needs. self._report.add_heading(repr_test(self.test_name, args, kw), 2) self.starttime = timelib.now() self.info("STARTTIME: %s" % (timelib.strftime( "%a, %d %b %Y %H:%M:%S %Z", timelib.localtime(self.starttime)), )) rv = None # in case of exception rv = self._initialize(rv) if rv is not None: # an exception happened return rv # test elapsed time does not include initializer time. teststarttime = timelib.now() # run execute try: rv = apply(self.execute, args, kw) except KeyboardInterrupt: if self._debug: ex, val, tb = sys.exc_info() debugger.post_mortem(tb, ex, val) rv = self.incomplete("%s: aborted by user." % self.test_name) self._finalize(rv) raise except TestFailError, errval: rv = self.failed("Caught Fail exception: %s" % (errval, ))
def send(self, smtp, mail_options=None, rcpt_options=None): """send off this message using the supplied SMTP sender object.""" mopts = mail_options or [] rcptopts = rcpt_options or [] if not self.mail_from or not self.rcpt_to: raise RuntimeError, "AutoMessage: cannot send. no From or recipients." if self.has_key("Bcc"): del self["Bcc"] now = timelib.now() self["Date"] = formatdate(now) self["Message-ID"] = "<%s.%x@%s>" % ( timelib.localtimestamp(now, fmt="%Y%m%d%H%M%S"), id(self) % 0x7fffffff, _get_hostname()) return smtp.sendmail(self.mail_from, self.rcpt_to, self.as_string(0), mopts, rcptopts)
def handle_read(self): ip = struct.unpack("!I", self.recv(4))[0] # network byte-order port = struct.unpack("!H", self.recv(2))[0] # network byte-order length = struct.unpack("i", self.recv(4))[0] # host byte-order src = IpAddress(ip) src.port = port msg = self.recv(length) assert length == len(msg) tlv = BER_decode.get_tlv(msg) # should be community based message version, community, pdu = tlv.decode() if version == 0: pdu = _translate2v2(ip, community, pdu) arglist = (now(), src, community, pdu) for handler in self._handlers: # handler returns False/None if other handlers may run, # returns True if handled, and no further processing required. if handler(*arglist): break
def __init__(self, guid=None): '''Use no args if you want the guid generated (this is the normal method) or send a string-typed guid to generate it from the string''' if guid is None: self.guid = self.__class__.lastguid while self.guid == self.__class__.lastguid: # time part now = int(timelib.now() * 1000) self.guid = ("%016x" % now) + self.__class__.hexip # random part self.guid += ("%03x" % (random.randrange(0, 4095))) self.__class__.lastguid = self.guid elif type(guid) == type(self): # if a GUID object, copy its value self.guid = str(guid) else: # if a string, just save its value self.guid = guid
def read_handler(self): ip = struct.unpack("!I", self.recv(4))[0] # network byte-order port = struct.unpack("!H", self.recv(2))[0] # network byte-order length = struct.unpack("i", self.recv(4))[0] # host byte-order src = IpAddress(ip) src.port = port msg = self.recv(length) assert length == len(msg) tlv = BER_decode.get_tlv(msg) # should be community based message version, community, pdu = tlv.decode() if version == 0: pdu = _translate2v2(ip, community, pdu) tr = TrapRecord(now(), src, community, pdu) for handler in self._handlers: # handler returns False/None. If other handlers may run # return False. Return True if handled, and no further processing required. if handler(tr): break
def Initialize(self): """Perform any initialization needed by the test runner. Initializes report. Sends runner and header messages to the report. """ cf = self.config cf.username = os.environ["USER"] os.chdir(cf.logfiledir) # Make sure runner CWD is a writable place. cf.runnerstarttime = starttime = timelib.now() try: rpt = cf.report except NoSuchReport, err: cf.UI.error( "No report with the name %r. Use of of the following." % (cf.reportname, )) cf.UI.print_list(err.args[0]) raise TestRunnerError, "No such report name: %r" % ( cf.reportname, )
def traffic(self, argv): """traffic Report the IP traffic counters. First time stores counters. Subsequent times also report delta and average rate.""" rpt = self._obj.GetIPCounters() timestamp = timelib.now() self._print(rpt) try: oldrpt = self._ip_traffic_report except AttributeError: pass else: self._print("\nDelta:") diff = rpt - oldrpt self._print(diff) self._print("\nRate (per sec):") self._print(diff / (timestamp - oldrpt.timestamp)) rpt.timestamp = timestamp self._ip_traffic_report = rpt
def initialize(self): """Perform any initialization needed by the test runner. Initializes report. Sends runner and header messages to the report. """ cf = self.config cf.username = os.environ["USER"] os.chdir(cf.logfiledir) # Make sure runner CWD is a writable place. cf.runnerstarttime = starttime = timelib.now() cf.runnertimestamp = timelib.strftime( "%Y%m%d%H%M%S", timelib.localtime(cf.runnerstarttime)) try: rpt = cf.get_report() except reports.ReportFindError as err: cf.UI.error(str(err)) cf.UI.printf("%YUse at least one of the following%N:") cf.UI.print_list(cf.reports.keys()) cf.UI.Print("\n") raise TestRunnerError("Cannot continue without report.") # Report file's names. save for future use. rpt.initialize(cf) cf.reportfilenames = rpt.filenames rpt.add_title("Test Results for %r." % " ".join(cf.get("argv", ["unknown"]))) arguments = cf.get("arguments") # Report command line arguments, if any. if arguments: rpt.add_message("RUNNERARGUMENTS", " ".join(arguments)) # Report comment, if any. comment = cf.get("comment") if comment: rpt.add_message("COMMENT", comment) # Report build here, if given. build = cf.get("build") if build: rpt.add_message("BUILD", build) rpt.add_message("RUNNERSTARTTIME", starttime, 0)
def initialize(self): """Perform any initialization needed by the test runner. Initializes report. Sends runner and header messages to the report. """ cf = self.config cf.username = os.environ["USER"] os.chdir(cf.logfiledir) # Make sure runner CWD is a writable place. cf.runnerstarttime = starttime = timelib.now() cf.runnertimestamp = timelib.strftime("%Y%m%d%H%M%S", timelib.localtime(cf.runnerstarttime)) try: rpt = cf.get_report() except reports.ReportFindError as err: cf.UI.error(str(err)) cf.UI.printf("%YUse at least one of the following%N:") cf.UI.print_list(cf.reports.keys()) cf.UI.Print("\n") raise TestRunnerError("Cannot continue without report.") # Report file's names. save for future use. rpt.initialize(cf) cf.reportfilenames = rpt.filenames rpt.add_title("Test Results for %r." % " ".join(cf.get("argv", ["unknown"]))) arguments = cf.get("arguments") # Report command line arguments, if any. if arguments: rpt.add_message("RUNNERARGUMENTS", " ".join(arguments)) # Report comment, if any. comment = cf.get("comment") if comment: rpt.add_message("COMMENT", comment) # Report build here, if given. build = cf.get("build") if build: rpt.add_message("BUILD", build) rpt.add_message("RUNNERSTARTTIME", starttime, 0)
raise except TestFailError, errval: rv = self.failed("Caught Fail exception: %s" % (errval,)) except TestIncompleteError, errval: rv = self.incomplete("Caught Incomplete exception: %s" % (errval,)) except AssertionError, errval: rv = self.failed("failed assertion: %s" % (errval,)) except TestSuiteAbort: raise # pass this one up to suite except: ex, val, tb = sys.exc_info() if self._debug: debugger.post_mortem(tb, ex, val) tb = None rv = self.failed("%s: Exception occured! (%s: %s)" % (self.test_name, ex, val)) endtime = timelib.now() minutes, seconds = divmod(endtime - teststarttime, 60.0) hours, minutes = divmod(minutes, 60.0) self.info("Time elapsed: %02.0f:%02.0f:%02.2f" % (hours, minutes, seconds)) return self._finalize(rv) def _initialize(self, rv): try: self.initialize() except: ex, val, tb = sys.exc_info() self.diagnostic("%s (%s)" % (ex, val)) if self._debug: debugger.post_mortem(tb, ex, val) rv = self.abort("Test initialization failed!") return rv
(errval, )) # Test asserts and validation errors are based on this. except AssertionError, errval: rv = self.Failed("failed assertion: %s" % (errval, )) except TestSuiteAbort: raise # pass this one up to suite except debugger.DebuggerQuit: # set_trace "leaks" BdbQuit rv = self.Incomplete("%s: Debugger exit." % (self.test_name, )) except: ex, val, tb = sys.exc_info() if self._debug: debugger.post_mortem(tb, ex, val) tb = None rv = self.Incomplete("%s: Exception occured! (%s: %s)" % \ (self.test_name, ex, val)) endtime = timelib.now() self._report.add_message("STARTTIME", teststarttime, 2) self._report.add_message("ENDTIME", endtime, 2) minutes, seconds = divmod(endtime - teststarttime, 60.0) hours, minutes = divmod(minutes, 60.0) self.Info("Time elapsed: %02.0f:%02.0f:%02.2f" % (hours, minutes, seconds)) return self._finalize(rv) def _initialize(self, rv): """initialize phase handler. Run user-defined `initialize()` and catch exceptions. If an exception occurs in the `initialize()` method (which establishes the pre-conditions for a test) then alter the return value to abort()
def datapoint(self, val): """Adds data to the list of collected data. A time stamp is added.""" self.datapoints.extend((timelib.now(), val))
def _ConvertEvent(evtext): # converts "0001 006a 00000001" to event type, code, and value. Also # supplies a local time stamp. evtypetext, evcodetext, evvaluetext = evtext.split() return (timelib.now(), int(evtypetext, 16), int(evcodetext, 16), int(evvaluetext, 16))
def time_it(count, callit, *args, **kwargs): start = now() for i in range(count): callit(*args, **kwargs) end = now() return (end - start) / count
def set_timestamp(self, time=None): if time is None: time = timelib.now() self["timestamp"] = timelib.localtime_mutable(time)
def __call__(self, timestamp, lastvalue): print timestamp, self._id, lastvalue if lastvalue is None: return 1 return lastvalue + 1 ctx = core.MeasurementContext() ctx.timespan = 300.0 mc = Sequencer(ctx) mc.AddFunction(_TestingMeasurer("4SEC"), period=4.0) mc.AddFunction(core.TimeProgressMeter(ctx), period=10) mc.AddFunction(_TestingMeasurer("DELAYED_2SEC"), period=2.0, delay=30) mc.AddFunction(_TestingMeasurer("2SEC4TENSEC"), period=2.0, delay=40, runtime=10) print mc.Run() Close() print "=== running 6, 7, 10, 30 second jobs. ===" for t in (6, 7, 10, 30): ctx.timespan = t mc = Sequencer(ctx) mc.AddFunction(_TestingMeasurer("1SEC"), period=1.0) mc.AddFunction(_TestingMeasurer("2SEC"), period=2.0) mc.AddFunction(_TestingMeasurer("3SEC"), period=3.0) starttime = timelib.now() print mc.Run() print "elapsed:", timelib.now() - starttime, "should be:", t print Close()
def time_it(count, callit, *args, **kwargs): start = now() for i in range(count): callit(*args, **kwargs) end = now() return (end - start)/count