Debian Codegraph @

ansible_collections/community/docker/tests/unit/plugins/module_utils/test__copy.py

raw
1 # Copyright 2022 Red Hat | Ansible
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 import typing as t
8
9 import pytest
10
11 from ansible_collections.community.docker.plugins.module_utils._copy import (
12 _stream_generator_to_fileobj,
13 )
14
15 if t.TYPE_CHECKING:
16 from collections.abc import Sequence
17
18 T = t.TypeVar("T")
19
20
21 def _simple_generator(sequence: Sequence[T]) -> t.Generator[T]:
22 yield from sequence
23
24
25 @pytest.mark.parametrize(
26 "chunks, read_sizes",
27 [
28 (
29 [
30 (1, b"1"),
31 (1, b"2"),
32 (1, b"3"),
33 (1, b"4"),
34 ],
35 [
36 1,
37 2,
38 3,
39 ],
40 ),
41 (
42 [
43 (1, b"123"),
44 (1, b"456"),
45 (1, b"789"),
46 ],
47 [
48 1,
49 4,
50 2,
51 2,
52 2,
53 ],
54 ),
55 (
56 [
57 (10 * 1024 * 1024, b"0"),
58 (10 * 1024 * 1024, b"1"),
59 ],
60 [
61 1024 * 1024 - 5,
62 5 * 1024 * 1024 - 3,
63 10 * 1024 * 1024 - 2,
64 2 * 1024 * 1024 - 1,
65 2 * 1024 * 1024 + 5 + 3 + 2 + 1,
66 ],
67 ),
68 ],
69 )
70 def test__stream_generator_to_fileobj(
71 chunks: list[tuple[int, bytes]], read_sizes: list[int]
72 ) -> None:
73 data_chunks = [count * data for count, data in chunks]
74 stream = _simple_generator(data_chunks)
75 expected = b"".join(data_chunks)
76
77 buffer = b""
78 totally_read = 0
79 f = _stream_generator_to_fileobj(stream)
80 for read_size in read_sizes:
81 chunk = f.read(read_size)
82 assert len(chunk) == min(read_size, len(expected) - len(buffer))
83 buffer += chunk
84 totally_read += read_size
85
86 assert buffer == expected[: len(buffer)]
87 assert min(totally_read, len(expected)) == len(buffer)