Skip to content

Commit f0a69e9

Browse files
prandlaveluca93
authored andcommitted
Optimize some unit tests
* Some tests end up having to hash passwords. Add a tweak that allows setting the hashing difficulty to a lower value for the tests. * file_middleware_test had a really inefficient setUp() method, which matters more now that the FileCacher block size is 1MB.
1 parent cc61a90 commit f0a69e9

File tree

3 files changed

+13
-3
lines changed

3 files changed

+13
-3
lines changed

cmscommon/crypto.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@
4848

4949
_RANDOM = Random.new()
5050

51+
# bcrypt difficulty parameter. This is here so that it can be set to a lower
52+
# value when running unit tests. It seems that the lowest accepted value is 4.
53+
BCRYPT_ROUNDS = 12
5154

5255
def get_random_key() -> bytes:
5356
"""Generate 16 random bytes, safe to be used as AES key.
@@ -226,7 +229,8 @@ def hash_password(password: str, method: str = "bcrypt") -> str:
226229
"""
227230
if method == "bcrypt":
228231
password_bytes = password.encode("utf-8")
229-
payload = bcrypt.hashpw(password_bytes, bcrypt.gensalt()).decode("ascii")
232+
salt = bcrypt.gensalt(BCRYPT_ROUNDS)
233+
payload = bcrypt.hashpw(password_bytes, salt).decode("ascii")
230234
elif method == "plaintext":
231235
payload = password
232236
else:
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# This file is meant to be used for creating pytest fixtures.
2+
# It's a bit of a hack, but we can put global initialization here.
3+
4+
# Make bcrypt run faster in tests. Default difficulty is 12,
5+
# which takes around 250ms per hash. This one takes <1ms.
6+
import cmscommon.crypto
7+
cmscommon.crypto.BCRYPT_ROUNDS = 4

cmstestsuite/unit_tests/server/file_middleware_test.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,7 @@
3838
class TestFileByDigestMiddleware(unittest.TestCase):
3939

4040
def setUp(self):
41-
self.content = \
42-
bytes(random.getrandbits(8) for _ in range(TESTFILE_LEN))
41+
self.content = random.randbytes(TESTFILE_LEN)
4342
self.digest = bytes_digest(self.content)
4443

4544
self.filename = "foobar.pdf"

0 commit comments

Comments
 (0)