Esempio n. 1
0
 def get_val(col, json_key, values):
     """Map the DB column to key in request JSON and get its value. Do a
     dump if column is of JSON type. Finds key in nested dictionaries."""
     try:
         values = values[json_key]
     except KeyError:
         key_chain = json_key.split('.')
         for _key in key_chain:
             values = values[_key]
     if strict and hasattr(col, 'read_only') and values:
         logger.info('Skipping field %s as it is read-only', col)
         return None
     if hasattr(col, 'is_json'):
         return json.dumps({json_key: values})
     if not values:
         return
     if isinstance(col.type, DateTime):
         return datetime.strptime(values, DATETIME_FORMAT)
     if isinstance(col.type, Date):
         try:
             values = datetime.strptime(values, DATE_FORMAT)
         except (TypeError, ValueError):
             try:
                 values = datetime.strptime(values, DATETIME_FORMAT)
             except (TypeError, ValueError):
                 logger.error("Unable to convert data to timestamp")
                 logger.error(traceback.format_exc())
                 return None
     return values
Esempio n. 2
0
def run_case(devices, poco):
    logger.info("{}进入unittest".format(devices))
    package = Madb(devices).get_packagename()

    class TC102(unittest.TestCase):
        u'''添加好友'''
        @classmethod
        def setUpClass(cls):
            """ 这里放需要在所有用例执行前执行的部分"""
            wake()

        def setUp(self):
            """这里放需要在每条用例前执行的部分"""
            start_app(package)
            sleep(2)

        def test_demo2(self):
            """此处添加用例描述"""
            poco(text='手机号登录').click()

        def tearDown(self):
            """这里放需要在每条用例后执行的部分"""
            sleep(5)
            stop_app(package)

        # @classmethod
        # def tearDownClass(cls):
        #     u"""这里放需要在所有用例后执行的部分"""
        #     stop_app("com.qywlandroid")
        #     sleep(1)

    srcSuite = unittest.TestLoader().loadTestsFromTestCase(TC102)
    # srcSuite = TC101("test_demo2")
    return srcSuite
Esempio n. 3
0
    def onModLoaded(self):
        """ Initialize the module """
        self.track     = None   # Current track
        self.status    = ''     # The currently used status
        self.paused    = False  # True if the current track is paused
        self.clients   = []     # Clients currently active
        self.cfgWindow = None   # Configuration window

        # Detect active clients
        try:
            import dbus

            session        = dbus.SessionBus()
            activeServices = session.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus').ListNames()
            for activeClient in [client for client in CLIENTS if client[IM_DBUS_SERVICE_NAME] in activeServices]:
                obj       = session.get_object(activeClient[IM_DBUS_SERVICE_NAME], activeClient[IM_DBUS_OBJECT_NAME])
                interface = dbus.Interface(obj, activeClient[IM_DBUS_INTERFACE_NAME])

                activeClient[IM_INSTANCE] = activeClient[IM_CLASS](interface)
                activeClient[IM_ACCOUNTS] = activeClient[IM_INSTANCE].listAccounts()

                logger.info('[%s] Found %s instance' % (MOD_NAME, activeClient[IM_NAME]))
                self.clients.append(activeClient)
        except:
            logger.error('[%s] Error while initializing\n\n%s' % (MOD_NAME, traceback.format_exc()))
Esempio n. 4
0
def test():
    with app.app_context():
        init_db()
        g.db = db_proxy
        g.db.connect()

        import all_tests.vk.request_tests as tests

        g.db.drop_tables([Account, Subscription, Messenger, AccessToken])
        create_db()

        tests.test_start()
        tests.test_add_indox_task()
        tests.test_add_project_task(
            proj_name='Work',
            content='В Work это новая задача в проекте',
            task='это новая задача в проекте')

        tests.test_add_project_task(
            proj_name='Work',
            content='Это новая задача в проекте в Work ',
            task='Это новая задача в проекте')
        tests.test_add_forwarded_mess()
        tests.test_add_task_with_date()

        logger.info('All tests are passed!')
        return 'ok'
Esempio n. 5
0
    def ECR(self, name):
        logger.info(f"Criando o ECR: {name}")
        project_name = f'ECR{name}'
        resource_name = ''.join(e for e in project_name if e.isalnum())
        p_service = Principal("Service", "codebuild.amazonaws.com")
        p_aws = Principal("AWS", [
            Sub("arn:aws:iam::${DevAccount}:root"),
            Sub("arn:aws:iam::${HomologAccount}:root"),
            Sub("arn:aws:iam::${ProdAccount}:root")
        ])

        policydocument = PolicyDocument(Version='2008-10-17',
                                        Statement=[
                                            Statement(
                                                Sid='AllowPushPull',
                                                Effect=Allow,
                                                Principal=p_service,
                                                Action=[Action("ecr", "*")],
                                            ),
                                            Statement(
                                                Sid='AllowPushPull',
                                                Effect=Allow,
                                                Principal=p_aws,
                                                Action=[Action("ecr", "*")],
                                            ),
                                        ])
        resource_ecr = Repository(resource_name,
                                  RepositoryName=name.lower(),
                                  RepositoryPolicyText=policydocument)
        return [resource_ecr]
def calc_multiband_norm(path_dir, image_list, image_feature_norm_csv,
                        kind='RGB-PanSharpen', channel_count=3, max_sample=100):
    band_values = {k: [] for k in range(channel_count)}
    band_cut_th = {k: dict(max=0, min=0) for k in range(channel_count)}
    #  first get all data, then use first part 0:1000 to calc threshold, then update all data
    for image_id in tqdm.tqdm(image_list[:max_sample]):
        image_loc = get_image_path_based_type_imageid(path_dir, kind, image_id)
        with rasterio.open(image_loc, 'r') as f:
            values = f.read().astype(np.float32)
            for i_chan in range(channel_count):
                values_ = values[i_chan].ravel().tolist()
                values_ = np.array(
                    [v for v in values_ if v != 0]
                )  # Remove sensored mask
                band_values[i_chan].append(values_)

    logger.info("Calc percentile point for normalization")
    for i_chan in range(channel_count):
        band_values[i_chan] = np.concatenate(
            band_values[i_chan]).ravel()
        band_cut_th[i_chan]['max'] = scipy.percentile(
            band_values[i_chan], 98)
        band_cut_th[i_chan]['min'] = scipy.percentile(
            band_values[i_chan], 2)

    stat = dict()
    stat['path'] = path_dir
    for chan_i in band_cut_th.keys():
        stat['chan{}_max'.format(chan_i)] = band_cut_th[chan_i]['max']
        stat['chan{}_min'.format(chan_i)] = band_cut_th[chan_i]['min']
    pd.DataFrame(stat, index=[0]).to_csv(image_feature_norm_csv, index=False)
Esempio n. 7
0
def setParams(payload, env):
    template = payload['payload']['template']
    dynamodb_template = get_dy_template(template)
    logger.info(f"Lendo template da pipeline do dynamodb")
    pipeline_stages = dynamodb_template.get('pipeline')
    estrutura = dynamodb_template.get('structure')
    dependencias = dynamodb_template.get('depends')
    release = get_sharedlibrary_release()
    imageCustom = get_imageCustom()
    params = {}
    for param in payload['payload']['Parameter']:
        params.update(param)
    template_params = {
        'env': env,
        'runtime': payload['payload']['runtime'],
        'stages': payload['payload']['pipeline'][env],
        'account': payload['account'],
        'pipeline_stages': pipeline_stages,
        'params': params,
        'release': release,
        'imageCustom': imageCustom,
        'type': template,
        'structure': estrutura,
        'depends': dependencias
    }
    logger.info(f'Parametros definidos para criacao do template')
    return template_params
    def change_item_count_in_cart(self, orderItem: OrderItem):
        """修改购物车商品的数量
        修改购物车中商品数量后,该商品将会被自动勾选上。

        :param orderItem:商品数据对象
        :return: 商品数量修改结果 True/False
        """
        url = "https://wq.jd.com/deal/mshopcart/modifycmdynum"
        # 选择item提交
        payload = {
            "commlist":
            f"{orderItem.pid},,{orderItem.count},{orderItem.pid},11,{orderItem.selectPromotion},0"
        }

        headers = {
            'User-Agent': self.user_agent,
            "Origin": "https://p.m.jd.com",
            "Referer": "https://p.m.jd.com/"
        }

        res = self.sess.get(url, params=payload, headers=headers)

        if res.status_code == requests.codes.OK:
            try:
                if res.json().get("errId", None) == "0":
                    logger.info("修改商品 %s 数量为 %s 成功", orderItem.pid,
                                orderItem.count)
                    return True
                logger.error(res.json().get("errMsg"))
            except Exception as e:
                logger.error(e)
                logger.error(traceback.format_exc())
        return False
    def cancel_select_all_in_cart(self):
        """取消勾选购物车中的所有商品
        :return: 取消勾选结果 True/False
        """
        logger.info(f'{time.ctime()} > 取消选择全部商品')
        url = "https://wq.jd.com/deal/mshopcart/uncheckcmdy"
        # 选择item提交
        payload = {"commlist": "", "all": 1}

        headers = {
            'User-Agent': self.user_agent,
            "Origin": "https://p.m.jd.com",
            "Referer": "https://p.m.jd.com/"
        }

        res = self.sess.post(url, data=payload, headers=headers)

        if res.status_code == requests.codes.OK:
            try:
                if res.json().get("errId", None) == "0":
                    logger.info("取消全部选择成功")
                    return True
                logger.error(res.json().get("errMsg"))
            except Exception as e:
                logger.error(e)
                logger.error(traceback.format_exc())

        logger.error("失败")
        logger.error(res.content.decode("utf8"))
        return False
Esempio n. 10
0
    def cancelOrder(self, orderId):
        """
        取消订单
        :param orderId:
        :return:
        """
        url = "https://wq.jd.com/ordercancel/cancelorder"

        payload = {
            "orderid": f"{orderId}",
            "cancelReason": "1100",
        }
        headers = {
            'User-Agent': self.user_agent,
            "Referer": "https://wqs.jd.com/"
        }

        res = self.sess.get(url, params=payload, headers=headers)

        if res.status_code == requests.codes.OK:
            try:
                res_json = demjson.decode(res.text)
                if str(res_json.get("retcode", None)) == "0":
                    order_id = res_json.get("data").get("orderid")
                    logger.info(f"取消订单成功!订单号:{order_id}")
                    return True
                logger.error(res_json.get("errMsg"))
            except Exception as e:
                logger.error(e)
                logger.error(traceback.format_exc())
        time.sleep(4)
        logger.error("提交Order失败")
        return False
Esempio n. 11
0
    def select_item_in_cart(self, orderItem: OrderItem):
        """
        在购物车选中候选商品
        :param orderItem: 候选商品
        :return:
        """
        logger.info(
            f'{time.ctime()} > 选择商品:{orderItem.pid}【{orderItem.pname}】x {orderItem.count}'
        )
        url = "https://wq.jd.com/deal/mshopcart/checkcmdy"
        # 选择item提交
        payload = {"commlist": f"{orderItem.pid},,{orderItem.count},,1,,0"}

        headers = {
            'User-Agent': self.user_agent,
            "Origin": "https://p.m.jd.com",
            "Referer": "https://p.m.jd.com/"
        }

        res = self.sess.post(url, data=payload, headers=headers)

        if res.status_code == requests.codes.OK:
            try:
                if res.json().get("errId", None) == "0":
                    logger.info("选择成功")
                    return True
            except Exception as e:
                logger.error(e)
                logger.error(traceback.format_exc())
            logger.error(res.json().get("errMsg"))
        logger.error("选择失败")
        logger.error(res.content.decode("utf8"))
        return False
Esempio n. 12
0
def debug_processing(strdata):
    print(strdata)

    data = json.loads(strdata)

    db_proxy.connect(True)
    logger.info('in processing')

    # Вконтакте в своих запросах всегда отправляет поле типа
    if 'type' not in data.keys():
        return 'not vk'

    if data['type'] == 'confirmation':
        return confirmation_token

    elif data['type'] == 'message_new' or data['type'] == 'service_reply':
        logger.info('pulled message: ' + str(data['object']))

        from tools.constants import Messenger
        data['messenger'] = str(Messenger.VK.name)

        session['bot'].reply_to_message(data)
        return 'ok'

    db_proxy.close()
    return 'ok'
Esempio n. 13
0
 def PushApk2Devices(self):
     skip_pushapk2devices = self.get_skip_pushapk2devices()
     skip_pushapk2devices = True if skip_pushapk2devices == "1" else False
     if skip_pushapk2devices:
         return "Skip"
     device = self.get_mdevice()
     skip_check_of_install = self.get_skip_check_of_install()
     skip_check_of_install = True if skip_check_of_install == "1" else False
     # 启动一个线程,执行AppInstall函数
     try:
         installThread = threading.Thread(target=self.AppInstall, args=())
         installThread.start()
         if not skip_check_of_install:
             # 如果配置上skip_check_of_install为True,则再开一个线程,执行安装权限点击操作
             logger.info(
                 "设备{},skip_check_of_install为{},开始进行安装点击权限操作".format(
                     device, skip_check_of_install))
             inputThread = threading.Thread(target=self.InputEvent, args=())
             inputThread.start()
             inputThread.join()
         else:
             logger.info("设备{},skip_check_of_install为{},不进行安装点击权限操作".format(
                 device, skip_check_of_install))
         installThread.join()
         # 从queue里获取线程函数的返回值
         result = q.get()
         if result == "Install Success":
             return "Success"
         else:
             return "Fail"
     except Exception as e:
         logger.error(e)
         pass
Esempio n. 14
0
    def __init__(self):
        logger.info('StateBase.__init__()')
        self._messages = ['Простите, у меня возникли непредвиденные проблемы. '
                          'Попробуйте позже или обратитесь за помощью к сообществу ']
                        # лучше пусть будет так по дефолту, чтобы бот не молчал и дебажить легче было бы

        self._next_state = self.get_default_next_state()
Esempio n. 15
0
def query_model_during_export(db_obj, model):
    """Retrieves query for existing columns of the table modified.

     During DB setup, newly added column throw error on querying. Those
     columns need to be skipped while querying.

     Doesn't export deleted campaigns.

     Args:
        db_obj: instance of DatabaseAPI
        model: instance of DB table

    Returns:
        All the results of the query.
    """
    except_cols = list()
    tbl_name = model.__tablename__
    while True:
        try:
            rows = db_obj.db_session.query(
                *[c for c in model.__table__.c if c.name not in
                  except_cols])
            rows = rows.all()
        except (TypeError, OperationalError) as e:
            if 'Unknown database' in e.message:
                raise e
            logger.debug(e.message)
            col_name = search(r"%s\.(.+?)'" % tbl_name, e.message).group(1)
            logger.info("Skipping new column %s", col_name)
            except_cols.append(col_name)
        else:
            return rows
Esempio n. 16
0
def test():
    with app.app_context():
        init_db()
        g.db = db_proxy
        g.db.connect()

        import all_tests.server_tests as tests

        g.db.drop_tables([AdminPage, TargetGroup, UserPage, SenderPage],
                         safe=True)  # TODO delete it
        create_db()

        tests.test_add_admin()
        tests.test_add_group()
        tests.test_add_sender()

        tests.test_change_mess_count()
        tests.test_change_text()
        tests.test_run_sender()

        tests.test_consumer_reply()
        tests.test_forward_messages()

        tests.test_consumer_mess()
        tests.test_not_command_mes()

        logger.info('All all_tests are passed!')
        return 'ok'
Esempio n. 17
0
def export_table(db_obj, model):
    """Dump rows of a table as pickle file.

    Args:
        db_obj: instance of DatabaseAPI
        model: instance of DB table
    """
    tbl_name = model.__tablename__
    logger.info("Exporting %s", tbl_name)
    file_name = tbl_name + '.pickle'
    # If a column is missing from database, likely as a result of a new column
    # just added, skip that column.
    try:
        rows = query_model_during_export(db_obj, model)
    except ProgrammingError as e:
        # New Table.
        logger.error(
            'Export failed for %s. Probably new table. Confirm message: %s',
            tbl_name, e.message)
        return
    result = []
    with open(join(BACKUP_DIR, file_name), "w") as fp:
        for row in rows:
            row_dict = row._asdict()
            result.append(row_dict)
        dump(result, fp)
Esempio n. 18
0
def import_table(db_obj, model):
    """Does exactly as the name suggests"""
    tbl_name = model.__tablename__
    file_name = tbl_name + '.pickle'
    logger.info("Importing %s", tbl_name)
    try:
        now = time()
        with open(join(BACKUP_DIR, file_name)) as fp:
            rows = load(fp)
            logger.info("No. of rows: %s", len(rows))
            if not rows:
                logger.info("Nothing to import. Skipping table %s.", tbl_name)
                return
            logger.info("Inserting the rows of %s in bulk", tbl_name)
            try:
                objs = [model(**row) for row in rows]
                db_obj.bulk_insert_or_update(objs)
            except DBAPIError:
                db_obj.db_session.rollback()
                logger.error("Error while inserting rows in bulk,"
                             "now inserting sequentially")
                insert_sequential(rows, model)
            logger.info(
                'Completed in %0.3s seconds', (time() - now))
    except IOError as e:
        logger.error(
            "Importing %s failed. Probably a new table. Confirm message: %s",
            tbl_name, e.message)
Esempio n. 19
0
 def findElements(self, *loc):
     try:
         return self.driver.find_elements(*loc)
     except NoSuchElementException as e:
         nowTime = time.strftime("%Y%m%d.%H.%M.%S")
         self.driver.save_screenshot('test/screenshot/%s.jpg' % nowTime)
         logger.info('Error details :%s' % (e.args[0]))
Esempio n. 20
0
 def setUpClass(self):
     logger.info(
         '############################### NEW CASE START ###############################'
     )
     self.brotype = config['Browse_Type']
     self.url = config['dfburl']
     self.driver = OpenBrower.is_brower(self.brotype, self.url)
Esempio n. 21
0
    def get_cart_detail(self):
        """获取购物车商品详情
        通过网页h5 获取购物车
        :return: 购物车商品信息 dict
        """
        """获取购物车商品详情
                :return: 购物车商品信息 dict
                """
        logger.info(f"获取{self.username}购物车详情")
        url = "https://wq.jd.com/deal/mshopcart/checkcmdy"
        # 选择item提交
        payload = {"commlist": "1,,1,1,1,,0"}

        headers = {
            'User-Agent': self.user_agent,
            "Origin": "https://p.m.jd.com",
            "Referer": "https://p.m.jd.com/"
        }
        res = self.sess.post(url, data=payload, headers=headers)
        if res.json().get("errId", None) == "0":
            cart = res.json().get("cart")
            cart_detail = self._parse_cart(cart)
            # logger.info(cart_detail)
            return cart_detail
        logger.error(res.json().get("errMsg"))
        logger.error("失败")
        logger.error(res.content.decode("utf8"))
        return None
    def handleMsg(self, msg, params):
        """ Handle messages sent to this module """
        if msg == consts.MSG_EVT_NEW_TRACK:
            self.onNewTrack(params['track'])

        elif msg == consts.MSG_EVT_STOPPED:
            if self.paused:
                self.currTrack[TRK_UNPAUSED_TIMESTAMP] = int(time())
            self.paused = False
            self.onTrackEnded()

        elif msg == consts.MSG_EVT_PAUSED:
            self.currTrack[TRK_PLAY_TIME] += (int(time()) - self.currTrack[TRK_UNPAUSED_TIMESTAMP])
            self.paused = True

        elif msg == consts.MSG_EVT_UNPAUSED:
            self.currTrack[TRK_UNPAUSED_TIMESTAMP] = int(time())
            self.paused = False

        elif msg == consts.MSG_EVT_APP_QUIT or msg == consts.MSG_EVT_MOD_UNLOADED:
            if self.paused:
                self.currTrack[TRK_UNPAUSED_TIMESTAMP] = int(time())
            self.paused = False
            self.addToCache()
            self.saveCache()
            if self.getCacheSize() != 0:
                logger.info('[%s] %u track(s) left in cache' % (MOD_NAME, self.getCacheSize()))

        elif msg == consts.MSG_EVT_APP_STARTED or msg == consts.MSG_EVT_MOD_LOADED:
            self.init()
Esempio n. 23
0
    def getExcel(self):
        logger.info("遍历用例目录读取用例excel开始。。。。。。。。。。。。。")
        file_name_list = os.walk(test_case_path, topdown=True)
        dict = {}

        for root, dirs, file_name in file_name_list:
            try:
                for name in file_name:
                    print(os.path.join(root, name))
                    logger.info("读取用例excel中sheet开始。。。。。。。。。。。。。")
                    workbook = load_workbook(os.path.join(root, name))
                    sheet = workbook['Sheet1']

                    lists = []
                    rows_sheet = sheet.iter_rows()
                    for item in rows_sheet:
                        if item[0].value == "api":
                            continue
                        list = []
                        for col in item:
                            # logger.info("遍历每一列加入到一行测试数据。。。。。。。。。。。。。")
                            list.append(col.value)
                        lists.append(list)
                    dict[name] = lists
            except Exception as e:
                logger.error("历用例目录读取用例excel执行出错,请查看问题!原因: s%", e)
        # print(dict)

        return dict
def parse_and_save_target(path_dir, image_id_csv, image_mask_h5, image_polygon_csv):
    image_list = []
    total_image_df = pd.DataFrame()
    for csv_f in path_dir.rglob('*.csv'):
        df = pd.read_csv(csv_f)
        total_image_df = total_image_df.append(df)
        image_list.extend(df['ImageId'].tolist())

    image_list = list(set(image_list))
    # for reduce running time
    # image_list = image_list[:100]
    logger.info("image list: {}".format(image_list))
    logger.info("image list length: {}".format(len(image_list)))
    image_list_df = pd.DataFrame(columns=['id', 'ImageId'], data=[i for i in zip(range(len(image_list)), image_list)])
    image_list_df.to_csv(image_id_csv, encoding='utf-8')

    image_polygon_df = image_list_df
    image_polygon_df['ImagePolygon'] = None

    with tb.open_file(image_mask_h5, 'w') as f:
        for index, image_id in tqdm.tqdm(enumerate(image_list)):
            im_mask, im_polygon = image_mask_from_summary(total_image_df, image_id)
            atom = tb.Atom.from_dtype(im_mask.dtype)
            filters = tb.Filters(complib='blosc', complevel=9)
            ds = f.create_carray(f.root, image_id, atom, im_mask.shape,
                                 filters=filters)
            ds[:] = im_mask

            image_polygon_df.at[index, 'ImagePolygon'] = im_polygon
    image_polygon_df.to_csv(image_polygon_csv, encoding='utf-8')
    return image_list
Esempio n. 25
0
    def toReport(self):
        logger.info("开始读取unittest测试核心目录")
        dir_path = unittest_path
        logger.info("开始使用discover到测试")
        try:
            discover = unittest.defaultTestLoader.discover(dir_path, pattern="*.py")
        except Exception as e:
            logger.error("加载unittest测试类路径失败,请查看问题!原因: s%", e)
        # 报告命名加上时间格式化
        logger.info("设置报告名称格式")
        time = datetime.now()
        now = time.strftime('%Y-%m-%d %H_%M_%S')
        # 报告绝对路径
        reportname = report_path + now
        reportpath= reportname + 'result.html'
        # 打开文件,写入测试结果
        # print(reportpath)
        logger.info("执行测试用例开始。。。。。。。。。。。。。")
        try:
            with open(reportpath, 'wb') as f:
                runner = HTMLTestRunner(stream=f, verbosity=2, title='接口ddt测试报告', description='用例执行详细信息')
                runner.run(discover)

            f.close()
            # result = BeautifulReport(discover)
            # result.report(description='用例执行详细信息', filename=reportname+"result")
        except Exception as e:
            logger.error("执行测试用例执行出错,请查看问题!原因: s%", e)
        logger.info("执行测试用例结束。。。。。。。。。。。。。")
Esempio n. 26
0
def processing():
    if debug_module.getDEBUG():
        logger.info('Run in debug.')

    logger.info('in processing')

    bindata = request.data
    # logger.info('data = {0}'.format(bindata))

    data = json.loads(bindata)

    # Вконтакте в своих запросах всегда отправляет поле типа
    if 'type' not in data.keys():
        logger.info('not vk')
        return 'not vk'

    if data['type'] == 'confirmation':
        logger.info('confirmation')
        return confirmation_token

    elif data['type'] == 'message_new' or data['type'] == 'service_reply':
        logger.info('pulled message: ' + str(data['object']))

        vkbot.reply_to_message(data)
        return 'ok'

    return 'ok'
Esempio n. 27
0
def test_add_group():  # working
    pass
    # TODO refact it
    g.db.close()

    group_id = 168619478
    query = TargetGroup.select().where(TargetGroup.vkid == group_id)

    if query.exists():
        group = query.get()
        users = UserPage.get(UserPage.target_group == group)

        logger.info(users)
        users.delete_instance()
        group.delete_instance()

    debug_processing(
        '{"type": "message_new", "object": {"id": 43, "date": 1492522323, '
        '"out": 0, "user_id": 142872618, "read_state": 0, '
        '"body": "Добавь группу https://vk.com/tatbottoo"}}')

    token_url = 'https://oauth.vk.com/blank.html#access_token=dc1d9037e112722ee805ae523345b4d96d1c86c8c07a2d8f1e44810b87e0305c736f55cce523e96876045&expires_in=0&user_id=142872618'

    debug_processing(
        '{"type": "message_new", "object": {"id": 43, "date": 1492522323, '
        '"out": 0, "user_id": 142872618, "read_state": 0, '
        '"body": "' + token_url + '"}}')

    query = TargetGroup.select().where(TargetGroup.vkid == group_id)
    assertTrue(query.exists(), __name__)

    tatbottoo = query.get()
    assertEqual(tatbottoo.vkid, group_id, __name__)
Esempio n. 28
0
    def report(self,
               description,
               brand,
               version,
               jenkins_branch,
               jenkins_time,
               filename: str = None,
               report_dir='.',
               log_path=None,
               theme='theme_default',
               report_flag=True):
        """
            生成测试报告,并放在当前运行路径下
        :param report_dir: 生成report的文件存储路径
        :param filename: 生成文件的filename
        :param description: 生成文件的注释
        :param theme: 报告主题名 theme_default theme_cyan theme_candy theme_memories
        :return:
        """
        from tools.log import logger
        if log_path:
            import warnings
            message = (
                '"log_path" is deprecated, please replace with "report_dir"\n'
                "e.g. result.report(filename='测试报告_demo', description='测试报告', report_dir='report',brand='oneplus6',version= '7.0.0',jenkins_time='2019-09-26 09:02:32',jenkins_branch='0927')"
            )
            warnings.warn(message)

        if filename:
            self.filename = filename if filename.endswith(
                '.html') else filename + '.html'

        if description:
            self.title = description

        if brand:
            self.brand1 = brand

        if version:
            self.version1 = version

        if jenkins_time:
            self.jenkins_time = jenkins_time

        if jenkins_branch:
            self.jenkins_branch = jenkins_branch

        self.report_dir = os.path.abspath(report_dir)
        os.makedirs(self.report_dir, exist_ok=True)
        self.suites.run(result=self)
        self.stopTestRun(self.title, self.brand1, self.version1,
                         self.jenkins_time, self.jenkins_branch)
        if not report_flag:
            self.output_report(theme)
            text = '测试已全部完成, 可打开 {} 查看报告'.format(
                os.path.join(self.report_dir, self.filename))
            logger.info(text)
        else:
            logger.info('跳过生成测试报告')
Esempio n. 29
0
def add():
    form = request.form
    user_id = current_user_id()
    note = Weekly(form, user_id=user_id)
    Weekly.new(note)
    flash('发表文章成功', 'success')
    logger.info('add new note id<{}> title<{}>'.format(note.id, note.title))
    return redirect(url_for('index.index'))
 def onModUnloaded(self):
     """ The module has been unloaded """
     if self.paused:
         self.currTrack[TRK_UNPAUSED_TIMESTAMP] = int(time())
     self.paused = False
     self.onTrackEnded(False)
     if self.getCacheSize() != 0:
         logger.info("[%s] %u track(s) left in cache" % (MOD_NAME, self.getCacheSize()))
Esempio n. 31
0
    def post(self, url, data=None, headers=None, **kargs):
        logger.info("执行post请求开始。。。。。。。。。。。。。")
        try:

            response = requests.post(url=url, data=data, headers=headers)
        except Exception as e:
            logger.error("执行post请求出错,请查看问题!原因: s%", e)
        return response
Esempio n. 32
0
    def get(self, url, params=None, headers=None, **kargs):
        logger.info("执行get请求开始。。。。。。。。。。。。")
        try:

            response = requests.get(url=url, params=params, headers=headers)
        except Exception as e:
            logger.error("执行get请求出错,请查看问题!原因: s%", e)
        return response
Esempio n. 33
0
 def ImageCustom(self, title, imagecustom, runtime):
     logger.info(f"Verificando se existe imagem customizada: {title}")
     if title in imagecustom:
         image = imagecustom[title][runtime] if runtime in imagecustom[
             title] else imagecustom[title]['all']
     else:
         image = False
     return image
Esempio n. 34
0
    def onModLoaded(self):
        """ The module has been loaded """
        self.client = None

        try:
            from zeitgeist.client import ZeitgeistClient

            self.client = ZeitgeistClient()
        except:
            logger.info('[%s] Could not create Zeitgeist client\n\n%s' % (MOD_INFO[modules.MODINFO_NAME], traceback.format_exc()))
Esempio n. 35
0
    def onModLoaded(self):
        """ The module has been loaded """
        self.client = None

        try:
            from zeitgeist.client import ZeitgeistClient
            from zeitgeist.datamodel import Event

            self.client = ZeitgeistClient()
            if self.client.get_version() >= [0, 3, 2, 999]:
                self.client.register_data_source("Pogo", "Pogo", "Play your music",
                            [Event.new_for_values(actor="application://pogo.desktop")])
        except:
            logger.info('[%s] Could not create Zeitgeist client\n\n%s' % (MOD_INFO[modules.MODINFO_NAME], traceback.format_exc()))
    def handshake(self):
        """ Authenticate the user to the submission servers, return True if OK """
        now             = int(time())
        self.session[:] = [None, None, None]

        # Postpone or cancel this handshake?
        if self.isBanned or (now - self.lastHandshake) < self.handshakeDelay:
            return False

        # Asking for login information must be done in the GTK main loop, because a dialog box might be displayed if needed
        self.gtkExecute(self.getAuthInfo)
        if self.passwd is None:
            return False

        # Compute the authentication token
        md5Pwd   = hashlib.md5()
        md5Token = hashlib.md5()

        md5Pwd.update(self.passwd)
        md5Token.update('%s%u' % (md5Pwd.hexdigest(), now))

        # Try to forget authentication info ASAP
        token              = md5Token.hexdigest()
        self.passwd        = None
        request            = 'http://%s/?hs=true&p=%s&c=%s&v=%s&u=%s&t=%d&a=%s' % (AS_SERVER, PROTO_VER, CLI_ID, CLI_VER, self.login, now, token)
        self.lastHandshake = now

        try:
            hardFailure = False
            reply       = urlopen(request).read().strip().split('\n')

            if reply[0] == 'OK':
                self.session[:]     = reply[1:]
                self.handshakeDelay = 0
                self.nbHardFailures = 0
                logger.info('[%s] Logged into Audioscrobbler server' % MOD_NAME)

            elif reply[0] == 'BANNED':
                logger.error('[%s] This version of %s has been banned from the server' % (MOD_NAME, consts.appName))
                self.isBanned = True

            elif reply[0] == 'BADAUTH':
                logger.error('[%s] Bad authentication information' % MOD_NAME)
                return self.handshake()

            elif reply[0] == 'BADTIME':
                logger.error('[%s] Server reported that the current system time is not correct, please correct it' % MOD_NAME)
                self.isBanned = True

            else:
                hardFailure = True
                logger.error('[%s] Hard failure during handshake' % MOD_NAME)

        except:
            hardFailure = True
            logger.error('[%s] Unable to perform handshake\n\n%s' % (MOD_NAME, traceback.format_exc()))

        if hardFailure:
            if   self.handshakeDelay == 0:     self.handshakeDelay  = 1*60         # Start at 1mn
            elif self.handshakeDelay >= 64*60: self.handshakeDelay  = 120*60       # Max 120mn
            else:                              self.handshakeDelay *= 2            # Double the delay

        self.login = None

        return self.session[SESSION_ID] is not None