Best Python code snippet using lemoncheesecake
test_with_test_vectors.py
Source:test_with_test_vectors.py
...12import pyseto13from pyseto import Key14from pyseto.versions.v3 import V3Public15from .utils import get_path16def _load_tests(paths: list) -> list:17 tests: list = []18 for path in paths:19 with open(get_path(path)) as tv_file:20 tv = json.loads(tv_file.read())21 tests += tv["tests"]22 return tests23def _name_to_version(name: str) -> int:24 v = name.split(".")[0]25 if len(v) != 2:26 raise ValueError("Invalid PASERK test name.")27 return int(v[1:])28def _public_key_compress(x: int, y: int) -> bytes:29 bx = x.to_bytes(48, byteorder="big")30 by = y.to_bytes((y.bit_length() + 7) // 8, byteorder="big")31 s = bytearray(1)32 s[0] = 0x02 + (by[len(by) - 1] & 1)33 return bytes(s) + bx34def _from_Ed25519PrivateKey_to_X25519PrivateKey(data: bytes) -> X25519PrivateKey:35 hasher = hashes.Hash(hashes.SHA512())36 hasher.update(data)37 h = bytearray(hasher.finalize())38 # curve25519 clamping39 h[0] &= 24840 h[31] &= 12741 h[31] |= 6442 return bytes(h[0:32])43class TestWithTestVectors:44 """45 Tests with test vectors defined in https://github.com/paseto-standard/test-vectors.46 """47 @pytest.mark.parametrize(48 "v",49 _load_tests(50 [51 "vectors/v1.json",52 "vectors/v2.json",53 "vectors/v3.json",54 "vectors/v4.json",55 ]56 ),57 )58 def test_with_test_vectors(self, v):59 token = v["token"].encode("utf-8")60 payload = v["payload"]61 footer = v["footer"].encode("utf-8")62 implicit_assertion = v["implicit-assertion"].encode("utf-8")63 version = int(v["name"].split("-")[0])64 purpose = v["name"].split("-")[1]65 if v["expect-fail"]:66 if "public-key" not in v:67 nonce = bytes.fromhex(v["nonce"])68 key = bytes.fromhex(v["key"])69 k = Key.new(version, "local", key=key)70 with pytest.raises(ValueError) as err:71 pyseto.encode(k, payload, footer, implicit_assertion, nonce=nonce)72 pytest.fail("encode should fail.")73 assert "payload should be bytes, str or dict." in str(err.value)74 return75 secret_key_pem = v["secret-key"] if version == 1 else v["secret-key-pem"]76 public_key_pem = v["public-key"] if version == 1 else v["public-key-pem"]77 sk = Key.new(version, "public", secret_key_pem)78 with pytest.raises(ValueError) as err:79 pyseto.encode(sk, payload, footer, implicit_assertion)80 pytest.fail("encode should fail.")81 assert "payload should be bytes, str or dict." in str(err.value)82 return83 payload = payload.encode("utf-8")84 if purpose == "E":85 nonce = bytes.fromhex(v["nonce"])86 key = bytes.fromhex(v["key"])87 k = Key.new(version, "local", key=key)88 encoded = pyseto.encode(k, payload, footer, implicit_assertion, nonce=nonce)89 decoded_token = pyseto.decode(k, token, implicit_assertion)90 decoded = pyseto.decode(k, encoded, implicit_assertion)91 assert payload == decoded_token.payload == decoded.payload92 return93 if purpose == "S":94 secret_key_pem = v["secret-key"] if version == 1 else v["secret-key-pem"]95 public_key_pem = v["public-key"] if version == 1 else v["public-key-pem"]96 sk = Key.new(version, "public", secret_key_pem)97 encoded = pyseto.encode(sk, payload, footer, implicit_assertion)98 pk = Key.new(version, "public", public_key_pem)99 decoded_token = pyseto.decode(pk, token, implicit_assertion)100 decoded = pyseto.decode(pk, encoded, implicit_assertion)101 assert payload == decoded_token.payload == decoded.payload102 if version == 1:103 return104 secret_key = bytes.fromhex(v["secret-key"])105 public_key = bytes.fromhex(v["public-key"])106 if version == 3:107 # TODO add support for secret-key/public-key on v3.public test vectors.108 return109 sk = Key.from_asymmetric_key_params(version, d=secret_key[0:32])110 encoded = pyseto.encode(sk, payload, footer, implicit_assertion)111 pk = Key.from_asymmetric_key_params(version, x=public_key)112 decoded_token = pyseto.decode(pk, token, implicit_assertion)113 decoded = pyseto.decode(pk, encoded, implicit_assertion)114 assert payload == decoded_token.payload == decoded.payload115 return116 pytest.fail(f"Invalid test name: {v['name']}")117 @pytest.mark.parametrize(118 "v",119 _load_tests(120 [121 "vectors/PASERK/k1.public.json",122 "vectors/PASERK/k2.public.json",123 "vectors/PASERK/k3.public.json",124 "vectors/PASERK/k4.public.json",125 ]126 ),127 )128 def test_with_test_vectors_paserk_public(self, v):129 version = _name_to_version(v["name"])130 if version == 1:131 k = Key.new(version, "public", v["key"])132 elif version == 2 or version == 4:133 k = Key.from_asymmetric_key_params(version, x=bytes.fromhex(v["key"]))134 elif version == 3:135 k = V3Public.from_public_bytes(bytes.fromhex(v["key"]))136 else:137 pytest.fail("Unsupported version.")138 assert k.to_paserk() == v["paserk"]139 k2 = Key.from_paserk(v["paserk"])140 assert k2.to_paserk() == v["paserk"]141 @pytest.mark.parametrize(142 "v",143 _load_tests(144 [145 "vectors/PASERK/k1.secret.json",146 "vectors/PASERK/k2.secret.json",147 "vectors/PASERK/k3.secret.json",148 "vectors/PASERK/k4.secret.json",149 ]150 ),151 )152 def test_with_test_vectors_paserk_secret(self, v):153 version = _name_to_version(v["name"])154 if version == 1:155 k = Key.new(version, "public", v["key"])156 elif version == 2 or version == 4:157 k = Key.from_asymmetric_key_params(version, d=bytes.fromhex(v["secret-key-seed"]))158 elif version == 3:159 pub_k = Key.new(version, "public", bytes.fromhex(v["public-key"]))160 bx = pub_k._key.public_numbers().x.to_bytes(48, byteorder="big")161 by = pub_k._key.public_numbers().y.to_bytes(48, byteorder="big")162 k = Key.from_asymmetric_key_params(version, x=bx, y=by, d=bytes.fromhex(v["key"]))163 else:164 pytest.fail("Unsupported version.")165 assert k.to_paserk() == v["paserk"]166 k2 = Key.from_paserk(v["paserk"])167 assert k2.to_paserk() == v["paserk"]168 @pytest.mark.parametrize(169 "v",170 _load_tests(171 [172 "vectors/PASERK/k1.local.json",173 "vectors/PASERK/k2.local.json",174 "vectors/PASERK/k3.local.json",175 "vectors/PASERK/k4.local.json",176 ]177 ),178 )179 def test_with_test_vectors_paserk_local(self, v):180 version = _name_to_version(v["name"])181 k = Key.new(version, "local", bytes.fromhex(v["key"]))182 k2 = Key.from_paserk(v["paserk"])183 assert k.to_paserk() == v["paserk"]184 assert k2.to_paserk() == v["paserk"]185 @pytest.mark.parametrize(186 "v",187 _load_tests(188 [189 "vectors/PASERK/k1.pid.json",190 "vectors/PASERK/k2.pid.json",191 "vectors/PASERK/k3.pid.json",192 "vectors/PASERK/k4.pid.json",193 ]194 ),195 )196 def test_with_test_vectors_paserk_pid(self, v):197 version = _name_to_version(v["name"])198 if version == 1:199 k = Key.new(version, "public", v["key"])200 elif version == 2 or version == 4:201 k = Key.from_asymmetric_key_params(version, x=bytes.fromhex(v["key"]))202 elif version == 3:203 k = V3Public.from_public_bytes(bytes.fromhex(v["key"]))204 else:205 pytest.fail("Unsupported version.")206 assert k.to_paserk_id() == v["paserk"]207 @pytest.mark.parametrize(208 "v",209 _load_tests(210 [211 "vectors/PASERK/k1.sid.json",212 "vectors/PASERK/k2.sid.json",213 "vectors/PASERK/k3.sid.json",214 "vectors/PASERK/k4.sid.json",215 ]216 ),217 )218 def test_with_test_vectors_paserk_sid(self, v):219 version = _name_to_version(v["name"])220 if version == 1:221 k = Key.new(version, "public", v["key"])222 elif version == 2 or version == 4:223 k = Key.from_asymmetric_key_params(version, d=bytes.fromhex(v["seed"]))224 elif version == 3:225 pub_k = Key.new(version, "public", bytes.fromhex(v["public-key"]))226 bx = pub_k._key.public_numbers().x.to_bytes(48, byteorder="big")227 by = pub_k._key.public_numbers().y.to_bytes(48, byteorder="big")228 k = Key.from_asymmetric_key_params(version, x=bx, y=by, d=bytes.fromhex(v["key"]))229 else:230 pytest.fail("Unsupported version.")231 assert k.to_paserk_id() == v["paserk"]232 @pytest.mark.parametrize(233 "v",234 _load_tests(235 [236 "vectors/PASERK/k1.lid.json",237 "vectors/PASERK/k2.lid.json",238 "vectors/PASERK/k3.lid.json",239 "vectors/PASERK/k4.lid.json",240 ]241 ),242 )243 def test_with_test_vectors_paserk_lid(self, v):244 version = _name_to_version(v["name"])245 k = Key.new(version, "local", bytes.fromhex(v["key"]))246 assert k.to_paserk_id() == v["paserk"]247 @pytest.mark.parametrize(248 "v",249 _load_tests(250 [251 "vectors/PASERK/k1.local-wrap.pie.json",252 "vectors/PASERK/k2.local-wrap.pie.json",253 "vectors/PASERK/k3.local-wrap.pie.json",254 "vectors/PASERK/k4.local-wrap.pie.json",255 ]256 ),257 )258 def test_with_test_vectors_paserk_local_wrap_pie(self, v):259 version = _name_to_version(v["name"])260 k = Key.from_paserk(v["paserk"], wrapping_key=bytes.fromhex(v["wrapping-key"]))261 k1 = Key.new(version, "local", bytes.fromhex(v["unwrapped"]))262 wpk = k1.to_paserk(wrapping_key=bytes.fromhex(v["wrapping-key"]))263 k2 = Key.from_paserk(wpk, wrapping_key=bytes.fromhex(v["wrapping-key"]))264 t = pyseto.encode(k, b"Hello world!")265 d = pyseto.decode(k, t)266 d1 = pyseto.decode(k1, t)267 d2 = pyseto.decode(k2, t)268 assert d.payload == d1.payload == d2.payload == b"Hello world!"269 t = pyseto.encode(k1, b"Hello world!")270 d1 = pyseto.decode(k1, t)271 d2 = pyseto.decode(k2, t)272 assert d1.payload == d2.payload == b"Hello world!"273 d = pyseto.decode(k, t)274 assert d.payload == b"Hello world!"275 @pytest.mark.parametrize(276 "v",277 _load_tests(278 [279 "vectors/PASERK/k1.secret-wrap.pie.json",280 "vectors/PASERK/k2.secret-wrap.pie.json",281 "vectors/PASERK/k3.secret-wrap.pie.json",282 "vectors/PASERK/k4.secret-wrap.pie.json",283 ]284 ),285 )286 def test_with_test_vectors_paserk_secret_wrap_pie(self, v):287 version = _name_to_version(v["name"])288 k = Key.from_paserk(v["paserk"], wrapping_key=bytes.fromhex(v["wrapping-key"]))289 if version == 1:290 k1 = Key.new(version, "public", v["unwrapped"])291 elif version == 2 or version == 4:292 k1 = Key.from_asymmetric_key_params(version, d=bytes.fromhex(v["unwrapped"])[0:32])293 elif version == 3:294 pub_k = Key.new(version, "public", bytes.fromhex(v["public-key"]))295 bx = pub_k._key.public_numbers().x.to_bytes(48, byteorder="big")296 by = pub_k._key.public_numbers().y.to_bytes(48, byteorder="big")297 k1 = Key.from_asymmetric_key_params(version, x=bx, y=by, d=bytes.fromhex(v["unwrapped"]))298 else:299 pytest.fail("Unsupported version.")300 wpk = k1.to_paserk(wrapping_key=bytes.fromhex(v["wrapping-key"]))301 k2 = Key.from_paserk(wpk, wrapping_key=bytes.fromhex(v["wrapping-key"]))302 t = pyseto.encode(k, b"Hello world!")303 d = pyseto.decode(k, t)304 d1 = pyseto.decode(k1, t)305 d2 = pyseto.decode(k2, t)306 assert d.payload == d1.payload == d2.payload == b"Hello world!"307 t = pyseto.encode(k1, b"Hello world!")308 d1 = pyseto.decode(k1, t)309 d2 = pyseto.decode(k2, t)310 assert d1.payload == d2.payload == b"Hello world!"311 d = pyseto.decode(k, t)312 assert d.payload == b"Hello world!"313 @pytest.mark.parametrize(314 "v",315 _load_tests(316 [317 "vectors/PASERK/k1.local-pw.json",318 "vectors/PASERK/k2.local-pw.json",319 "vectors/PASERK/k3.local-pw.json",320 "vectors/PASERK/k4.local-pw.json",321 ]322 ),323 )324 def test_with_test_vectors_paserk_local_pw(self, v):325 version = _name_to_version(v["name"])326 k = Key.from_paserk(v["paserk"], password=v["password"])327 k1 = Key.new(version, "local", bytes.fromhex(v["unwrapped"]))328 if version in [1, 3]:329 wpk = k1.to_paserk(password=v["password"], iteration=v["options"]["iterations"])330 elif version in [2, 4]:331 wpk = k1.to_paserk(332 password=v["password"],333 memory_cost=int(v["options"]["memlimit"] / 1024),334 time_cost=v["options"]["opslimit"],335 )336 else:337 pytest.fail("Unsupported version.")338 k2 = Key.from_paserk(wpk, password=v["password"])339 assert k1._key == k2._key340 t = pyseto.encode(k, b"Hello world!")341 d = pyseto.decode(k, t)342 d1 = pyseto.decode(k1, t)343 d2 = pyseto.decode(k2, t)344 assert d.payload == d1.payload == d2.payload == b"Hello world!"345 t = pyseto.encode(k1, b"Hello world!")346 d1 = pyseto.decode(k1, t)347 d2 = pyseto.decode(k2, t)348 assert d1.payload == d2.payload == b"Hello world!"349 d = pyseto.decode(k, t)350 assert d.payload == b"Hello world!"351 version = _name_to_version(v["name"])352 @pytest.mark.parametrize(353 "v",354 _load_tests(355 [356 "vectors/PASERK/k1.secret-pw.json",357 "vectors/PASERK/k2.secret-pw.json",358 "vectors/PASERK/k3.secret-pw.json",359 "vectors/PASERK/k4.secret-pw.json",360 ]361 ),362 )363 def test_with_test_vectors_paserk_secret_pw(self, v):364 version = _name_to_version(v["name"])365 k = Key.from_paserk(v["paserk"], password=v["password"])366 if version == 1:367 k1 = Key.new(version, "public", v["unwrapped"])368 elif version == 2 or version == 4:369 k1 = Key.from_asymmetric_key_params(version, d=bytes.fromhex(v["unwrapped"])[0:32])370 elif version == 3:371 pub_k = Key.new(version, "public", bytes.fromhex(v["public-key"]))372 bx = pub_k._key.public_numbers().x.to_bytes(48, byteorder="big")373 by = pub_k._key.public_numbers().y.to_bytes(48, byteorder="big")374 k1 = Key.from_asymmetric_key_params(version, x=bx, y=by, d=bytes.fromhex(v["unwrapped"]))375 else:376 pytest.fail("Unsupported version.")377 if version in [1, 3]:378 wpk = k1.to_paserk(password=v["password"], iteration=v["options"]["iterations"])379 elif version in [2, 4]:380 wpk = k1.to_paserk(381 password=v["password"],382 memory_cost=int(v["options"]["memlimit"] / 1024),383 time_cost=v["options"]["opslimit"],384 )385 else:386 pytest.fail("Unsupported version.")387 k2 = Key.from_paserk(wpk, password=v["password"])388 t = pyseto.encode(k, b"Hello world!")389 d = pyseto.decode(k, t)390 d1 = pyseto.decode(k1, t)391 d2 = pyseto.decode(k2, t)392 assert d.payload == d1.payload == d2.payload == b"Hello world!"393 t = pyseto.encode(k1, b"Hello world!")394 d1 = pyseto.decode(k1, t)395 d2 = pyseto.decode(k2, t)396 assert d1.payload == d2.payload == b"Hello world!"397 d = pyseto.decode(k, t)398 assert d.payload == b"Hello world!"399 @pytest.mark.parametrize(400 "v",401 _load_tests(402 [403 "vectors/PASERK/k2.seal.json",404 "vectors/PASERK/k4.seal.json",405 ]406 ),407 )408 def test_with_test_vectors_paserk_seal_v2_v4(self, v):409 version = _name_to_version(v["name"])410 if version == 1:411 raise NotImplementedError("Not implemented.")412 elif version in [2, 4]:413 sk_ed25519 = bytes.fromhex(v["sealing-secret-key"])[0:32]414 tmp_key = _from_Ed25519PrivateKey_to_X25519PrivateKey(sk_ed25519)415 sk_x25519 = X25519PrivateKey.from_private_bytes(tmp_key)416 unsealing_key = sk_x25519.private_bytes(417 Encoding.PEM,418 PrivateFormat.PKCS8,419 NoEncryption(),420 )421 sealing_key = sk_x25519.public_key().public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)422 elif version == 3:423 sk = load_pem_private_key(v["sealing-secret-key"].encode("utf-8"), password=None)424 unsealing_key = sk.private_numbers().private_value.to_bytes(48, byteorder="big")425 sealing_key = _public_key_compress(426 sk.private_numbers().public_numbers.x,427 sk.private_numbers().public_numbers.y,428 )429 else:430 pytest.fail("Unsupported version.")431 k = Key.from_paserk(v["paserk"], unsealing_key=unsealing_key)432 k1 = Key.new(version, "local", bytes.fromhex(v["unsealed"]))433 wpk = k1.to_paserk(sealing_key=sealing_key)434 k2 = Key.from_paserk(wpk, unsealing_key=unsealing_key)435 assert k1._key == k2._key436 t = pyseto.encode(k, b"Hello world!")437 d = pyseto.decode(k, t)438 d1 = pyseto.decode(k1, t)439 d2 = pyseto.decode(k2, t)440 assert d.payload == d1.payload == d2.payload == b"Hello world!"441 t = pyseto.encode(k1, b"Hello world!")442 d1 = pyseto.decode(k1, t)443 d2 = pyseto.decode(k2, t)444 assert d1.payload == d2.payload == b"Hello world!"445 d = pyseto.decode(k, t)446 assert d.payload == b"Hello world!"447 # @pytest.mark.parametrize(448 # "v",449 # _load_tests(450 # [451 # # "vectors/PASERK/k1.seal.json",452 # "vectors/PASERK/k3.seal.json",453 # ]454 # ),455 # )456 # def test_with_test_vectors_paserk_seal_v1_v3(self, v):457 # version = _name_to_version(v["name"])458 # if version == 1:459 # raise NotImplementedError("Not implemented.")460 # elif version == 3:461 # sk = load_pem_private_key(462 # v["sealing-secret-key"].encode("utf-8"), password=None463 # )...
__init__.py
Source:__init__.py
1import unittest2import os.path3def _load_tests(loader, standard_tests, pattern):4 this_dir = os.path.dirname(__file__)5 package_tests = loader.discover(start_dir=this_dir, pattern=pattern)6 standard_tests.addTests(package_tests)7 return standard_tests8def get_tests():...
main.py
Source:main.py
1import unittest2def _load_tests():3 """Test suite for tests"""4 test_loader = unittest.TestLoader()5 test_suite = test_loader.discover('.')6 return test_suite7if __name__ == "__main__":8 result = unittest.TextTestRunner(verbosity=2).run(_load_tests())9 if result.wasSuccessful():10 exit(0)11 else:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!