Esempio n. 1
0
    def send_qual_start_email(self):
        self.log('INFO', 'Sending qual start email ...')
        if self.obj_release == None:
            list_image_basename = []
        else:
            list_image_full_path = self.obj_release.image_files_full_path()
            list_image_basename = []
            for each_image_full_path in list_image_full_path:
                list_image_basename.append(
                    os.path.basename(each_image_full_path))

        if list_image_basename != []:
            list_info = list_image_basename
        else:
            list_info = self.all_cases()

        if not self.str_test_title:
            str_title = self.task_id()
        else:
            str_title = self.str_test_title

        list_information_qual_start = [[
            self.str_platform.capitalize() + ':' + str_title,
            self.str_hwimo_version, Env.str_version
        ], list_info, []]
        Env.send_email('Qual Start', list_information_qual_start)
Esempio n. 2
0
    def send_qual_start_email(self):
        self.log('INFO', 'Sending qual start email ...')
        if self.obj_release == None:
            list_image_basename = []
        else:
            list_image_full_path = self.obj_release.image_files_full_path()
            list_image_basename = []
            for each_image_full_path in list_image_full_path:
                list_image_basename.append(os.path.basename(each_image_full_path))

        if list_image_basename != []:
            list_info = list_image_basename
        else:
            list_info = self.all_cases()

        if not self.str_test_title:
            str_title = self.task_id()
        else:
            str_title = self.str_test_title

        list_information_qual_start = [[self.str_platform.capitalize()+':'+ str_title,
                                        self.str_hwimo_version,
                                        Env.str_version],
                                       list_info,
                                       []]
        Env.send_email('Qual Start', list_information_qual_start)
Esempio n. 3
0
    def CriComHelp(self):

        liq = self.dbliq
        mt = liq._totali
        cc = liq._cricom

        class CriComHelp(wx.PopupTransientWindow):
            """
            Frame aiuto credito iva compensabile
            Viene evidenziato il credito ad inizio anno e quello residuo
            """
            def __init__(self, parent):

                wx.PopupTransientWindow.__init__(self, parent,\
                                                 style=wx.SIMPLE_BORDER)
                wdr.LiqIvaCriComHelpFunc(self)

                cn = lambda x: self.FindWindowById(x)

                cn(wdr.ID_STORIACIC).Enable(liq._liqeff.RowsCount() > 0)
                cn(wdr.ID_USACIC).Enable(\
                    cc['cricomdisp'] > 0 and mt['docfin1'] > 0)

                def UsaCIC(*args):
                    c = parent.FindWindowById(wdr.ID_CRICOM2)
                    c.SetValue(min(cc['cricomdisp'], mt['docfin1']))

                self.Bind(wx.EVT_BUTTON, UsaCIC, id=wdr.ID_USACIC)

                def StoriaCIC(*args):
                    scc = wx.Dialog(parent,
                                    title="Utilizzo credito iva compensabile",
                                    size=(750, 300),
                                    style=wx.DEFAULT_DIALOG_STYLE)
                    GridUtiCIC(scc, liq._liqeff)
                    scc.Fit()
                    scc.Layout()
                    scc.CenterOnScreen()
                    scc.Show()
                    scc.SetFocus()

                self.Bind(wx.EVT_BUTTON, StoriaCIC, id=wdr.ID_STORIACIC)

        year = self.dbliq._year
        t = self.FindWindowById(wdr.ID_CRICOM2)
        p = t.ClientToScreen((0, 0))
        s = t.GetSize()
        h = CriComHelp(self)
        for lid, lbl in (\
            (wdr.ID_CCHELP_TITLE, "Disponibile all'inizio del %s" % year),\
            (wdr.ID_CCHELP_START, Env.StrImp(cc['cricomstart'])),\
            (wdr.ID_CCHELP_DISP,  Env.StrImp(cc['cricomdisp']))):
            h.FindWindowById(lid).SetLabel(lbl)
        h.Fit()
        h.Layout()
        h.Position(p, (s[0] + 10, 0))
        h.Popup()
Esempio n. 4
0
def run_in_normal_mode():
    
    Env.log('INFO', 'ATOM Normal Mode')
    
    start_all_tm()

    '''
    To capture CTRL+C and other exception.
    join() will block the main thread and signal will be ignored.
    ATOM never exit so join() is not necessary.
    '''
    while True:
        time.sleep(1)
    '''
Esempio n. 5
0
def run():

    parse_options()

    build_puffer_main_logger(obj_options.str_alias)

    Env.log('INFO', 'Puffer %s Running' % Env.str_version)

    try:
        load_environment()
    except Exception, e:
        Env.log('ERROR', 'Fail to load test environment')
        import traceback
        print traceback.format_exc()
        return
Esempio n. 6
0
def run(): 
    
    parse_options()

    build_puffer_main_logger(obj_options.str_alias)
    
    Env.log('INFO', 'Puffer %s Running' % Env.str_version)

    try:
        load_environment()
    except Exception, e:
        Env.log('ERROR', 'Fail to load test environment')
        import traceback
        print traceback.format_exc()
        return
Esempio n. 7
0
    def send_qual_complete_email(self):
        self.log('INFO', 'Sending qual completed email ...')

        if self.str_test_title == '':
            str_title = self.task_id()
        else:
            str_title = self.str_test_title

        list_information_qual_complete = [[self.str_platform.capitalize() + ':' + str_title,
                                           self.str_hwimo_version,
                                           self.time_create,
                                           self.time_complete,
                                           Env.str_version],
                                          [self.str_report_file,],
                                          [self.str_report_file,]]
        Env.send_email('Qual Complete', list_information_qual_complete)
Esempio n. 8
0
    def send_qual_complete_email(self):
        self.log('INFO', 'Sending qual completed email ...')

        if self.str_test_title == '':
            str_title = self.task_id()
        else:
            str_title = self.str_test_title

        list_information_qual_complete = [[self.str_platform.capitalize() + ':' + str_title,
                                           self.str_hwimo_version,
                                           self.time_create,
                                           self.time_complete,
                                           Env.str_version],
                                          [self.str_report_file,],
                                          [self.str_report_file,]]
        Env.send_email('Qual Complete', list_information_qual_complete)
Esempio n. 9
0
def EVAL(ast, env):
    if not type(ast) is list:
        return eval_ast(ast, env)

    elif len(ast) == 0:
        return ast

    elif type(ast) is list:
        first_symbol = ast[0]

        if first_symbol == 'def!':
            key = ast[1]
            value = EVAL(ast[2], env)
            env.set(key, value)
            return value

        elif first_symbol == 'let*':
            let_env = Env.Env(env)
            e1 = ast[1]
            e2 = ast[2]
            for i in range(0, len(e1), 2):
                let_env.set(e1[i], EVAL(e1[i + 1], let_env))
            return EVAL(e2, let_env)

        else:
            fn = eval_ast(ast, env)
            return Mal.Number(eval_function(fn))

    else:
        raise Exception("EVAL: Type Error")
Esempio n. 10
0
def main():
    #repl
    env = Env.Environment()
    print("Welcome to the lisp interpreter")
    while True:
        str = input()
        if str == "!quit":
            print("Quitting lisp interpreter")
            break

        if len(str) >= 5 and str[0:5] == "!load":
            print("loading file")
            filename = str[6:]
            with open(filename) as f:
                for line in f:
                    ev.eval(par.parse(par.tokenize(line)), env)

        else:
            toke_str = par.tokenize(str)
            syntax_tree = par.parse(toke_str)
            #insert_quote(syntax_tree)
            out = ev.eval(syntax_tree, env)
            if out is not None:
                #need to check is return value is is a list
                #if it is, need to recursivley turn the list into a symbol instead of returning a list
                print(out)
Esempio n. 11
0
    def start(self):
        # init environment
        self.board_row = int(self.size_setting.row.get())
        self.board_col = int(self.size_setting.col.get())
        self.env = Env.Env(board_row=self.board_row, board_col=self.board_col)

        # init players
        i = 0
        for player_setting in [self.player1, self.player2]:
            if player_setting.type.get() == 0:  # human
                self.players[i] = 0
                if player_setting.name.get():
                    self.names[i] = player_setting.name.get()
                else:
                    self.names[i] = "Human " + str(i + 1)
            elif player_setting.type.get() == 1:  # computer
                self.players[i] = 1
                self.names[i] = "Computer " + str(i + 1)
            i += 1
        self.env.players = self.players
        self.env.turn_to_player = {0: self.names[0], 1: self.names[1]}
        print(self.players, self.names)

        # init prediction
        self.env.prediction = self.predict_setting.predict_int.get()

        # init game_board
        if self.game_board:
            self.game_board.frame.destroy()
        self.game_board = GameBoard(master=self.window, board_row=self.board_row, board_col=self.board_col,
                                    env=self.env)
        self.game_board.frame.grid(row=1, column=0)
Esempio n. 12
0
    def run(self, policy):
        testConf = T.testIntruderConfig()

        moving_mem = []

        for i in range(testConf.num):
            for t in range(testConf.steps[i]):
                if t == 0:
                    if i == 0:
                        moving = np.array([0, 0])
                    self.intruder = Env.intruder()
                    self.intruder.vel = testConf.vels[i]
                    self.intruder.start = testConf.starts[i]
                    self.intruder.end = testConf.ends[i]
                    self.intruder.x = self.intruder.start[0]
                    self.intruder.y = self.intruder.start[1]
                    self.intruders.append(self.intruder)

                self.intruder_update(moving)
                self.f1 = pygame.surfarray.array3d(Env.win)
                self.intruder_update([0, 0])
                self.f2 = pygame.surfarray.array3d(Env.win)
                moving = self.act(policy)
                moving_mem.append(moving)
        return np.array(moving_mem)
Esempio n. 13
0
 def OnSaveLiq(self, event):
     liq = self.dbliq
     if liq.TestValori():
         mt = self.dbliq._totali
         ver, deb, cred = mt['vertra1'], mt['docfin1'], mt['docfin2']
         if ver:
             message =\
                     """Questa liquidazione porta ad un versamento """\
                     """di Euro """+Env.StrImp(ver)
         else:
             if deb:
                 message =\
                         """Questa liquidazione porta ad un debito di imposta di Euro %s\n"""\
                         """da non versare poiché inferiore al limite minimo di versamento\n"""\
                         """di Euro 25,82.\n"""\
                         """Il debito di Euro %s verrà riportato nella prossima liquidazione."""\
                         % (Env.StrImp(deb), Env.StrImp(deb))
             elif cred:
                 message =\
                         """Con questa liquidazione non c'è da versare nulla.\n"""\
                         """Il credito di Euro %s verrà riportato nella prossima liquidazione."""\
                         % Env.StrImp(cred)
             else:
                 message =\
                         """Questa liquidazione è a zero."""
         message += """\n\nConfermi l'operazione?"""
         r = awu.MsgDialog(self,
                           message,
                           "Conferma liquidazione",
                           style=wx.ICON_QUESTION | wx.YES_NO
                           | wx.NO_DEFAULT)
         if r == wx.ID_YES:
             cn = self.FindWindowByName
             if liq.SaveLiq(self.regivasta,
                            cn('intanno').GetValue(),
                            cn('intpag').GetValue() - 1):
                 awu.MsgDialog(self,
                               """La liquidazione è stata confermata.""")
                 evt = FineLiquidEvent(_evtLIQEND)
                 evt.SetEventObject(self)
                 self.GetEventHandler().AddPendingEvent(evt)
             else:
                 awu.MsgDialog(
                     self, """Problemi nel salvataggio della """
                     """liquidazione\n%s""" % repr(liq.GetError()))
     event.Skip()
Esempio n. 14
0
def runTest(frame, nb, log):
    import Env
    Env.InitSettings()
    db = dbm.adb.DB()
    db.Connect()
    win = DocIntDialog()
    win.Show()
    return win
Esempio n. 15
0
def runTest(frame, nb, log):
    import Env
    Env.InitSettings()
    db = dbc.adb.DB()
    db.Connect()
    win = CtrCassaDialog()
    win.Show()
    return win
Esempio n. 16
0
def runTest(frame, nb, log):
    import Env
    Env.InitSettings()
    db = dbc.adb.DB()
    db.Connect()
    win = PdcQuadPcfContFrame()
    win.ShowModal()
    return win
Esempio n. 17
0
 def __init__(self, numTran, numStep, volume, time, frunflag):
     self.numSteps = numStep
     self.lastAction = None
     self.lastState = None
     self.env = Env.EnvCls(numTran, frunflag, volume, time)
     self.agent = Agent_base.Agentbase(volume, time)
     self.lastStep = 0
     self.totalRewards = 0
     self.fepisode_over = False
Esempio n. 18
0
 def __init__(self, parent_edge):
     '''
   Parameter: 
   edges : a list of edges that this state will point to
   '''
     self.v = 0  # Change
     self.board = Env()
     self.edge_pointers = []
     self.parent_edge = parent_edge
Esempio n. 19
0
        def handle_test(extra_data=None, **overwrite):
            """
            create env, run test and record test results

            :param extra_data: extra data that runner or main passed to test case
            :param overwrite: args that runner or main want to overwrite
            :return: None
            """
            # create env instance
            env_config = DefaultEnvConfig.get_default_config()
            for key in kwargs:
                if key in env_config:
                    env_config[key] = kwargs[key]

            env_config.update(overwrite)
            env_inst = Env.Env(**env_config)
            # prepare for xunit test results
            xunit_file = os.path.join(
                env_inst.app_cls.get_log_folder(env_config["test_suite_name"]),
                XUNIT_FILE_NAME)
            XUNIT_RECEIVER.begin_case(test_func.__name__, time.time(),
                                      test_func_file_name)
            try:
                Utility.console_log("starting running test: " +
                                    test_func.__name__,
                                    color="green")
                # execute test function
                test_func(env_inst, extra_data)
                # if finish without exception, test result is True
                result = True
            except Exception as e:
                # handle all the exceptions here
                traceback.print_exc()
                result = False
                # log failure
                XUNIT_RECEIVER.failure(str(e), test_func_file_name)
            finally:
                # do close all DUTs
                env_inst.close()
            # end case and output result
            XUNIT_RECEIVER.end_case(test_func.__name__, time.time())
            with open(xunit_file, "ab+") as f:
                f.write(
                    xunitgen.toxml(XUNIT_RECEIVER.results(),
                                   XUNIT_DEFAULT_TEST_SUITE))

            if result:
                Utility.console_log("Test Succeed: " + test_func.__name__,
                                    color="green")
            else:
                Utility.console_log(("Test Fail: " + test_func.__name__),
                                    color="red")
            TestResult.set_result(result, test_func.__name__)
            return result
Esempio n. 20
0
def fitness_function(individual_swarm):
    # Initializes the environment, which in turn creates everything else (agent, brain, nest, rscs)
    env = Env.Environment(individual_swarm)
    best_agents_inputs = []

    for i in range(RUN_DURATION):
        env.step()
    # total_population_output[num_gen] = generational_total_output

    # Setting a default fitness value so the requisite
    # data structures get created
    fitness_score = 0.0001

    # Main loop for assigning fitness
    for agent in env.agents:
        for i in range(0, len(agent.rscs_detected_hist[0])):
            # Zero behavior: activate sensory neurons upon seeing red rsc
            if agent.rscs_detected_hist[0][
                    i] != 0.0001 and agent.rscs_detected_hist[1][i] != 0.0001:
                # With the revisions to rscs detected, the lowest possible value is 0.0,
                # which indicates a rsc being right on top of an agent
                # Thus, fitness should reward lower scores and penalize higher ones,
                # and a log scale is not likely to be as useful
                if 0. <= abs(agent.brain.current_outputs[-3] -
                             agent.brain.current_outputs[-2]) <= 0.3:
                    fitness_score += abs(
                        math.log(
                            abs(agent.rscs_detected_hist[0][i] +
                                agent.rscs_detected_hist[1][i])))

                # First behavior: track a red resource
                # Conditional that checks the difference bt motor neuron outputs and
                # assigns higher fitness based on slower turning
                #fitness_score += abs(math.log(abs(agent.rscs_detected_hist[0][i]+agent.rscs_detected_hist[1][i])))

                # Second behavior: locomote toward a resource
                #if 0.5 <= agent.brain.current_outputs[-4] <= 1.0:
                # if 0.1 <= abs(agent.rscs_detected_hist[0][i]+agent.rscs_detected_hist[1][i]) <= 100:
                #     fitness_score += abs(math.log(1/abs(agent.rscs_detected_hist[0][i]+agent.rscs_detected_hist[1][i])))

        # Setting the best fitness and appropriate data for plotting/tracking
        if fitness_score > ga.best_fitness:
            ga.best_outputs = agent.brain.hist_outputs
            ga.best_agent_all_gens = agent
        if ga.population_fitness:
            if len(ga.population_fitness) > 1:
                if fitness_score >= max(ga.population_fitness):
                    ga.best_agent_this_gen = agent
            else:
                ga.best_agent_this_gen = agent

    window.update()
    #window.clearscreen()
    return fitness_score
Esempio n. 21
0
def buildenv(args):

    # Build Env
    if args.Environment == "MAB":
        env = Env.MAB(args.num_act)
    elif args.Environment.startswith("MAB_"):
        num_arms = [int(s) for s in args.Environment.split("_") if s.isdigit()]
        num_arms = num_arms[0]
        np.random.seed(num_arms)
        env = Env.MAB(num_arms, np.random.uniform(0, 1, num_arms))
        np.random.seed(int(time.time()))
    elif args.Environment == "MDP":
        env = Env.MDP()
    elif args.Environment.startswith("MDP_"):
        nums = [int(s) for s in args.Environment.split("_") if s.isdigit()]
        np.random.seed(nums[0] * nums[1])
        env = Env.MDP(nums[0], nums[1])
        np.random.seed(int(time.time()))

    # Build Agent
    if args.Agent == "RandomAgent":
        agent = Agent.RandomAgent(env.num_act)
    elif args.Agent == "UCB1":
        agent = Agent.UCB1(env.num_act, args.ucb1_c)
    elif args.Agent == "Greedy":
        agent = Agent.Greedy(env.num_act, args.greedy_eps, args.greedy_decay)
    elif args.Agent == "QL" or args.Agent == "QLearning":
        agent = Agent.TabQLearning(env.num_state,
                                   env.num_act,
                                   lr=args.lr,
                                   eps=args.greedy_eps,
                                   decay_steps=args.greedy_decay,
                                   gamma=args.gamma)
    elif args.Agent == "PG" or args.Agent == "PolicyGrad":
        agent = Agent.TabPolicyGrad(env.num_state,
                                    env.num_act,
                                    lr=args.lr,
                                    eps=args.greedy_eps,
                                    decay_steps=args.greedy_decay,
                                    gamma=args.gamma)
    return env, agent
Esempio n. 22
0
        def handle_test(extra_data=None, **overwrite):
            """
            create env, run test and record test results

            :param extra_data: extra data that runner or main passed to test case
            :param overwrite: args that runner or main want to overwrite
            :return: None
            """
            # create env instance
            env_config = DefaultEnvConfig.get_default_config()
            for key in kwargs:
                if key in env_config:
                    env_config[key] = kwargs[key]

            env_config.update(overwrite)
            env_inst = Env.Env(**env_config)

            # prepare for xunit test results
            junit_file_path = env_inst.app_cls.get_log_folder(
                env_config["test_suite_name"])
            junit_test_case = JunitReport.create_test_case(case_info["name"])
            result = False

            try:
                Utility.console_log("starting running test: " +
                                    test_func.__name__,
                                    color="green")
                # execute test function
                test_func(env_inst, extra_data)
                # if finish without exception, test result is True
                result = True
            except Exception as e:
                # handle all the exceptions here
                traceback.print_exc()
                # log failure
                junit_test_case.add_failure_info(
                    str(e) + ":\r\n" + traceback.format_exc())
            finally:
                if not case_info["junit_report_by_case"]:
                    JunitReport.test_case_finish(junit_test_case)
                # do close all DUTs, if result is False then print DUT debug info
                env_inst.close(dut_debug=(not result))

            # end case and output result
            JunitReport.output_report(junit_file_path)

            if result:
                Utility.console_log("Test Succeed: " + test_func.__name__,
                                    color="green")
            else:
                Utility.console_log(("Test Fail: " + test_func.__name__),
                                    color="red")
            return result
Esempio n. 23
0
 def update_case_name_in_task_file(self):
     '''
     if the script name is only an ID, update the field with
     full script name
     '''
     for each_xmlnode_case in self.list_xmlnode_case:
         str_original_case_name = each_xmlnode_case.find('script_name').text
         str_updated_case_name = Env.get_case(str_original_case_name)
         if not str_updated_case_name:
             continue
         each_xmlnode_case.find('script_name').text = str_updated_case_name
     self.save_status()
Esempio n. 24
0
 def update_case_name_in_task_file(self):
     '''
     if the script name is only an ID, update the field with
     full script name
     '''
     for each_xmlnode_case in self.list_xmlnode_case:
         str_original_case_name = each_xmlnode_case.find('script_name').text
         str_updated_case_name = Env.get_case(str_original_case_name)
         if not str_updated_case_name:
             continue
         each_xmlnode_case.find('script_name').text = str_updated_case_name
     self.save_status()
Esempio n. 25
0
 def execute(self):
     while True:
         yield hold, self, random.uniform(0,60)
         if Controller.Mode == Mode.CallGen and ALE.Controller.Mode == ALE.Mode.Scanning: #Check that it is still valid to send a call
             targetNodeID = random.randint(Env.G.num_nodes) #write function for this
             dataType = Env.dataType.CALL
             dataChan = -1 #Unknown at this stage - decided in ALE
             dataSize = random.uniform(15,256) #write function for this
             dataTime = -1 #Note: Size*Env.G.max_bitrate is THEORETICAL MAX and needs to be multiplied by LQA
             dataLQA = -1 #Which is also unknown at this stage, as channel is unknown!
             data = Env.dataStruct(self.ID,targetNodeID,dataType,dataChan,dataSize,dataTime,dataLQA)
             Controller.CallMade.signal(data)
Esempio n. 26
0
def import_case(str_case_name):
    Env.log('INFO', 'importing case %s' % str_case_name)
    obj_case = None
    if str_case_name.lower().endswith('.py'):
        length = len(str_case_name)
        str_case_name = str_case_name[:length - 3]

    try:
        # import the case module
        exec('from case.%s import %s' % (str_case_name, str_case_name))
        # create the case object
        exec('obj_case = %s()' %  str_case_name)
    except:
        #log the reason of case import failure.
        import traceback
        errmsg='Unexpected exception happened when importing test case, \
                trace back: \n%s' % traceback.format_exc()
        Env.log('ERROR', errmsg)  
        obj_case = None

    return obj_case
Esempio n. 27
0
def run(): 
    
    parse_options()
    
    b_in_command_line_mode = False
    if obj_options.str_task or \
       obj_options.str_case_list or \
       obj_options.str_cases or \
       obj_options.test_suite:
#        Env.str_log_folder = os.path.join(Env.str_root_folder, 'temp')
        b_in_command_line_mode = True

    build_atom_main_logger(obj_options.str_alias)
    
    Env.log('INFO', 'ATOM %s Running' % Env.str_version)
    
    load_environment()
    
    if obj_options.b_start_email:
        Env.start_email_server()
        
    if obj_options.b_start_jsonrpc:
        Env.start_jsonrpc_server()
        
    Env.b_update_enclosure_before_test = obj_options.b_update_before_test
    
    if b_in_command_line_mode:
        run_in_command_line_mode()
    else:
        run_in_normal_mode()
        
    os.chdir(Env.str_original_cwd)
Esempio n. 28
0
def eval_def(exp, env):
    # Define a function
    if type(exp[1]) == list:
        proc = Env.Procedure(exp[1][1:], exp[2:], env)
        env.define_var(exp[1][0], proc)
        return 'ok'
    # Define variable
    elif len(exp) == 3:
        val = exp[2]
        env.define_var( exp[1], Eval(val, env) )
        return 'ok'
    else :
        raise ValueError, 'Bad syntax :' + str(exp)
Esempio n. 29
0
 def execute(self):
     while True:
         yield hold, self, random.uniform(0,20)
         if Controller.Mode == Mode.CallGen and ALE.Controller.Mode == ALE.Mode.Scanning: #Check that it is still valid to send a call
             'Send ALE signal MHS_Incoming'
             targetNodeID = random.randint(Env.G.num_nodes) #write function for this
             dataType = Env.dataType.CALL
             dataChan = -1 #Unknown at this stage - decided in ALE
             dataSize = random.uniform(15,256) #write function for this
             dataTime = -1 #Note: Size*Env.G.max_bitrate is THEORETICAL MAX and needs to be multiplied by LQA
             dataLQA = -1 #Which is also unknown at this stage, as channel is unknown!
             data = Env.dataStruct(self.ID,targetNodeID,dataType,dataChan,dataSize,dataTime)
             ALE.Controller.MHS_Incoming.signal('data')
Esempio n. 30
0
 def __init__(self):
     self.commands = {
         "cd": Commands.cd,
         "clr": Commands.clr,
         "dir": Commands.dir,
         "environ": Commands.environ,
         "echo": Commands.echo,
         "display": Commands.echo,
         "help": Commands.displayHelp,
         "pause": Commands.pause,
         "quit": Commands.quitShell,
     }
     self.env = Env.Env(os.path.abspath(os.path.dirname(sys.argv[0])))
Esempio n. 31
0
    def launch_case(self, obj_xmlnode_next_case):
        str_case_name_or_id = obj_xmlnode_next_case.find('script_name').text
        self.log('INFO', 'Start launching case(%s)' % (str_case_name_or_id))
        str_case_name = Env.get_case(str_case_name_or_id)
        if str_case_name == '':
            self.log('WARNING', 'Case(%s) not found' % str_case_name_or_id)
            obj_xmlnode_next_case.find('status').text = STATUS_COMPLETED
            obj_xmlnode_next_case.find('result').text = 'skip'
            obj_xmlnode_next_case.find('error_code').text = 'Case script not found'
            obj_xmlnode_next_case.find('start_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('complete_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('duration_time').text = '0'
            self.save_status()
            return
        # import case
        obj_case = self.import_case(str_case_name)

        # Failed to import the case, mark the result na, and update error code
        if obj_case == None:
            self.log('ERROR', 'failed to import case %s' % str_case_name)
            obj_xmlnode_next_case.find('status').text = STATUS_COMPLETED
            obj_xmlnode_next_case.find('result').text = 'fail'
            obj_xmlnode_next_case.find('error_code').text = 'Failed to import case'
            obj_xmlnode_next_case.find('start_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('complete_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('duration_time').text = '0'
            self.save_status()
            return
        obj_case.obj_xmlnode_case = obj_xmlnode_next_case
        # success import the case, prepare and run the case
        self.update_case_with_te_info(obj_case)
        # set environment variable for cases
        obj_case.monorail = Env.obj_hwimo
        obj_case.stack = Env.obj_stack
        # validate the case
        obj_case.validate()
        if not obj_case.b_valid:
            self.log('WARNING', 'case %s: %s' % (str_case_name, obj_case.str_error_code))
            self.log('INFO','Skip case %s' %str_case_name)
            obj_xmlnode_next_case.find('status').text = STATUS_COMPLETED
            obj_xmlnode_next_case.find('result').text = 'block'
            obj_xmlnode_next_case.find('error_code').text = obj_case.str_error_code
            obj_xmlnode_next_case.find('start_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('complete_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('duration_time').text = '0'
            self.save_status()
            return

        self.execute_daemon(obj_case)

        return
Esempio n. 32
0
    def launch_case(self, obj_xmlnode_next_case):
        str_case_name_or_id = obj_xmlnode_next_case.find('script_name').text
        self.log('INFO', 'Start launching case(%s)' % (str_case_name_or_id))
        str_case_name = Env.get_case(str_case_name_or_id)
        if str_case_name == '':
            self.log('WARNING', 'Case(%s) not found' % str_case_name_or_id)
            obj_xmlnode_next_case.find('status').text = STATUS_COMPLETED
            obj_xmlnode_next_case.find('result').text = 'skip'
            obj_xmlnode_next_case.find('error_code').text = 'Case script not found'
            obj_xmlnode_next_case.find('start_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('complete_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('duration_time').text = '0'
            self.save_status()
            return
        # import case
        obj_case = self.import_case(str_case_name)

        # Failed to import the case, mark the result na, and update error code
        if obj_case == None:
            self.log('ERROR', 'failed to import case %s' % str_case_name)
            obj_xmlnode_next_case.find('status').text = STATUS_COMPLETED
            obj_xmlnode_next_case.find('result').text = 'fail'
            obj_xmlnode_next_case.find('error_code').text = 'Failed to import case'
            obj_xmlnode_next_case.find('start_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('complete_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('duration_time').text = '0'
            self.save_status()
            return
        obj_case.obj_xmlnode_case = obj_xmlnode_next_case
        # success import the case, prepare and run the case
        self.update_case_with_te_info(obj_case)
        # set environment variable for cases
        obj_case.monorail = Env.obj_hwimo
        obj_case.stack = Env.obj_stack
        # validate the case
        obj_case.validate()
        if not obj_case.b_valid:
            self.log('WARNING', 'case %s: %s' % (str_case_name, obj_case.str_error_code))
            self.log('INFO','Skip case %s' %str_case_name)
            obj_xmlnode_next_case.find('status').text = STATUS_COMPLETED
            obj_xmlnode_next_case.find('result').text = 'block'
            obj_xmlnode_next_case.find('error_code').text = obj_case.str_error_code
            obj_xmlnode_next_case.find('start_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('complete_time').text = str(datetime.datetime.now())
            obj_xmlnode_next_case.find('duration_time').text = '0'
            self.save_status()
            return

        self.execute_daemon(obj_case)

        return
Esempio n. 33
0
def execute_cases(list_case, str_enclosure_id = '', str_release_folder = ''):
    if obj_options.str_alias == '':
        str_work_directory = os.path.join('temp', time.strftime('%Y%m%d%H%M%S'))
    else:
        str_work_directory = os.path.join('temp', \
                                          '_'.join([time.strftime('%Y%m%d%H%M%S'), obj_options.str_alias]))
    if not os.path.isdir(str_work_directory):
        os.makedirs(str_work_directory)
    str_report = os.path.join(str_work_directory, 'report.xml')
    str_test = '''
    <test>
    </test>
    '''
    obj_xmlnode_test = ET.fromstring(str_test)
    for each_case in list_case:
        obj_xmlnode_case = execute_case(each_case, str_work_directory, str_enclosure_id, str_release_folder)
        if obj_xmlnode_case==None:
            continue
        obj_xmlnode_test.append(obj_xmlnode_case)
    f_write = open(str_report,'w')
    f_write.write(ET.tostring(obj_xmlnode_test))
    f_write.close()
    Env.log('INFO', 'All cases completed, report at:%s' % str_report)
Esempio n. 34
0
 def execute(self):
     while True:
         yield hold, self, random.uniform(0, 60)
         if self.Controller.Mode == Mode.CallGen and self.ALE_Controller.Mode == self.ALE_Mode.Scanning:  #Check that it is still valid to send a call
             targetNodeID = -1
             while targetNodeID == self.ID or targetNodeID == -1:  #Mini function to make sure
                 targetNodeID = random.randint(0, Env.G.num_nodes -
                                               1)  #target isn't itself
             dataType = Env.dataType.CALL
             dataChan = -1  #Unknown at this stage - decided in ALE
             dataSize = random.uniform(15, 256)  #write function for this
             dataTime = -1  #Note: Size*Env.G.max_bitrate is THEORETICAL MAX and needs to be multiplied by LQA
             dataLQA = -1  #Which is also unknown at this stage, as channel is unknown!
             data = Env.dataStruct(self.ID, targetNodeID, dataType,
                                   dataChan, dataSize, dataTime, dataLQA)
             self.Controller.CallMade.signal(data)
Esempio n. 35
0
 def GeneraDesRif(self, num, lastrig, doc, bodyfields):
     dr = self.docrag
     mg = self.movgen
     mg.CreateNewRow()
     lastrig += 1
     bodyfields['id_doc'] =    -num #attribuito in fase di conferma
     bodyfields['id_tipmov'] = dr._movmap[dr._movdes[doc.id_tipdoc]]
     #bodyfields['id_moveva'] = -d.id
     bodyfields['numriga'] = lastrig
     
     for field, value in bodyfields.iteritems():
         mg.__setattr__(field, value)
     mg.__setattr__('descriz', "Rif.to %s n. %s del %s"\
               % (doc.tipdoc.descriz, doc.numdoc, Env.StrDate(doc.datdoc)))
     
     return lastrig
Esempio n. 36
0
def Eval(exp, env):
    # classifing expressions
    if self_eval(exp): return eval_self_eval(exp)
    elif is_var(exp): return env.lookup_var_val(exp)
    elif is_quoted(exp): return text_of_quotation(exp)
    elif is_assign(exp): return eval_assign(exp, env)
    elif is_def(exp): return eval_def(exp, env)
    elif is_if(exp): return eval_if(exp, env)
    elif is_lambda(exp): return Env.Procedure(exp[1], exp[2:], env)
    elif is_begin(exp): return eval_seq(exp[1:], env)
    elif is_cond(exp): return eval_cond2if(exp, env)
    elif is_app(exp, env):
        logging.info(str(exp[0]) + ' will be applied')
        return Apply.Apply( Eval(exp[0], env),
            list_of_vals(exp[1:], env))
    else: raise Exception, 'Unknonw expression : Eval '+ str(exp)
Esempio n. 37
0
def calculate_average(num):
    sum = 0
    for i in range(num):
        mine_map = Env.map(10, 60)
        agent = Known_mines(mine_map)
        agent.run()
        # agent.print_map()
        # agent.pick()
        # agent.pick()
        # agent.print_map()
        agent.show_knowledge()
        score = agent.reveal / agent.env.mines
        sum += score
        print("score: {}".format(agent.reveal / agent.env.mines))
    print("average {}".format(sum / num))
    return sum / num
Esempio n. 38
0
    def intruder_update(self,moving):
        Env.win.fill((144, 72, 17))
        conflict = 0

        for intruder in self.intruders:
            intruder.update()
            intruder.x, intruder.y = np.array([intruder.x, intruder.y]) - moving
            self.det_x, self.det_y = np.array([self.det_x, self.det_y]) - moving
            if intruder.x > max_x + intruder.radius or intruder.x < 0 - intruder.radius or intruder.y > max_y + intruder.radius or intruder.y < 0 - intruder.radius:
                self.intruders.pop(self.intruders.index(intruder))
                self.intruders.append(Env.intruder())
            if np.sqrt((intruder.x - max_x/2)**2 + (intruder.y - max_y/2)**2) <= 5:
                conflict += 1
            intruder.shade()
            intruder.draw(Env.win)
        self.draw_flight_plan()
        return conflict
Esempio n. 39
0
def start_all_tm():
    Env.log('INFO', 'start all test manager')
    _create_tm_for_all_tracking_platforms()
    for each_platform_tm in Env.list_platform_tm:
        obj_tm = each_platform_tm[1]
        if not obj_tm.is_valid():
            Env.log('INFO', 'TM%d for %s invalid, removing..' % (obj_tm.int_tm_id, obj_tm.str_platform))
        thread_tm_running = Thread(target=obj_tm.run)
        Env.list_thread_tm.append(thread_tm_running)
        
        thread_tm_running.setDaemon(True)
        thread_tm_running.start()
        Env.log('INFO', 'TM%d for %s running' % (obj_tm.int_tm_id, obj_tm.str_platform))
Esempio n. 40
0
    def __init__(self):
        self.Environment = Env.Board_2048(boardSize)
        Frame.__init__(self)

        # agent = Agent.Agent(2,
        #                     n_neurons=n_neurons, activations=activations,
        #                     epsilon_stop_episode=epsilon_stop_episode, mem_size=mem_size,
        #                     discount=discount, replay_start_size=replay_start_size)

        self.grid()
        self.master.title('2048')

        self.grid_cells = []
        self.init_grid()
        self.update_grid_cells()
        root = Tk()
        root.update()
        root.withdraw()
        self.Run_Game()
        self.mainloop()
    def __init__(self, numTran, numStep, volume, time, frunflag, parm):
        self.numSteps = numStep
        self.lastAction = None
        self.lastState = None
        self.env = Env.EnvCls(numTran, frunflag, volume, time)
        """Calls separate Agent modules based on different strategies"""
        if parm == "greedy":
            self.agent = Agent.AgentCls(volume, time)
        elif parm == "random":
            self.agent = Agent_rnd.AgentRand(volume, time)
        else:
            self.agent = Agent_baseline.Agentbase(volume, time)

        self.lastStep = 0
        self.totalRewards = 0

        if parm == "greedy" and frunflag == False:
            self.fepisode_over = False
        else:
            self.fepisode_over = True
Esempio n. 42
0
def check_new_plugins(read_setup=True):
    import Env
    files = glob.glob(Env.opj(Env.plugin_base_path, '*.zip'))
    files.sort()
    new_plugins = []
    for _file in files:
        _file = _file.replace('\\','/')
        n = _file.rindex('/')
        name = _file[n+1:-4]
        if not name in Env.plugins:
            if read_setup:
                #test plugin disabilitato sull'azienda
                setup = Env.adb.DbTable('cfgsetup', 'setup')
                setup.AddFilter('setup.chiave="%s_plugin_version" AND setup.flag=0' % name)
                setup.Retrieve()
                append = setup.IsEmpty()
            else:
                append = True
            if append:
                new_plugins.append(name)
    return new_plugins
Esempio n. 43
0
def _create_tm_for_platform(str_platform_type):
    str_xmlnode_tm = ''' 
    <test_manager>
        <platform></platform>
        <source_folder>
            <path></path>
            <branch></branch>
        </source_folder>
        <level></level>
        <enclosure_id></enclosure_id>
    </test_manager>
    '''
    # check if there is a test manager node
    Env.log('INFO', 'check if there is special TM for platform:%s' % str_platform_type)
    list_xmlnode_tm = Env.obj_config_manager.tm_nodes_for_platform(str_platform_type)
    if list_xmlnode_tm == None:
        Env.log('INFO', 'no additional TM request is found for platform: %s' % str_platform_type)
    for each_xmlnode_tm in list_xmlnode_tm:
        Env.log('INFO', 'additional TM%d created for platform(%s)' % (Env.int_tm_id, str_platform_type))
        obj_tm = TestManager.CTestManager(each_xmlnode_tm, Env.int_tm_id, str_platform_type)
        if not obj_tm.is_valid():
            Env.log('WARNING', 'TM%d invalid:%s' % (obj_tm.int_tm_id, obj_tm.str_error_code))
            Env.int_tm_id += 1
            continue
#        str_tm_logger_name = '%s.tm%d(%s)' % (str_logger_name, Env.int_tm_id, str_platform_type)
#        Env.log('INFO', 'create logger for TM%d with name %s' % (Env.int_tm_id, str_tm_logger_name))
#        obj_tm.create_logger(str_tm_logger_name)
        Env.int_tm_id += 1
        Env.list_platform_tm.append([str_platform_type, obj_tm])
        Env.dict_ID_TM[obj_tm.int_tm_id] = obj_tm
        
    # create default tm for the platform
    if not Env.get_idle_enclosure(str_platform_type):
        Env.log('INFO', 'No other idle system, skip creating \
default TM for platform(%s)' % str_platform_type)
        return
    xmlnode_tm = ET.fromstring(str_xmlnode_tm)
    xmlnode_tm.find('platform').text = str_platform_type
    xmlnode_tm.find('source_folder').text = Env.str_source_folder
    Env.log('INFO', 'create default TM for platform %s' % str_platform_type)
    obj_tm = TestManager.CTestManager(xmlnode_tm, Env.int_tm_id, str_platform_type)
    Env.log('INFO', 'TM%d for platform %s created' % (Env.int_tm_id, str_platform_type))
    if not obj_tm.is_valid():
        Env.log('WARNING', 'TM%d invalid:%s' % (obj_tm.int_tm_id, obj_tm.str_error_code))
        Env.int_tm_id += 1
        return
    str_tm_logger_name = '%s.tm%d(%s)' % (Env.str_logger_name, Env.int_tm_id, str_platform_type)
    Env.log('INFO', 'create logger for TM%d with name %s' % (Env.int_tm_id, str_tm_logger_name))
    obj_tm.create_logger(str_tm_logger_name)
    Env.int_tm_id += 1
    Env.list_platform_tm.append([str_platform_type, obj_tm])
    Env.dict_ID_TM[obj_tm.int_tm_id] = obj_tm
Esempio n. 44
0
def run_in_command_line_mode():
    """
    main entry point for puffer command line mode.
    """
    global obj_options
    
    Env.log('INFO', 'Puffer command: %s' % ' '.join(sys.argv))
    
    '''
    list_case contains 3 part:
        1. loose case
        2. content of test list file
        3. test suite
        folders are expended and checked in TestManager.py/parse_case_list()
    '''
    list_case = []
    str_work_directory = ''

    # whether to remove duplicated cases in the task;
    # determined by --dedub.
    flag_dedup = obj_options.dedup
    test_run_id = obj_options.test_run_id

    # Alias
    Env.str_alias = obj_options.str_alias

    # Case list by -s, test suite: folder.
    test_suite = obj_options.test_suite
    if test_suite:
        msg = 'Include cases in test suite(%s) into task file' % test_suite
        Env.log('INFO', msg)
        list_case += test_suite.split(',')

    # Case list by -l, test list file
    list_file = obj_options.str_case_list
    if list_file:
        # parse the file and add to list_case
        for one_list in list_file.split(','):
            msg = 'Include cases in list file(%s) into task file' % list_file
            Env.log('INFO', msg)
            if not os.path.isfile(one_list):
                Env.log('WARNING', 'Case list file(%s) not found' % one_list)
            else:
                lines = open(one_list, 'r').read().splitlines()
                for i in lines:
                    if not i.strip():
                        continue
                    if i.startswith('#' or '/'):
                        # commented out. ignore.
                        continue
                    list_case.append(i.strip())

    # Case list by -c, loose test cases
    if obj_options.str_cases:
        Env.log('INFO', 'Included cases(%s) into task file' % obj_options.str_cases)
        list_case += obj_options.str_cases.split(',')

    # Test environment
    # 1. HWIMO and stack both
    if Env.dict_stack and Env.dict_hwimo:
        str_platform = Env.dict_hwimo['platform']
    # 2. HWIMO only
    elif Env.dict_hwimo:
        str_platform = Env.dict_hwimo['platform']
    # 3. Stack only
    elif Env.dict_stack:
        str_platform = 'InfraSIM'
    # 4. No HWIMO, no stack
    # Wait to see if it's run with task file
    else:
        Env.log('ERROR', 'Quit with no DUT information, please issue --stack or --ip')
        return
    
    # alias: datetime+given name.
    test_run_alias = time.strftime('%Y%m%d%H%M%S')
    if obj_options.str_alias != '':
        if os.sep in obj_options.str_alias:
            obj_options.str_alias = obj_options.str_alias.replace(os.sep, '_')
        test_run_alias += '_%s' % obj_options.str_alias

    str_work_directory = os.path.join(Env.str_log_folder,
                                      str_platform,
                                      test_run_alias)
    Env.log('INFO', 'Logs are available at: %s' % str_work_directory)
    
    # check test result uploading setting

    if test_run_id:

        if obj_options.testrail_user and obj_options.testrail_password:
            str_source = 'command line option: --testrail_user, --testrail_password'
        else:
            str_source = '<testrail_config> in conf.xml'

        testrail = TestRailClient(str_server_addr=Env.str_testrail_root,
                                  str_user=Env.str_testrail_username,
                                  str_password=Env.str_testrail_password)

        # test run id provided. validate it
        try:
            testrail.get_test_run(test_run_id)
            msg = 'Test result will be uploaded to test run %d' % test_run_id
            Env.log('INFO', msg)
        except:
            Env.log('WARNING', 'TestRail connection fail, please check {}'.format(str_source))

    # Detect HWIMO revision
    str_hwimo_rev = ''
    if Env.obj_hwimo:
        str_hwimo_rev = Env.obj_hwimo.get_revision()

    str_task_file = TestManager.create_task_file(str_platform,
                                                 Env.str_alias,
                                                 str_hwimo_rev,
                                                 obj_options.str_hwimo_ip,
                                                 obj_options.str_stack,
                                                 str_work_directory,
                                                 list_file,
                                                 list_case,
                                                 obj_options.str_release_folder,
                                                 flag_dedup,
                                                 test_run_id)

    if obj_options.str_task != '':
        str_task_file = obj_options.str_task
        
    if str_task_file == '':
        Env.log('ERROR', 'Command invalid, please check the arguments')
        return 
        
    obj_TE = TestExecutor.CTestExecutor(str_task_file)
    if not obj_TE.is_valid():
        Env.log('INFO', 'Task file(%s) invalid' % str_task_file)
        return

    obj_TE.create_logger(obj_TE.task_id())

    obj_TE.run()
    
    now = time.clock()
    while True:
        # exit if all the queued emails are sent
        if Env.obj_email_server.is_idle():
            break
        # quit when the 10 min timer expired
        if time.clock() - now > 600:
            break
        time.sleep(0.01)
    
    Env.log('INFO', 'Puffer quits')
Esempio n. 45
0
    parse_options()

    build_puffer_main_logger(obj_options.str_alias)
    
    Env.log('INFO', 'Puffer %s Running' % Env.str_version)

    try:
        load_environment()
    except Exception, e:
        Env.log('ERROR', 'Fail to load test environment')
        import traceback
        print traceback.format_exc()
        return
    
    if obj_options.b_start_email:
        Env.start_email_server()
        
    Env.b_update_enclosure_before_test = obj_options.b_update_before_test

    run_in_command_line_mode()
        
    os.chdir(Env.str_original_cwd)
    
def parse_options(): 
    global obj_options
       
    usage = 'usage: %prog [option]'
    
    parser = OptionParser(usage=usage)

    # general options
Esempio n. 46
0
def execute_case(str_case_name, str_work_directory = '', str_enclosure_id = '', str_release_folder = ''):    
    global dict_ID_case
        
    # Add support for case id
    Env.refresh_case_pool()
    if dict_ID_case.has_key(str_case_name):
        str_case_name = dict_ID_case[str_case_name]
    if dict_ID_case.values().count(str_case_name) == 0:
        Env.log('INFO', 'Case(%s) not found' % str_case_name)
        return None
    
    # get enclosure
    if str_enclosure_id == '':
        obj_enclosure = Env.dict_ID_enclosure.values()[0]
    elif Env.dict_ID_enclosure.has_key(str_enclosure_id):
        obj_enclosure = Env.dict_ID_enclosure[str_enclosure_id]
    else:
        Env.log('ERROR', 'Enclosure(%s) not found, exit' % str_enclosure_id)
        return None
    
    # get release
    obj_release = parse_fw_release(str_release_folder, obj_enclosure.str_platform)        
    
    Env.log('INFO', 'Executing case(%s) on enclosure(%s) with release(%s)' % (str_case_name, \
                                                                           obj_enclosure.str_enclosure_id,\
                                                                           str_release_folder))
    
    # create XML node
    str_xmlnode_case = '''
    <case>
        <script_name></script_name>
        <case_id></case_id>
        <status></status>
        <result />
        <error_code />
        <tested_on />
        <start_time />
        <complete_time />
        <duration_time />
    </case>
    '''
    obj_xmlnode_case = ET.fromstring(str_xmlnode_case)
    obj_xmlnode_case.find('script_name').text = str_case_name
    obj_xmlnode_case.find('status').text = 'ongoing'
    obj_xmlnode_case.find('case_id').text = str(uuid.uuid1(clock_seq=int(time.strftime('%Y%m%d%H%M%S'),10)))
    
    # import and update case object
    obj_case = import_case(str_case_name)
    if obj_case == None:
        return None
    
    if str_work_directory == '':
        if obj_options.str_alias == '':
            str_work_directory = os.path.join('temp', time.strftime('%Y%m%d%H%M%S'))
        else:
            str_work_directory = os.path.join('temp', \
                                              '_'.join([time.strftime('%Y%m%d%H%M%S'), obj_options.str_alias]))
            
    obj_case.str_work_directory = os.path.join(str_work_directory, \
                                               ''.join([obj_xmlnode_case.find('script_name').text[1:5],\
                                                        '_',\
                                                       obj_xmlnode_case.find('case_id').text]))
    if not os.path.isdir(obj_case.str_work_directory):
        os.makedirs(obj_case.str_work_directory)
    obj_case.enclosure = obj_enclosure
    obj_case.obj_xmlnode_case = obj_xmlnode_case
    if obj_release != None:
        Env.log('INFO', 'Copy release to work directory: %s' % str_work_directory)
        obj_release.copy_to(str_work_directory)
        Env.log('INFO', 'Unzip image package')
        obj_release.unzip_image_package()
        obj_case.obj_release = obj_release
    obj_case.validate()
    if not obj_case.b_valid:
        Env.log('ERROR', 'Case(%s) invalid:%s' % (str_case_name, obj_case.str_error_code))
        obj_xmlnode_case.find('status').text = 'completed'
        obj_xmlnode_case.find('error_code').text = obj_case.str_error_code
        obj_xmlnode_case.find('result').text = 'skip'
        return obj_xmlnode_case
        
    # run case
    obj_case.run()
    
    Env.log('INFO', 'Case(%s) on enclosure(%s) completed, logs available at:%s' % (str_case_name,\
                                                                                obj_enclosure.str_enclosure_id,\
                                                                                obj_case.str_work_directory))
    
    return obj_xmlnode_case
Esempio n. 47
0
def run_in_command_line_mode():
    '''
    main entry point for ATOM command line mode.
    '''
    global obj_options
    
    Env.log('INFO', 'ATOM Command Line Mode:%s' % ' '.join(sys.argv))
    
    '''
    list_case contains 3 part:
        1. loose case
        2. content of test list file
        3. test suite
        folders are expended and checked in TestManager.py/parse_case_list()
    '''
    list_case = []
    str_work_directory = ''
    #whether to remove duplicated cases in the task;
    #determined by --dedub.
    flag_dedup=obj_options.dedup
    flag_upload=obj_options.flag_upload
    test_run_id=obj_options.test_run_id

    #test suite: folder.
    test_suite=obj_options.test_suite
    if test_suite:
        msg='Include cases in test suite(%s) into task file'%test_suite
        Env.log('INFO', msg)
        list_case+=test_suite.split(',')

    #test list file
    list_file=obj_options.str_case_list
    if list_file:
        msg='Include cases in list file(%s) into task file'%list_file
        Env.log('INFO', msg)
        #parse the file and add to list_case
        if not os.path.isfile(list_file):
            Env.log('WARNING', 'Case list file(%s) not found'%list_file)
        else:
            lines = open(list_file,'r').read().splitlines()
            for i in lines:
                if i.startswith('#' or '/'):
                    #commented out. ignore.
                    continue
                list_case.append(i.strip())

    #loose test cases
    if obj_options.str_cases:
        Env.log('INFO', 'Included cases(%s) into task file' % obj_options.str_cases)
        list_case+=obj_options.str_cases.split(',')

    if obj_options.str_enclosure_id != '':
        list_enclosure_id = obj_options.str_enclosure_id.split(',')
        list_target_enclosures = []
        for each_enclosure in list_enclosure_id:
            if Env.dict_ID_enclosure.has_key(each_enclosure):
                list_target_enclosures.append(each_enclosure)
    elif obj_options.str_platform != '':
        list_target_enclosures = Env.get_all_enclosure_id(obj_options.str_platform)
    else:
        list_target_enclosures = []
            
    if list_target_enclosures == []:
        Env.log('ERROR', 'No DUT information')
        return
    
    str_platform = Env.get_enclosure(list_target_enclosures[0]).platform()
    
    #alias: datetime+given name.
    test_run_alias=time.strftime('%Y%m%d%H%M%S')
    if obj_options.str_alias != '':
        if '\\' in obj_options.str_alias:
            obj_options.str_alias = obj_options.str_alias.replace('\\','_')
        test_run_alias += '_%s' % obj_options.str_alias

    str_work_directory = os.path.join(Env.str_log_folder, \
                                      str_platform, \
                                      test_run_alias)
    Env.log('INFO', 'Logs are available at: %s' % str_work_directory)
    
    #check test result uploading setting

    if test_run_id:
        #test_run_id is provided but --upload is not:
        #shall we use the id or just ignore it?
        #use the id first.
        flag_upload=True

    if flag_upload:
        testrail=TestRailClient()

        if test_run_id:
            # test run id provided. validate it
            try:
                testrail.get_test_run(test_run_id)
                msg='Test result will be uploaded to test run %d'%test_run_id
                Env.log('INFO', msg)
            except:
                Env.log('ERROR', traceback.format_exc())
                raise Exception('Invalid test run id: %d'%test_run_id)
        else:
            '''
            need to create a new test run.
            set include_all so the test scope remains the same.
            '''
            test_run_name='ATOM_%s_%s'%(str_platform, test_run_alias)
            PROJECT_FFV=1
            TEST_SUITE_ATOM=13
            ret=testrail.add_test_run(PROJECT_FFV, test_run_name, [], TEST_SUITE_ATOM)
            Env.log('INFO', 'new test run %s created.'%test_run_name)
            test_run_id=ret['id']

    str_task_file = TestManager.create_task_file(str_platform, \
                                                 str_work_directory, \
                                                 list_file, \
                                                 list_case, \
                                                 obj_options.str_release_folder, \
                                                 list_target_enclosures, \
                                                 flag_dedup, \
                                                 test_run_id)
    if obj_options.str_task != '':
        str_task_file = obj_options.str_task
        
    if str_task_file == '':
        Env.log('ERROR', 'Command invalid, please check the arguments')
        return 
        
    obj_TE = TestExecutor.CTestExecutor(str_task_file)
    if not obj_TE.is_valid():
        Env.log('INFO', 'Task file(%s) invalid' % str_task_file)
        return

    obj_TE.create_logger(obj_TE.task_id())
    
    obj_TE.run()
    
    now = time.clock()
    while True:
        # exit if all the queued emails are sent
        if Env.obj_email_server.is_idle():
            break
        # quit when the 10 min timer expired
        if time.clock() - now > 600:
            break
        time.sleep(0.01)
    
    Env.log('INFO', 'ATOM quit command line mode')
Esempio n. 48
0
from __future__ import division
#from ..Settings import MAX_CHANNELS
from SCLang import *
from SynthDef import SynthDef
import Env

# TODO - check this!!!
NUM_CHANNELS = MAX_CHANNELS = 1

# Sample Player

with SynthDef("play") as play:
    play.defaults.update(room=0.1 ,rate=1, bitcrush=24)
    play.rate = play.scrub * LFPar.kr(play.scrub / 4) + play.rate - play.scrub
    play.osc  = PlayBuf.ar(NUM_CHANNELS, play.buf, BufRateScale.ir(play.buf) * play.rate)
    play.osc  = play.osc * Env.ramp(amp=[1,1,0], sus=[play.sus * 2,0], doneAction=0) * play.amp * 3
    play.env  = Env.ramp(sus=2)

# Synth Players

with SynthDef("pads") as pads:
    pads.amp = pads.amp / 2
    pads.osc = SinOsc.ar([pads.freq, pads.freq + 2], mul=pads.amp)
    pads.env = Env.perc()

noise = SynthDef("noise")
noise.osc = LFNoise0.ar(noise.freq, noise.amp)
noise.env = Env.env()
noise.add()

with SynthDef("dab") as synth:
Esempio n. 49
0
    def generate_junit_report(self):
        self.log('INFO', 'Create Junit report for %s' % self.str_task_ID)
        str_junit_report = os.path.join(self.str_work_directory, 'junit_%s.xml' % self.str_task_ID)
        list_cases = []
        for xmlnode_case in self.list_xmlnode_case:
            # name
            str_case_name = xmlnode_case.find('script_name').text
            str_case_name = Env.get_case(str_case_name)
            str_package_name=str_case_name.replace(os.sep, '.')
            str_case_name=os.path.basename(str_case_name)
            if not str_case_name:
                self.log('WARNING', 'Case(%s) not included in JUnit report. It is not found' % str_case_name)
                continue

            # status check
            str_status = xmlnode_case.find('status').text
            if str_status != 'completed':
                self.log('WARNING', 'Case(%s) not included in JUnit report. It is not completed' % str_case_name)
                continue

            # duration
            try:
                str_duration = xmlnode_case.find('duration_time').text
                list_h_m_s = str_duration.split(':')
                int_hour = int(list_h_m_s[0], 10)
                int_minute = int(list_h_m_s[1], 10)
                int_second = int(list_h_m_s[2], 10)
                int_duration = 3600*int_hour + 60*int_minute + int_second
            except:
                int_duration = None

            # create TestCase object
            junit_test_case = JUnit.TestCase(name = str_case_name,\
                                             classname = str_package_name,\
                                             elapsed_sec=int_duration)
            # result update
            str_result = xmlnode_case.find('result').text
            str_error_code = xmlnode_case.find('error_code').text
            if str_result in ['fail', 'block']:
                junit_test_case.add_failure_info(failuretype=str_result,\
                                                 message = str_error_code)
            elif str_result == 'error':
                junit_test_case.add_error_info(errortype=str_result, message=str_error_code)
            elif str_result == 'skip':
                junit_test_case.add_skipped_info(message=str_error_code)
            elif str_result != 'pass':
                self.log('WARNING', 'Case(%s) not included in JUnit report. Result(%s) not recognized' % (str_case_name,\
                                                                                                      str_result))
                continue
            list_cases.append(junit_test_case)

        # generate TestSuites
        junit_test_suite = JUnit.TestSuite(name='puffer',\
                                           test_cases=list_cases,\
                                           timestamp=self.time_start)

        # generate Junit report
        try:
            JUnit.TestSuite.to_file(str_junit_report, [junit_test_suite,])
        except:
            self.log('WARNING', 'Failed to generate Junit report for %s: %s' % (self.str_task_ID,\
                                                                                traceback.format_exc()))
        else:
            self.log('INFO', 'JUnit report generated for %s' % self.str_task_ID)
Esempio n. 50
0
def load_environment():
    
    Env.refresh_case_pool()
    
    Env.log('INFO', 'Load the system configuration for config file')
    Env.obj_config_manager = ConfigManager.CConfigManager(Env.str_config_file)
    Env.obj_config_manager.set_logger(Env.atom_logger.obj_logger)
    Env.obj_config_manager.parse_configuration()
    Env.log('INFO', 'Done loading the system configuration for config file')
    
    # source folder
    Env.log('INFO', 'Parse the source folder information')
    Env.str_source_folder = Env.obj_config_manager.get_source_folder()
    if Env.str_source_folder == '':
        Env.log('WARNING', 'Default source folder not set or cannot be accessed.')
    else:
        Env.log('INFO', 'Source folder: %s' % Env.str_source_folder)
    
    # enclosure info
    Env.log('INFO', 'Load enclosure information')
    list_xmlnode_enclosure = Env.obj_config_manager.get_enclosure_nodes()
    for each_xmlnode_enclosure in list_xmlnode_enclosure:
        try:
            str_platform_type = each_xmlnode_enclosure.find('platform').text.lower()
        except:
            continue
        obj_enclosure = Enclosure.CEnclosure(str_platform_type ,each_xmlnode_enclosure, None)
        #[bruce]Add the ATOM logger to the device tree. The whole process of the device building will
        #[bruce]be logeged in the ATOM logger
        # Bruce 08/03: remove the logger setting here so that the device tree building process
        #     will not be printed to console. In each case, the device tree logger will be set
        #     to the case logger
        #obj_enclosure.set_logger(Env.atom_logger.obj_logger)
        if obj_enclosure.build() != 0:
            continue
        str_enclosure_id = obj_enclosure.str_enclosure_id.lower()
        if Env.dict_ID_enclosure.has_key(str_enclosure_id):
            Env.log('ERROR', 'enclosure ID conflict: %s' % str_enclosure_id)
            time.sleep(5)
            exit()
        Env.log('INFO', 'add enclosure %s' % str_enclosure_id)
        Env.dict_ID_enclosure[str_enclosure_id] = obj_enclosure
        Env.dict_enclosureID_TMID[str_enclosure_id] = None
        if not Env.dict_platform_enclosureIDs.has_key(str_platform_type):
            Env.dict_platform_enclosureIDs[str_platform_type] = []
        Env.dict_platform_enclosureIDs[str_platform_type].append(str_enclosure_id)
    Env.list_tracked_platform_types = Env.obj_config_manager.tracked_platform_types()
    Env.log('INFO', 'Done loading enclosure information')
    
    # apc info
    Env.log('INFO', 'Load apc information')
    #global obj_apc_server
    list_xmlnode_apc = Env.obj_config_manager.get_apc_nodes()
    APC.obj_apc_server = APC.CAPCServer(list_xmlnode_apc)
    Env.log('INFO', 'Done loading apc information')
    
    # build tftp server
    Env.log('INFO', 'Load TFTP server information')
    Env.obj_tftp_server = TFTPServer.CTFTPServer(Env.obj_config_manager.get_tftp_node())
    if Env.obj_tftp_server.is_valid():
        Env.log('INFO', 'Done loading TFTP server information')
    else: 
        Env.log('WARNING', 'TFTP server invalid(%s) and service will be unavailable' % str(Env.obj_tftp_server.error()))
        
    # build email server
    Env.obj_email_server = EmailWorker.CEmailServer()
    
    Env.obj_email_server.obj_email_sender.set_SMTP_host_address(Env.str_smpt_server)
    
    try:
        list_xmlnode_notification_event = Env.obj_config_manager.get_smpt_server_node().findall('notification_event')
    except:
        Env.log('WARNING', 'Failed to get notification event configuration, email will not work')
        Env.obj_email_server = None
        return -1
    for each_notification_event in list_xmlnode_notification_event:
        Env.obj_email_server.obj_email_builder.add_template_xml(each_notification_event)
Esempio n. 51
0
def load_environment():

    global obj_options

    Env.refresh_case_pool()

    Env.log('INFO', 'Load puffer configuration ...')
    Env.obj_config_manager = ConfigManager.CConfigManager(Env.str_config_file)
    Env.obj_config_manager.set_logger(Env.puffer_logger.obj_logger)
    Env.obj_config_manager.parse_configuration()
    Env.log('INFO', 'Load puffer configuration done')

    # Configure testrail setting
    Env.log('INFO', 'Load TestRail configuration ...')
    if obj_options.test_run_id:
        dict_testrail = Env.obj_config_manager.get_testrail()
        if obj_options.testrail_root:
            Env.str_testrail_root = obj_options.testrail_root
        else:
            Env.str_testrail_root = dict_testrail.get('testrail_root', '')

        if obj_options.testrail_user and obj_options.testrail_password:
            Env.str_testrail_username = obj_options.testrail_user
            Env.str_testrail_password = obj_options.testrail_password
        else:
            if not obj_options.testrail_user and not obj_options.testrail_password:
                pass
            elif not obj_options.testrail_user:
                Env.log('WARNING', 'TestRail user is missing in options, '
                                    'please use --testrail_user to set')
            else:
                Env.log('WARNING', 'TestRail password is missing in options, '
                                    'please use --testrail_user to set')
            Env.log('INFO', 'Load TestRail authentication from conf.xml')
            Env.str_testrail_username = dict_testrail.get('username', '')
            Env.str_testrail_password = dict_testrail.get('password', '')
    Env.log('INFO', 'Load TestRail configuration done')

    # Configure test device information
    # Configure enclosure with stack_xxx.json
    if obj_options.str_stack:
        # Load stack informations
        Env.log('INFO', 'Load stack information...')
        Env.load_stack(obj_options.str_stack)
        # Initialize stack in next commit
        Env.obj_stack = CStack(Env.dict_stack)
        Env.log('INFO', 'Load stack information done')
    else:
        Env.log('WARNING', 'No stack information provided')
    # Configure HWIMO with IP and hwimo.json
    if obj_options.str_hwimo_ip:
        # Load HWIMO informations
        Env.log('INFO', 'Load HWIMO information...')
        Env.load_hwimo(obj_options.str_hwimo_ip,
                       obj_options.str_hwimo_username,
                       obj_options.str_hwimo_password)
        Env.obj_hwimo = CMonorail(Env.dict_hwimo)
        Env.log('INFO', 'Load HWIMO information done')
    else:
        Env.log('WARNING', 'No HWIMO information provided')

    if obj_options.str_stack or obj_options.str_hwimo_ip:
        pass
    else:
        Env.log('WARNING', 'Both stack and HWIMO information are missing')

    # Configure email server
    try:
        obj_mail_node = Env.obj_config_manager.get_smpt_server_node()

        # Parse information
        Env.str_smtp_server = obj_mail_node.find('server').text
        str_mail_from_address = obj_mail_node.find('from_address').text
        str_mail_from_name = obj_mail_node.find('from_name').text
        Env.str_mail_from = '"{}" <{}>'.format(str_mail_from_name, str_mail_from_address)
        if str_mail_from_address:
            EmailWorker.set_default_from_address(Env.str_mail_from)

        # Build mail server
        Env.obj_email_server = EmailWorker.CEmailServer()
        Env.obj_email_server.obj_email_sender.set_SMTP_host_address(Env.str_smtp_server)
    except:
        import traceback
        print traceback.format_exc()
        Env.log('WARNING', 'Fail to get mail configuration, email will not work')
        return -1
    try:
        list_xmlnode_notification_event = obj_mail_node.findall('notification_event')
    except:
        Env.log('WARNING', 'Failed to get notification event configuration, email will not work')
        Env.obj_email_server = None
        return -1

    for each_notification_event in list_xmlnode_notification_event:
        Env.obj_email_server.obj_email_builder.add_template_xml(each_notification_event)

    # Get puffer root for remote access to log file
    Env.str_puffer_remote_root = Env.obj_config_manager.get_puffer_root()
Esempio n. 52
0
File: x4ga.py Progetto: ziomar/X4GA
        app.splash.Destroy()
    import wx
    import awc.util as awu
    awu.MsgDialog(None, 
                  """X4 necessita di una licenza d'uso per funzionare """
                  """correttamente.\nImpossibile proseguire in mancanza """
                  """delle informazioni richieste.""",
                  style=wx.ICON_WARNING)
    import os
    os.sys.exit()

#aggancio plugins
if hasattr(sys, 'frozen'):
    plugins = Env.plugins
    #carico plugins
    files = glob.glob(Env.opj(Env.plugin_base_path, '*.zip'))
    files.sort()
    for file in files:
        file = file.replace('\\','/')
        n = file.rindex('/')
        name = file[n+1:-4]
        n2i = name
        if not n2i.endswith('_plugin'):
            n2i += '_plugin'
        try:
            #aggancio plugin
            m = __import__(n2i)
            if hasattr(m, 'TabStru'):
                m.TabStru(Env.Azienda.BaseTab)
        except ImportError, e:
            print 'import fallito di %s: %s' % (name, repr(e.args))
Esempio n. 53
0
def _create_tm_for_all_tracking_platforms():
    Env.log('INFO', 'create TM for each platform')
    for each_platform_type in Env.list_tracked_platform_types:
        _create_tm_for_platform(each_platform_type)