|
| 1 | +# ------------------------------------------------------------------------- |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +# Licensed under the MIT License. See LICENSE.txt in the project root for |
| 4 | +# license information. |
| 5 | +# ------------------------------------------------------------------------- |
| 6 | +import json |
| 7 | +import random |
| 8 | +import string |
| 9 | +import zlib |
| 10 | + |
| 11 | +import pytest |
| 12 | + |
| 13 | +from azure.monitor.ingestion._helpers import ( |
| 14 | + _create_gzip_requests, |
| 15 | + _split_chunks, |
| 16 | + MAX_CHUNK_SIZE_BYTES, |
| 17 | + GZIP_MAGIC_NUMBER |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +ALPHANUMERIC_CHARACTERS = string.ascii_letters + string.digits |
| 22 | + |
| 23 | +random.seed(42) # For repeatibility |
| 24 | + |
| 25 | + |
| 26 | +def _get_random_string(length: int): |
| 27 | + return ''.join(random.choice(ALPHANUMERIC_CHARACTERS) for _ in range(length)) |
| 28 | + |
| 29 | + |
| 30 | +class TestHelpers: |
| 31 | + |
| 32 | + @pytest.mark.parametrize("content", ["bar", "\uc548\ub155\ud558\uc138\uc694"]) |
| 33 | + def test_split_chunks(self, content): |
| 34 | + obj = {"foo": content} |
| 35 | + logs = [obj] * 100 |
| 36 | + |
| 37 | + entry_size = len(json.dumps(obj).encode("utf-8")) |
| 38 | + |
| 39 | + chunks = list(_split_chunks(logs, max_size_bytes=entry_size)) |
| 40 | + assert len(chunks) == 100 |
| 41 | + |
| 42 | + chunks = list(_split_chunks(logs, max_size_bytes=entry_size*2)) |
| 43 | + assert len(chunks) == 50 |
| 44 | + |
| 45 | + chunks = list(_split_chunks(logs, max_size_bytes=entry_size*100)) |
| 46 | + assert len(chunks) == 1 |
| 47 | + |
| 48 | + def test_split_chunks_larger_than_max(self): |
| 49 | + obj = {"foo": "some-long-string"} |
| 50 | + logs = [obj] * 3 |
| 51 | + # If each entry in the log is greater than the max chunk size, then each entry should be its own chunk. |
| 52 | + chunks = list(_split_chunks(logs, max_size_bytes=10)) |
| 53 | + assert len(chunks) == 3 |
| 54 | + |
| 55 | + @pytest.mark.parametrize("num_entries", [100, 10000]) |
| 56 | + def test_create_gzip_requests(self, num_entries): |
| 57 | + logs = [{_get_random_string(20): _get_random_string(500)} for _ in range(num_entries)] |
| 58 | + for compressed_bytes, raw_data in _create_gzip_requests(logs): |
| 59 | + assert len(compressed_bytes) < MAX_CHUNK_SIZE_BYTES |
| 60 | + assert compressed_bytes[:2] == GZIP_MAGIC_NUMBER |
| 61 | + assert zlib.decompress(compressed_bytes, 16+zlib.MAX_WBITS) == json.dumps(raw_data).encode("utf-8") |
0 commit comments