|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). You |
| 4 | +# may not use this file except in compliance with the License. A copy of |
| 5 | +# the License is located at |
| 6 | +# |
| 7 | +# http://aws.amazon.com/apache2.0/ |
| 8 | +# |
| 9 | +# or in the "license" file accompanying this file. This file is |
| 10 | +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF |
| 11 | +# ANY KIND, either express or implied. See the License for the specific |
| 12 | +# language governing permissions and limitations under the License. |
| 13 | +import random |
| 14 | +from binascii import crc32 |
| 15 | + |
| 16 | +from s3transfer.checksums import combine_crc32 |
| 17 | + |
| 18 | + |
| 19 | +class TestCombineCrc32: |
| 20 | + def test_combine(self): |
| 21 | + for _ in range(100): |
| 22 | + data1 = random.randbytes(32) |
| 23 | + crc1 = crc32(data1) |
| 24 | + data2 = random.randbytes(32) |
| 25 | + crc2 = crc32(data2) |
| 26 | + serial = crc32(data1 + data2) |
| 27 | + combined = combine_crc32(crc1, crc2, len(data2)) |
| 28 | + assert serial == combined |
| 29 | + |
| 30 | + def test_combine_no_update(self): |
| 31 | + data = random.randbytes(32) |
| 32 | + init = random.randint(1, 0x80000000) |
| 33 | + serial = crc32(data, init) |
| 34 | + combined = combine_crc32(init, crc32(data), len(data)) |
| 35 | + assert serial == combined |
| 36 | + |
| 37 | + def test_combine_many_parts(self): |
| 38 | + parts = [f"Part{i}".encode() for i in range(1000)] |
| 39 | + |
| 40 | + serial_crc = crc32(b"".join(parts)) |
| 41 | + combined_crc = crc32(parts[0]) |
| 42 | + for i in range(1, len(parts)): |
| 43 | + part_crc = crc32(parts[i]) |
| 44 | + combined_crc = combine_crc32(combined_crc, part_crc, len(parts[i])) |
| 45 | + |
| 46 | + assert combined_crc == serial_crc |
| 47 | + |
| 48 | + def test_combine_associative_property(self): |
| 49 | + data_a = b"foo" |
| 50 | + data_b = b"bar" |
| 51 | + data_c = b"baz" |
| 52 | + |
| 53 | + serial_crc = crc32(data_a + data_b + data_c) |
| 54 | + |
| 55 | + crc_a = crc32(data_a) |
| 56 | + crc_b = crc32(data_b) |
| 57 | + crc_c = crc32(data_c) |
| 58 | + |
| 59 | + # (a+b) + c |
| 60 | + crc_ab = combine_crc32(crc_a, crc_b, len(data_b)) |
| 61 | + crc_ab_c = combine_crc32(crc_ab, crc_c, len(data_c)) |
| 62 | + |
| 63 | + # a + (b+c) |
| 64 | + crc_bc = combine_crc32(crc_b, crc_c, len(data_c)) |
| 65 | + crc_a_bc = combine_crc32(crc_a, crc_bc, len(data_b + data_c)) |
| 66 | + |
| 67 | + assert serial_crc == crc_ab_c == crc_a_bc |
0 commit comments