コード例 #1
0
def test_example_from_readme():
    request = RequestBuilder.from_dict({
        "host": "api.github.com",
        "protocol": "https",
        "method": "get",
        "pathname": "/v1/users",
        "query": {
            "a": "b",
            "q": ["1", "2"]
        },
    })

    response = ResponseBuilder.from_dict({
        "statusCode": 200,
        "headers": {
            "content-type": "text/plain"
        },
        "body": "(response body string)",
    })

    exchange = HttpExchange(request=request, response=response)

    output_file = StringIO()
    writer = HttpExchangeWriter(output_file)
    writer.write(exchange)

    input_file = output_file
    input_file.seek(0)

    for exchange in HttpExchangeReader.from_jsonl(input_file):
        assert exchange.request.method == HttpMethod.GET
        assert exchange.request.protocol == Protocol.HTTPS
        assert exchange.response.statusCode == 200
コード例 #2
0
ファイル: log.py プロジェクト: wilsonify/hmt
    def put(self, request: Request, response: Response):
        self._interactions = [
            *self._interactions,
            LoggedHttpExchange(
                request=request,
                response=response,
                meta=MeeshkanMeta(timestamp=int(time.time() * 1000),
                                  scope=self._scope.get()),
            ),
        ]
        exchange = HttpExchangeWriter.to_dict(
            HttpExchange(
                request=request,
                response=response,
            ))
        interaction = {
            **exchange,
            "meta": {
                "timestamp":
                self._interactions[-1].meta.timestamp,
                **({
                    "scope": self._interactions[-1].meta.scope
                } if self._interactions[-1].meta.scope is not None else {}),
            },
        }

        self._interactions_as_json = [*self._interactions_as_json, interaction]
        if self._sink is not None:
            self._sink.write(self._interactions_as_json)
コード例 #3
0
def test_writing_json():
    buffer = StringIO()
    writer = HttpExchangeWriter(buffer)

    original_exchanges = []
    with open(SAMPLE_JSONL, "r", encoding="utf-8") as f:
        for exchange in HttpExchangeReader.from_jsonl(f):
            original_exchanges.append(exchange)
            writer.write(exchange)

    buffer.seek(0)
    schema = read_schema()
    for line in buffer:
        jsonschema.validate(instance=json.loads(line), schema=schema)

    buffer.seek(0)
    exchanges = list(HttpExchangeReader.from_jsonl(buffer))
    validate_sample_exchanges(exchanges)
    assert original_exchanges == exchanges
コード例 #4
0
def test_serializing_to_dict(exchanges: Sequence[HttpExchange]):
    exchange = exchanges[0]
    as_dict = HttpExchangeWriter.to_dict(exchange)
    assert "request" in as_dict
    assert "response" in as_dict
    request = as_dict["request"]
    assert "method" in request
    assert request["method"] == "get"
    assert "headers" in request
    assert "query" in request
    response = as_dict["response"]
    assert "body" in response
    assert isinstance(response["body"], str)
コード例 #5
0
ファイル: data_callback.py プロジェクト: wilsonify/hmt
    def log(self, request: Request, response: Response):
        RequestBuilder.validate(request)
        ResponseBuilder.validate(response)

        host = request.host
        reqres = HttpExchange(request=request, response=response)
        if host not in self._logs:
            log_file = os.path.join(self._log_dir,
                                    "{}-recordings.jsonl".format(host))
            if self._append and os.path.exists(log_file):
                self._logs[host] = open(log_file, "a")
            else:
                self._logs[host] = open(log_file, "w")

        HttpExchangeWriter(self._logs[host]).write(reqres)
        self._logs[host].flush()

        logger.debug("Logs for %s were updated", host)

        if self._update_mode:
            spec_file = os.path.join(
                self._specs_dir,
                "{}_{}.json".format(host, self._update_mode.name.lower()),
            )

            if host not in self._specs:
                if os.path.exists(spec_file) and self._append:
                    with open(spec_file, "r") as f:
                        self._specs[host] = convert_to_openapi(json.load(f))
                else:
                    self._specs[host] = BASE_SCHEMA

            self._specs[host] = update_openapi(self._specs[host], reqres,
                                               self._update_mode)

            with open(spec_file, "w") as f:
                spec = convert_from_openapi(self._specs[host])
                json.dump(spec, f)
                f.flush()

            logger.debug("Schema for %s was updated", host)
コード例 #6
0
def test_serializing_to_json_and_back(exchanges: Sequence[HttpExchange]):
    exchange = exchanges[0]
    as_json = HttpExchangeWriter.to_json(exchange)
    assert isinstance(as_json, str)
    decoded = HttpExchangeReader.from_json(as_json)
    assert isinstance(decoded, HttpExchange)