예제 #1
0
def sys_init():
    # sys log init
    global LOG
    LOG = MyLogger(os.path.abspath(sys.argv[0]).replace(
        'py', 'log'), clevel=logging.DEBUG, renable=False)
    global cprint
    cprint = cprint(os.path.abspath(sys.argv[0]).replace('py', 'log'))

    # cmd arg init
    global arg_handle
    arg_handle = ArgHandle()
    arg_handle.run()
    LOG.info("Let's go!!!")
예제 #2
0
파일: p.py 프로젝트: gx303841541/testtoolsx
def sys_init():
    global LOG
    LOG = MyLogger(os.path.abspath(sys.argv[0]).replace('py', 'log'), clevel=logging.INFO,
                   rlevel=logging.WARN)
    global cprint
    cprint = cprint(__name__)

    global arg_handle
    arg_handle = ArgHandle()
    arg_handle.run()

    global thread_list
    thread_list = []
    LOG.info("Let's go!!!")
예제 #3
0
class Task():
    def __init__(self, name='default-task', logger=None):
        self.tasks = {}
        self.lock = threading.RLock()
        if logger:
            self.LOG = logger
        else:
            self.LOG = MyLogger(name + '.log', clevel=logging.DEBUG)
        self.need_stop = False

    def stop(self):
        self.need_stop = True
        self.LOG.warn('Thread %s stoped!' % (__name__))

    def add_task(self, name, func, run_times=1, interval=5, *argv):
        self.lock.acquire()
        if name and func and int(run_times) >= 1 and int(interval) >= 1:
            pass
        else:
            self.LOG.error("Invalid task: %s, run_times: %d, internal: %d" %
                           (name, int(run_times), int(interval)))
        self.LOG.info("To add task: %s, run_times: %d, internal: %d" %
                      (name, int(run_times), int(interval)))
        self.tasks[name] = {
            'func': func,
            'run_times': int(run_times),
            'interval': int(interval),
            'now_seconds': 0,
            'argv': argv,
            'state': 'active',
            'name': name
        }
        self.lock.release()

    def del_task(self, name):
        self.lock.acquire()
        self.LOG.warn("To delete task:%s" % (name))
        if name in self.tasks:
            del self.tasks[name]
        self.lock.release()

    def show_tasks(self):
        if self.tasks:
            for task in self.tasks:
                self.LOG.info(task + ":")
                for item in sorted(self.tasks[task]):
                    self.LOG.yinfo("    " + item.ljust(20) + ':' +
                                   str(self.tasks[task][item]).rjust(20))
        else:
            self.LOG.warn("No task...")

    def task_proc(self):
        while self.need_stop == False:
            if len(self.tasks) == 0:
                self.LOG.debug("No task!\n")
            '''
            for task in self.tasks:
                if self.tasks[task]['state'] == 'inactive':
                    self.del_task(task)
            '''
            try:
                self.lock.acquire()
                for task in self.tasks:
                    if self.tasks[task]['state'] != 'active':
                        continue
                    self.tasks[task]['now_seconds'] += 1
                    if self.tasks[task]['now_seconds'] >= self.tasks[task][
                            'interval']:
                        if callable(self.tasks[task]['func']):
                            # self.LOG.info("It is time to run %s: " % (
                            #    task) + self.tasks[task]['func'].__name__ + str(self.tasks[task]['argv']))
                            self.tasks[task]['func'](
                                *(self.tasks[task]['argv']))
                        elif callable(eval(self.tasks[task]['func'])):
                            # self.LOG.info("It is time to run %s: " % (
                            #    task) + self.tasks[task]['func'] + str(self.tasks[task]['argv']))
                            eval(self.tasks[task]['func'] + '(*' +
                                 str(self.tasks[task]['argv']) + ')')
                        else:
                            self.LOG.error(
                                "Uncallable task: %s, will disable it!")
                            self.tasks[task]['state'] = 'inactive'
                        self.tasks[task]['now_seconds'] = 0
                        self.tasks[task]['run_times'] -= 1
                        if self.tasks[task]['run_times'] == 0:
                            self.LOG.info("stop task:%s" % (task))
                            self.tasks[task]['state'] = 'inactive'
                    else:
                        pass
                self.lock.release()
                time.sleep(0.1)

            except RuntimeError:
                pass
예제 #4
0
        (arg_handle.get_args('server_IP'), arg_handle.get_args('server_port')),
        logger=LOG)
    thread_list.append([app.schedule_loop])
    thread_list.append([app.send_data_loop])
    thread_list.append([app.recv_data_loop])

    # run threads
    sys_proc()

    try:
        while app.connection.get_connected() != True:
            pass
        msg = login_router(
            arg_handle.get_args('router_username'),
            common_APIs.get_md5(arg_handle.get_args('router_password')))
        LOG.info("To login router: " + msg.strip())
        app.queue_out.put(msg)
        time.sleep(1)

        if arg_handle.get_args('device_type') == 'debug':
            for i in range(arg_handle.get_args('number_to_send')):
                j = 100000
                req_id = i + 11000000
                for uuid in uuids:
                    req_id += j
                    j += 1
                    msg = debug(req_id, uuid)
                    app.msgst[req_id]['send_time'] = datetime.datetime.now()
                    app.queue_out.put(msg)
                    LOG.info("send: " + msg.strip())
                    time.sleep(arg_handle.get_args('t2') / 1000.0)
예제 #5
0
class TestCase(object):
    __metaclass__ = ABCMeta

    def _init_(self, name, log_dir):
        self.name = name
        self.log_dir = log_dir
        self.log_dir += os.path.sep + datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + \
            '-' + self.name + os.path.sep
        self.log_dir = common_APIs.dirit(self.log_dir)
        try:
            os.mkdir(self.log_dir)
        except Exception as er:
            print('Can not create log dir: %s\n[[%s]]' % (
                self.log_dir, str(er)))
            sys.exit()

        # create the log obj
        self.LOG = MyLogger(self.log_dir + 'output.log',
                            cenable=True, with_print=True)

    def setup(self):
        pass

    def teardown(self):
        pass

    #@istest
    #@with_setup(setup, teardown)
    def test(self):
        self.common_init()
        result = 0
        try:
            result = self.run()
        # except Exception as e:
        #    traceback.print_exc()
        #    self.LOG.critical(str(e))
        #    assert False
        finally:
            self.common_cleanup()

    @abstractmethod
    def run(self):
        pass

    def common_init(self):
        pass

    def common_cleanup(self):
        pass

    def case_pass(self, success_info='pass'):
        self.LOG.info(success_info)
        assert True
        return True

    def case_fail(self, error_info='fail'):
        self.LOG.error(error_info)
        assert False
        return False

    def do_setup(self, config_data):
        self.LOG.info('call do_setup')
        if 'setup' in config_data:
            self.LOG.info('Maybe have data')
            setup_list = config_data['setup']
            for i in setup_list:
                for k in i:
                    self.LOG.info(k)

    def do_run(self, config_data):
        self.LOG.info('call core')

    def do_teardown(self, config_data):
        self.LOG.info('call do_teardown')
예제 #6
0
    i = 0
    rs = []
    for pic in all_pics * 10:
        if i >= arg_handle.get_args('count'):
            break
        LOG.debug('create info for pic: %s' % pic)
        r = copy.deepcopy(msg)
        with open(picpath + os.path.sep + pic, "rb") as f:
            pic_str = base64.b64encode(f.read()).decode('utf-8')
        pic_type = 'jpeg'
        id = '%04d' % i
        r["name"] = "小狗狗" + id
        r["idenNum"] = "21122319850606" + id
        r["phone"] = "1888885" + id
        r["fileName"] = r["name"] + '.jpg'
        r["facePicBase64"] = "data:image/" + \
            pic_type + ';base64,' + pic_str
        r["fingerCode1"] = fingerCode_list[random.randint(
            0, len(fingerCode_list) - 1)]
        i += 1
        rs.append(r)
        LOG.warn('name: %s, picname: %s, fingerCode1: %s' %
                 (r["name"], pic, r["fingerCode1"]))

    update_token()
    for r in rs:
        LOG.info('Insert user: %s' % r["name"])
        send(url='http://%s:%s/scp-mdmapp/user/insertUser' % (arg_handle.get_args('server_IP'), arg_handle.get_args('server_port')),
             method='POST', payload=r)
        time.sleep(0.05)