|
| 1 | +# |
| 2 | +# Copyright (c) 2025 Airbyte, Inc., all rights reserved. |
| 3 | +# |
| 4 | +import gzip |
| 5 | +import json |
| 6 | +import zipfile |
| 7 | +from io import BytesIO |
| 8 | +from typing import Union |
| 9 | + |
| 10 | +import pytest |
| 11 | +import requests |
| 12 | + |
| 13 | +from airbyte_cdk.sources.declarative.decoders import GzipParser, JsonParser, ZipfileDecoder |
| 14 | + |
| 15 | + |
| 16 | +def create_zip_from_dict(data: Union[dict, list]) -> bytes: |
| 17 | + zip_buffer = BytesIO() |
| 18 | + with zipfile.ZipFile(zip_buffer, mode="w") as zip_file: |
| 19 | + zip_file.writestr("data.json", data) |
| 20 | + return zip_buffer.getvalue() |
| 21 | + |
| 22 | + |
| 23 | +def create_multi_zip_from_dict(data: list) -> bytes: |
| 24 | + zip_buffer = BytesIO() |
| 25 | + |
| 26 | + with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file: |
| 27 | + for i, content in enumerate(data): |
| 28 | + file_content = json.dumps(content).encode("utf-8") |
| 29 | + zip_file.writestr(f"file_{i}.json", file_content) |
| 30 | + return zip_buffer.getvalue() |
| 31 | + |
| 32 | + |
| 33 | +@pytest.mark.parametrize( |
| 34 | + "json_data", |
| 35 | + [ |
| 36 | + {"test": "test"}, |
| 37 | + {"responses": [{"id": 1}, {"id": 2}]}, |
| 38 | + [{"id": 1}, {"id": 2}], |
| 39 | + {}, |
| 40 | + ], |
| 41 | +) |
| 42 | +def test_zipfile_decoder_with_single_file_response(requests_mock, json_data): |
| 43 | + zipfile_decoder = ZipfileDecoder(parser=GzipParser(inner_parser=JsonParser())) |
| 44 | + compressed_data = gzip.compress(json.dumps(json_data).encode()) |
| 45 | + zipped_data = create_zip_from_dict(compressed_data) |
| 46 | + requests_mock.register_uri("GET", "https://airbyte.io/", content=zipped_data) |
| 47 | + response = requests.get("https://airbyte.io/") |
| 48 | + |
| 49 | + if isinstance(json_data, list): |
| 50 | + for i, actual in enumerate(zipfile_decoder.decode(response=response)): |
| 51 | + assert actual == json_data[i] |
| 52 | + else: |
| 53 | + assert next(zipfile_decoder.decode(response=response)) == json_data |
| 54 | + |
| 55 | + |
| 56 | +def test_zipfile_decoder_with_multi_file_response(requests_mock): |
| 57 | + data_to_zip = [{"key1": "value1"}, {"key2": "value2"}, {"key3": "value3"}] |
| 58 | + |
| 59 | + mocked_response = create_multi_zip_from_dict(data_to_zip) |
| 60 | + |
| 61 | + decoder = ZipfileDecoder(parser=JsonParser()) |
| 62 | + requests_mock.register_uri("GET", "https://airbyte.io/", content=mocked_response) |
| 63 | + response = requests.get("https://airbyte.io/") |
| 64 | + results = list(decoder.decode(response)) |
| 65 | + |
| 66 | + assert len(results) == 3 |
| 67 | + for i, actual in enumerate(results): |
| 68 | + assert actual == data_to_zip[i] |
0 commit comments