Debian Codegraph @

tests/test_utils.py

raw ◀ ▶
1 Debian patch touch this file
1 from contextlib import nullcontext
2
3 import pytest
4
•5 import base64
6 import warnings
7 from contextlib import AbstractContextManager
8
•9 from jwt.utils import (
10 base64url_decode,
11 force_bytes,
12 from_base64url_uint,
13 is_ssh_key,
14 to_base64url_uint,
15 )
16
17
18 @pytest.mark.parametrize(
19 "inputval,expected",
20 [
21 (0, nullcontext(b"AA")),
22 (1, nullcontext(b"AQ")),
23 (255, nullcontext(b"_w")),
24 (65537, nullcontext(b"AQAB")),
25 (123456789, nullcontext(b"B1vNFQ")),
26 (-1, pytest.raises(ValueError)),
27 ],
28 )
29 def test_to_base64url_uint(
30 inputval: int, expected: AbstractContextManager[bytes]
31 ) -> None:
32 with expected as e:
33 actual = to_base64url_uint(inputval)
34 assert actual == e
35
36
37 @pytest.mark.parametrize(
38 "inputval,expected",
39 [
40 (b"AA", 0),
41 (b"AQ", 1),
42 (b"_w", 255),
43 (b"AQAB", 65537),
44 (b"B1vNFQ", 123456789),
45 ],
46 )
47 def test_from_base64url_uint(inputval: bytes, expected: int) -> None:
48 actual = from_base64url_uint(inputval)
49 assert actual == expected
50
51
•52 def test_base64url_decode_handles_standard_alphabet() -> None:
53 # The same bytes encoded with the standard ("+/") and the URL-safe ("-_")
54 # alphabets must decode to the same value. ``base64url_decode`` normalises
55 # the standard alphabet so historical callers keep working.
56 raw = bytes(range(256))
57 standard = base64.b64encode(raw)
58 urlsafe = base64.urlsafe_b64encode(raw).rstrip(b"=")
59
60 assert b"+" in standard or b"/" in standard
61 assert base64url_decode(standard) == raw
62 assert base64url_decode(urlsafe) == raw
63
64
65 def test_base64url_decode_does_not_warn_on_urlsafe_input() -> None:
66 # Valid URL-safe input must never trigger the Python 3.15+ FutureWarning
67 # about "+"/"/" in URL-safe Base64 data (jpadilla/pyjwt#1167).
68 raw = bytes(range(256))
69 standard = base64.b64encode(raw)
70 urlsafe = base64.urlsafe_b64encode(raw).rstrip(b"=")
71
72 with warnings.catch_warnings():
73 warnings.simplefilter("error", FutureWarning)
74 assert base64url_decode(urlsafe) == raw
75 # A standard-alphabet input is normalised first, so it must also be
76 # decoded without emitting the FutureWarning.
77 assert base64url_decode(standard) == raw
78
79
80 def test_force_bytes_raises_error_on_invalid_object() -> None:
81 with pytest.raises(TypeError):
82 force_bytes({}) # type: ignore[arg-type]
83
84
85 @pytest.mark.parametrize(
86 "key_format",
87 (
88 b"ssh-ed25519",
89 b"ssh-rsa",
90 b"ssh-dss",
91 b"ecdsa-sha2-nistp256",
92 b"ecdsa-sha2-nistp384",
93 b"ecdsa-sha2-nistp521",
94 ),
95 )
96 def test_is_ssh_key(key_format: bytes) -> None:
97 assert is_ssh_key(key_format + b" any") is True
98 assert is_ssh_key(b"not a ssh key") is False