Пример #1
0
def test_module_load(dummy_module, tmp_module_dir):
    debug(tmp_module_dir)
    dummy_module.save()

    m = Module.load()
    assert m == dummy_module
    assert m is not dummy_module
Пример #2
0
def check_response(response: Response):
    if response.is_error:
        try:
            debug(response.json())
        except JSONDecodeError:
            pass
        response.raise_for_status()
Пример #3
0
def create_one(client, obj_path, obj, obj_get_class):
    obj_json = obj.json(exclude_unset=True)
    debug(obj_json)
    response = client.post(f'/api/{obj_path}/', data=obj_json)
    check_response(response)
    new_obj = obj_get_class.parse_obj(response.json())
    return new_obj
Пример #4
0
def _check_invoice_blockchain_state(client,
                                    invoice_uid: str,
                                    expected_state: str = None):
    invoice = get_invoice_blockchain_state(client, invoice_uid)
    debug(invoice)
    if expected_state:
        assert invoice.state == expected_state
Пример #5
0
def test_json_with_quote_escape():
    curl = (
        'curl --url http://localhost:3000/posts -H "Content-Type: application/json;charset=UTF-8" '
        r'-d "{\"title\":\"murat\",\"author\":\"öner\"}"')
    httpie = curl_to_httpie(curl).httpie
    debug(httpie)
    assert httpie == "http localhost:3000/posts title=murat author='öner'"
Пример #6
0
    async def initial(
        self,
        bot: GroupCommonBot,
        chain: MessageChain,
        sender: Sender,
        context: Dict,
        messageQueue: List[UserMessage],
        **kwargs,
    ):
        try:
            match = re.search(r".*?(\S*)", chain.pure_text)
            if not match or not len(match.groups()) >= 1:

                raise Exception()

            for part in match.groups():
                if not part:
                    raise Exception()

            debug(match.groups())

            await bot.group_msg(Text(f"成功解析参数 城市{match.groups()[0]}"))

        except:
            await bot.group_msg(Text("请按照 /查询装备 城市 的格式输入"))

        return self.initial
Пример #7
0
def ansi_to_html(ansi):
    lines = []

    def add_line(line_):
        line_ = replace_ansi(line_)

        # convert table borders to a funky colour, will this mess up with just pipe operators?
        line_ = re.sub('([┌┬┐└┴┘├┼┤─│]+)',
                       r'<span class="table-line">\1</span>', line_)

        for indent in range(20, 0, -1):
            regex = re.compile('^ {%s}' % (7 + indent))
            if regex.search(line_):
                lines.append(
                    f'<div class="indent-{indent}">{regex.sub("", line_)}</div>'
                )
                return
        if seven_spaces.search(line_):
            # normal line
            lines.append(seven_spaces.sub('', line_ + '\n'))
        elif three_spaces.search(line_):
            lines.append(f'<h4>{three_spaces.sub("", line_)}</h4>')
        else:
            # line is weird and has non standard indent, could use and h4 here?
            lines.append(f'<div class="dedent">{line_}</div>')

    in_para = False
    in_section = False
    for line in ansi.split('\n')[1:-2]:
        if heading.search(line):
            if in_para:
                lines.append('</pre>\n')
                in_para = False
            if in_section:
                lines.append('</section>\n\n')
            h = heading.sub(r'\1', line)
            lines.append(f'<h3>{strip_ansi(h)}</h3>\n<section>\n')
            in_section = True
        elif line == '':
            if in_para:
                lines.append('</pre>\n')
                in_para = False
        else:
            if not in_para:
                lines.append('<pre class="c">')
                in_para = True
            add_line(line)

    if in_section:
        lines.append('</section>\n')
    html = ''.join(lines)

    m = ansi_re.search(html)
    if m:
        debug(html[m.start() - 100:m.end() + 100])
        raise RuntimeError('ansi strings found in html')
    html = template.replace('{{html}}', html)
    styles = '\n'.join(f'.indent-{v} {{margin-left: {v/2:0.1f}rem;}}'
                       for v in range(1, 21))
    return html.replace('{{styles}}', styles)
Пример #8
0
async def create_cast(payload: CastIn):
    cast_id = await service.create_cast(payload)

    response = {'id': cast_id, **payload.dict()}

    debug(response)
    return response
Пример #9
0
 async def get(self, event_name:str, version:int,dbname:str) -> Table:
     table_key = "{name}/{version}".format(name=event_name,version=version)
     if table_key in self.tables:
         return self.tables[table_key]
     name = urllib.parse.quote(event_name) 
     meta_url =   "http://{host}:{port}/api/meta/events/?name={name}&version={version}".format(
         host=self.meta['host'],
         port=self.meta['port'],
         name=name,
         version = version)
     debug(meta_url)    
     async with aiohttp.ClientSession() as session:
         async with session.get(meta_url) as resp:
             status_code = resp.status
             if status_code == 404:
                 logger.error("event {name} has no metatable".format(name=event_name))
                 return 
             data = await resp.text()
             
             data = json.loads(data)
             data = data['data']
             debug(data)
             event_id = data['id']
             meta = data['meta']
             table = Table.read_avro(meta,dbname,version)
             self.tables[table_key] = table
             return table
Пример #10
0
 def wrapped_debug(element, description: Optional[str] = None) -> None:
     if Helpers.should_debug:
         print(f"\n{Helpers.separator}\n")
         if description:
             print(f"{description}\n")
         debug(element)
         print(f"\n{Helpers.separator}\n")
Пример #11
0
 async def onebot_group_message(
     self,
     bot: OnebotV11GroupBot,
     chain: MessageChain,
 ):
     debug("in group_message")
     debug(bot)
Пример #12
0
def test_multi_line():
    curl = (
        """curl -X POST \\\nhttp://172.16.0.19/api/access-cards/2392919198/call-elevator \\\n-H 'Accept: */*' """
        """\\\n-H 'Accept-Encoding: gzip, deflate' \\\n-H 'Authorization: """
        """Basic dXNlcjp4eHg=' \\\n-H 'Cache-Control: no-cache' """
        """\\\n-H 'Connection: keep-alive' \\\n-H 'Content-Length: 407' \\\n"""
        """-H 'Content-Type: multipart/form-data; boundary=--------------------------539724411903816199149731' """
        """\\\n-H 'Host: 172.16.0.19' \\\n-H 'Postman-Token: 24e4f6f7' \\\n"""
        """-H 'User-Agent: PostmanRuntime/7.19.0' """
        """\\\n-H 'cache-control: no-cache' \\\n-H 'content-type: multipart/form-data; """
        """boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \\\n"""
        """-F boarding_floor=1 \\\n-F destination_floor=9 \\\n-F elevator_bank_number=3"""
    )
    httpie = curl_to_httpie(curl).httpie
    debug(httpie)
    assert httpie == (
        """http -fa user:xxx 172.16.0.19/api/access-cards/2392919198/call-elevator """
        """Accept:'*/*' Accept-Encoding:'gzip, deflate' Cache-Control:no-cache """
        """Connection:keep-alive Content-Length:407 """
        """Content-Type:'multipart/form-data; """
        """boundary=--------------------------539724411903816199149731' """
        """Host:172.16.0.19 Postman-Token:24e4f6f7 User-Agent:PostmanRuntime/7.19.0 """
        """cache-control:no-cache content-type:'multipart/form-data; """
        """boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' """
        """boarding_floor=1 destination_floor=9 elevator_bank_number=3""")
Пример #13
0
def test_curl_form_data_multi_mixed():
    cmline = "-d name=admin -d shoesize=12 -d color=green&food=wet http://quan.hoabinh.vn"
    args = parsed_args(cmline)
    assert args.data == ['name=admin', 'shoesize=12', 'color=green&food=wet']
    debug(args._data)
    assert tuple(args._data) == (('name', 'admin'), ('shoesize', '12'),
                                 ('color', 'green'), ('food', 'wet'))
Пример #14
0
def test_return_args(capsys):
    assert debug('foo') == 'foo'
    assert debug('foo', 'bar') == ('foo', 'bar')
    assert debug('foo', 'bar', spam=123) == ('foo', 'bar', {'spam': 123})
    assert debug(spam=123) == ({'spam': 123}, )
    stdout, stderr = capsys.readouterr()
    print(stdout)
Пример #15
0
 def _process(self, event):
     """Handle CLOSE_WRITE"""
     debug(event)
     try:
         self.__handler(event)
     except Exception as exc:  # pylint: disable=broad-except
         self.__error_handler(exc)
Пример #16
0
def invoice_register(c):
    w3 = create_w3()
    contract = create_invoice_registry(w3)
    owner_key = os.getenv('chainvoice_qadmin_private_key')
    owner = Account.from_key(owner_key)
    debug(w3.eth.getBalance(owner.address))
    other_address = os.getenv('chainvoice_other_address')
    debug(owner.address)
    debug(other_address)
    invoice_id = uuid4().int
    token_id = 1
    invoice_amount = 1000
    contract_call = contract.contract.functions.registerInvoice1(
        invoice_id, other_address, token_id, invoice_amount)
    nonce = w3.eth.getTransactionCount(owner.address)
    txn = contract_call.buildTransaction({
        'nonce': nonce,
        'gas': 1000000,
    })
    signed_txn = w3.eth.account.sign_transaction(txn, private_key=owner.key)
    txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
    txn_receipt = w3.eth.waitForTransactionReceipt(txn_hash)
    debug(invoice_id)
    print(f'txn_receipt: {txn_receipt}')
    print(f"transaction status: {txn_receipt['status']}")
    debug(contract.contract.functions.invoices(invoice_id).call())
Пример #17
0
async def main_httpx2():
    start = time.time()
    async with httpx.AsyncClient() as session:
        await asyncio.gather(*[call_url(session) for x in range(N)])

    dt = time.time() - start
    debug(f"{N} call(s) in {dt} seconds, {N / dt} req/s")
Пример #18
0
def play() -> None:
    markup = Path(f'tests/data/{args.file}.html').read_text()
    distilled, errors = distill(markup)
    for node in distilled.nodes:
        debug(node)
    if errors:
        debug(errors)
Пример #19
0
    async def mock_update(self, conn, hint, primary_id) -> None:
        tpl = DDLTemplate.get_update_template()
        columns = [
            column.name for column in self.columns
            if column.autoincrement is False
        ]
        data = {
            column.name: fake(column, hint)
            for column in self.columns if column.primary_key is False
        }
        items = []
        for k, v in data.items():
            column = self.meta[k]
            if isinstance(column,StringColumn) or \
                isinstance(column, DateColumn) or \
                    isinstance(column, DateTimeColumn):
                items.append("{k}='{v}'".format(k=k, v=v))
            else:
                items.append("{k}={v}".format(k=k, v=v))

        sql = tpl.format(table_name=self.name,
                         dml=",".join(items),
                         primary_key=self.primary_key.name,
                         value=primary_id)
        debug(sql)
        r = await conn.execute(sql)
        return r
Пример #20
0
    async def __schedule(self):
        """
        根据runnerContext,编译出真正的执行链

        包括对catch的切片
        """

        debug(self.context)

        # todo 类型转换,int | None => int
        targetGroup: Any = None
        # targetGroup:Optional[int]=None
        # todo 先预处理一下,而不是直接执行,因为要切片catch
        for item in self.context:
            # todo 不判断字符串,直接判断 action == SingleGroup.members,直接判断函数是否相等
            if item.action == "select_group":
                targetGroup = item.payload

            elif item.action == "send_message":
                await api.group_msg(targetGroup, *item.args)

            elif item.action == "sleep":
                await asyncio.sleep(item.args[0])

            elif item.action == "members":
                return await api.members(targetGroup)

        return
Пример #21
0
    def visit_HorizontalLoop(self, node: nir.HorizontalLoop, *, symtable, **kwargs):

        kernel_ctx = self.KernelContext(node.iteration_space.name)
        body = self.visit(
            node.stmt, kernel_ctx=kernel_ctx, symtable={**symtable, **node.symtable_}, **kwargs
        )
        primary_composite = usid.SidComposite(
            name=node.iteration_space.name, entries=kernel_ctx.primary_composite_entries
        )
        composites = kernel_ctx.composites
        secondary_composites = [
            usid.SidComposite(name=name, entries=entries) for name, entries in composites.items()
        ]

        kernel_name = "kernel_" + str(id(node))
        debug(primary_composite)
        debug(secondary_composites)
        kernel = usid.Kernel(
            name=kernel_name,
            primary_location=node.iteration_space.location_type,
            primary_composite=primary_composite,
            secondary_composites=secondary_composites,
            body=body,
        )
        return kernel, usid.KernelCall(name=kernel_name)
Пример #22
0
    def visit_Computation(self, node: nir.Computation, **kwargs):
        parameters = []
        for f in node.params:  # before visiting stencils!
            converted_param = self.visit(f)
            parameters.append(converted_param)
            self.fields[converted_param.name] = converted_param

        temporaries = []
        for tmp in node.declarations or []:
            converted_tmp = self.visit(tmp)
            temporaries.append(converted_tmp)
            self.fields[converted_tmp.name] = converted_tmp

        kernels = []
        ctrlflow_ast = []
        for s in node.stencils:
            kernel, kernel_call = self.visit(s)
            kernels.extend(kernel)
            ctrlflow_ast.extend(kernel_call)

        debug(kernels)

        return usid.Computation(
            name=node.name,
            parameters=parameters,
            temporaries=temporaries,
            kernels=kernels,
            ctrlflow_ast=ctrlflow_ast,
        )
async def test_secrets_create_update():
    ts = time.perf_counter()
    bprint('Test: Secrets Create/Update', 'top')

    async with VaultClient(
            cfg=f'{getenv("CFG_HOME")}/hashicorp_vault_test.toml') as vc:
        model = CreateUpdateSecret(
            data=SecretData(
                secret_name='client-temp',
                key='je1234-eclient',
                value='1260094080553877',
                path='je1234/unbound/sandbox'  # {cmdb}/unbound/{partition}
            ),
            options=SecretOptions())

        debug(model)
        debug(model.endpoint)
        debug(model.parameters)
        debug(model.json())
        debug(model.dict())

        results = await vc.make_request(models=model)

        assert type(results) is Results
        assert results.success is not None
        assert not results.failure

        tprint(results, top=5)

    bprint(f'Completed in {(time.perf_counter() - ts):f} seconds.', 'bottom')
Пример #24
0
    async def first(self, bot: GroupCommonBot, chain: MessageChain,
                    sender: Sender, **kwargs):
        # game = messages["game"]
        # reply("你选择的是{game}的{character}角色,需要查询他的什么装备呢?")

        try:
            # 参数过多需要报错吗?还是省略就好了——省略
            # todo 友好的定义pattern的方式
            # todo 支持表情,图片等等,而不仅是文字
            match = re.search(r".*?(\S*)\s*(\S*)", chain.pure_text)
            if not match or not len(match.groups()) == 2:

                raise Exception()

            for part in match.groups():
                if not part:
                    raise Exception()

            debug(match.groups())
            await bot.group_msg(
                Text(f"成功解析参数 游戏名{match.groups()[0]} 装备名{match.groups()[1]}"))

        except:
            await bot.group_msg(Text("请按照 /查询装备 游戏名 装备名 的格式输入"))
            # todo 参数不够(需要哪几个,什么类型,只提供了什么),
            # todo 参数类型错误(哪个参数类型错误),
            # todo 友好的提示信息

            return self.first
Пример #25
0
def parent(
        version: bool = typer.Option(False,
                                     '--version',
                                     is_eager=True,
                                     callback=version_callback,
                                     show_default=False),
        verbose: int = typer.Option(0, '--verbose', '-v', count=True),
):
    """
        Keep watch with resilience

        You may \033[32mregister\033[0m as many URLs you want to watch.
        They can be either automatically checks every given number of seconds,
        or on demand with \033[32mcheck\033[0m command
    """
    if verbose == 0:
        logging_level = logging.WARNING
    elif verbose == 1:
        logging_level = logging.INFO
    elif verbose == 2:
        logging_level = logging.DEBUG
        debug(Settings().dict())

    logging.basicConfig(level=logging_level)
    logging.info(f"Logging level set to {logging.getLevelName(logging_level)}")
Пример #26
0
def map_loads(level):
    if level == "okres":
        with open('static\\okresy.json', encoding='utf-8') as myfile:
            data = myfile.read()
    elif level == "kraj":
        with open('static\\kraje.json', encoding='utf-8') as myfile:
            data = myfile.read()
    else:
        with open('static\\slovensko.json', encoding='utf-8') as myfile:
            data = myfile.read()
    vis2 = json.loads(data)
    for zaznam in vis2:
        debug(zaznam)
        #print(zaznam['type'])
    #debug(vis2)
    # url = (
    #     "http://download.freemap.sk/AdminLevel"
    # )

    # print(url)

    # #vis1 = json.loads(requests.get(f"{url}/okresy.json").text)
    # #vis2 = json.loads(requests.get(f"{url}/okresy-005.json").text)
    # #http://download.freemap.sk/AdminLevel/kraje.json

    m = folium.Map(location=[49.0, 19.5],
                   zoom_start=8,
                   width='100%',
                   height='85%')
    #folium.GeoJson(vis1, name="geojson").add_to(m)
    g = folium.GeoJson(vis2, name="geojson").add_to(m)

    folium.GeoJsonTooltip(fields=['TXT']).add_to(g)
    m.save('templates/map.html')
    return
Пример #27
0
    async def register(self, *, expires):
        common_headers = (
            f'From: <sip:{self.settings.sip_username}@{self.settings.sip_host}:{self.settings.sip_port}>',
            f'To: <sip:{self.settings.sip_username}@{self.settings.sip_host}:{self.settings.sip_port}>',
            f'Call-ID: {self.call_id}',
            f'Contact: <sip:{self.settings.sip_username}@{self.local_ip}>',
            f'Expires: {expires}',
            'Max-Forwards: 70',
            'User-Agent: TutorCruncher Mithra',
            'Content-Length: 0',
        )

        r1: Response = await self.request(
            f'REGISTER sip:{self.settings.sip_host}:{self.settings.sip_port} SIP/2.0',
            f'Via: SIP/2.0/UDP {self.local_ip}:5060;rport;branch={self.gen_branch()}',
            f'CSeq: {self.cseq} REGISTER',
            *common_headers,
        )
        if r1.status != 401:
            debug('unexpected response to first REGISTER', r1)
            logger.warning('unexpected response to first REGISTER %s != 401',
                           r1.status,
                           extra={'data': {
                               'response': r1
                           }})
            # honor "Retry-After"
            return int(r1.headers.get('Retry-After', self.ERROR_WAIT))

        auth = r1.headers['WWW-Authenticate']
        realm = REALM_REGEX.search(auth).groups()[0]
        nonce = NONCE_REGEX.search(auth).groups()[0]
        ha1 = md5digest(self.settings.sip_username, realm,
                        self.settings.sip_password)
        ha2 = md5digest('REGISTER', self.settings.sip_uri)
        r2: Response = await self.request(
            f'REGISTER sip:{self.settings.sip_host}:{self.settings.sip_port} SIP/2.0',
            f'Via: SIP/2.0/UDP {self.local_ip}:5060;rport;branch={self.gen_branch()}',
            f'CSeq: {self.cseq} REGISTER',
            (f'Authorization: Digest username="******", realm="{realm}", nonce="{nonce}", '
             f'uri="{self.settings.sip_uri}", response="{md5digest(ha1, nonce, ha2)}", algorithm=MD5'
             ),
            *common_headers,
        )
        if expires == 0:
            logger.info('un-registered, response: %d', r2.status)
        elif r2.status != 200:
            debug('unexpected response to second REGISTER', r2)
            logger.warning('unexpected response to second REGISTER %d != 200',
                           r2.status,
                           extra={'data': {
                               'response': r2
                           }})
            # honor "Retry-After"
            return int(r2.headers.get('Retry-After', self.ERROR_WAIT))
        else:
            re_register = max(10, expires - 1)
            logger.info('successfully registered')
            self.sentinal_file.touch(exist_ok=True)
            return re_register
Пример #28
0
async def test_user_login_failure(async_client: AsyncClient):
    login_data = {"user": {"email": "u1596352021", "password": "******"}}
    r = await async_client.post("/api/users/login", json=login_data)
    user_response = r.json()
    debug(r.json())
    assert r.status_code == status.HTTP_400_BAD_REQUEST
    assert "detail" in user_response
    assert user_response["detail"] == "Incorrect email or password"
Пример #29
0
    def handle(self) -> int:
        if not hannah_optimizer_available:
            self.line(
                "<error>autojail explore currently depends on unreleased package hannah-tvm</error>"
            )
            self.line(
                "Please contact [email protected] if you want to use it."
            )
            return 1

        if not self.autojail_config:
            self.line(f"<error>could not find {self.CONFIG_NAME}</error>")
            return 1

        self.cells_yml_path = Path.cwd() / self.CELLS_CONFIG_NAME

        if not self.cells_yml_path.exists():
            self.line(
                f"<error>{self.cells_yml_path} could not be found</error>")
            return 1

        board_yml_path = Path.cwd() / self.BOARD_CONFIG_NAME
        if not board_yml_path.exists():
            self.line(f"<error>{board_yml_path} could not be found</error>")
            self.line("Please run <comment>automate extract</comment> first")
            return 1

        with board_yml_path.open() as f:
            yaml = ruamel.yaml.YAML()
            board_dict = yaml.load(f)
            board_info = Board(**board_dict)

        self.board_info = board_info

        gen_params = GenerateParameters()
        set_params = None

        step = 0

        result = self._run_config(step, set_params, gen_params)
        print(result)

        optimizer = AgingEvolution(
            10,
            1,
            0.1,
            {"test", 0.5},
            gen_params.dict(),
            numpy.random.RandomState(1234),
        )
        for _step in range(1, 20):
            set_params = optimizer.ask()
            from devtools import debug

            debug(set_params.flatten())

        return 0
Пример #30
0
def test_app(fixed_tmp_path, file_regression):
    result = runner.invoke(app, ["tests/test_cli/test.bib", str(fixed_tmp_path)])
    debug(result.stdout)
    try:
        debug(result.stderr)
    except:
        pass
    assert result.exit_code == 0
    file_regression.check(result.stdout)