예제 #1
0
def test_invalid_timestamp_in_json():
    with open(SAMPLE_JSON, "r", encoding="utf-8") as f:
        json_string = f.read().replace("2018-11-13T20:20:39+02:00", "INVALID_STRING")
        try:
            HttpExchangeReader.from_json(json_string)
            raise AssertionError("No exception raised from invalid timestamp")
        except ValueError as e:
            assert str(e) == "Invalid isoformat string: INVALID_STRING"
예제 #2
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
def generate_schema():
    """Return a generated schema built from posted HTTP recordings."""
    if request.headers["content-type"].startswith("multipart/form-data"):
        uploaded_file = request.files["file"]
        uploaded_file.seek(0)
        file_content = TextIOWrapper(uploaded_file)
    else:
        file_content = request.stream

    try:
        http_exchanges = HttpExchangeReader.from_jsonl(file_content)
        openapi_schema = meeshkan.build_schema_batch(http_exchanges)
        response_text = yaml.safe_dump(convert_from_openapi(openapi_schema))
        return (
            response_text,
            200,
            {
                "content-type": "application/vnd.oai.openapi",
                "content-disposition":
                'attachment; filename="openapi-schema.yml"',
            },
        )
    except JSONDecodeError:
        response_text = "Content is not JSON\r\n"
        return response_text, 400, {"content-type": "text/plain"}
예제 #4
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
예제 #5
0
def test_request_logging_gen(tmp_dir):
    request = RequestBuilder.from_dict(
        dict(
            method="get",
            host="api.com",
            pathname="/echo",
            query={"message": "Hello"},
            body="",
            protocol="http",
            headers={},
        ))
    response = ResponseBuilder.from_dict(
        dict(
            statusCode=200,
            body='{"message": "hello"}',
            bodyAsJson={"message": "hello"},
            headers={},
        ))

    log_dir = os.path.join(tmp_dir, "logs")
    specs_dir = os.path.join(tmp_dir, "specs")
    with RequestLoggingCallback(log_dir=log_dir,
                                specs_dir=specs_dir,
                                update_mode=UpdateMode.GEN) as data_callback:
        data_callback.log(request, response)

    expected_recordings_path = os.path.join(log_dir,
                                            "api.com-recordings.jsonl")
    assert os.path.exists(expected_recordings_path)

    expected_specs_path = os.path.join(specs_dir, "api.com_gen.json")
    assert os.path.exists(expected_specs_path)

    with open(expected_recordings_path, "r") as f:
        data = [x for x in f.read().split("\n") if x != ""]
        assert 1 == len(data)
        http_exchange = HttpExchangeReader.from_json(data[0])
        assert request == http_exchange.request
        assert response == http_exchange.response
예제 #6
0
def test_from_json():
    with open(SAMPLE_JSON, "r", encoding="utf-8") as f:
        exchange = HttpExchangeReader.from_json(f.read())
        assert exchange.request.timestamp == isoparse(
            "2018-11-13T20:20:39+02:00")
        assert exchange.response.timestamp == isoparse("2020-01-31T13:34:15")
예제 #7
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)
예제 #8
0
def exchanges():
    with open(SAMPLE_JSONL, "r", encoding="utf-8") as f:
        return [exchange for exchange in HttpExchangeReader.from_jsonl(f)]
예제 #9
0
def test_from_jsonl():
    with open(SAMPLE_JSONL, "r", encoding="utf-8") as f:
        exchanges = list(HttpExchangeReader.from_jsonl(f))
        validate_sample_exchanges(exchanges)