def handle(self, *args, **options):
        from terrainapp.models.Race import Race
        from terrainapp.models.RaceEvent import RaceEvent
        from terrainapp.models.RaceEventType import RaceEventType
        id = int(options['id'])

        type = RaceEventTypeEnum[id]

        if type == 'quick':
            name = "Quick race!"
        elif type == 'hourly':
            name = "Hourly race!"
        elif type == 'daily':
            name = "Daily race!"
        else:
            return

        minutes = RaceEventLengths[type]
        now = util.utcnow()
        race = random.choice(Race.objects.all())
        gap = datetime.timedelta(minutes=minutes)
        ret = RaceEventType.objects.get(id=id)
        er = RaceEvent(name=name,
                       race=race,
                       startdate=now,
                       enddate=now + gap,
                       active=True,
                       eventtype=ret)
        er.save()
Exemple #2
0
def getCurrentEvents():
    now=util.utcnow()
    #get by having startdate - not exactly right.
    permanent = RaceEvent.objects.filter(active=True,
                                   eventtype__id=RaceEventTypeEnum['permanent'])
    eph = getEphemeralEvents()
    return permanent | eph
Exemple #3
0
    def GetEventDescription(self, onlyTopLevel=False):
        now=util.utcnow()
        remainingtext=''

        if self.badge:
            badgetext='Badge award: "%s"!'%self.badge.name
        else:
            badgetext=''

        if self.eventtype:
            if self.eventtype.id in RaceEventTypeIdsWhichEnd:
                if not self.enddate:
                    raise
                timeTilEnd=(self.enddate-now).total_seconds()
                if timeTilEnd>0:
                    remainingtext='%s left!'%util.safeTimeIntervalAsString(timeTilEnd, onlyTopLevel)
                else:
                    remainingtext='It ended %s ago!'%util.safeTimeIntervalAsString(-1*timeTilEnd, onlyTopLevel)
        
        #this is confusing that it's showing all-time.
        br=BestRun.GetFirstPlaceBestRunForRace(self.race)
        if br   :
            leaderText='The current leader is %s, who took %0.3fs'%(br.user.username, br.raceMilliseconds/1000.0)
        else:
            leaderText='Nobody has run it yet.'

        return '%s %s %s %s %s'\
            %(self.name, 
            self.race, 
            badgetext,
            remainingtext, leaderText)
Exemple #4
0
    def onConnect(self, connectionRequest):
        if self.debug:
            log.msg(
                "connection received from %s speaking WebSockets protocol %d - upgrade request for host '%s', path '%s', params %s, origin '%s', protocols %s, headers %s"
                % (connectionRequest.peerstr, connectionRequest.version,
                   connectionRequest.host, connectionRequest.path,
                   str(connectionRequest.params), connectionRequest.origin,
                   str(connectionRequest.protocols),
                   str(connectionRequest.headers)))

        if connectionRequest.params.has_key("agent"):
            if len(connectionRequest.params["agent"]) > 1:
                raise Exception("multiple agents specified")
            self.caseAgent = connectionRequest.params["agent"][0]
        else:
            #raise Exception("no agent specified")
            self.caseAgent = None

        if connectionRequest.params.has_key("case"):
            if len(connectionRequest.params["case"]) > 1:
                raise Exception("multiple test cases specified")
            try:
                self.case = int(connectionRequest.params["case"][0])
            except:
                raise Exception("invalid test case ID %s" %
                                connectionRequest.params["case"][0])

        if self.case:
            if self.case >= 1 and self.case <= len(self.factory.specCases):
                self.Case = CasesById[self.factory.specCases[self.case - 1]]
                self.runCase = self.Case(self)
            else:
                raise Exception("case %s not found" % self.case)

        if connectionRequest.path == "/runCase":
            if not self.runCase:
                raise Exception("need case to run")
            if not self.caseAgent:
                raise Exception("need agent to run case")
            self.caseStarted = utcnow()
            print "Running test case ID %s for agent %s from peer %s" % (
                caseClasstoId(
                    self.Case), self.caseAgent, connectionRequest.peerstr)

        elif connectionRequest.path == "/updateReports":
            if not self.caseAgent:
                raise Exception("need agent to update reports for")
            print "Updating reports, requested by peer %s" % connectionRequest.peerstr

        elif connectionRequest.path == "/getCaseCount":
            pass

        else:
            print "Entering direct command mode for peer %s" % connectionRequest.peerstr

        self.path = connectionRequest.path

        return None
Exemple #5
0
    def add(db, **kwargs):
        # We need to hash down the payload if there is one.
        if 'payload' in kwargs and kwargs['payload'] is not None:
            kwargs['payload'] = json.dumps(dict(kwargs.get('payload')))

        kwargs["inserted_at"] = util.utcnow()
        log_trade = LogTrade(**kwargs)
        db.add(log_trade)
        db.commit()
Exemple #6
0
 def test_add(self):
     product = Product()
     product.title = "title"
     product.descr = "desc"
     product.type = ProductType.MATERIAL
     product.updated_at = product.inserted_at = util.utcnow()
     self.db.add(product)
     self.db.commit()
     self.assertTrue(True)
   def connectionMade(self):
      FuzzingProtocol.connectionMade(self)
      WebSocketClientProtocol.connectionMade(self)

      self.caseAgent = self.factory.agent
      self.case = self.factory.currentCaseIndex
      self.Case = Cases[self.case - 1]
      self.runCase = self.Case(self)
      self.caseStarted = utcnow()
      print "Running test case ID %s for agent %s from peer %s" % (caseClasstoId(self.Case), self.caseAgent, self.peerstr)
Exemple #8
0
    def connectionMade(self):
        FuzzingProtocol.connectionMade(self)
        WebSocketClientProtocol.connectionMade(self)

        self.caseAgent = self.factory.agent
        self.case = self.factory.currentCaseIndex
        self.Case = Cases[self.case - 1]
        self.runCase = self.Case(self)
        self.caseStarted = utcnow()
        print "Running test case ID %s for agent %s from peer %s" % (
            caseClasstoId(self.Case), self.caseAgent, self.peerstr)
Exemple #9
0
 def test_add(self):
     kwargs = {
         "component": "payment",
         "trade_id": self.gen_uid(),
         "payload": None,
         "inserted_at": util.utcnow()
     }
     log_trade = LogTrade(**kwargs)
     self.db.add(log_trade)
     self.db.commit()
     self.assertTrue(True)
Exemple #10
0
def movie_create():
    """Creates a movie and returns it."""

    input = request.json
    input.pop("id", 0) # ignore id if given, is set by db

    m = dict_to_model(db.Movie, input)
    m.modified = m.created = util.utcnow()
    m.creator = get_myself()
    m.save()

    return jsonify(m), 201
Exemple #11
0
    def test_add(self):
        product = Product()
        product.title = "title"
        product.descr = "desc"
        product.type = ProductType.MATERIAL
        product.updated_at = product.inserted_at = util.utcnow()
        self.db.add(product)

        trade = Trade()
        trade.trade_id = self.gen_uid()
        trade.timeout = "1d"
        trade.fee = 0.01
        trade.status = TradeStatus.PENDING
        trade.channel = ChannelType.WAP
        trade.show_url = "url"
        trade.updated_at = trade.inserted_at = util.utcnow()
        trade.product = product

        self.db.add(trade)
        self.db.commit()
        self.assertTrue(True)
Exemple #12
0
    def get(self):
        trade_id = self.valid("trade_id")
        fee = self.valid("fee", force_type=float)

        if self.errors:
            reason=self.errors.values()[0]
            raise HTTPError(422, "Validation Failed", reason=reason)

        trade = self.db.query(Trade).filter_by(trade_id=trade_id).first()
        if trade is None:
            reason = "Invalid trade ID"
            raise HTTPError(422, "Validation Failed", reason=reason)

        if float(fee) != trade.fee:
            reason = "Your fee not equal total fee"
            raise HTTPError(422, "Validation Failed", reason=reason)

        if trade.status == TradeStatus.REFUND:
            reason = "Trade ID has been refund"
            raise HTTPError(422, "Validation Failed", reason=reason)

        alipay = AliWapPay(app_id=config.ali_app_id,
                           private_key_path=config.private_key_path,
                           sign_type= config.ali_sign_type
                           )
        query_string = alipay.refund(trade_id, fee)
        url = config.ali_gateway + "?" + query_string

        client = AsyncHTTPClient()
        response = yield client.fetch(url)

        resp_body = json.loads(response.body)
        refund_info = resp_body["alipay_trade_refund_response"]

        code = refund_info["code"]
        if code == "10000":
            # Refund successfully.
            trade.status = TradeStatus.REFUND
            trade.updated_at = util.utcnow()
            self.db.commit()
            refund_to_client = {"code": code}

        else:
            refund_to_client = {
                "code": code,
                "msg": refund_info["msg"],
                "sub_code": refund_info["sub_code"],
                "sub_msg": refund_info["sub_msg"]
            }

        self.finish({"refund": refund_to_client})
Exemple #13
0
def movie_update(id):
    """Updates a movie and returns it."""

    input = request.json
    # don't update created/creator-fields
    input.pop("created", 0)
    input.pop("creator", 0)

    m = db.get_movie(id)
    update_model_from_dict(m, input)
    m.modified = util.utcnow()
    m.save()

    return jsonify(m), 200
Exemple #14
0
   def onConnect(self, connectionRequest):
      if self.debug:
         log.msg("connection received from %s speaking WebSockets protocol %d - upgrade request for host '%s', path '%s', params %s, origin '%s', protocols %s, headers %s" % (connectionRequest.peerstr, connectionRequest.version, connectionRequest.host, connectionRequest.path, str(connectionRequest.params), connectionRequest.origin, str(connectionRequest.protocols), str(connectionRequest.headers)))

      if connectionRequest.params.has_key("agent"):
         if len(connectionRequest.params["agent"]) > 1:
            raise Exception("multiple agents specified")
         self.caseAgent = connectionRequest.params["agent"][0]
      else:
         #raise Exception("no agent specified")
         self.caseAgent = None

      if connectionRequest.params.has_key("case"):
         if len(connectionRequest.params["case"]) > 1:
            raise Exception("multiple test cases specified")
         try:
            self.case = int(connectionRequest.params["case"][0])
         except:
            raise Exception("invalid test case ID %s" % connectionRequest.params["case"][0])

      if self.case:
         if self.case >= 1 and self.case <= len(self.factory.specCases):
            self.Case = CasesById[self.factory.specCases[self.case - 1]]
            self.runCase = self.Case(self)
         else:
            raise Exception("case %s not found" % self.case)

      if connectionRequest.path == "/runCase":
         if not self.runCase:
            raise Exception("need case to run")
         if not self.caseAgent:
            raise Exception("need agent to run case")
         self.caseStarted = utcnow()
         print "Running test case ID %s for agent %s from peer %s" % (caseClasstoId(self.Case), self.caseAgent, connectionRequest.peerstr)

      elif connectionRequest.path == "/updateReports":
         if not self.caseAgent:
            raise Exception("need agent to update reports for")
         print "Updating reports, requested by peer %s" % connectionRequest.peerstr

      elif connectionRequest.path == "/getCaseCount":
         pass

      else:
         print "Entering direct command mode for peer %s" % connectionRequest.peerstr

      self.path = connectionRequest.path

      return None
Exemple #15
0
    def get(self):
        trade_id = self.valid("trade_id")
        title = self.valid("title")
        fee = self.valid("fee", force_type=float,
                         validator=RangeValidator(0.01, 100000000).validate)
        show_url = self.valid("show_url")
        # Minutes as the calculating unit.
        timeout = self.valid("timeout", force_type=int)

        # Optional arguments
        descr = self.valid("descr", required=False)
        type_ = self.valid("type", required=False) or ProductType.MATERIAL

        if self.errors:
            reason=self.errors.values()[0]
            raise HTTPError(422, "Validation Failed", reason=reason)

        # Validate `trade_id` unique.
        is_unique = TradeMgr.is_unique(self.db, trade_id)
        logging.info("trade id:{} is_unique:{}".format(trade_id, is_unique))
        if not is_unique:
          reason = "Trade ID is not unique"
          raise HTTPError(422, "Validation Failed", reason=reason)

        timeout = "{}m".format(str(timeout))

        notify_url = self.notify_host + URL_WAP_PAY_NOTIFY
        alipay = AliWapPay(notify_url=notify_url,
                           app_id=config.ali_app_id,
                           private_key_path=config.private_key_path,
                           sign_type= config.ali_sign_type,
                           seller_id=config.ali_seller_id
                           )

        # Create trade URL query string.
        product_info = {"title": title, "type": type_, "descr": descr}
        callback_url = self.host + URL_WAP_PAY_CALLBACK
        trade_qs = alipay.create_trade(trade_id,
                                       fee,
                                       timeout,
                                       callback_url,
                                       product_info
                                       )

        utcnow = util.utcnow()
        product = Product(title=title,
                          descr=descr,
                          type=type_,
                          updated_at=utcnow,
                          inserted_at=utcnow
                          )
        trade = Trade(trade_id=trade_id,
                      fee=fee,
                      status=TradeStatus.PENDING,
                      channel=ChannelType.WAP,
                      show_url=show_url,
                      inserted_at=utcnow,
                      updated_at=utcnow,
                      timeout=timeout,
                      product=product
                      )

        self.db.add_all([product, trade])
        self.db.commit()
        self.finish(config.ali_gateway + "?" + trade_qs)
Exemple #16
0
    def post(self):
        logging.info("arguments:{}".format(self.request.arguments))

        payment_id = self.valid("trade_no")
        trade_id = self.valid("out_trade_no")
        fee = self.valid("total_amount", force_type=float)
        seller_id = self.valid("seller_id")
        trade_status = self.valid("trade_status", required=False)
        payor_id = self.valid("buyer_id", required=False) or ""
        created_at = self.valid("gmt_create", required=False) or ""
        payment_at = self.valid("gmt_payment", required=False) or ""

        # Add log.
        kwargs = {
          "trade_id": trade_id,
          "component": "wap_notify",
          "payload": self.request.arguments
        }
        LogTradeMgr.add(self.db, **kwargs)

        if self.errors:
            reason=self.errors.values()[0]
            raise HTTPError(422, "Arguments invalid", reason=reason)

        # Validate trade ID and total fee.
        trade = self.db.query(Trade).filter_by(trade_id=trade_id).first()
        if trade is None or float(fee) != float(trade.fee):
            # Notice is an exception notification, should be ignore.
            logging.exception("exception notificaton, trade_id:{}".format(trade_id))
            return self.finish("success")

        # Validate seller ID.
        if seller_id is not None and seller_id != config.ali_seller_id:
            # Notice is an exception notification, should be ignore.
            logging.exception("exception notificaton, trade_id:{}".format(trade_id))
            return self.finish("success")

        utcnow = util.utcnow()

        if trade_status in ["TRADE_SUCCESS", "TRADE_FINISHED"]:
            kwargs = {
              "payor_id": payor_id,
              "status": trade_status,
              "created_at": created_at,
              "payment_at": payment_at,
              "trade": trade,
              "inserted_at": utcnow,
              "updated_at": utcnow,
              "payment_id": payment_id
            }
            payment = Payment(**kwargs)
            if trade_status == "TRADE_SUCCESS":
                trade.status = TradeStatus.SUCCESS
            else:
                # Trade finished, No refundable
                trade.status = TradeStatus.FINISHED

            self.db.add(payment)
            self.db.commit()
        elif trade_status == "TRADE_CLOSED":
            # TODO
            pass
        else:
            # TODO
            pass

        self.finish("success")
Exemple #17
0
    def createMasterReport(self, outdir):

        report_filename = "index.html"
        f = open(os.path.join(outdir, report_filename), 'w')

        f.write(
            '<!DOCTYPE html><html><body><head><meta charset="utf-8" /><style lang="css">%s %s</style><script language="javascript">%s</script></head>'
            % (FuzzingFactory.css_common, FuzzingFactory.css_master,
               self.js_master()))

        f.write('<h1>WebSockets Protocol Test Report</h1>')

        f.write('<p id="intro">Test summary report generated on</p>')
        f.write('<p id="intro" style="margin-left: 80px;"><i>%s</i></p>' %
                utcnow())
        f.write('<p id="intro">by <a href="%s">Autobahn</a> WebSockets.</p>' %
                "http://www.tavendo.de/autobahn")

        f.write(
            '<p id="intro"><a href="#" onclick="toggleClose();">Toggle Close Results</a></p>'
        )

        f.write('<h2>Test Results</h2>')

        f.write('<table id="agent_case_results">')

        ## sorted list of agents for which test cases where run
        ##
        agentList = sorted(self.agents.keys())

        ## create list ordered list of case Ids
        ##
        cl = []
        for c in Cases:
            t = caseClasstoIdTuple(c)
            cl.append((t, caseIdTupletoId(t)))
        cl = sorted(cl)
        caseList = []
        for c in cl:
            caseList.append(c[1])

        lastCaseCategory = None
        lastCaseSubCategory = None

        for caseId in caseList:

            caseCategoryIndex = caseId.split('.')[0]
            caseCategory = CaseCategories.get(caseCategoryIndex, "Misc")
            caseSubCategoryIndex = '.'.join(caseId.split('.')[:2])
            caseSubCategory = CaseSubCategories.get(caseSubCategoryIndex, None)

            ## Category row
            ##
            if caseCategory != lastCaseCategory:
                f.write('<tr id="case_category_row">')
                f.write('<td id="case_category">%s %s</td>' %
                        (caseCategoryIndex, caseCategory))
                for agentId in agentList:
                    f.write(
                        '<td class="agent close_flex" colspan="2">%s</td>' %
                        agentId)
                f.write('</tr>')
                lastCaseCategory = caseCategory
                lastCaseSubCategory = None

            if caseSubCategory != lastCaseSubCategory:
                f.write('<tr id="case_subcategory_row">')
                f.write(
                    '<td class="case_subcategory" colspan="%d">%s %s</td>' %
                    (len(agentList) * 2 + 1, caseSubCategoryIndex,
                     caseSubCategory))
                lastCaseSubCategory = caseSubCategory

            f.write('<tr id="agent_case_result_row">')
            f.write('<td id="case"><a href="#case_desc_%s">Case %s</a></td>' %
                    (caseId.replace('.', '_'), caseId))

            ## Agent/Case Result
            ##
            for agentId in agentList:
                if self.agents[agentId].has_key(caseId):

                    case = self.agents[agentId][caseId]

                    agent_case_report_file = self.makeAgentCaseReportFilename(
                        agentId, caseId)

                    if case["behavior"] == Case.OK:
                        td_text = "Pass"
                        td_class = "case_ok"
                    elif case["behavior"] == Case.NON_STRICT:
                        td_text = "Non-Strict"
                        td_class = "case_non_strict"
                    elif case["behavior"] == Case.NO_CLOSE:
                        td_text = "No Close"
                        td_class = "case_no_close"
                    else:
                        td_text = "Fail"
                        td_class = "case_failed"

                    if case["behaviorClose"] == Case.OK:
                        ctd_text = "%s" % str(case["remoteCloseCode"])
                        ctd_class = "case_ok"
                    elif case["behaviorClose"] == Case.FAILED_BY_CLIENT:
                        ctd_text = "%s" % str(case["remoteCloseCode"])
                        ctd_class = "case_almost"
                    elif case["behaviorClose"] == Case.WRONG_CODE:
                        ctd_text = "%s" % str(case["remoteCloseCode"])
                        ctd_class = "case_non_strict"
                    elif case["behaviorClose"] == Case.UNCLEAN:
                        ctd_text = "Unclean"
                        ctd_class = "case_failed"
                    else:
                        ctd_text = "Fail"
                        ctd_class = "case_failed"

                    if case["reportTime"]:
                        f.write(
                            '<td class="%s"><a href="%s">%s</a><br/><span id="case_duration">%s ms</span></td><td class="close close_hide %s"><span class="close_code">%s</span></td>'
                            % (td_class, agent_case_report_file, td_text,
                               case["duration"], ctd_class, ctd_text))
                    else:
                        f.write(
                            '<td class="%s"><a href="%s">%s</a></td><td class="close close_hide %s"><span class="close_code">%s</span></td>'
                            % (td_class, agent_case_report_file, td_text,
                               ctd_class, ctd_text))

                else:
                    f.write(
                        '<td class="case_missing close_flex" colspan="2">Missing</td>'
                    )

            f.write("</tr>")
Exemple #18
0
    def createMasterReport(self, outdir):
        """
      Create report master HTML file.

      :param outdir: Directory where to create file.
      :type outdir: str
      :returns: str -- Name of created file.
      """

        ## open report file in create / write-truncate mode
        ##
        report_filename = "index.html"
        f = open(os.path.join(outdir, report_filename), 'w')

        ## write HTML
        ##
        f.write('<!DOCTYPE html>\n')
        f.write('<html>\n')
        f.write('   <head>\n')
        f.write('      <meta charset="utf-8" />\n')
        f.write('      <style lang="css">%s</style>\n' % CSS_COMMON)
        f.write('      <style lang="css">%s</style>\n' % CSS_MASTER_REPORT)
        f.write('      <script language="javascript">%s</script>\n' %
                JS_MASTER_REPORT % {"agents_cnt": len(self.agents.keys())})
        f.write('   </head>\n')
        f.write('   <body>\n')
        f.write(
            '      <a href="#"><div id="toggle_button" class="unselectable" onclick="toggleClose();">Toggle Details</div></a>\n'
        )
        f.write('      <a name="top"></a>\n')
        f.write('      <br/>\n')

        ## top logos
        f.write(
            '      <center><img src="http://www.tavendo.de/static/autobahn/ws_protocol_test_report.png" border="0" width="820" height="46" alt="WebSockets Protocol Test Report"></img></a></center>\n'
        )
        f.write(
            '      <center><a href="http://www.tavendo.de/autobahn" title="Autobahn WebSockets"><img src="http://www.tavendo.de/static/autobahn/ws_protocol_test_report_autobahn.png" border="0" width="300" height="68" alt="Autobahn WebSockets"></img></a></center>\n'
        )

        ## write report header
        ##
        f.write('      <div id="master_report_header" class="block">\n')
        f.write(
            '         <p id="intro">Summary report generated on %s (UTC) by <a href="%s">Autobahn WebSockets</a> v%s.</p>\n'
            % (utcnow(), "http://www.tavendo.de/autobahn", str(
                autobahn.version)))
        f.write("""
      <table id="case_outcome_desc">
         <tr>
            <td class="case_ok">Pass</td>
            <td class="outcome_desc">Test case was executed and passed successfully.</td>
         </tr>
         <tr>
            <td class="case_non_strict">Non-Strict</td>
            <td class="outcome_desc">Test case was executed and passed non-strictly.
            A non-strict behavior is one that does not adhere to a SHOULD-behavior as described in the protocol specification or
            a well-defined, canonical behavior that appears to be desirable but left open in the protocol specification.
            An implementation with non-strict behavior is still conformant to the protocol specification.</td>
         </tr>
         <tr>
            <td class="case_failed">Fail</td>
            <td class="outcome_desc">Test case was executed and failed. An implementation which fails a test case - other
            than a performance/limits related one - is non-conforming to a MUST-behavior as described in the protocol specification.</td>
         </tr>
         <tr>
            <td class="case_info">Info</td>
            <td class="outcome_desc">Informational test case which detects certain implementation behavior left unspecified by the spec
            but nevertheless potentially interesting to implementors.</td>
         </tr>
         <tr>
            <td class="case_missing">Missing</td>
            <td class="outcome_desc">Test case is missing, either because it was skipped via the test suite configuration
            or deactivated, i.e. because the implementation does not implement the tested feature or breaks during running
            the test case.</td>
         </tr>
      </table>
      """)
        f.write('      </div>\n')

        ## write big agent/case report table
        ##
        f.write('      <table id="agent_case_results">\n')

        ## sorted list of agents for which test cases where run
        ##
        agentList = sorted(self.agents.keys())

        ## create list ordered list of case Ids
        ##
        cl = []
        for c in Cases:
            t = caseClasstoIdTuple(c)
            cl.append((t, caseIdTupletoId(t)))
        cl = sorted(cl)
        caseList = []
        for c in cl:
            caseList.append(c[1])

        lastCaseCategory = None
        lastCaseSubCategory = None

        for caseId in caseList:

            caseCategoryIndex = caseId.split('.')[0]
            caseCategory = CaseCategories.get(caseCategoryIndex, "Misc")
            caseSubCategoryIndex = '.'.join(caseId.split('.')[:2])
            caseSubCategory = CaseSubCategories.get(caseSubCategoryIndex, None)

            ## Category/Agents row
            ##
            if caseCategory != lastCaseCategory or (
                    self.repeatAgentRowPerSubcategory
                    and caseSubCategory != lastCaseSubCategory):
                f.write('         <tr class="case_category_row">\n')
                f.write('            <td class="case_category">%s %s</td>\n' %
                        (caseCategoryIndex, caseCategory))
                for agentId in agentList:
                    f.write(
                        '            <td class="agent close_flex" colspan="2">%s</td>\n'
                        % agentId)
                f.write('         </tr>\n')
                lastCaseCategory = caseCategory
                lastCaseSubCategory = None

            ## Subcategory row
            ##
            if caseSubCategory != lastCaseSubCategory:
                f.write('         <tr class="case_subcategory_row">\n')
                f.write(
                    '            <td class="case_subcategory" colspan="%d">%s %s</td>\n'
                    % (len(agentList) * 2 + 1, caseSubCategoryIndex,
                       caseSubCategory))
                f.write('         </tr>\n')
                lastCaseSubCategory = caseSubCategory

            ## Cases row
            ##
            f.write('         <tr class="agent_case_result_row">\n')
            f.write(
                '            <td class="case"><a href="#case_desc_%s">Case %s</a></td>\n'
                % (caseId.replace('.', '_'), caseId))

            ## Case results
            ##
            for agentId in agentList:
                if self.agents[agentId].has_key(caseId):

                    case = self.agents[agentId][caseId]

                    agent_case_report_file = self.makeAgentCaseReportFilename(
                        agentId, caseId)

                    if case["behavior"] == Case.OK:
                        td_text = "Pass"
                        td_class = "case_ok"
                    elif case["behavior"] == Case.NON_STRICT:
                        td_text = "Non-Strict"
                        td_class = "case_non_strict"
                    elif case["behavior"] == Case.NO_CLOSE:
                        td_text = "No Close"
                        td_class = "case_no_close"
                    elif case["behavior"] == Case.INFORMATIONAL:
                        td_text = "Info"
                        td_class = "case_info"
                    else:
                        td_text = "Fail"
                        td_class = "case_failed"

                    if case["behaviorClose"] == Case.OK:
                        ctd_text = "%s" % str(case["remoteCloseCode"])
                        ctd_class = "case_ok"
                    elif case["behaviorClose"] == Case.FAILED_BY_CLIENT:
                        ctd_text = "%s" % str(case["remoteCloseCode"])
                        ctd_class = "case_almost"
                    elif case["behaviorClose"] == Case.WRONG_CODE:
                        ctd_text = "%s" % str(case["remoteCloseCode"])
                        ctd_class = "case_non_strict"
                    elif case["behaviorClose"] == Case.UNCLEAN:
                        ctd_text = "Unclean"
                        ctd_class = "case_failed"
                    elif case["behaviorClose"] == Case.INFORMATIONAL:
                        ctd_text = "%s" % str(case["remoteCloseCode"])
                        ctd_class = "case_info"
                    else:
                        ctd_text = "Fail"
                        ctd_class = "case_failed"

                    if case["reportTime"]:
                        f.write(
                            '            <td class="%s"><a href="%s">%s</a><br/><span class="case_duration">%s ms</span></td><td class="close close_hide %s"><span class="close_code">%s</span></td>\n'
                            % (td_class, agent_case_report_file, td_text,
                               case["duration"], ctd_class, ctd_text))
                    else:
                        f.write(
                            '            <td class="%s"><a href="%s">%s</a></td><td class="close close_hide %s"><span class="close_code">%s</span></td>\n'
                            % (td_class, agent_case_report_file, td_text,
                               ctd_class, ctd_text))

                else:
                    f.write(
                        '            <td class="case_missing close_flex" colspan="2">Missing</td>\n'
                    )

            f.write("         </tr>\n")
Exemple #19
0
 def uptime_seconds(self) -> float:
     return (utcnow() - self.registered_at).total_seconds()
Exemple #20
0
def getEphemeralEvents():
    now=util.utcnow()
    #get by having startdate - not exactly right.
    res = RaceEvent.objects.filter(startdate__lt=now, enddate__gt=now, active=True,
                                   eventtype__id__in=RaceEventTypeIdsWhichEnd)
    return res
Exemple #21
0
def GetActiveRaceEvents():
    res1 = RaceEvent.objects.filter(active=True, eventtype__id=RaceEventTypeEnum['permanent'])
    now=util.utcnow()
    res2 = RaceEvent.objects.filter(startdate__lt=now, enddate__gt=now, active=True)
    return res1|res2
 def myrunning_now(self, obj):
     now = util.utcnow()
     if obj.startdate and obj.enddate:
         return obj.startdate < now and obj.enddate > now
     return True
   def createMasterReport(self, outdir):

      report_filename = "index.html"
      f = open(os.path.join(outdir, report_filename), 'w')

      f.write('<!DOCTYPE html><html><body><head><meta charset="utf-8" /><style lang="css">%s %s</style><script language="javascript">%s</script></head>' % (FuzzingFactory.css_common, FuzzingFactory.css_master, self.js_master()))

      f.write('<h1>WebSockets Protocol Test Report</h1>')

      f.write('<p id="intro">Test summary report generated on</p>')
      f.write('<p id="intro" style="margin-left: 80px;"><i>%s</i></p>' % utcnow())
      f.write('<p id="intro">by <a href="%s">Autobahn</a> WebSockets.</p>' % "http://www.tavendo.de/autobahn")

      f.write('<p id="intro"><a href="#" onclick="toggleClose();">Toggle Close Results</a></p>')

      f.write('<h2>Test Results</h2>')

      f.write('<table id="agent_case_results">')

      ## sorted list of agents for which test cases where run
      ##
      agentList = sorted(self.agents.keys())

      ## create list ordered list of case Ids
      ##
      cl = []
      for c in Cases:
         t = caseClasstoIdTuple(c)
         cl.append((t, caseIdTupletoId(t)))
      cl = sorted(cl)
      caseList = []
      for c in cl:
         caseList.append(c[1])

      lastCaseCategory = None
      lastCaseSubCategory = None

      for caseId in caseList:

         caseCategoryIndex = caseId.split('.')[0]
         caseCategory = CaseCategories.get(caseCategoryIndex, "Misc")
         caseSubCategoryIndex = '.'.join(caseId.split('.')[:2])
         caseSubCategory = CaseSubCategories.get(caseSubCategoryIndex, None)

         ## Category row
         ##
         if caseCategory != lastCaseCategory:
            f.write('<tr id="case_category_row">')
            f.write('<td id="case_category">%s %s</td>' % (caseCategoryIndex, caseCategory))
            for agentId in agentList:
               f.write('<td class="agent close_flex" colspan="2">%s</td>' % agentId)
            f.write('</tr>')
            lastCaseCategory = caseCategory
            lastCaseSubCategory = None

         if caseSubCategory != lastCaseSubCategory:
            f.write('<tr id="case_subcategory_row">')
            f.write('<td class="case_subcategory" colspan="%d">%s %s</td>' % (len(agentList)*2 + 1, caseSubCategoryIndex, caseSubCategory))
            lastCaseSubCategory = caseSubCategory

         f.write('<tr id="agent_case_result_row">')
         f.write('<td id="case"><a href="#case_desc_%s">Case %s</a></td>' % (caseId.replace('.', '_'), caseId))

         ## Agent/Case Result
         ##
         for agentId in agentList:
            if self.agents[agentId].has_key(caseId):

               case = self.agents[agentId][caseId]

               agent_case_report_file = self.makeAgentCaseReportFilename(agentId, caseId)

               if case["behavior"] == Case.OK:
                  td_text = "Pass"
                  td_class = "case_ok"
               elif case["behavior"] == Case.NON_STRICT:
                  td_text = "Non-Strict"
                  td_class = "case_non_strict"
               elif case["behavior"] == Case.NO_CLOSE:
                  td_text = "No Close"
                  td_class = "case_no_close"
               else:
                  td_text = "Fail"
                  td_class = "case_failed"

               if case["behaviorClose"] == Case.OK:
                  ctd_text = "%s" % str(case["remoteCloseCode"])
                  ctd_class = "case_ok"
               elif case["behaviorClose"] == Case.FAILED_BY_CLIENT:
                  ctd_text = "%s" % str(case["remoteCloseCode"])
                  ctd_class = "case_almost"
               elif case["behaviorClose"] == Case.WRONG_CODE:
                  ctd_text = "%s" % str(case["remoteCloseCode"])
                  ctd_class = "case_non_strict"
               elif case["behaviorClose"] == Case.UNCLEAN:
                  ctd_text = "Unclean"
                  ctd_class = "case_failed"
               else:
                  ctd_text = "Fail"
                  ctd_class = "case_failed"

               if case["reportTime"]:
                  f.write('<td class="%s"><a href="%s">%s</a><br/><span id="case_duration">%s ms</span></td><td class="close close_hide %s"><span class="close_code">%s</span></td>' % (td_class, agent_case_report_file, td_text, case["duration"],ctd_class,ctd_text))
               else:
                  f.write('<td class="%s"><a href="%s">%s</a></td><td class="close close_hide %s"><span class="close_code">%s</span></td>' % (td_class, agent_case_report_file, td_text,ctd_class,ctd_text))

            else:
               f.write('<td class="case_missing close_flex" colspan="2">Missing</td>')

         f.write("</tr>")

      f.write("</table>")

      f.write('<h2>Test Cases</h2>')

      for caseId in caseList:

         CCase = CasesById[caseId]

         f.write('<a name="case_desc_%s"></a>' % caseId.replace('.', '_'))
         f.write('<h3 id="case_desc_title">Case %s</h2>' % caseId)
         f.write('<p id="case_desc"><i>Description</i><br/><br/> %s</p>' % CCase.DESCRIPTION)
         f.write('<p id="case_expect"><i>Expectation</i><br/><br/> %s</p>' % CCase.EXPECTATION)

      f.write("</body></html>")

      f.close()
      return report_filename
Exemple #24
0
    def createMasterReport(self, outdir):
        """
      Create report master HTML file.

      :param outdir: Directory where to create file.
      :type outdir: str
      :returns: str -- Name of created file.
      """

        ## open report file in create / write-truncate mode
        ##
        report_filename = "index.html"
        f = open(os.path.join(outdir, report_filename), "w")

        ## write HTML
        ##
        f.write("<!DOCTYPE html>\n")
        f.write("<html>\n")
        f.write("   <head>\n")
        f.write('      <meta charset="utf-8" />\n')
        f.write('      <style lang="css">%s</style>\n' % CSS_COMMON)
        f.write('      <style lang="css">%s</style>\n' % CSS_MASTER_REPORT)
        f.write(
            '      <script language="javascript">%s</script>\n'
            % JS_MASTER_REPORT
            % {"agents_cnt": len(self.agents.keys())}
        )
        f.write("   </head>\n")
        f.write("   <body>\n")
        f.write(
            '      <a href="#"><div id="toggle_button" class="unselectable" onclick="toggleClose();">Toggle Details</div></a>\n'
        )
        f.write('      <a name="top"></a>\n')
        f.write("      <br/>\n")

        ## top logos
        f.write(
            '      <center><img src="http://www.tavendo.de/static/autobahn/ws_protocol_test_report.png" border="0" width="820" height="46" alt="WebSockets Protocol Test Report"></img></a></center>\n'
        )
        f.write(
            '      <center><a href="http://www.tavendo.de/autobahn" title="Autobahn WebSockets"><img src="http://www.tavendo.de/static/autobahn/ws_protocol_test_report_autobahn.png" border="0" width="300" height="68" alt="Autobahn WebSockets"></img></a></center>\n'
        )

        ## write report header
        ##
        f.write('      <div id="master_report_header" class="block">\n')
        f.write(
            '         <p id="intro">Summary report generated on %s (UTC) by <a href="%s">Autobahn WebSockets</a> v%s.</p>\n'
            % (utcnow(), "http://www.tavendo.de/autobahn", str(autobahn.version))
        )
        f.write(
            """
      <table id="case_outcome_desc">
         <tr>
            <td class="case_ok">Pass</td>
            <td class="outcome_desc">Test case was executed and passed successfully.</td>
         </tr>
         <tr>
            <td class="case_non_strict">Non-Strict</td>
            <td class="outcome_desc">Test case was executed and passed non-strictly.
            A non-strict behavior is one that does not adhere to a SHOULD-behavior as described in the protocol specification or
            a well-defined, canonical behavior that appears to be desirable but left open in the protocol specification.
            An implementation with non-strict behavior is still conformant to the protocol specification.</td>
         </tr>
         <tr>
            <td class="case_failed">Fail</td>
            <td class="outcome_desc">Test case was executed and failed. An implementation which fails a test case - other
            than a performance/limits related one - is non-conforming to a MUST-behavior as described in the protocol specification.</td>
         </tr>
         <tr>
            <td class="case_missing">Missing</td>
            <td class="outcome_desc">Test case is missing, either because it was skipped via the test suite configuration
            or deactivated, i.e. because the implementation does not implement the tested feature or breaks during running
            the test case.</td>
         </tr>
      </table>
      """
        )
        f.write("      </div>\n")

        ## write big agent/case report table
        ##
        f.write('      <table id="agent_case_results">\n')

        ## sorted list of agents for which test cases where run
        ##
        agentList = sorted(self.agents.keys())

        ## create list ordered list of case Ids
        ##
        cl = []
        for c in Cases:
            t = caseClasstoIdTuple(c)
            cl.append((t, caseIdTupletoId(t)))
        cl = sorted(cl)
        caseList = []
        for c in cl:
            caseList.append(c[1])

        lastCaseCategory = None
        lastCaseSubCategory = None

        for caseId in caseList:

            caseCategoryIndex = caseId.split(".")[0]
            caseCategory = CaseCategories.get(caseCategoryIndex, "Misc")
            caseSubCategoryIndex = ".".join(caseId.split(".")[:2])
            caseSubCategory = CaseSubCategories.get(caseSubCategoryIndex, None)

            ## Category/Agents row
            ##
            if caseCategory != lastCaseCategory or (
                self.repeatAgentRowPerSubcategory and caseSubCategory != lastCaseSubCategory
            ):
                f.write('         <tr class="case_category_row">\n')
                f.write('            <td class="case_category">%s %s</td>\n' % (caseCategoryIndex, caseCategory))
                for agentId in agentList:
                    f.write('            <td class="agent close_flex" colspan="2">%s</td>\n' % agentId)
                f.write("         </tr>\n")
                lastCaseCategory = caseCategory
                lastCaseSubCategory = None

            ## Subcategory row
            ##
            if caseSubCategory != lastCaseSubCategory:
                f.write('         <tr class="case_subcategory_row">\n')
                f.write(
                    '            <td class="case_subcategory" colspan="%d">%s %s</td>\n'
                    % (len(agentList) * 2 + 1, caseSubCategoryIndex, caseSubCategory)
                )
                f.write("         </tr>\n")
                lastCaseSubCategory = caseSubCategory

            ## Cases row
            ##
            f.write('         <tr class="agent_case_result_row">\n')
            f.write(
                '            <td class="case"><a href="#case_desc_%s">Case %s</a></td>\n'
                % (caseId.replace(".", "_"), caseId)
            )

            ## Case results
            ##
            for agentId in agentList:
                if self.agents[agentId].has_key(caseId):

                    case = self.agents[agentId][caseId]

                    agent_case_report_file = self.makeAgentCaseReportFilename(agentId, caseId)

                    if case["behavior"] == Case.OK:
                        td_text = "Pass"
                        td_class = "case_ok"
                    elif case["behavior"] == Case.NON_STRICT:
                        td_text = "Non-Strict"
                        td_class = "case_non_strict"
                    elif case["behavior"] == Case.NO_CLOSE:
                        td_text = "No Close"
                        td_class = "case_no_close"
                    elif case["behavior"] == Case.INFORMATIONAL:
                        td_text = "Info"
                        td_class = "case_info"
                    else:
                        td_text = "Fail"
                        td_class = "case_failed"

                    if case["behaviorClose"] == Case.OK:
                        ctd_text = "%s" % str(case["remoteCloseCode"])
                        ctd_class = "case_ok"
                    elif case["behaviorClose"] == Case.FAILED_BY_CLIENT:
                        ctd_text = "%s" % str(case["remoteCloseCode"])
                        ctd_class = "case_almost"
                    elif case["behaviorClose"] == Case.WRONG_CODE:
                        ctd_text = "%s" % str(case["remoteCloseCode"])
                        ctd_class = "case_non_strict"
                    elif case["behaviorClose"] == Case.UNCLEAN:
                        ctd_text = "Unclean"
                        ctd_class = "case_failed"
                    elif case["behaviorClose"] == Case.INFORMATIONAL:
                        ctd_text = "%s" % str(case["remoteCloseCode"])
                        ctd_class = "case_info"
                    else:
                        ctd_text = "Fail"
                        ctd_class = "case_failed"

                    if case["reportTime"]:
                        f.write(
                            '            <td class="%s"><a href="%s">%s</a><br/><span class="case_duration">%s ms</span></td><td class="close close_hide %s"><span class="close_code">%s</span></td>\n'
                            % (td_class, agent_case_report_file, td_text, case["duration"], ctd_class, ctd_text)
                        )
                    else:
                        f.write(
                            '            <td class="%s"><a href="%s">%s</a></td><td class="close close_hide %s"><span class="close_code">%s</span></td>\n'
                            % (td_class, agent_case_report_file, td_text, ctd_class, ctd_text)
                        )

                else:
                    f.write('            <td class="case_missing close_flex" colspan="2">Missing</td>\n')

            f.write("         </tr>\n")

        f.write("      </table>\n")
        f.write("      <br/><hr/>\n")

        ## Case descriptions
        ##
        f.write('      <div id="test_case_descriptions">\n')
        for caseId in caseList:
            CCase = CasesById[caseId]
            f.write("      <br/>\n")
            f.write('      <a name="case_desc_%s"></a>\n' % caseId.replace(".", "_"))
            f.write("      <h2>Case %s</h2>\n" % caseId)
            f.write('      <a class="up" href="#top">Up</a>\n')
            f.write(
                '      <p class="case_text_block case_desc"><b>Case Description</b><br/><br/>%s</p>\n'
                % CCase.DESCRIPTION
            )
            f.write(
                '      <p class="case_text_block case_expect"><b>Case Expectation</b><br/><br/>%s</p>\n'
                % CCase.EXPECTATION
            )
        f.write("      </div>\n")
        f.write("      <br/><hr/>\n")

        ## end of HTML
        ##
        f.write("   </body>\n")
        f.write("</html>\n")

        ## close created HTML file and return filename
        ##
        f.close()
        return report_filename