Skip to content

Commit

Permalink
Rewrite the chunking test to use mmap
Browse files Browse the repository at this point in the history
This makes it no longer rely on implementation details
  • Loading branch information
alex committed Nov 11, 2023
1 parent 1fb0d8a commit 5d02004
Showing 1 changed file with 19 additions and 36 deletions.
55 changes: 19 additions & 36 deletions tests/hazmat/primitives/test_ciphers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@


import binascii
import mmap
import os
import sys

import pytest

Expand Down Expand Up @@ -355,39 +357,20 @@ def test_update_into_buffer_too_small_gcm(self, backend):
with pytest.raises(ValueError):
encryptor.update_into(b"testing", buf)

def test_update_into_auto_chunking(self, backend, monkeypatch):
key = b"\x00" * 16
c = ciphers.Cipher(AES(key), modes.ECB(), backend)
encryptor = c.encryptor()
# Lower max chunk size so we can test chunking
monkeypatch.setattr(
encryptor._ctx, # type: ignore[attr-defined]
"_MAX_CHUNK_SIZE",
40,
)
buf = bytearray(527)
pt = b"abcdefghijklmnopqrstuvwxyz012345" * 16 # 512 bytes
processed = encryptor.update_into(pt, buf)
assert processed == 512
decryptor = c.decryptor()
# Change max chunk size to verify alternate boundaries don't matter
monkeypatch.setattr(
decryptor._ctx, # type: ignore[attr-defined]
"_MAX_CHUNK_SIZE",
73,
)
decbuf = bytearray(527)
decprocessed = decryptor.update_into(buf[:processed], decbuf)
assert decbuf[:decprocessed] == pt

def test_max_chunk_size_fits_in_int32(self, backend):
# max chunk must fit in signed int32 or else a call large enough to
# cause chunking will result in the very OverflowError we want to
# avoid with chunking.
key = b"\x00" * 16
c = ciphers.Cipher(AES(key), modes.ECB(), backend)
encryptor = c.encryptor()
backend._ffi.new(
"int *",
encryptor._ctx._MAX_CHUNK_SIZE, # type: ignore[attr-defined]
)

@pytest.mark.skipif(
sys.platform not in {"linux", "darwin"}, reason="mmap required"
)
def test_update_auto_chunking(self, backend, monkeypatch):
large_data = mmap.mmap(-1, 2**31, prot=mmap.PROT_READ)

key = b"\x00" * 16
c = ciphers.Cipher(AES(key), modes.ECB(), backend)
encryptor = c.encryptor()

result = encryptor.update(memoryview(large_data))
assert len(result) == len(large_data)

decryptor = c.decryptor()
result = decryptor.update(result)
assert result == large_data[:]

0 comments on commit 5d02004

Please sign in to comment.