From 1e46458705f79cc134a69ec4c11b2d576f8186f3 Mon Sep 17 00:00:00 2001 From: Daana Honarmand <68249577+DaanaH-dev@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:37:43 -0500 Subject: [PATCH 01/12] removed previous tests --- .devcontainer/devcontainer.json | 22 ++ tests/crypto_addresses/test_bsc_address.py | 52 --- tests/crypto_addresses/test_btc_address.py | 43 --- .../test_complete_addresses.py | 25 -- tests/crypto_addresses/test_eth_address.py | 46 --- tests/crypto_addresses/test_trx_address.py | 54 ---- tests/i18n/test_es.py | 155 --------- tests/i18n/test_fi.py | 110 ------- tests/i18n/test_fr.py | 100 ------ tests/i18n/test_ind.py | 48 --- tests/i18n/test_ru.py | 67 ---- tests/test.py | 0 tests/test__extremes.py | 56 ---- tests/test_between.py | 40 --- tests/test_card.py | 219 ------------- tests/test_complete_values.py | 31 -- tests/test_country.py | 84 ----- tests/test_cron.py | 59 ---- tests/test_domain.py | 239 -------------- tests/test_email.py | 74 ----- tests/test_encoding.py | 151 --------- tests/test_finance.py | 90 ------ tests/test_hashes.py | 246 -------------- tests/test_hostname.py | 173 ---------- tests/test_iban.py | 33 -- tests/test_ip_address.py | 206 ------------ tests/test_length.py | 25 -- tests/test_mac_address.py | 35 -- tests/test_slug.py | 143 --------- tests/test_uri.py | 75 ----- tests/test_url.py | 301 ------------------ tests/test_uuid.py | 39 --- tests/test_validation_failure.py | 71 ----- 33 files changed, 22 insertions(+), 3090 deletions(-) create mode 100644 .devcontainer/devcontainer.json delete mode 100644 tests/crypto_addresses/test_bsc_address.py delete mode 100644 tests/crypto_addresses/test_btc_address.py delete mode 100644 tests/crypto_addresses/test_complete_addresses.py delete mode 100644 tests/crypto_addresses/test_eth_address.py delete mode 100644 tests/crypto_addresses/test_trx_address.py delete mode 100644 tests/i18n/test_es.py delete mode 100644 tests/i18n/test_fi.py delete mode 100644 tests/i18n/test_fr.py delete mode 100644 tests/i18n/test_ind.py delete mode 100644 tests/i18n/test_ru.py create mode 100644 tests/test.py delete mode 100644 tests/test__extremes.py delete mode 100644 tests/test_between.py delete mode 100644 tests/test_card.py delete mode 100644 tests/test_complete_values.py delete mode 100644 tests/test_country.py delete mode 100644 tests/test_cron.py delete mode 100644 tests/test_domain.py delete mode 100644 tests/test_email.py delete mode 100644 tests/test_encoding.py delete mode 100644 tests/test_finance.py delete mode 100644 tests/test_hashes.py delete mode 100644 tests/test_hostname.py delete mode 100644 tests/test_iban.py delete mode 100644 tests/test_ip_address.py delete mode 100644 tests/test_length.py delete mode 100644 tests/test_mac_address.py delete mode 100644 tests/test_slug.py delete mode 100644 tests/test_uri.py delete mode 100644 tests/test_url.py delete mode 100644 tests/test_uuid.py delete mode 100644 tests/test_validation_failure.py diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 00000000..1bf3a2a1 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,22 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/python +{ + "name": "Python 3", + // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile + "image": "mcr.microsoft.com/devcontainers/python:3-3.11-bookworm" + + // Features to add to the dev container. More info: https://containers.dev/features. + // "features": {}, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Use 'postCreateCommand' to run commands after the container is created. + // "postCreateCommand": "pip3 install --user -r requirements.txt", + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/tests/crypto_addresses/test_bsc_address.py b/tests/crypto_addresses/test_bsc_address.py deleted file mode 100644 index 8e61dbc4..00000000 --- a/tests/crypto_addresses/test_bsc_address.py +++ /dev/null @@ -1,52 +0,0 @@ -"""Test BSC address.""" - -# external -import pytest - -# local -from validators import ValidationError, bsc_address - - -@pytest.mark.parametrize( - "value", - [ - "0x4e5acf9684652BEa56F2f01b7101a225Ee33d23f", - "0x22B0f92af10FdC25659e4C3A590c2F0D0c809c27", - "0xb61724F993E7942ef2d8e4A94fF7c9e1cc26995F", - "0x9c3dF8a511Fec8076D4B8EFb4d5E733B9F953dD7", - "0x4536337B91c0623a4FD098023E6065e4773117c5", - "0xAC484e1CE274eD1d40A7C2AeAb0bEA863634286F", - "0x1FDE521fBe3483Cbb5957E6275028225a74387e4", - "0x1693c3D1bA787Ba2bf81ac8897614AAaee5cb800", - "0xf4C3Fd476A40658aEd9e595DA49c37d8965D2fFE", - "0xc053E3D4932640787D6Cf67FcA36021E7BE62653", - "0xaFd563A5aED0bC363e802842aD93Af46c1168b8a", - ], -) -def test_returns_true_on_valid_bsc_address(value: str): - """Test returns true on valid bsc address.""" - assert bsc_address(value) - - -@pytest.mark.parametrize( - "value", - [ - "1x32Be343B94f860124dC4fEe278FDCBD38C102D88", - "0x32Be343B94f860124dC4fEe278FDCBD38C102D", - "0x32Be343B94f860124dC4fEe278FDCBD38C102D88aabbcc", - "0x4g5acf9684652BEa56F2f01b7101a225Eh33d23z", - "0x", - "Wrong@Address.com", - "0x32Be343B94f860124dC4fEe278FDCBD38C102D__", - "0x32Be343B94f860124dC4fEe278FDCBD38C102D88G", - "0X32Be343B94f860124dC4fEe278FDCBD38C102D88", - "0X32BE343B94F860124DCFEE278FDCBD38C102D88", - "0x32Be 343B94f860124dC4fEe278FDCBD38C102D88", - "0x32Be343B94f860124dC4fEe278FDCBD38C102D88!", - "ox32Be343B94f860124dC4fEe278FDCBD38C102D88", - "0x32Be343B94f860124dC4fEe278FDCBD38C102D88XYZ", - ], -) -def test_returns_failed_validation_on_invalid_bsc_address(value: str): - """Test returns failed validation on invalid bsc address.""" - assert isinstance(bsc_address(value), ValidationError) diff --git a/tests/crypto_addresses/test_btc_address.py b/tests/crypto_addresses/test_btc_address.py deleted file mode 100644 index 96647eab..00000000 --- a/tests/crypto_addresses/test_btc_address.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Test BTC address.""" - -# external -import pytest - -# local -from validators import ValidationError, btc_address - - -@pytest.mark.parametrize( - "value", - [ - # P2PKH (Pay-to-PubkeyHash) type - "1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2", - # P2SH (Pay to script hash) type - "3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy", - # Bech32/segwit type - "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", - "bc1qc7slrfxkknqcq2jevvvkdgvrt8080852dfjewde450xdlk4ugp7szw5tk9", - # Bech32/segwit testnet (tb prefix) - "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx", - "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3", - ], -) -def test_returns_true_on_valid_btc_address(value: str): - """Test returns true on valid btc address.""" - assert btc_address(value) - - -@pytest.mark.parametrize( - "value", - [ - "ff3Cwgr2g7vsi1bXDUkpEnVoRLA9w4FZfC69", - "b3Cgwgr2g7vsi1bXyjyDUkphEnVoRLA9w4FZfC69", - # incorrect header - "1BvBMsEYstWetqTFn5Au4m4GFg7xJaNVN2", - # incorrect checksum - "3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLz", - ], -) -def test_returns_failed_validation_on_invalid_btc_address(value: str): - """Test returns failed validation on invalid btc address.""" - assert isinstance(btc_address(value), ValidationError) diff --git a/tests/crypto_addresses/test_complete_addresses.py b/tests/crypto_addresses/test_complete_addresses.py deleted file mode 100644 index 362d2d5c..00000000 --- a/tests/crypto_addresses/test_complete_addresses.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Require complete BTC and ETH addresses.""" - -from typing import Callable - -import pytest - -from validators import ValidationError, btc_address, eth_address - - -@pytest.mark.parametrize( - "validate,value", - [ - (btc_address, "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq"), - (btc_address, "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx"), - (eth_address, "0x9cc14ba4f9f68ca159ea4ebf2c292a808aaeb598"), - (eth_address, "0x9CC14BA4F9F68CA159EA4EBF2C292A808AAEB598"), - ], -) -@pytest.mark.parametrize("suffix", ["", "\n", "\r\n", " ", "\nextra"]) -def test_complete_address(validate: Callable[[str], object], value: str, suffix: str): - """Accept the address alone and reject trailing characters.""" - if suffix: - assert isinstance(validate(value + suffix), ValidationError) - else: - assert validate(value) is True diff --git a/tests/crypto_addresses/test_eth_address.py b/tests/crypto_addresses/test_eth_address.py deleted file mode 100644 index de2fd313..00000000 --- a/tests/crypto_addresses/test_eth_address.py +++ /dev/null @@ -1,46 +0,0 @@ -"""Test ETH address.""" - -# external -import pytest - -# local -from validators import ValidationError, eth_address - - -@pytest.mark.parametrize( - "value", - [ - "0x8ba1f109551bd432803012645ac136ddd64dba72", - "0x9cc14ba4f9f68ca159ea4ebf2c292a808aaeb598", - "0x5AEDA56215b167893e80B4fE645BA6d5Bab767DE", - "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", - "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", - "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984", - "0x1234567890123456789012345678901234567890", - "0x57Ab1ec28D129707052df4dF418D58a2D46d5f51", - ], -) -def test_returns_true_on_valid_eth_address(value: str): - """Test returns true on valid eth address.""" - assert eth_address(value) - - -@pytest.mark.parametrize( - "value", - [ - "0x742d35Cc6634C0532925a3b844Bc454e4438f44g", - "0x742d35Cc6634C0532925a3b844Bc454e4438f44", - "0xAbcdefg1234567890Abcdefg1234567890Abcdefg", - "0x7c8EE9977c6f96b6b9774b3e8e4Cc9B93B12b2c72", - "0x80fBD7F8B3f81D0e1d6EACAb69AF104A6508AFB1", - "0x7c8EE9977c6f96b6b9774b3e8e4Cc9B93B12b2c7g", - "0x7c8EE9977c6f96b6b9774b3e8e4Cc9B93B12b2c", - "0x7Fb21a171205f3B8d8E4d88A2d2f8A56E45DdB5c", - "validators.eth", - # non-hex characters (the checksum path used to accept these) - "0x" + "*" * 40, - ], -) -def test_returns_failed_validation_on_invalid_eth_address(value: str): - """Test returns failed validation on invalid eth address.""" - assert isinstance(eth_address(value), ValidationError) diff --git a/tests/crypto_addresses/test_trx_address.py b/tests/crypto_addresses/test_trx_address.py deleted file mode 100644 index 68bb0d94..00000000 --- a/tests/crypto_addresses/test_trx_address.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Test TRX address.""" - -# external -import pytest - -# local -from validators import ValidationError, trx_address - - -@pytest.mark.parametrize( - "value", - [ - "TLjfbTbpZYDQ4EoA4N5CLNgGjfbF8ZWz38", - "TDQ6C92wuNqvMWE967sMptCFaXq77uj1PF", - "TFuGbxCQGSL4oLnJzVsen844LDwFbrUY4e", - "TFAPKADDRhkSe3v27CsR8TZSjN8eJ8ycDK", - "TSJHywLNva2MNjCD5iYfn5QAKD9Rk5Ncit", - "TEi1qhi5LuTicg1u9oAstyXCSf5uibSyqo", - "TAGvx5An6VBeHTu91cQwdABNcAYMRPcP4n", - "TXbE5tXTejqT3Q47sYKCDb9NJDm3xrFpab", - "TMTxQWNuWHXvHcYXc5D1wQhFmZFJijAxcG", - "TPHgw9E8QYM3esNWih5KVnUVpUHwLTPfpA", - "TFFLtBTi9jdaGwV3hznjCmPYaJme5AeqwU", - "TC74QG8tbtixG5Raa4fEifywgjrFs45fNz", - ], -) -def test_returns_true_on_valid_trx_address(value: str): - """Test returns true on valid trx address.""" - assert trx_address(value) - - -@pytest.mark.parametrize( - "value", - [ - "T12345678901234567890123456789012345", - "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678", - "TR2G7Rm4vFqF8EpY4U5xdLdQ7XgJ2U8Vd", - "TP6ah2v5mdsj8Z3hGz1yDMvDq7BzEbK8o", - "TQmmhp6uz2Xre8yL3FsPYZyo4mhtw4vg4XX", - "TQNy2C6VHJPk4P32bsEX3QSGx2Qqm4J2k9", - "TP6ah2v5mdsj8Z3hGz1yDMvDq7BzEbK8oN", - "TSTVdfU1x4L7K3Bc3v5C28Gp2J1rPyeL3f", - "THPByuCzvU5QER9j2NC2mUQ2JPyRCam4e7", - "TW5eZqUZgdW4rxFKAKsc2ryJbfFA94WXvD", - "TR2G7Rm4vFqF8EpY4U5xdLdQ7XgJ2U8Vdd", - "tQmmhp6uz2Xre8yL3FsPYZyo4mhtw4vg4X", - "TR2G7Rm4vFqF8EpY4U5xdLdQ7Xg", - "TQmmhp6uz2Xre8yL3FsPYZyo4mhtw4vg4x", - "my-trox-address.trx", - ], -) -def test_returns_failed_validation_on_invalid_trx_address(value: str): - """Test returns failed validation on invalid trx address.""" - assert isinstance(trx_address(value), ValidationError) diff --git a/tests/i18n/test_es.py b/tests/i18n/test_es.py deleted file mode 100644 index 55790400..00000000 --- a/tests/i18n/test_es.py +++ /dev/null @@ -1,155 +0,0 @@ -"""Test i18n/es.""" - -from typing import Callable - -# external -import pytest - -# local -from validators import ValidationError, es_cif, es_doi, es_nie, es_nif - - -@pytest.mark.parametrize( - ("value",), - [ - ("B25162520",), - ("U4839822F",), - ("B96817697",), - ("P7067074J",), - ("Q7899705C",), - ("C75098681",), - ("G76061860",), - ("C71345375",), - ("G20558169",), - ("U5021960I",), - ], -) -def test_returns_true_on_valid_cif(value: str): - """Test returns true on valid cif.""" - assert es_cif(value) - - -@pytest.mark.parametrize( - ("value",), - [ - ("12345",), - ("ABCDEFGHI",), - ("Z5021960I",), - ], -) -def test_returns_false_on_invalid_cif(value: str): - """Test returns false on invalid cif.""" - result = es_cif(value) - assert isinstance(result, ValidationError) - - -@pytest.mark.parametrize( - ("value",), - [ - ("X0095892M",), - ("X8868108K",), - ("X2911154K",), - ("Y2584969J",), - ("X7536157T",), - ("Y5840388N",), - ("Z2915723H",), - ("Y4002236C",), - ("X7750702R",), - ("Y0408759V",), - ], -) -def test_returns_true_on_valid_nie(value: str): - """Test returns true on valid nie.""" - assert es_nie(value) - - -@pytest.mark.parametrize( - ("value",), - [ - ("K0000023T",), - ("L0000024R",), - ("M0000025W",), - ("00000026A",), - ("00000027G",), - ("00000028M",), - ("00000029Y",), - ("00000030F",), - ("00000031P",), - ("00000032D",), - ("00000033X",), - ("00000034B",), - ("00000035N",), - ("00000036J",), - ("00000037Z",), - ("00000038S",), - ("00000039Q",), - ("00000040V",), - ("00000041H",), - ("00000042L",), - ("00000043C",), - ("00000044K",), - ("00000045E",), - ], -) -def test_returns_true_on_valid_nif(value: str): - """Test returns true on valid nif.""" - assert es_nif(value) - - -def test_returns_false_on_invalid_nif(): - """Test returns false on invalid nif.""" - result = es_nif("12345") - assert isinstance(result, ValidationError) - - -@pytest.mark.parametrize( - ("value",), - [ - # CIFs - ("B25162520",), - ("U4839822F",), - ("B96817697",), - # NIEs - ("X0000000T",), - ("X0095892M",), - ("X8868108K",), - ("X2911154K",), - # NIFs - ("00000001R",), - ("00000000T",), - ("26643189N",), - ("07060225F",), - ("49166693F",), - ], -) -def test_returns_true_on_valid_doi(value: str): - """Test returns true on valid doi.""" - assert es_doi(value) - - -@pytest.mark.parametrize( - "digits", - [ - "\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19", - "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669", - "\u0966\u0967\u0968\u0969\u096a\u096b\u096c\u096d\u096e\u096f", - ], -) -@pytest.mark.parametrize( - "validate,value", - [ - (es_nif, "26643189N"), - (es_nie, "X0095892M"), - (es_cif, "B25162520"), - (es_doi, "26643189N"), - (es_doi, "X0095892M"), - (es_doi, "B25162520"), - ], -) -def test_spanish_identifiers_reject_non_ascii_digits( - validate: Callable[[str], object], value: str, digits: str -): - """Reject lookalike digit bodies even when their numeric checksums agree.""" - translated = value[:-1].translate(str.maketrans("0123456789", digits)) + value[-1] - assert validate(value) is True - assert isinstance(validate(translated), ValidationError) diff --git a/tests/i18n/test_fi.py b/tests/i18n/test_fi.py deleted file mode 100644 index ffbe206e..00000000 --- a/tests/i18n/test_fi.py +++ /dev/null @@ -1,110 +0,0 @@ -"""Test i18n/es.""" - -# external -import pytest - -# local -from validators import ValidationError -from validators.i18n.fi import fi_business_id, fi_ssn - - -@pytest.mark.parametrize( - ("value",), - [ - ("2336509-6",), # Supercell - ("0112038-9",), # Fast Monkeys - ("2417581-7",), # Nokia - ], -) -def test_returns_true_on_valid_business_id(value: str): - """Test returns true on valid business id.""" - assert fi_business_id(value) - - -@pytest.mark.parametrize( - ("value",), - [ - (None,), - ("",), - ("1233312312",), - ("1333333-8",), - ("1231233-9",), - ], -) -def test_returns_failed_validation_on_invalid_business_id(value: str): - """Test returns failed validation on invalid business id.""" - assert isinstance(fi_business_id(value), ValidationError) - - -@pytest.mark.parametrize( - ("value",), - [ - ("010190-002R",), - ("010101-0101",), - ("010101+0101",), - ("010101A0101",), - ("010190-900P",), - ("020516C903K",), - ("010594Y9032",), - ], -) -def test_returns_true_on_valid_ssn(value: str): - """Test returns true on valid ssn.""" - assert fi_ssn(value) - - -@pytest.mark.parametrize( - ("value",), - [ - (None,), - ("",), - ("010190-001P",), # Too low serial - ("010190-000N",), # Too low serial - ("000190-0023",), # Invalid day - ("010090-002X",), # Invalid month - ("010190-002r",), # Invalid checksum - ("101010-0102",), - ("10a010-0101",), - ("101010-0\xe401",), - ("101010b0101",), - ("0205169C03K",), - ("0105949Y032",), - ], -) -def test_returns_failed_validation_on_invalid_ssn(value: str): - """Test returns failed validation on invalid_ssn.""" - assert isinstance(fi_ssn(value), ValidationError) - - -def test_returns_failed_validation_on_temporal_ssn_when_not_allowed(): - """Test returns failed validation on temporal-ssn when not allowed.""" - assert isinstance(fi_ssn("010190-900P", allow_temporal_ssn=False), ValidationError) - - -@pytest.mark.parametrize( - ("birth_date", "century", "valid"), - [ - ("310299", "-", False), - ("310499", "-", False), - ("290201", "A", False), - ("290200", "+", False), - ("290200", "-", False), - ("290200", "Y", False), - ("290200", "A", True), - ("290200", "F", True), - ("290204", "-", True), - ("290204", "U", True), - ], -) -def test_ssn_validates_birth_date_in_its_century(birth_date: str, century: str, valid: bool): - """Reject impossible birth dates even when the control character is correct.""" - serial = "010" - checksum = "0123456789ABCDEFHJKLMNPRSTUVWXY"[int(birth_date + serial) % 31] - value = birth_date + century + serial + checksum - assert bool(fi_ssn(value)) is valid - - -@pytest.mark.parametrize("value", ["1\u06631052-308T", "1310\u06652-308T", "131052-3\u06608T"]) -def test_returns_failed_validation_on_non_ascii_digits_in_ssn(value: str): - """Test returns failed validation when a script other than ASCII supplies the digits.""" - assert isinstance(fi_ssn(value), ValidationError) diff --git a/tests/i18n/test_fr.py b/tests/i18n/test_fr.py deleted file mode 100644 index f25c87c5..00000000 --- a/tests/i18n/test_fr.py +++ /dev/null @@ -1,100 +0,0 @@ -"""Test French validators.""" - -# standard -from typing import Union - -# external -import pytest - -# local -from validators import ValidationError -from validators.i18n.fr import fr_department, fr_ssn - - -@pytest.mark.parametrize( - ("value",), - [ - ("1 84 12 76 451 089 46",), - ("1 84 12 76 451 089",), # control key is optional - ("2 99 05 75 202 818 97",), - ("2 99 05 75 202 817 01",), - ("2 99 05 2A 202 817 58",), - ("2 99 05 2B 202 817 85",), - ("2 99 05 971 12 817 70",), - ], -) -def test_returns_true_on_valid_ssn(value: str): - """Test returns true on valid ssn.""" - assert fr_ssn(value) - - -@pytest.mark.parametrize( - ("value",), - [ - (None,), - ("",), - ("3 84 12 76 451 089 46",), # wrong gender number - (", 84 12 76 451 089",), # comma is not a valid gender (regex char-class bug) - ("1 84 12 76 451 089 47",), # wrong control key - ("1 84 00 76 451 089",), # invalid month - ("1 84 13 76 451 089",), # invalid month - ("1 84 12 00 451 089",), # invalid department - ("1 84 12 2C 451 089",), - ("1 84 12 98 451 089",), # invalid department - # ("1 84 12 971 451 089",), # ? - ], -) -def test_returns_failed_validation_on_invalid_ssn(value: str): - """Test returns failed validation on invalid_ssn.""" - assert isinstance(fr_ssn(value), ValidationError) - - -@pytest.mark.parametrize( - ("value",), - [ - ("01",), - ("2A",), # Corsica - ("2B",), - (14,), - ("95",), - ("971",), - (971,), - ], -) -def test_returns_true_on_valid_department(value: Union[str, int]): - """Test returns true on valid department.""" - assert fr_department(value) - - -@pytest.mark.parametrize( - ("value",), - [ - (None,), - ("",), - ("00",), - (0,), - ("2C",), - ("97",), - ("978",), - ("98",), - ("96",), - ("20",), - (20,), - ], -) -def test_returns_failed_validation_on_invalid_department(value: Union[str, int]): - """Test returns failed validation on invalid department.""" - assert isinstance(fr_department(value), ValidationError) - - -@pytest.mark.parametrize( - "value", - [ - "1 \u06684 12 76 451 089 46", # Arabic-Indic digit - "1 84 12 76 451 089 \uff146", # fullwidth digit - "1\u00a084 12 76 451 089 46", # no-break space - ], -) -def test_returns_failed_validation_on_non_ascii_digits_or_spaces_in_ssn(value: str): - """Test returns failed validation on digits or spaces outside ASCII.""" - assert isinstance(fr_ssn(value), ValidationError) diff --git a/tests/i18n/test_ind.py b/tests/i18n/test_ind.py deleted file mode 100644 index 9ee64028..00000000 --- a/tests/i18n/test_ind.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Test Indian validators.""" - -# external -import pytest - -# local -from validators import ValidationError -from validators.i18n import ind_aadhar, ind_pan - - -@pytest.mark.parametrize("value", ["3675 9834 6012", "5046 3182 4299"]) -def test_returns_true_on_valid_ind_aadhar(value: str): - """Test returns true on valid ind aadhar.""" - assert ind_aadhar(value) - - -@pytest.mark.parametrize("value", ["3675 9834 6012 8", "417598346012", "3675 98AF 60#2"]) -def test_returns_failed_validation_on_invalid_ind_aadhar(value: str): - """Test returns failed validation on invalid ind aadhar.""" - assert isinstance(ind_aadhar(value), ValidationError) - - -@pytest.mark.parametrize("value", ["ABCDE9999K", "AAAPL1234C"]) -def test_returns_true_on_valid_ind_pan(value: str): - """Test returns true on valid ind pan.""" - assert ind_pan(value) - - -@pytest.mark.parametrize( - "value", ["ABC5d7896B", "417598346012", "AaaPL1234C", "ABCDE9999Kextra", "ABCDE9999K "] -) -def test_returns_failed_validation_on_invalid_ind_pan(value: str): - """Test returns failed validation on invalid ind pan.""" - assert isinstance(ind_pan(value), ValidationError) - - -@pytest.mark.parametrize( - "value", ["3\u066675 9834 6012", "3675 9834 601\uff12", "3675\u00a09834 6012"] -) -def test_returns_failed_validation_on_non_ascii_digits_or_spaces_in_ind_aadhar(value: str): - """Test returns failed validation on digits or spaces outside ASCII.""" - assert isinstance(ind_aadhar(value), ValidationError) - - -@pytest.mark.parametrize("value", ["ABCDE\u0669999K", "ABCDE999\uff19K"]) -def test_returns_failed_validation_on_non_ascii_digits_in_ind_pan(value: str): - """Test returns failed validation when a script other than ASCII supplies the digits.""" - assert isinstance(ind_pan(value), ValidationError) diff --git a/tests/i18n/test_ru.py b/tests/i18n/test_ru.py deleted file mode 100644 index 5c7017e4..00000000 --- a/tests/i18n/test_ru.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Test i18n/inn.""" - -# external -import pytest - -# local -from validators import ValidationError -from validators.i18n.ru import ru_inn - - -@pytest.mark.parametrize( - ("value",), - [ - ("2222058686",), - ("7709439560",), - ("5003052454",), - ("7730257499",), - ("3664016814",), - ("026504247480",), - ("780103209220",), - ("7707012148",), - ("140700989885",), - ("774334078053",), - ], -) -def test_returns_true_on_valid_ru_inn(value: str): - """Test returns true on valid russian individual tax number.""" - assert ru_inn(value) - - -@pytest.mark.parametrize( - ("value",), - [ - ("2222058687",), - ("7709439561",), - ("5003052453",), - ("7730257490",), - ("3664016815",), - ("026504247481",), - ("780103209222",), - ("7707012149",), - ("140700989886",), - ("774334078054",), - ], -) -def test_returns_false_on_valid_ru_inn(value: str): - """Test returns true on valid russian individual tax number.""" - assert isinstance(ru_inn(value), ValidationError) - - -@pytest.mark.parametrize( - "value", - [ - "500100732266", # First check digit is wrong; the second matches. - "100000001103", # First remainder is 10; the second check digit is wrong. - "100000000781", # Second remainder is 10; its check digit must be zero. - ], -) -def test_individual_inn_requires_both_check_digits(value: str): - """Reject an individual INN when either check digit is wrong.""" - assert isinstance(ru_inn(value), ValidationError) - - -@pytest.mark.parametrize("value", ["500100732259", "100000001102", "100000000780"]) -def test_individual_inn_check_digit_remainders(value: str): - """Accept both ordinary remainders and remainder 10 mapped to zero.""" - assert ru_inn(value) is True diff --git a/tests/test.py b/tests/test.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/test__extremes.py b/tests/test__extremes.py deleted file mode 100644 index 412d2092..00000000 --- a/tests/test__extremes.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Test Extremes.""" - -# standard -from typing import Any - -# external -import pytest - -# local -from validators._extremes import AbsMax, AbsMin - -abs_max = AbsMax() -abs_min = AbsMin() - - -@pytest.mark.parametrize( - ("value",), - [(None,), ("",), (12,), (abs_min,)], -) -def test_abs_max_is_greater_than_every_other_value(value: Any): - """Test if AbsMax is greater than every other value.""" - assert value < abs_max - assert abs_max > value - - -def test_abs_max_is_not_greater_than_itself(): - """Test if AbsMax is not greater than itself.""" - assert not (abs_max > abs_max) - - -def test_other_comparison_methods_for_abs_max(): - """Test other comparison methods for AbsMax.""" - assert abs_max <= abs_max - assert abs_max == abs_max - assert abs_max == abs_max - - -@pytest.mark.parametrize( - ("value",), - [(None,), ("",), (12,), (abs_max,)], -) -def test_abs_min_is_smaller_than_every_other_value(value: Any): - """Test if AbsMin is less than every other value.""" - assert value > abs_min - - -def test_abs_min_is_not_greater_than_itself(): - """Test if AbsMin is not less than itself.""" - assert not (abs_min < abs_min) - - -def test_other_comparison_methods_for_abs_min(): - """Test other comparison methods for AbsMin.""" - assert abs_min <= abs_min - assert abs_min == abs_min - assert abs_min == abs_min diff --git a/tests/test_between.py b/tests/test_between.py deleted file mode 100644 index bdb71551..00000000 --- a/tests/test_between.py +++ /dev/null @@ -1,40 +0,0 @@ -"""Test Between.""" - -# standard -from datetime import datetime -from typing import TypeVar - -# external -import pytest - -# local -from validators import ValidationError, between - -T = TypeVar("T", int, float, str, datetime) - - -@pytest.mark.parametrize( - ("value", "min_val", "max_val"), - [(12, 11, 13), (12, None, 14), (12, 11, None), (12, 12, 12), (0, 0, 0), (0, -1, 3)], -) -def test_returns_true_on_valid_range(value: T, min_val: T, max_val: T): - """Test returns true on valid range.""" - assert between(value, min_val=min_val, max_val=max_val) - - -@pytest.mark.parametrize( - ("value", "min_val", "max_val"), - [ - (None, 13, 14), - (12, 13, 14), - (12, None, 11), - (12, 13, None), - (12, "13.5", datetime(1970, 1, 1)), - ("12", 20.5, "None"), - (datetime(1970, 1, 1), 20, "string"), - (30, 40, "string"), - ], -) -def test_returns_failed_validation_on_invalid_range(value: T, min_val: T, max_val: T): - """Test returns failed validation on invalid range.""" - assert isinstance(between(value, min_val=min_val, max_val=max_val), ValidationError) diff --git a/tests/test_card.py b/tests/test_card.py deleted file mode 100644 index c17f5d95..00000000 --- a/tests/test_card.py +++ /dev/null @@ -1,219 +0,0 @@ -"""Test Card.""" - -# external -import pytest - -# local -from validators import ( - ValidationError, - amex, - card_number, - diners, - discover, - jcb, - mastercard, - mir, - unionpay, - visa, -) - -visa_cards = ["4242424242424242", "4000002760003184"] -mastercard_cards = ["5555555555554444", "2223003122003222"] -amex_cards = ["378282246310005", "371449635398431"] -unionpay_cards = ["6200000000000005"] -diners_cards = ["3056930009020004", "36227206271667"] -jcb_cards = ["3566002020360505"] -discover_cards = ["6011111111111117", "6011000990139424"] -mir_cards = ["2200123456789019", "2204987654321098"] - - -@pytest.mark.parametrize( - "value", - visa_cards - + mastercard_cards - + amex_cards - + unionpay_cards - + diners_cards - + jcb_cards - + discover_cards - + mir_cards, -) -def test_returns_true_on_valid_card_number(value: str): - """Test returns true on valid card number.""" - assert card_number(value) - - -@pytest.mark.parametrize( - "value", - [ - "4242424242424240", - "4000002760003180", - "400000276000318X", - "220012345678901X", - ], -) -def test_returns_failed_on_valid_card_number(value: str): - """Test returns failed on valid card number.""" - assert isinstance(card_number(value), ValidationError) - - -@pytest.mark.parametrize("value", visa_cards) -def test_returns_true_on_valid_visa(value: str): - """Test returns true on valid visa.""" - assert visa(value) - - -@pytest.mark.parametrize( - "value", - mastercard_cards + amex_cards + unionpay_cards + diners_cards + jcb_cards + discover_cards, -) -def test_returns_failed_on_valid_visa(value: str): - """Test returns failed on valid visa.""" - assert isinstance(visa(value), ValidationError) - - -@pytest.mark.parametrize("value", mastercard_cards) -def test_returns_true_on_valid_mastercard(value: str): - """Test returns true on valid mastercard.""" - assert mastercard(value) - - -@pytest.mark.parametrize( - "value", - visa_cards - + amex_cards - + unionpay_cards - + diners_cards - + jcb_cards - + discover_cards - + mir_cards, -) -def test_returns_failed_on_valid_mastercard(value: str): - """Test returns failed on valid mastercard.""" - assert isinstance(mastercard(value), ValidationError) - - -@pytest.mark.parametrize("value", amex_cards) -def test_returns_true_on_valid_amex(value: str): - """Test returns true on valid amex.""" - assert amex(value) - - -@pytest.mark.parametrize( - "value", - visa_cards - + mastercard_cards - + unionpay_cards - + diners_cards - + jcb_cards - + discover_cards - + mir_cards, -) -def test_returns_failed_on_valid_amex(value: str): - """Test returns failed on valid amex.""" - assert isinstance(amex(value), ValidationError) - - -@pytest.mark.parametrize("value", unionpay_cards) -def test_returns_true_on_valid_unionpay(value: str): - """Test returns true on valid unionpay.""" - assert unionpay(value) - - -@pytest.mark.parametrize( - "value", - visa_cards - + mastercard_cards - + amex_cards - + diners_cards - + jcb_cards - + discover_cards - + mir_cards, -) -def test_returns_failed_on_valid_unionpay(value: str): - """Test returns failed on valid unionpay.""" - assert isinstance(unionpay(value), ValidationError) - - -@pytest.mark.parametrize("value", diners_cards) -def test_returns_true_on_valid_diners(value: str): - """Test returns true on valid diners.""" - assert diners(value) - - -@pytest.mark.parametrize( - "value", - visa_cards - + mastercard_cards - + amex_cards - + unionpay_cards - + jcb_cards - + discover_cards - + mir_cards, -) -def test_returns_failed_on_valid_diners(value: str): - """Test returns failed on valid diners.""" - assert isinstance(diners(value), ValidationError) - - -@pytest.mark.parametrize("value", jcb_cards) -def test_returns_true_on_valid_jcb(value: str): - """Test returns true on valid jcb.""" - assert jcb(value) - - -@pytest.mark.parametrize( - "value", - visa_cards - + mastercard_cards - + amex_cards - + unionpay_cards - + diners_cards - + discover_cards - + mir_cards, -) -def test_returns_failed_on_valid_jcb(value: str): - """Test returns failed on valid jcb.""" - assert isinstance(jcb(value), ValidationError) - - -@pytest.mark.parametrize("value", discover_cards) -def test_returns_true_on_valid_discover(value: str): - """Test returns true on valid discover.""" - assert discover(value) - - -@pytest.mark.parametrize( - "value", - visa_cards - + mastercard_cards - + amex_cards - + unionpay_cards - + diners_cards - + jcb_cards - + mir_cards, -) -def test_returns_failed_on_valid_discover(value: str): - """Test returns failed on valid discover.""" - assert isinstance(discover(value), ValidationError) - - -@pytest.mark.parametrize("value", mir_cards) -def test_returns_true_on_valid_mir(value: str): - """Test returns true on valid Mir card.""" - assert mir(value) - - -@pytest.mark.parametrize( - "value", - visa_cards - + mastercard_cards - + amex_cards - + unionpay_cards - + diners_cards - + jcb_cards - + discover_cards, -) -def test_returns_failed_on_valid_mir(value: str): - """Test returns failed on invalid Mir card (other payment systems).""" - assert isinstance(mir(value), ValidationError) diff --git a/tests/test_complete_values.py b/tests/test_complete_values.py deleted file mode 100644 index 8e1589a7..00000000 --- a/tests/test_complete_values.py +++ /dev/null @@ -1,31 +0,0 @@ -"""Validate complete MAC addresses and regional identifiers.""" - -from typing import Callable - -import pytest - -from validators import ValidationError, mac_address -from validators.i18n.fi import fi_business_id, fi_ssn -from validators.i18n.fr import fr_ssn -from validators.i18n.ind import ind_aadhar - - -@pytest.mark.parametrize( - "validate,value", - [ - (mac_address, "01:23:45:67:ab:CD"), - (mac_address, "01-23-45-67-ab-CD"), - (fi_business_id, "0112038-9"), - (fi_ssn, "010101-0101"), - (fr_ssn, "1 84 12 76 451 089 46"), - (fr_ssn, "1 84 12 76 451 089"), - (ind_aadhar, "3675 9834 6015"), - ], -) -@pytest.mark.parametrize("suffix", ["", "\n", "\r\n", " ", "\nextra"]) -def test_complete_identifier(validate: Callable[[str], object], value: str, suffix: str): - """Accept the identifier alone and reject any trailing characters.""" - if suffix: - assert isinstance(validate(value + suffix), ValidationError) - else: - assert validate(value) is True diff --git a/tests/test_country.py b/tests/test_country.py deleted file mode 100644 index 1485d265..00000000 --- a/tests/test_country.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Test Country.""" - -# external -import pytest - -# local -from validators import ValidationError, calling_code, country_code, currency - - -@pytest.mark.parametrize(("value"), ["+1", "+371"]) -def test_returns_true_on_valid_calling_code(value: str): - """Test returns true on valid calling code.""" - assert calling_code(value) - - -@pytest.mark.parametrize(("value"), ["+19", "+37", "-9"]) -def test_returns_failed_validation_invalid_calling_code(value: str): - """Test returns failed validation invalid calling code.""" - assert isinstance(calling_code(value), ValidationError) - - -@pytest.mark.parametrize( - ("value", "iso_format"), - [ - ("ISR", "auto"), - ("US", "alpha2"), - ("USA", "alpha3"), - ("840", "numeric"), - ], -) -def test_returns_true_on_valid_country_code(value: str, iso_format: str): - """Test returns true on valid country code.""" - assert country_code(value, iso_format=iso_format) - - -@pytest.mark.parametrize( - ("value", "iso_format"), - [ - (None, "auto"), - ("", "auto"), - ("123456", "auto"), - ("XY", "alpha2"), - ("PPP", "alpha3"), - ("123", "numeric"), - ("us", "auto"), - ("uSa", "auto"), - ("US ", "auto"), - ("U.S", "auto"), - ("1ND", "unknown"), - ("ISR", None), - ], -) -def test_returns_failed_validation_on_invalid_country_code(value: str, iso_format: str): - """Test returns failed validation on invalid country code.""" - assert isinstance(country_code(value, iso_format=iso_format), ValidationError) - - -@pytest.mark.parametrize( - ("value", "skip_symbols", "ignore_case"), - [("$", False, False), ("⃀", False, False), ("৳", False, False), ("uSd", True, True)], -) -def test_returns_true_on_valid_currency(value: str, skip_symbols: bool, ignore_case: bool): - """Test returns true on valid currency.""" - assert currency(value, skip_symbols=skip_symbols, ignore_case=ignore_case) - - -@pytest.mark.parametrize( - ("value", "skip_symbols", "ignore_case"), - [ - ("$", True, False), - ("⃀", True, False), - ("৳", True, False), - ("⃀৳", False, False), - ("uSd", True, False), - ("Bucks", True, True), - ], -) -def test_returns_failed_validation_invalid_currency( - value: str, skip_symbols: bool, ignore_case: bool -): - """Test returns failed validation invalid currency.""" - assert isinstance( - currency(value, skip_symbols=skip_symbols, ignore_case=ignore_case), ValidationError - ) diff --git a/tests/test_cron.py b/tests/test_cron.py deleted file mode 100644 index 86723965..00000000 --- a/tests/test_cron.py +++ /dev/null @@ -1,59 +0,0 @@ -"""Test Cron.""" - -# external -import pytest - -# local -from validators import ValidationError, cron - - -@pytest.mark.parametrize( - "value", - [ - "* * * * *", - "*/5 * * * *", - "0 0 * * *", - "30 3 * * 1-5", - "15 5 * * 1,3,5", - "0 12 1 */2 *", - "0 */3 * * *", - "0 0 1 1 *", - "0 12 * 1-6 1-5", - "0 3-6 * * *", - "*/15 0,6,12,18 * * *", - "0 12 * * 0", - "0 12 * * 7", - "0 0 * * 0-7", - "0 0 * * 0,7", - "*/61 * * * *", - "5-10/2 * * * *", - "1-30/2 * * * *", - "15,45 6-18/3 * * *", - ], -) -def test_returns_true_on_valid_cron(value: str): - """Test returns true on valid cron string.""" - assert cron(value) - - -@pytest.mark.parametrize( - "value", - [ - "* * * * * *", - "* * * *", - "*/5 25 * * *", - "*/5 * *-1 * *", - "32-30 * * * *", - "0 12 32 * *", - "0 12 * * 8", - "0 */0 * * *", - "30-20 * * * *", - "10-* * * * *", - "*/15 0,6,12,24 * * *", - "& * * & * *", - "* - * * - *", - ], -) -def test_returns_failed_validation_on_invalid_cron(value: str): - """Test returns failed validation on invalid cron string.""" - assert isinstance(cron(value), ValidationError) diff --git a/tests/test_domain.py b/tests/test_domain.py deleted file mode 100644 index 533dde97..00000000 --- a/tests/test_domain.py +++ /dev/null @@ -1,239 +0,0 @@ -"""Test Domain.""" - -# external -import pytest - -# local -from validators import ValidationError, domain - - -@pytest.mark.parametrize( - ("value", "rfc_1034", "rfc_2782"), - [ - ("example.com", False, False), - ("exa_mple.com", False, True), - ("xn----gtbspbbmkef.xn--p1ai", False, False), - ("underscore_subdomain.example.com", False, True), - ("something.versicherung", False, False), - ("someThing.versicherung.", True, False), - ("11.com", False, False), - ("3.cn.", True, False), - ("_example.com", False, True), - ("example_.com", False, True), - ("_exa_mple_.com", False, True), - ("a.cn", False, False), - ("sub1.sub2.sample.co.uk", False, False), - ("somerandomexample.xn--fiqs8s", False, False), - ("kräuter.com.", True, False), - ("über.com", False, False), - ], -) -def test_returns_true_on_valid_domain(value: str, rfc_1034: bool, rfc_2782: bool): - """Test returns true on valid domain.""" - assert domain(value, rfc_1034=rfc_1034, rfc_2782=rfc_2782) - - -@pytest.mark.parametrize( - ("value", "consider_tld", "rfc_1034", "rfc_2782"), - [ - ("example.com", True, False, False), - ("exa_mple.com", True, False, True), - ("xn----gtbspbbmkef.xn--p1ai", True, False, False), - ("underscore_subdomain.example.com", True, False, True), - ("someThing.versicherung.", True, True, False), - ("11.com", True, False, False), - ("3.cn.", True, True, False), - ("_example.com", True, False, True), - ("example_.com", True, False, True), - ("somerandomexample.xn--fiqs8s", True, False, False), - ("somerandomexample.onion", True, False, False), - # delegated 2026-07-23 - ("somerandomexample.web", True, False, False), - ("пример.рф", True, False, False), - ("пример.рф.", True, True, False), - ("例子.中国", True, False, False), - ], -) -def test_returns_true_on_valid_top_level_domain( - value: str, consider_tld: bool, rfc_1034: bool, rfc_2782: bool -): - """Test returns true on valid top level domain.""" - assert domain(value, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782) - - -@pytest.mark.parametrize( - ("value", "rfc_1034", "rfc_2782"), - [ - ("example.com/.", True, False), - ("example.com:4444", False, False), - ("example.-com", False, False), - ("example.", False, False), - ("-example.com", False, False), - ("example-.com.", True, False), - ("_example.com", False, False), - ("_example._com", False, False), - ("example_.com", False, False), - ("example", False, False), - ("example.com!", True, False), - ("example?.com", True, False), - ("__exa__mple__.com", False, True), - ("a......b.com", False, False), - ("a.123", False, False), - ("foo.ba_r", False, False), - ("foo.ba_r", False, True), - ("example.co_uk", False, False), - ("123.123", False, False), - ("123.123.123.", True, False), - ("123.123.123.123", False, False), - ], -) -def test_returns_failed_validation_on_invalid_domain(value: str, rfc_1034: bool, rfc_2782: bool): - """Test returns failed validation on invalid domain.""" - assert isinstance(domain(value, rfc_1034=rfc_1034, rfc_2782=rfc_2782), ValidationError) - - -@pytest.mark.parametrize( - ("value", "consider_tld", "rfc_1034", "rfc_2782"), - [ - ("example.266", True, False, False), - ("exa_mple.org_", True, False, True), - ("xn----gtbspbbmkef.xn-p1ai", True, False, False), - ("underscore_subdomain.example.flat", True, False, True), - ("someThing.versicherung.reddit.", True, True, False), - ("11.twitter", True, False, False), - ("3.cnx.", True, True, False), - ("_example.#13", True, False, True), - ("example_.fo-ul", True, False, True), - ("somerandomexample.xn-n-fiqs8s", True, False, False), - # retired from the root zone - ("somerandomexample.goo", True, False, False), - ("пример.рфы", True, False, False), - ], -) -def test_returns_failed_validation_invalid_top_level_domain( - value: str, consider_tld: bool, rfc_1034: bool, rfc_2782: bool -): - """Test returns failed validation invalid top level domain.""" - assert isinstance( - domain(value, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782), - ValidationError, - ) - - -def _name_of_length(length: int): - """Build a dotted name of exactly `length` characters, ending with `.com`.""" - labels: list[str] = [] - remaining = length - len(".com") - while remaining > 0: - size = min(61, remaining) - if remaining - size == 1: # avoid leaving a lone "." behind - size -= 1 - labels.append("a" * size) - remaining -= size + 1 - name = ".".join(labels) + ".com" - assert len(name) == length - return name - - -@pytest.mark.parametrize( - "value", - [ - # total length: at most 253 characters (RFC 1035) - _name_of_length(253), - # label length: at most 63 characters (RFC 1035) - "a" * 63 + ".com", - # a label may start with a digit (RFC 1123) - "1host.example.com", - # the limit is in octets of the encoded name, not characters: 189 characters - # here, but 225 octets once IDNA-encoded - ".".join(["ü" * 30] * 6) + ".com", - ], -) -def test_returns_true_on_domain_within_rfc_length_limits(value: str): - """Test returns true on domain within RFC length limits.""" - assert domain(value) - - -@pytest.mark.parametrize( - "value", - [ - _name_of_length(254), - _name_of_length(255), - # many short, dot-separated labels that exceed 253 characters; see #413 - ".".join(["kld8MXQh6YalMqKRbfs895gMjW5T4p2EwToPoCSThPHHbXgmXc"] * 4) - + ".kld8MXQh6YalMqKRbfs895gMjW5T4p2EwToPoCSThPHHbXgmXcab", - "a" * 64 + ".com", - # fewer than 253 characters (220), but 262 octets once IDNA-encoded - ".".join(["ü" * 30] * 7) + ".com", - # the example from #407 (261 characters) - "www." + ".".join(["abcdefghijklmnop"] * 15) + ".fr", - # a label must not start or end with a hyphen - "-host.example.com", - "host-.example.com", - ], -) -def test_returns_failed_validation_on_domain_beyond_rfc_limits(value: str): - """Test returns failed validation on domain beyond RFC limits.""" - assert isinstance(domain(value), ValidationError) - - -@pytest.mark.parametrize( - "value", - [ - # IDNA 2003 maps these to "example.com"; see `_relies_on_idna_mapping` - "example.\uff43\uff4f\uff4d", # fullwidth letters - "\uff45\uff58\uff41\uff4d\uff50\uff4c\uff45.com", - "example.\u217dom", # small roman numeral one hundred - "\u212aelvin.com", # Kelvin sign - "\u017fhop.com", # long s - "example\u3002com", # ideographic full stop - "example\uff0ecom", # fullwidth full stop - "example\uff61com", # halfwidth ideographic full stop - "exam\u00adple.com", # soft hyphen - "example.co\u200bm", # zero width space - "exa\u200dmple.com", # zero width joiner - "exam\ufe0fple.com", # variation selector - "examp\u2060le.com", # word joiner - "\ufeffexample.com", # zero width no-break space - "exämple.com".replace("ä", "a\u0308"), # not NFC - ], -) -@pytest.mark.parametrize("consider_tld", [False, True]) -def test_returns_failed_validation_on_idna_mapped_lookalike(value: str, consider_tld: bool): - """Test returns failed validation on names that only IDNA 2003 mapping makes valid.""" - assert isinstance(domain(value, consider_tld=consider_tld), ValidationError) - - -@pytest.mark.parametrize( - "value", - ["пример.рф", "ПРИМЕР.РФ", "例子.中国", "kräuter.com", "straße.de", "ς.gr", "εχαμπλε.gr"], -) -def test_returns_true_on_idn_without_lookalike_mapping(value: str): - """Test returns true on internationalized names that need no lossy mapping.""" - assert domain(value) - - -@pytest.mark.parametrize( - "value", - [ - "10.0.0.\u0661", # Arabic-Indic one; looks like 10.0.0.1 - "example.\u0661\u0662\u0663", - "example.\u0968", # Devanagari two - "123.5.77.\u06688", # Arabic-Indic and ASCII digits - ], -) -@pytest.mark.parametrize("rfc_1034", [False, True]) -def test_returns_failed_validation_on_all_numeric_idn_tld(value: str, rfc_1034: bool): - """Test returns failed validation on a TLD made only of digits from any script.""" - assert isinstance(domain(value, rfc_1034=rfc_1034), ValidationError) - - -def test_returns_failed_validation_on_all_numeric_idn_tld_with_trailing_dot(): - """Test returns failed validation on an all-numeric IDN TLD followed by a trailing dot.""" - assert isinstance(domain("example.\u0661.", rfc_1034=True), ValidationError) - - -@pytest.mark.parametrize("value", ["\u0661\u0662.com", "example.\u0661a", "1.example.com"]) -def test_returns_true_on_digits_outside_or_mixed_in_tld(value: str): - """Test returns true when digits appear only in other labels or alongside letters.""" - assert domain(value) diff --git a/tests/test_email.py b/tests/test_email.py deleted file mode 100644 index 9b82eb46..00000000 --- a/tests/test_email.py +++ /dev/null @@ -1,74 +0,0 @@ -"""Test eMail.""" - -# external -import pytest - -# local -from validators import ValidationError, email - - -@pytest.mark.parametrize( - ("value",), - [ - ("email@here.com",), - ("weirder-email@here.and.there.com",), - ("email@127.local.home.arpa",), - ("example@valid-----hyphens.com",), - ("example@valid-with-hyphens.com",), - ("test@domain.with.idn.tld.उदाहरण.परीक्षा",), - ("email@localhost.in",), - ("Łókaść@email.com",), - ("łemłail@here.com",), - ("email@localdomain.org",), - ('"\\\011"@here.com',), - ], -) -def test_returns_true_on_valid_email(value: str): - """Test returns true on valid email.""" - assert email(value) - - -@pytest.mark.parametrize( - ("value",), - [ - (None,), - ("",), - ("abc",), - ("abc@",), - ("abc@bar",), - ("a @x.cz",), - ("abc@.com",), - ("something@@somewhere.com",), - ("email@127.0.0.1",), - ("example@invalid-.com",), - ("example@-invalid.com",), - ("example@inv-.alid-.com",), - ("example@inv-.-alid.com",), - ("john56789.john56789.john56789.john56789.john56789.john56789.john5@example.com",), - ('"test@test"@example.com',), - # Quoted-string format (CR not allowed) - ('"\\\012"@here.com',), - # Non-quoted space/semicolon not allowed - ("stephen smith@example.com",), - ("stephen;smith@example.com",), - ], -) -def test_returns_failed_validation_on_invalid_email(value: str): - """Test returns failed validation on invalid email.""" - assert isinstance(email(value), ValidationError) - - -@pytest.mark.parametrize( - "local_part", ["person", "person.name", "\u0141\u00f3ka\u015b\u0107", '"person"'] -) -def test_rejects_newline_after_local_part(local_part: str): - """Test the whole local part, including its final character.""" - # 2026-10-11: A newline before the at-sign is not part of a valid local part. - assert email(f"{local_part}@example.com") is True - assert isinstance(email(f"{local_part}\n@example.com"), ValidationError) - - -@pytest.mark.parametrize("domain_part", ["example.\uff43\uff4f\uff4d", "exam\u00adple.com"]) -def test_returns_failed_validation_on_idna_mapped_lookalike_domain(domain_part: str): - """Test returns failed validation on email domains that only IDNA 2003 mapping makes valid.""" - assert isinstance(email(f"user@{domain_part}"), ValidationError) diff --git a/tests/test_encoding.py b/tests/test_encoding.py deleted file mode 100644 index b47fe6fe..00000000 --- a/tests/test_encoding.py +++ /dev/null @@ -1,151 +0,0 @@ -"""Test Encodings.""" - -# standard -from typing import Callable - -# external -import pytest - -# local -from validators import ValidationError, base16, base32, base58, base64 - -# ==> base16 <== # - - -@pytest.mark.parametrize( - "value", - [ - "a3f4b2", - "01ef", - "abcdef0123456789", - "1234567890abcdef", - "1a2b3c", - "abcdef", - "000102030405060708090A0B0C0D0E0F", - ], -) -def test_returns_true_on_valid_base16(value: str): - """Test returns true on valid base16.""" - assert base16(value) - - -@pytest.mark.parametrize( - "value", - ["12345g", "hello world", "1234567890abcdeg", "GHIJKL", "12345G", "!@#$%^", "1a2h3c", "a3f4Z1"], -) -def test_returns_failed_validation_on_invalid_base16(value: str): - """Test returns failed validation on invalid base16.""" - assert isinstance(base16(value), ValidationError) - - -@pytest.mark.parametrize("value", ["0", "a", "ABC", "012345678", "abcdef01234567890"]) -def test_base16_rejects_incomplete_bytes(value: str): - """Reject a dangling half-byte even when every character is hexadecimal.""" - assert isinstance(base16(value), ValidationError) - - -# ==> base32 <== # - - -@pytest.mark.parametrize( - "value", - [ - "JBSWY3DPEHPK3PXP", - "MFRGGZDFMZTWQ2LK", - "MZXW6YTBOI======", - "MFZWIZLTOQ======", - "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", - "MFRGGZDFMZTWQ2LKNNWG23Q=", - ], -) -def test_returns_true_on_valid_base32(value: str): - """Test returns true on valid base32.""" - assert base32(value) - - -@pytest.mark.parametrize( - "value", - [ - "ThisIsNotBase32!", - "12345!", - "Any==invalid=base32=", - "MzXW6yTBOI======", - "JBSWY8DPEHPK9PXP", - "MfZW3zLT9Q======", - ], -) -def test_returns_failed_validation_on_invalid_base32(value: str): - """Test returns failed validation on invalid base32.""" - assert isinstance(base32(value), ValidationError) - - -# ==> base58 <== # - - -@pytest.mark.parametrize( - "value", - [ - "cUSECaVvAiV3srWbFRvVPzm5YzcXJwPSwZfE7veYPHoXmR9h6YMQ", - "18KToMF5ckjXBYt2HAj77qsG3GPeej3PZn", - "n4FFXRNNEW1aA2WPscSuzHTCjzjs4TVE2Z", - "38XzQ9dPGb1uqbZsjPtUajp7omy8aefjqj", - ], -) -def test_returns_true_on_valid_base58(value: str): - """Test returns true on valid base58.""" - assert base58(value) - - -@pytest.mark.parametrize( - "value", - ["ThisIsAReallyLongStringThatIsDefinitelyNotBase58Encoded", "abcABC!@#", "InvalidBase58!"], -) -def test_returns_failed_validation_on_invalid_base58(value: str): - """Test returns failed validation on invalid base58.""" - assert isinstance(base58(value), ValidationError) - - -# ==> base64 <== # - - -@pytest.mark.parametrize( - "value", - ["SGVsbG8gV29ybGQ=", "U29tZSBkYXRhIHN0cmluZw==", "YW55IGNhcm5hbCBwbGVhcw=="], -) -def test_returns_true_on_valid_base64(value: str): - """Test returns true on valid base64.""" - assert base64(value) - - -@pytest.mark.parametrize( - "value", - ["SGVsbG8gV29ybGQ", "U29tZSBkYXRhIHN0cmluZw", "YW55IGNhcm5hbCBwbGVhc"], -) -def test_returns_failed_validation_on_invalid_base64(value: str): - """Test returns failed validation on invalid base64.""" - assert isinstance(base64(value), ValidationError) - - -@pytest.mark.parametrize( - "validate, value", - [(base16, "a3f4b2"), (base32, "MFZWIZLTOQ======"), (base58, "18KToMF5"), (base64, "SGVsbG8=")], -) -@pytest.mark.parametrize("suffix", ["\n", "\r\n", " ", "\nextra"]) -def test_encoding_rejects_trailing_characters( - validate: Callable[[str], object], value: str, suffix: str -): - """Reject characters outside the encoded value.""" - assert isinstance(validate(value + suffix), ValidationError) - - -@pytest.mark.parametrize("value", ["A", "AAA", "AAAAAA", "AB=", "AB===", "AB=======", "ABCDEFGH="]) -def test_base32_rejects_invalid_length_and_padding(value: str): - """Reject symbol counts and padding that cannot encode whole bytes.""" - assert isinstance(base32(value), ValidationError) - - -@pytest.mark.parametrize("value", ["MY======", "MZXQ====", "MZXW6===", "MZXW6YQ=", "MZXW6YTB"]) -def test_base32_accepts_valid_final_quanta(value: str): - """Accept each legal final quantum with or without padding.""" - assert base32(value) is True - assert base32(value.rstrip("=")) is True diff --git a/tests/test_finance.py b/tests/test_finance.py deleted file mode 100644 index 052281ac..00000000 --- a/tests/test_finance.py +++ /dev/null @@ -1,90 +0,0 @@ -"""Test Finance.""" - -# standard -from typing import Callable - -# external -import pytest - -# local -from validators import ValidationError, cusip, isin, sedol - -# ==> CUSIP <== # - - -@pytest.mark.parametrize("value", ["912796X38", "912796X20", "912796x20"]) -def test_returns_true_on_valid_cusip(value: str): - """Test returns true on valid cusip.""" - assert cusip(value) - - -@pytest.mark.parametrize("value", ["912796T67", "912796T68", "XCVF", "00^^^1234"]) -def test_returns_failed_validation_on_invalid_cusip(value: str): - """Test returns failed validation on invalid cusip.""" - assert isinstance(cusip(value), ValidationError) - - -# ==> ISIN <== # - - -@pytest.mark.parametrize("value", ["US0004026250", "US0378331005", "GB0002634946", "DE000BAY0017"]) -def test_returns_true_on_valid_isin(value: str): - """Test returns true on valid isin.""" - assert isin(value) - - -@pytest.mark.parametrize( - "value", - [ - "010378331005", - "XCVF", - "00^^^1234", - "A000009", - # valid length and characters but wrong check digit - "US0378331006", - "US0004026251", - "GB0002634947", - ], -) -def test_returns_failed_validation_on_invalid_isin(value: str): - """Test returns failed validation on invalid isin.""" - assert isinstance(isin(value), ValidationError) - - -# ==> SEDOL <== # - - -@pytest.mark.parametrize("value", ["0263494", "0540528", "B000009"]) -def test_returns_true_on_valid_sedol(value: str): - """Test returns true on valid sedol.""" - assert sedol(value) - - -@pytest.mark.parametrize("value", ["0540526", "XCVF", "00^^^1234", "A000009"]) -def test_returns_failed_validation_on_invalid_sedol(value: str): - """Test returns failed validation on invalid sedol.""" - assert isinstance(sedol(value), ValidationError) - - -@pytest.mark.parametrize( - "validate, value", - [ - (cusip, "03783310J"), - (cusip, "03783310j"), - (cusip, "03783310@"), - (sedol, "293692L"), - (sedol, "B12345G"), - (sedol, "B12345Q"), - ], -) -def test_rejects_non_numeric_check_digit(validate: Callable[[str], object], value: str): - """Reject letters and symbols that accidentally satisfy the checksum.""" - assert isinstance(validate(value), ValidationError) - - -@pytest.mark.parametrize( - "validate, value", [(cusip, "037833100"), (sedol, "2936921"), (sedol, "B123456")] -) -def test_accepts_numeric_check_digit(validate: Callable[[str], object], value: str): - """Keep valid numeric check digits, including alphanumeric identifiers.""" - assert validate(value) is True diff --git a/tests/test_hashes.py b/tests/test_hashes.py deleted file mode 100644 index 6e78260e..00000000 --- a/tests/test_hashes.py +++ /dev/null @@ -1,246 +0,0 @@ -"""Test Hashes.""" - -# standard -from typing import Callable - -# external -import pytest - -# local -from validators import ValidationError, base58, base64, md5, sha1, sha224, sha256, sha384, sha512 - -# ==> base58 <== # - - -@pytest.mark.parametrize( - "value", - [ - "cUSECaVvAiV3srWbFRvVPzm5YzcXJwPSwZfE7veYPHoXmR9h6YMQ", - "18KToMF5ckjXBYt2HAj77qsG3GPeej3PZn", - "n4FFXRNNEW1aA2WPscSuzHTCjzjs4TVE2Z", - "38XzQ9dPGb1uqbZsjPtUajp7omy8aefjqj", - ], -) -def test_returns_true_on_valid_base58(value: str): - """Test returns true on valid base58.""" - assert base58(value) - - -@pytest.mark.parametrize( - "value", - ["ThisIsAReallyLongStringThatIsDefinitelyNotBase58Encoded", "abcABC!@#", "InvalidBase58!"], -) -def test_returns_failed_validation_on_invalid_base58(value: str): - """Test returns failed validation on invalid base58.""" - assert isinstance(base58(value), ValidationError) - - -# ==> base64 <== # - - -@pytest.mark.parametrize( - "value", - ["SGVsbG8gV29ybGQ=", "U29tZSBkYXRhIHN0cmluZw==", "YW55IGNhcm5hbCBwbGVhcw=="], -) -def test_returns_true_on_valid_base64(value: str): - """Test returns true on valid base64.""" - assert base64(value) - - -@pytest.mark.parametrize( - "value", - ["SGVsbG8gV29ybGQ", "U29tZSBkYXRhIHN0cmluZw", "YW55IGNhcm5hbCBwbGVhc"], -) -def test_returns_failed_validation_on_invalid_base64(value: str): - """Test returns failed validation on invalid base64.""" - assert isinstance(base64(value), ValidationError) - - -# ==> md5 <== # - - -@pytest.mark.parametrize( - "value", ["d41d8cd98f00b204e9800998ecf8427e", "D41D8CD98F00B204E9800998ECF8427E"] -) -def test_returns_true_on_valid_md5(value: str): - """Test returns true on valid md5.""" - assert md5(value) - - -@pytest.mark.parametrize( - "value", - [ - "z41d8cd98f00b204e9800998ecf8427e", - "z8cd98f00b204e9800998ecf8427e", - "z4aaaa1d8cd98f00b204e9800998ecf8427e", - ], -) -def test_returns_failed_validation_on_invalid_md5(value: str): - """Test returns failed validation on invalid md5.""" - assert isinstance(md5(value), ValidationError) - - -# ==> sha1 <== # - - -@pytest.mark.parametrize( - "value", - ["da39a3ee5e6b4b0d3255bfef95601890afd80709", "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709"], -) -def test_returns_true_on_valid_sha1(value: str): - """Test returns true on valid sha1.""" - assert sha1(value) - - -@pytest.mark.parametrize( - "value", - [ - "za39a3ee5e6b4b0d3255bfef95601890afd80709", - "da39e5e6b4b0d3255bfef95601890afd80709", - "daaaa39a3ee5e6b4b0d3255bfef95601890afd80709", - ], -) -def test_returns_failed_validation_on_invalid_sha1(value: str): - """Test returns failed validation on invalid sha1.""" - assert isinstance(sha1(value), ValidationError) - - -# ==> sha224 <== # - - -@pytest.mark.parametrize( - "value", - [ - "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", - "D14A028C2A3A2BC9476102BB288234C415A2B01F828EA62AC5B3E42F", - ], -) -def test_returns_true_on_valid_sha224(value: str): - """Test returns true on valid sha224.""" - assert sha224(value) - - -@pytest.mark.parametrize( - "value", - [ - "z14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", - "d028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", - "daaa14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", - ], -) -def test_returns_failed_validation_on_invalid_sha224(value: str): - """Test returns failed validation on invalid sha224.""" - assert isinstance(sha224(value), ValidationError) - - -# ==> sha256 <== # - - -@pytest.mark.parametrize( - "value", - [ - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", - ], -) -def test_returns_true_on_valid_sha256(value: str): - """Test returns true on valid sha256.""" - assert sha256(value) - - -@pytest.mark.parametrize( - "value", - [ - "z3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "ec44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "eaaaa3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - ], -) -def test_returns_failed_validation_on_invalid_sha256(value: str): - """Test returns failed validation on invalid sha256.""" - assert isinstance(sha256(value), ValidationError) - - -# ==> sha384 <== # - - -@pytest.mark.parametrize( - "value", - [ - "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7", - "CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7", - "bfd76c0ebbd006fee583410547c1887b0292be76d582d96c242d2a792723e3fd6fd061f9d5cfd13b8f961358e6adba4a", - "F21EF1F8DBF806106813C8504AF864D8D9BFDFA8D67FA9B7DFF1C5B61C2584394A05897C4F157CEEE0E8FBC29205BB8B", - ], -) -def test_returns_true_on_valid_sha384(value: str): - """Test returns true on valid sha384.""" - assert sha384(value) - - -@pytest.mark.parametrize( - "value", - [ - "zb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7", - "c753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7", - "cb00aaaa753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7", - ], -) -def test_returns_failed_validation_on_invalid_sha384(value: str): - """Test returns failed validation on invalid sha384.""" - assert isinstance(sha384(value), ValidationError) - - -# ==> sha512 <== # - - -@pytest.mark.parametrize( - "value", - [ - ( - "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d" - "13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" - ), - ( - "CF83E1357EEFB8BDF1542850D66D8007D620E4050B5715DC83F4A921D36CE9CE47D0D" - "13C5D85F2B0FF8318D2877EEC2F63B931BD47417A81A538327AF927DA3E" - ), - ], -) -def test_returns_true_on_valid_sha512(value: str): - """Test returns true on valid sha512.""" - assert sha512(value) - - -@pytest.mark.parametrize( - "value", - [ - ( - "zf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d" - "13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" - ), - ( - "cf8357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c" - "5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" - ), - ( - "cf8aaaa3e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce4" - "7d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" - ), - ], -) -def test_returns_failed_validation_on_invalid_sha512(value: str): - """Test returns failed validation on invalid sha512.""" - assert isinstance(sha512(value), ValidationError) - - -@pytest.mark.parametrize( - "validate, size", - [(md5, 32), (sha1, 40), (sha224, 56), (sha256, 64), (sha384, 96), (sha512, 128)], -) -@pytest.mark.parametrize("suffix", ["\n", "\r\n", " ", "\nextra"]) -def test_hash_rejects_trailing_characters( - validate: Callable[[str], object], size: int, suffix: str -): - """Reject characters outside the fixed-length digest.""" - assert isinstance(validate("a" * size + suffix), ValidationError) diff --git a/tests/test_hostname.py b/tests/test_hostname.py deleted file mode 100644 index 83f00212..00000000 --- a/tests/test_hostname.py +++ /dev/null @@ -1,173 +0,0 @@ -"""Test Hostname.""" - -# external -import pytest - -# local -from validators import ValidationError, hostname - - -@pytest.mark.parametrize( - ("value", "rfc_1034", "rfc_2782"), - [ - # simple hostname w/ optional ports - ("ubuntu-pc:443", False, False), - ("this-pc", False, False), - ("lab-01a-notebook:404", False, False), - ("4-oh-4", False, False), - # simple, single-label hostname w/ trailing dot (RFC 1034); see #442 - ("this-pc.", True, False), - ("ie.", True, False), - # hostname w/ optional ports - ("example.com:4444", False, False), - ("kräuter.com.", True, False), - ("xn----gtbspbbmkef.xn--p1ai:65535", False, False), - ("_example.com", False, True), - # ipv4 addr w/ optional ports - ("123.123.123.123:9090", False, False), - ("127.0.0.1:43512", False, False), - ("123.5.77.88:31000", False, False), - ("12.12.12.12:5353", False, False), - # ipv6 addr w/ optional ports - ("[::1]:22", False, False), - ("[dead:beef:0:0:0:0000:42:1]:5731", False, False), - ("[0:0:0:0:0:ffff:1.2.3.4]:80", False, False), - ("[0:a:b:c:d:e:f::]:53", False, False), - ], -) -def test_returns_true_on_valid_hostname(value: str, rfc_1034: bool, rfc_2782: bool): - """Test returns true on valid hostname.""" - assert hostname(value, rfc_1034=rfc_1034, rfc_2782=rfc_2782) - - -@pytest.mark.parametrize( - ("value", "rfc_1034", "rfc_2782"), - [ - # bad (simple hostname w/ optional ports) - ("ubuntu-pc:443080", False, False), - ("this-pc-is-sh*t", False, False), - ("lab-01a-note._com_.com:404", False, False), - ("4-oh-4:@.com", False, False), - # trailing dot is only allowed with rfc_1034; see #442 - ("this-pc.", False, False), - # bad (hostname w/ optional ports) - ("example.com:-4444", False, False), - ("xn----gtbspbbmkef.xn--p1ai:65538", False, False), - ("_example.com:0", False, True), - ("kräuter.com.:81_00", True, False), - # bad (ipv4 addr w/ optional ports) - ("123.123.123.123:99999", False, False), - ("127.0.0.1:", False, False), - ("123.5.-12.88:8080", False, False), - ("12.12.12.12:$#", False, False), - # bad (ipv6 addr w/ optional ports) - ("[::1]:[22]", False, False), - ("[dead:beef:0:-:0:-:42:1]:5731", False, False), - ("[0:0:0:0:0:ffff:1.2.3.4]:-65538", False, False), - ("[0:&:b:c:@:e:f:::9999", False, False), - ], -) -def test_returns_failed_validation_on_invalid_hostname(value: str, rfc_1034: bool, rfc_2782: bool): - """Test returns failed validation on invalid hostname.""" - assert isinstance(hostname(value, rfc_1034=rfc_1034, rfc_2782=rfc_2782), ValidationError) - - -@pytest.mark.parametrize( - "value", - [ - # total length: at most 253 characters (RFC 1035) - ".".join(["a" * 63, "a" * 63, "a" * 63, "a" * 61]), - # label length: at most 63 characters (RFC 1035) - "a" * 63 + ".com", - # a label may start with a digit (RFC 1123) - "1host.example.com", - # the limit is in octets of the encoded name, not characters - ".".join(["ü" * 30] * 6) + ".com", - ], -) -def test_returns_true_on_hostname_within_rfc_length_limits(value: str): - """Test returns true on hostname within RFC length limits.""" - assert hostname(value) - - -@pytest.mark.parametrize( - "value", - [ - # many short, dot-separated labels that exceed 253 characters; see #413 - ".".join(["kld8MXQh6YalMqKRbfs895gMjW5T4p2EwToPoCSThPHHbXgmXc"] * 4) - + ".kld8MXQh6YalMqKRbfs895gMjW5T4p2EwToPoCSThPHHbXgmXcab", - ".".join(["a" * 63, "a" * 63, "a" * 63, "a" * 62]), - "a" * 64 + ".com", - # fewer than 253 characters (220), but 262 octets once IDNA-encoded - ".".join(["ü" * 30] * 7) + ".com", - # a label must not start or end with a hyphen, nor contain an underscore - "-host.example.com", - "host-.example.com", - "ho_st.example.com", - ], -) -def test_returns_failed_validation_on_hostname_beyond_rfc_limits(value: str): - """Test returns failed validation on hostname beyond RFC limits.""" - assert isinstance(hostname(value), ValidationError) - - -@pytest.mark.parametrize( - "value", - [ - "ubuntu-pc\n", - "ubuntu-pc:443\n", - "example.com:443\n", - "127.0.0.1:22\n", - "[::1]:22\n", - "[dead:beef:0:0:0:0000:42:1]:5731\n", - ], -) -def test_rejects_trailing_newline_in_hostnames_and_ports(value: str): - """Test rejects trailing newline in hostnames and ports.""" - assert isinstance(hostname(value), ValidationError) - - -@pytest.mark.parametrize( - "value", ["\u017ferver", "\u212aelvin", "\u0131ntranet", "\u0130ntranet:8080"] -) -def test_returns_failed_validation_on_non_ascii_simple_hostname(value: str): - """Test returns failed validation on non-ASCII case equivalents in simple hostnames.""" - assert isinstance(hostname(value), ValidationError) - - -@pytest.mark.parametrize("value", ["example.\uff43\uff4f\uff4d", "exam\u00adple.com:443"]) -def test_returns_failed_validation_on_idna_mapped_lookalike_hostname(value: str): - """Test returns failed validation on hostnames that only IDNA 2003 mapping makes valid.""" - assert isinstance(hostname(value), ValidationError) - - -@pytest.mark.parametrize("value", ["10.0.0.\u0661", "123.5.77.\u06688:31000"]) -def test_returns_failed_validation_on_ipv4_lookalike_hostname(value: str): - """Test returns failed validation on dotted names whose last label is non-ASCII digits.""" - assert isinstance(hostname(value), ValidationError) - - -@pytest.mark.parametrize( - "value", - [ - "example.com:443", - "xn--e1afmkfd.xn--p1ai", - "пример.рф", - "пример.рф:8080", - ], -) -def test_returns_true_on_valid_top_level_domain_hostname(value: str): - """Test returns true on hostname with a TLD allowed by IANA.""" - assert hostname(value, consider_tld=True) - - -@pytest.mark.parametrize( - "value", - [ - "example.flat:443", - "пример.рфы", - ], -) -def test_returns_failed_validation_on_invalid_top_level_domain_hostname(value: str): - """Test returns failed validation on hostname with a TLD not allowed by IANA.""" - assert isinstance(hostname(value, consider_tld=True), ValidationError) diff --git a/tests/test_iban.py b/tests/test_iban.py deleted file mode 100644 index 73f12d88..00000000 --- a/tests/test_iban.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Test IBAN.""" - -# external -import pytest - -# local -from validators import ValidationError, iban - - -@pytest.mark.parametrize("value", ["GB82WEST12345698765432", "NO9386011117947"]) -def test_returns_true_on_valid_iban(value: str): - """Test returns true on valid iban.""" - assert iban(value) - - -@pytest.mark.parametrize("value", ["gb82west12345698765432", "No9386011117947"]) -def test_returns_true_on_valid_lowercase_iban(value: str): - """Lowercase/mixed-case IBANs are accepted (the format regex is case-insensitive).""" - assert iban(value) - - -@pytest.mark.parametrize("value", ["GB81WEST12345698765432", "NO9186011117947"]) -def test_returns_failed_validation_on_invalid_iban(value: str): - """Test returns failed validation on invalid iban.""" - assert isinstance(iban(value), ValidationError) - - -@pytest.mark.parametrize( - "value", ["\u0131T60X0542811101000000123456", "GB82WE\u017fT12345698765432"] -) -def test_rejects_non_ascii_case_equivalents(value: str): - """Unicode case equivalents must not pass the ASCII IBAN format check.""" - assert isinstance(iban(value), ValidationError) diff --git a/tests/test_ip_address.py b/tests/test_ip_address.py deleted file mode 100644 index ed6fd7d4..00000000 --- a/tests/test_ip_address.py +++ /dev/null @@ -1,206 +0,0 @@ -"""Test IP Address.""" - -# external -import pytest - -# local -from validators import ValidationError, ipv4, ipv6 - - -@pytest.mark.parametrize( - ("address",), - [ - ("127.0.0.1",), - ("123.5.77.88",), - ("12.12.12.12",), - ], -) -def test_returns_true_on_valid_ipv4_address(address: str): - """Test returns true on valid ipv4 address.""" - assert ipv4(address) - assert not ipv6(address) - - -@pytest.mark.parametrize( - ("address", "cidr", "strict", "host_bit"), - [ - ("127.0.0.1/0", True, True, True), - ("123.5.77.88", True, False, True), - ("12.12.12.0/24", True, True, False), - ], -) -def test_returns_true_on_valid_ipv4_cidr_address( - address: str, cidr: bool, strict: bool, host_bit: bool -): - """Test returns true on valid ipv4 CIDR address.""" - assert ipv4(address, cidr=cidr, strict=strict, host_bit=host_bit) - assert not ipv6(address, cidr=cidr, strict=strict, host_bit=host_bit) - - -@pytest.mark.parametrize( - ("address",), - [ - # leading zeroes error-out from Python 3.9.5 - # ("100.100.033.033",), - ("900.200.100.75",), - ("0127.0.0.1",), - ("abc.0.0.1",), - ], -) -def test_returns_failed_validation_on_invalid_ipv4_address(address: str): - """Test returns failed validation on invalid ipv4 address.""" - assert isinstance(ipv4(address), ValidationError) - - -@pytest.mark.parametrize( - ("address", "cidr", "strict", "host_bit"), - [ - ("1.1.1.1/1", False, True, True), - ("1.1.1.1/33", True, False, True), - ("1.1.1.1/24", True, True, False), - ("1.1.1.1/-1", True, True, True), - ], -) -def test_returns_failed_validation_on_invalid_ipv4_cidr_address( - address: str, cidr: bool, strict: bool, host_bit: bool -): - """Test returns failed validation on invalid ipv4 CIDR address.""" - assert isinstance(ipv4(address, cidr=cidr, strict=strict, host_bit=host_bit), ValidationError) - - -@pytest.mark.parametrize( - ("address",), - [ - ("::",), - ("::1",), - ("1::",), - ("dead:beef:0:0:0:0000:42:1",), - ("abcd:ef::42:1",), - ("0:0:0:0:0:ffff:1.2.3.4",), - ("::192.168.30.2",), - ("0000:0000:0000:0000:0000::",), - ("0:a:b:c:d:e:f::",), - ], -) -def test_returns_true_on_valid_ipv6_address(address: str): - """Test returns true on valid ipv6 address.""" - assert ipv6(address) - assert not ipv4(address) - - -@pytest.mark.parametrize( - ("address", "cidr", "strict", "host_bit"), - [ - ("::1/128", True, True, True), - ("::1/0", True, True, True), - ("dead:beef:0:0:0:0:42:1/8", True, True, True), - ("abcd:ef::42:1/32", True, True, True), - ("0:0:0:0:0:ffff:1.2.3.4/16", True, True, True), - ("2001:0db8:85a3:0000:0000:8a2e:0370:7334/64", True, True, True), - ("::192.168.30.2/128", True, True, True), - ], -) -def test_returns_true_on_valid_ipv6_cidr_address( - address: str, cidr: bool, strict: bool, host_bit: bool -): - """Test returns true on valid ipv6 CIDR address.""" - assert ipv6(address, cidr=cidr, strict=strict, host_bit=host_bit) - assert not ipv4(address, cidr=cidr, strict=strict, host_bit=host_bit) - - -@pytest.mark.parametrize( - ("address",), - [ - ("abc.0.0.1",), - ("abcd:1234::123::1",), - ("1:2:3:4:5:6:7:8:9",), - ("1:2:3:4:5:6:7:8::",), - ("1:2:3:4:5:6:7::8:9",), - ("abcd::1ffff",), - ("1111:",), - (":8888",), - (":1.2.3.4",), - ("18:05",), - (":",), - (":1:2:",), - (":1:2::",), - ("::1:2::",), - ("8::1:2::9",), - ("02001:0000:1234:0000:0000:C1C0:ABCD:0876",), - ], -) -def test_returns_failed_validation_on_invalid_ipv6_address(address: str): - """Test returns failed validation on invalid ipv6 address.""" - assert isinstance(ipv6(address), ValidationError) - - -@pytest.mark.parametrize( - ("address", "cidr", "strict", "host_bit"), - [ - ("::1/128", False, True, True), - ("::1/129", True, False, True), - ("dead:beef:0:0:0:0:42:1/8", True, True, False), - ("::1/-130", True, True, True), - ], -) -def test_returns_failed_validation_on_invalid_ipv6_cidr_address( - address: str, cidr: bool, strict: bool, host_bit: bool -): - """Test returns failed validation on invalid ipv6 CIDR address.""" - assert isinstance(ipv6(address, cidr=cidr, strict=strict, host_bit=host_bit), ValidationError) - - -@pytest.mark.parametrize( - ("address", "private"), - [ - ("10.1.1.1", True), - ("192.168.1.1", True), - ("169.254.1.1", True), - ("127.0.0.1", True), - ("0.0.0.0", True), - ], -) -def test_returns_true_on_valid_private_ipv4_address(address: str, private: bool): - """Test returns true on private ipv4 address.""" - assert ipv4(address, private=private) - - -@pytest.mark.parametrize( - ("address", "private"), - [ - ("1.1.1.1", True), - ("192.169.1.1", True), - ("7.53.12.1", True), - ], -) -def test_returns_failed_validation_on_invalid_private_ipv4_address(address: str, private: bool): - """Test returns failed validation on invalid private ipv4 address.""" - assert isinstance(ipv4(address, private=private), ValidationError) - - -@pytest.mark.parametrize( - ("address", "private"), - [ - ("1.1.1.1", False), - ("192.169.1.1", False), - ("7.53.12.1", False), - ], -) -def test_returns_true_on_valid_public_ipv4_address(address: str, private: bool): - """Test returns true on valid public ipv4 address.""" - assert ipv4(address, private=private) - - -@pytest.mark.parametrize( - ("address", "private"), - [ - ("10.1.1.1", False), - ("192.168.1.1", False), - ("169.254.1.1", False), - ("127.0.0.1", False), - ("0.0.0.0", False), - ], -) -def test_returns_failed_validation_on_invalid_public_ipv4_address(address: str, private: bool): - """Test returns failed validation on private ipv4 address.""" - assert isinstance(ipv4(address, private=private), ValidationError) diff --git a/tests/test_length.py b/tests/test_length.py deleted file mode 100644 index c9cd1dc1..00000000 --- a/tests/test_length.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Test Length.""" - -# external -import pytest - -# local -from validators import ValidationError, length - - -@pytest.mark.parametrize( - ("value", "min_val", "max_val"), - [("password", 2, None), ("password", None, None), ("password", 0, 10), ("password", 8, 8)], -) -def test_returns_true_on_valid_length(value: str, min_val: int, max_val: int): - """Test returns true on valid length.""" - assert length(value, min_val=min_val, max_val=max_val) - - -@pytest.mark.parametrize( - ("value", "min_val", "max_val"), - [("something", 14, 12), ("something", -10, -20), ("something", 0, -2), ("something", 13, 14)], -) -def test_returns_failed_validation_on_invalid_range(value: str, min_val: int, max_val: int): - """Test returns failed validation on invalid range.""" - assert isinstance(length(value, min_val=min_val, max_val=max_val), ValidationError) diff --git a/tests/test_mac_address.py b/tests/test_mac_address.py deleted file mode 100644 index 71b6c041..00000000 --- a/tests/test_mac_address.py +++ /dev/null @@ -1,35 +0,0 @@ -"""MAC Address.""" - -# external -import pytest - -# local -from validators import ValidationError, mac_address - - -@pytest.mark.parametrize( - ("address",), - [ - ("01:23:45:67:ab:CD",), - ("01-23-45-67-ab-CD",), - ("01:2F:45:37:ab:CD",), - ("A1-2F-4E-68-ab-CD",), - ], -) -def test_returns_true_on_valid_mac_address(address: str): - """Test returns true on valid mac address.""" - assert mac_address(address) - - -@pytest.mark.parametrize( - ("address",), - [ - ("00-00:-00-00-00",), - ("01:23:45:67:89:",), - ("01:23-45:67-89:gh",), - ("123:23:45:67:89:00",), - ], -) -def test_returns_failed_validation_on_invalid_mac_address(address: str): - """Test returns failed validation on invalid mac address.""" - assert isinstance(mac_address(address), ValidationError) diff --git a/tests/test_slug.py b/tests/test_slug.py deleted file mode 100644 index 45b59813..00000000 --- a/tests/test_slug.py +++ /dev/null @@ -1,143 +0,0 @@ -"""Test Slug.""" - -# external - -from typing import Any - -import pytest - -# local -from validators import ValidationError, slug - - -@pytest.mark.parametrize( - "value", - [ - # with numbers - "hello123", - "123hello", - "123", - # with hyphens - "hello-world", - "hello-world-test", - "test-123-abc", - # with mixed alphanumeric - "hello123-world456", - "123-456-789", - "a1-b2-c3", - # with single character - "a", - "1", - "z", - # with complex slug - "test-123-abc-456-def", - "this-is-a-very-long-slug-with-many-words", - # with multiple hyphens - "a-b-c", - "1-2-3", - # very long - "a" * 100, - # very long with hyphens - "a-" * 50 + "end", - # very long with hyphens and different alphabets|letters - "a1-b2-c3-d4-e5-f6-g7-h8-i9-j0", - # old - "123-asd-7sda", - "123-k-123", - "dac-12sa-459", - "dac-12sa7-ad31as", - ], -) -def test_returns_true_on_valid_slug(value: str): - """Test returns true on valid slug.""" - assert slug(value) - - -@pytest.mark.parametrize( - "value", - [ - # trailing newline must not be accepted ($ matches before a final \n) - "hello-world\n", - "\n", - # with empty_string - "", - # with upper case - "Hello", - "HELLO", - "hello-World", - "Test-Slug", - # with special characters - "hello world", - "hello_world", - "hello.world", - "hello@world", - "hello#world", - "hello$world", - # starting with hyphen - "-hello", - "-123", - "-hello-world", - # with consecutive hyphens - "hello--world", - "test---slug", - "a--b", - # with unicode characters - "café", - "привет", - "東京", - "hello-мир", - # with spaces - "hello world", - " hello ", - "hello world", - # with only hyphens - "-", - "--", - "---", - # with mixed case - "HelloWorld", - "helloWorld", - "HELLOworld", - # old - "some.slug&", - "1231321%", - " 21312", - "-47q-p--123", - ], -) -def test_returns_failed_validation_on_invalid_slug(value: str): - """Test returns failed validation on invalid slug.""" - assert isinstance(slug(value), ValidationError) - - -@pytest.mark.parametrize( - ("val", "input_type"), - [ - (1, "int"), - (1.0, "float"), - (None, "NoneType"), - ([], "list"), - ((), "tuple"), - ({}, "dict"), - ], -) -def test_non_string_input(val: Any, input_type: Any): - """Test with non string input.""" - # given - message = f"expected string or bytes-like object, got '{input_type}'" - # when - result = slug(val) - # then - assert isinstance(result, ValidationError) - assert result.reason == message - - -def test_slug_function_signature(): - """Test with keyword argument.""" - # given - message = "slug() got some positional-only arguments passed as keyword arguments: 'value'" - # when - result = slug(value="test-slug") - # then - assert isinstance(result, ValidationError) - assert result.reason == message diff --git a/tests/test_uri.py b/tests/test_uri.py deleted file mode 100644 index f33865ec..00000000 --- a/tests/test_uri.py +++ /dev/null @@ -1,75 +0,0 @@ -"""Test URI.""" - -# external -import pytest - -# local -from validators.uri import uri - - -@pytest.mark.parametrize( - "value", - [ - "telnet://example.com", - "telnet://example.com/", - "telnet://example.com:23", - "telnet://example.com:23/", - "telnet://192.168.1.1", - "telnet://192.168.1.1:23", - "telnet://user:password@example.com", - "telnet://user:password@example.com:23/", - ], -) -def test_valid_telnet_uri(value: str): - """Test valid telnet URI.""" - assert uri(value) - - -@pytest.mark.parametrize( - "value", - [ - "telnet://", - "telnet://example.com/path", - "telnet://example.com?query=1", - "telnet://example.com#frag", - # urlsplit would silently strip these control characters - "telnet://example.com\n", - "telnet://exa\nmple.com", - "telnet://example.com\t", - ], -) -def test_invalid_telnet_uri(value: str): - """Test invalid telnet URI.""" - assert not uri(value) - - -@pytest.mark.parametrize( - "value", - [ - "file:///tmp/readme.txt", - "ipfs://QmYwAPJzv5CZsnAzt8auVZRnGiUncKEy6PBDoDeZ7hA9Rx/readme.txt", - "magnet:?xt=urn:btih:0123456789012345678901234567890123456789", - "tel:+1234567890", - "data:text/plain;base64,SGVsbG8=", - "urn:isbn:9780140328721", - "urc:example", - ], -) -@pytest.mark.parametrize("invalid_char", ["\x00", "\t", "\n", "\r", " ", "\x7f"]) -def test_rejects_raw_ascii_controls_and_spaces_in_uri(value: str, invalid_char: str): - """Test rejects raw ASCII controls and spaces in URI.""" - assert not uri(value + invalid_char) - - -@pytest.mark.parametrize( - "value", - [ - "file:///tmp/readme%20name.txt", - "ipfs://QmYwAPJzv5CZsnAzt8auVZRnGiUncKEy6PBDoDeZ7hA9Rx/readme%0A.txt", - "magnet:?xt=urn:btih:0123456789012345678901234567890123456789&dn=readme%20name", - "data:text/plain,hello%20world", - ], -) -def test_accepts_percent_encoded_characters_in_uri(value: str): - """Test accepts percent encoded characters in URI.""" - assert uri(value) diff --git a/tests/test_url.py b/tests/test_url.py deleted file mode 100644 index d48a03ec..00000000 --- a/tests/test_url.py +++ /dev/null @@ -1,301 +0,0 @@ -"""Test URL.""" - -# standard -from typing import Optional - -# external -import pytest - -# local -from validators import ValidationError, url - - -@pytest.mark.parametrize( - "value", - [ - "http://foobar.dk", - "http://foobar.museum/foobar", - "http://fo.com", - "http://FOO.com", - "http://foo.com/blah_blah", - "http://foo.com/blah_blah/", - "http://foo.com/blah_blah_(wikipedia)", - "http://foo.com/blah_blah_(wikipedia)_(again)", - "http://www.example.com/wpstyle/?p=364", - "https://www.example.com?bar=baz", - "http://✪df.ws/123", - "http://userid:password@example.com:8080", - "http://userid:password@example.com:8080/", - "http://userid@example.com", - "http://userid@example.com/", - "http://userid@example.com:8080", - "http://userid@example.com:8080/", - "http://userid:password@example.com", - "http://userid:password@example.com/", - "http://142.42.1.1/", - "http://142.42.1.1:8080/", - "http://➡.ws/䨹", - "http://⌘.ws", - "http://⌘.ws/", - "http://foo.com/blah_(wikipedia)#cite-1", - "http://foo.com/blah_(wikipedia)_blah#cite-1", - "http://foo.com/unicode_(✪)_in_parens", - "http://foo.com/(something)?after=parens", - "http://☺.damowmow.com/", - "http://code.google.com/events/#&product=browser", - "http://j.mp", - "ftp://foo.bar/baz", - "http://foo.bar/?q=Test%20URL-encoded%20stuff", - "http://مثال.إختبار", - "http://例子.测试", - "http://उदाहरण.परीक्षा", - "http://www.😉.com", - "http://😉.com/😁", - "http://উদাহরণ.বাংলা", - "http://xn--d5b6ci4b4b3a.xn--54b7fta0cc", - "http://дом-м.рф/1/asdf", - "http://xn----gtbybh.xn--p1ai/1/asdf", - "http://1337.net", - "http://a.b-c.de", - "http://a.b--c.de/", - "http://0.0.0.0", - "http://224.1.1.1", - "http://223.255.255.254", - "http://10.1.1.0", - "http://10.1.1.1", - "http://10.1.1.254", - "http://10.1.1.255", - "http://127.0.0.1:8080", - "http://127.0.10.150", - "http://47.96.118.255:2333/", - "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html", - "http://[1080:0:0:0:8:800:200C:417A]/index.html", - "http://[3ffe:2a00:100:7031::1]", - "http://[1080::8:800:200C:417A]/foo", - "http://[::192.9.5.5]/ipng", - "http://[::FFFF:129.144.52.38]:80/index.html", - "http://[2010:836B:4179::836B:4179]", - "http://foo.bar", - "http://foo.bar/📍", - "http://google.com:9/test", - "http://5.196.190.0/", - "http://username:password@example.com:4010/", - "http://username:password@112.168.10.10:4010/", - "http://base-test-site.local", - "http://президент.рф/", - "http://10.24.90.255:83/", - "https://travel-usa.com/wisconsin/旅行/", - "http://:::::::::::::@exmp.com", - "http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com", - "https://exchange.jetswap.finance/#/swap", - "https://www.foo.com/bar#/baz/test", - "https://matrix.to/#/!BSqRHgvCtIsGittkBG:talk.puri.sm/$1551464398" - + "853539kMJNP:matrix.org?via=talk.puri.sm&via=matrix.org&via=disroot.org", - "https://example.org/path#2022%201040%20(Cornelius%20Morgan%20G).pdf", - # when simple_host=True - # "http://localhost", - # "http://localhost:8000", - # "http://pc:8081/", - # "http://3628126748", - # "http://foobar", - # when strict_query=False - # "https://www.example.com/foo/?bar=baz&inga=42&quux", - # "https://foo.bar.net/baz.php?-/inga/test-lenient-query/", - # "https://foo.com/img/bar/baz.jpg?-62169987208", - # "https://example.com/foo/?bar#!baz/inga/8SA-M3as7A8", - ], -) -def test_returns_true_on_valid_url(value: str): - """Test returns true on valid url.""" - assert url(value) - - -@pytest.mark.parametrize( - "value, private", - [ - ("http://username:password@10.0.10.1/", True), - ("http://username:password@192.168.10.10:4010/", True), - ("http://127.0.0.1", True), - ], -) -def test_returns_true_on_valid_private_url(value: str, private: Optional[bool]): - """Test returns true on valid private url.""" - assert url(value, private=private) - - -@pytest.mark.parametrize( - "value", - [ - "foobar.dk", - "http://127.0.0/asdf", - "http://foobar.d", - "http://foobar.12", - "htp://foobar.com", - "http://foobar..com", - "http://fo..com", - "http://", - "http://.", - "http://..", - "http://../", - "http://?", - "http://??", - "http://??/", - "http://#", - "http://##", - "http://##/", - "http://foo.bar?q=Spaces should be encoded", - "//", - "//a", - "///a", - "///", - "http:///a", - "foo.com", - "rdar://1234", - "h://test", - "http:// shouldfail.com", - ":// should fail", - "http://foo.bar/foo(bar)baz quux", - "http://-error-.invalid/", - "http://www.\ufffd.ch", - "http://-a.b.co", - "http://a.b-.co", - "http://1.1.1.1.1", - "http://123.123.123", - "http://.www.foo.bar/", - "http://www.foo.bar./", - "http://.www.foo.bar./", - "http://127.12.0.260", - 'http://example.com/">user@example.com', - "http://[2010:836B:4179::836B:4179", - "http://2010:836B:4179::836B:4179", - "http://2010:836B:4179::836B:4179:80/index.html", - "https://example.org?q=search');alert(document.domain);", - "https://www.example.com/foo/?bar=baz&inga=42&quux", - "https://foo.com/img/bar/baz.jpg?-62169987208", - "https://foo.bar.net/baz.php?-/inga/test-lenient-query/", - "https://example.com/foo/?bar#!baz/inga/8SA-M3as7A8", - "http://0.00.00.00.00.00.00.00.00.00.00.00.00.00.00." - + "00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00." - + "00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00." - + "00.00.00.00.00.00.00.00.00.00.00.00.00.", # ReDoS - "http://172.20.201.135-10.10.10.1656172.20.11.80-10." - + "10.10.1746172.16.9.13-192.168.17.68610.10.10.226-192." - + "168.17.64610.10.10.226-192.168.17.63610.10.10.226-192." - + "168.17.62610.10.10.226-192.168.17.61610.10.10.226-192." - + "168.17.60610.10.10.226-192.168.17.59610.10.10.226-192." - + "168.17.58610.10.10.226-192.168.17.57610.10.10.226-192." - + "168.17.56610.10.10.226-192.168.17.55610.10.10.226-192." - + "168.17.54610.10.10.226-192.168.17.53610.10.10.226-192." - + "168.17.52610.10.10.226-192.168.17.51610.10.10.195-10." - + "10.10.2610.10.10.194-192.168.17.685172.20.11.52-10.10." - + "10.195510.10.10.226-192.168.17.50510.10.10.186-172.20." - + "11.1510.10.10.165-198.41.0.54192.168.84.1-192.168.17." - + "684192.168.222.1-192.168.17.684172.20.11.52-10.10.10." - + "174410.10.10.232-172.20.201.198410.10.10.228-172.20.201." - + "1983192.168.17.135-10.10.10.1423192.168.17.135-10.10.10." - + "122310.10.10.224-172.20.201.198310.10.10.195-172.20.11." - + "1310.10.10.160-172.20.201.198310.10.10.142-192.168.17." - + "1352192.168.22.207-10.10.10.2242192.168.17.66-10.10.10." - + "1122192.168.17.135-10.10.10.1122192.168.17.129-10.10.10." - + "1122172.20.201.198-10.10.10.2282172.20.201.198-10.10.10." - + "2242172.20.201.1-10.10.10.1652172.20.11.2-10.10.10.1412172." - + "16.8.229-12.162.170.196210.10.10.212-192.168.22.133", # ReDoS - ], -) -def test_returns_failed_validation_on_invalid_url(value: str): - """Test returns failed validation on invalid url.""" - assert isinstance(url(value), ValidationError) - - -@pytest.mark.parametrize( - "value, private", - [ - ("http://username:password@192.168.10.10:4010", False), - ("http://username:password@127.0.0.1:8080", False), - ("http://10.0.10.1", False), - ("http://255.255.255.255", False), - ], -) -def test_returns_failed_validation_on_invalid_private_url(value: str, private: Optional[bool]): - """Test returns failed validation on invalid private url.""" - assert isinstance(url(value, private=private), ValidationError) - - -@pytest.mark.parametrize( - "value", - [ - "file:///var/www", - "file:///C:/Windows", - "file://localhost/var/www", - ], -) -def test_returns_string_for_valid_file_url(value: str): - """Test returns true on valid file url. Ref: RFC 8089.""" - assert url(value) - - -@pytest.mark.parametrize("control", [chr(code) for code in range(32)] + ["\x7f"]) -@pytest.mark.parametrize( - "template", - [ - "{control}https://example.com/", - "https://user{control}@example.com/", - "https://example.com/a{control}b", - "https://example.com/?q=a{control}b", - "https://example.com/#a{control}b", - ], -) -def test_url_rejects_raw_ascii_controls(control: str, template: str): - """Reject raw control characters before URL parsing can discard them.""" - assert isinstance(url(template.format(control=control)), ValidationError) - - -@pytest.mark.parametrize("encoded", ["%00", "%09", "%0A", "%1F", "%7F"]) -@pytest.mark.parametrize( - "template", ["https://example.com/a{encoded}b", "https://example.com/?q=a{encoded}b"] -) -def test_url_accepts_percent_encoded_controls(encoded: str, template: str): - """Keep escaped data valid while rejecting literal control characters.""" - assert url(template.format(encoded=encoded)) is True - - -@pytest.mark.parametrize( - "value", - ["https://example.\uff43\uff4f\uff4d/", "https://exam\u00adple.com/", "http://\u017ferver/"], -) -def test_returns_failed_validation_on_idna_mapped_lookalike_url(value: str): - """Test returns failed validation on url hosts that only IDNA 2003 mapping makes valid.""" - assert isinstance(url(value, simple_host=True), ValidationError) - - -@pytest.mark.parametrize("value", ["http://10.0.0.\u0661/", "https://192.168.1.\u0661:8080/"]) -@pytest.mark.parametrize("private", [None, False, True]) -def test_returns_failed_validation_on_ipv4_lookalike_url(value: str, private: Optional[bool]): - """Test returns failed validation on hosts that only look like an IPv4 address.""" - assert isinstance(url(value, private=private), ValidationError) - - -@pytest.mark.parametrize( - "value", - [ - "https://example.com/path", - "https://xn--e1afmkfd.xn--p1ai/", - "https://пример.рф/", - "http://例子.中国:8080/index.html", - ], -) -def test_returns_true_on_valid_top_level_domain_url(value: str): - """Test returns true on url with a TLD allowed by IANA.""" - assert url(value, consider_tld=True) - - -@pytest.mark.parametrize( - "value", - [ - "https://example.flat/", - "https://пример.рфы/", - ], -) -def test_returns_failed_validation_on_invalid_top_level_domain_url(value: str): - """Test returns failed validation on url with a TLD not allowed by IANA.""" - assert isinstance(url(value, consider_tld=True), ValidationError) diff --git a/tests/test_uuid.py b/tests/test_uuid.py deleted file mode 100644 index b4f40d29..00000000 --- a/tests/test_uuid.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Test UUIDs.""" - -# standard -from typing import Union -from uuid import UUID, uuid4 - -# external -import pytest - -# local -from validators import ValidationError, uuid - - -@pytest.mark.parametrize( - ("value",), - [ - (uuid4(),), - ("2bc1c94f-0deb-43e9-92a1-4775189ec9f8",), - (uuid4(),), - ("888256d7c49341f19fa33f29d3f820d7",), - ], -) -def test_returns_true_on_valid_uuid(value: Union[str, UUID]): - """Test returns true on valid uuid.""" - assert uuid(value) - - -@pytest.mark.parametrize( - ("value",), - [ - ("2bc1c94f-deb-43e9-92a1-4775189ec9f8",), - ("2bc1c94f-0deb-43e9-92a1-4775189ec9f",), - ("gbc1c94f-0deb-43e9-92a1-4775189ec9f8",), - ("2bc1c94f 0deb-43e9-92a1-4775189ec9f8",), - ], -) -def test_returns_failed_validation_on_invalid_uuid(value: Union[str, UUID]): - """Test returns failed validation on invalid uuid.""" - assert isinstance(uuid(value), ValidationError) diff --git a/tests/test_validation_failure.py b/tests/test_validation_failure.py deleted file mode 100644 index df308410..00000000 --- a/tests/test_validation_failure.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Test validation Failure.""" - -# standard -from typing import Any, Callable - -# third-party -import pytest - -# local -from validators import ValidationError, between, slug, uuid - - -@pytest.mark.parametrize("function,value", [(slug, "invalid_"), (uuid, "not-a-uuid")]) -def test_false_raise_validation_error_flag( - function: Callable[..., Any], value: str, monkeypatch: pytest.MonkeyPatch -) -> None: - """A false flag returns validation errors instead of raising them.""" - monkeypatch.delenv("RAISE_VALIDATION_ERROR", raising=False) - result = function(value, r_ve=False) - assert isinstance(result, ValidationError) - assert not result - - -@pytest.mark.parametrize("function,value", [(slug, "invalid_"), (uuid, "not-a-uuid")]) -def test_environment_still_enables_raise_validation_error( - function: Callable[..., Any], value: str, monkeypatch: pytest.MonkeyPatch -) -> None: - """The environment option enables raising even when the call flag is false.""" - monkeypatch.setenv("RAISE_VALIDATION_ERROR", "True") - with pytest.raises(ValidationError): - function(value, r_ve=False) - - -@pytest.mark.parametrize("function,value", [(slug, "invalid_"), (uuid, "not-a-uuid")]) -def test_true_raise_validation_error_flag( - function: Callable[..., Any], value: str, monkeypatch: pytest.MonkeyPatch -) -> None: - """A true call flag continues to raise validation errors.""" - monkeypatch.delenv("RAISE_VALIDATION_ERROR", raising=False) - with pytest.raises(ValidationError): - function(value, r_ve=True) - - -failed_obj_repr = "ValidationError(func=between" - - -class TestValidationError: - """Test validation Failure.""" - - def setup_method(self): - """Setup Method.""" - self.is_in_between = between(3, min_val=4, max_val=5) - - def test_boolean_coerce(self): - """Test Boolean.""" - assert not bool(self.is_in_between) - assert not self.is_in_between - - def test_repr(self): - """Test Repr.""" - assert failed_obj_repr in repr(self.is_in_between) - - def test_string(self): - """Test Repr.""" - assert failed_obj_repr in str(self.is_in_between) - - def test_arguments_as_properties(self): - """Test argument properties.""" - assert self.is_in_between.__dict__["value"] == 3 - assert self.is_in_between.__dict__["min_val"] == 4 - assert self.is_in_between.__dict__["max_val"] == 5 From 9cbf6ddc77ed313f7caa344705192cfff85cd7d7 Mon Sep 17 00:00:00 2001 From: Daana Honarmand <68249577+DaanaH-dev@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:39:55 -0500 Subject: [PATCH 02/12] Delete .devcontainer directory --- .devcontainer/devcontainer.json | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 .devcontainer/devcontainer.json diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json deleted file mode 100644 index 1bf3a2a1..00000000 --- a/.devcontainer/devcontainer.json +++ /dev/null @@ -1,22 +0,0 @@ -// For format details, see https://aka.ms/devcontainer.json. For config options, see the -// README at: https://github.com/devcontainers/templates/tree/main/src/python -{ - "name": "Python 3", - // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile - "image": "mcr.microsoft.com/devcontainers/python:3-3.11-bookworm" - - // Features to add to the dev container. More info: https://containers.dev/features. - // "features": {}, - - // Use 'forwardPorts' to make a list of ports inside the container available locally. - // "forwardPorts": [], - - // Use 'postCreateCommand' to run commands after the container is created. - // "postCreateCommand": "pip3 install --user -r requirements.txt", - - // Configure tool-specific properties. - // "customizations": {}, - - // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. - // "remoteUser": "root" -} From e87d906e68c28398d40fda7d600f77904d476c49 Mon Sep 17 00:00:00 2001 From: Daana Honarmand <68249577+DaanaH-dev@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:49:54 +0000 Subject: [PATCH 03/12] Made a initial test file for the card validator, also added markdown file for instructions on how to run the tests + coverage check. --- .devcontainer/devcontainer.json | 22 +++ .gitignore | 2 + tests/card_test.py | 243 ++++++++++++++++++++++++++++++++ tests/test.py | 0 tests/test_cmdline_running.md | 17 +++ 5 files changed, 284 insertions(+) create mode 100644 .devcontainer/devcontainer.json create mode 100644 tests/card_test.py delete mode 100644 tests/test.py create mode 100644 tests/test_cmdline_running.md diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 00000000..1bf3a2a1 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,22 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/python +{ + "name": "Python 3", + // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile + "image": "mcr.microsoft.com/devcontainers/python:3-3.11-bookworm" + + // Features to add to the dev container. More info: https://containers.dev/features. + // "features": {}, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Use 'postCreateCommand' to run commands after the container is created. + // "postCreateCommand": "pip3 install --user -r requirements.txt", + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.gitignore b/.gitignore index fed27396..de296a33 100644 --- a/.gitignore +++ b/.gitignore @@ -179,3 +179,5 @@ mise.toml # taplo .taplo.toml + +./.devcontainer/* diff --git a/tests/card_test.py b/tests/card_test.py new file mode 100644 index 00000000..bc415eec --- /dev/null +++ b/tests/card_test.py @@ -0,0 +1,243 @@ +"""ISP and Logic Coverage tests for validators.card.""" + +import pytest + +from validators.card import ( + amex, + card_number, + diners, + discover, + jcb, + mastercard, + mir, + unionpay, + visa, +) +from validators.utils import ValidationError + + +# --------------------------------------------------------------------------- +# Test Oracles +# --------------------------------------------------------------------------- +def assert_valid(result) -> None: + """Assert strict boolean True for valid inputs.""" + assert result is True + + +def assert_invalid(result) -> None: + """Assert falsy ValidationError object for invalid inputs.""" + assert not result + assert isinstance(result, ValidationError) + + +ALL_VALIDATORS = [ + card_number, + visa, + mastercard, + amex, + unionpay, + diners, + jcb, + discover, + mir, +] + +ISSUER_VALIDATORS = [ + visa, + mastercard, + amex, + unionpay, + diners, + jcb, + discover, + mir, +] + + +# --------------------------------------------------------------------------- +# 1. ISP: Argument Type (ECC across all validators) + card_number Edge Cases +# --------------------------------------------------------------------------- +@pytest.mark.parametrize("func", ALL_VALIDATORS, ids=lambda f: f.__name__) +@pytest.mark.parametrize( + "value", + [ + pytest.param(None, id="ISP-CARD-TYPE-NONE"), + pytest.param(123, id="ISP-CARD-TYPE-INT"), + pytest.param(4242424242424242, id="ISP-CARD-TYPE-VALID-LUHN-INT"), + pytest.param(b"4242424242424242", id="ISP-CARD-TYPE-BYTES"), + pytest.param(b"", id="ISP-CARD-TYPE-EMPTY-BYTES"), + pytest.param("", id="ISP-CARD-TYPE-EMPTY-STR"), + ], +) +def test_non_string_and_empty_argument_types(func, value): + """Non-str argument types and empty strings must return ValidationError.""" + assert_invalid(func(value)) + + +@pytest.mark.parametrize( + "value, expected_valid", + [ + # Luhn passes (str) + pytest.param("4242424242424242", True, id="ISP-CARDNUM-LUHN-PASS-16"), + pytest.param("0", True, id="ISP-CARDNUM-LUHN-PASS-SINGLE-ZERO"), + pytest.param("42", True, id="ISP-CARDNUM-LUHN-PASS-2DIGIT"), + # Luhn fails (str) + pytest.param("4242424242424241", False, id="ISP-CARDNUM-LUHN-FAIL-16"), + pytest.param("7", False, id="ISP-CARDNUM-LUHN-FAIL-SINGLE"), + pytest.param("41", False, id="ISP-CARDNUM-LUHN-FAIL-2DIGIT"), + # ValueError branch inside card_number (non-digit characters) + pytest.param("424242424242424a", False, id="ISP-CARDNUM-NONDIGIT-ALPHA"), + pytest.param("4242-4242-4242-4242", False, id="ISP-CARDNUM-NONDIGIT-HYPHEN"), + pytest.param("4242 4242 4242 4242", False, id="ISP-CARDNUM-NONDIGIT-SPACE"), + pytest.param("42.42", False, id="ISP-CARDNUM-NONDIGIT-DOT"), + ], +) +def test_card_number_luhn_and_format(value, expected_valid): + """Test card_number valid/invalid Luhn checksums and ValueError exception path.""" + result = card_number(value) + assert_valid(result) if expected_valid else assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 2. ISP (ACoC) + Logic Coverage (CACC) for Compound Predicates in Issuers +# --------------------------------------------------------------------------- +@pytest.mark.parametrize( + "func, value, expected_valid", + [ + # ---- visa (len=16, ^4) ---- + pytest.param(visa, "4242424242424242", True, id="LC-VISA-CACC-TTT_ISP-ACOC-PASS-OK"), + pytest.param(visa, "4242424242424241", False, id="LC-VISA-CACC-FTT_ISP-ACOC-FAIL-OK"), + pytest.param(visa, "400000000000006", False, id="LC-VISA-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), + pytest.param(visa, "5100000000000008", False, id="LC-VISA-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), + pytest.param(visa, "400000000000005", False, id="ISP-VISA-ACOC-FAIL-WRONGLEN15"), + pytest.param(visa, "5100000000000007", False, id="ISP-VISA-ACOC-FAIL-WRONGPFX"), + pytest.param(visa, "510000000000000", False, id="ISP-VISA-FAIL-WRONGLEN-WRONGPFX"), + # ---- mastercard (len=16, ^(5[1-5]|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)) ---- + pytest.param(mastercard, "5555555555554444", True, id="LC-MC-CACC-TTT_ISP-ACOC-PASS-OK"), + pytest.param(mastercard, "5555555555554443", False, id="LC-MC-CACC-FTT_ISP-ACOC-FAIL-OK"), + pytest.param(mastercard, "510000000000003", False, id="LC-MC-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), + pytest.param(mastercard, "4242424242424242", False, id="LC-MC-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), + pytest.param(mastercard, "510000000000002", False, id="ISP-MC-ACOC-FAIL-WRONGLEN15"), + pytest.param(mastercard, "4242424242424241", False, id="ISP-MC-ACOC-FAIL-WRONGPFX"), + pytest.param(mastercard, "400000000000000", False, id="ISP-MC-FAIL-WRONGLEN-WRONGPFX"), + # ---- amex (len=15, ^(34|37)) ---- + pytest.param(amex, "378282246310005", True, id="LC-AMEX-CACC-TTT_ISP-ACOC-PASS-OK"), + pytest.param(amex, "378282246310004", False, id="LC-AMEX-CACC-FTT_ISP-ACOC-FAIL-OK"), + pytest.param(amex, "34000000000000", False, id="LC-AMEX-CACC-TFT_ISP-ACOC-PASS-WRONGLEN14"), + pytest.param(amex, "350000000000006", False, id="LC-AMEX-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), + pytest.param(amex, "34000000000001", False, id="ISP-AMEX-ACOC-FAIL-WRONGLEN14"), + pytest.param(amex, "350000000000005", False, id="ISP-AMEX-ACOC-FAIL-WRONGPFX"), + pytest.param(amex, "4242424242424241", False, id="ISP-AMEX-FAIL-WRONGLEN-WRONGPFX"), + # ---- unionpay (len=16, ^62) ---- + pytest.param(unionpay, "6200000000000005", True, id="LC-UP-CACC-TTT_ISP-ACOC-PASS-OK"), + pytest.param(unionpay, "6200000000000004", False, id="LC-UP-CACC-FTT_ISP-ACOC-FAIL-OK"), + pytest.param(unionpay, "620000000000000", False, id="LC-UP-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), + pytest.param(unionpay, "4242424242424242", False, id="LC-UP-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), + pytest.param(unionpay, "620000000000001", False, id="ISP-UP-ACOC-FAIL-WRONGLEN15"), + pytest.param(unionpay, "4242424242424241", False, id="ISP-UP-ACOC-FAIL-WRONGPFX"), + pytest.param(unionpay, "400000000000000", False, id="ISP-UP-FAIL-WRONGLEN-WRONGPFX"), + # ---- diners (len in {14, 16}, ^(30|36|38|39)) ---- + pytest.param(diners, "3056930009020004", True, id="LC-DINERS-CACC-TTT_ISP-ACOC-PASS-OK"), + pytest.param(diners, "3056930009020003", False, id="LC-DINERS-CACC-FTT_ISP-ACOC-FAIL-OK"), + pytest.param(diners, "300000000000007", False, id="LC-DINERS-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), + pytest.param(diners, "4242424242424242", False, id="LC-DINERS-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), + pytest.param(diners, "300000000000006", False, id="ISP-DINERS-ACOC-FAIL-WRONGLEN15"), + pytest.param(diners, "4242424242424241", False, id="ISP-DINERS-ACOC-FAIL-WRONGPFX"), + pytest.param(diners, "400000000000000", False, id="ISP-DINERS-FAIL-WRONGLEN-WRONGPFX"), + # ---- jcb (len=16, ^35) ---- + pytest.param(jcb, "3566002020360505", True, id="LC-JCB-CACC-TTT_ISP-ACOC-PASS-OK"), + pytest.param(jcb, "3566002020360504", False, id="LC-JCB-CACC-FTT_ISP-ACOC-FAIL-OK"), + pytest.param(jcb, "350000000000006", False, id="LC-JCB-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), + pytest.param(jcb, "4242424242424242", False, id="LC-JCB-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), + pytest.param(jcb, "350000000000005", False, id="ISP-JCB-ACOC-FAIL-WRONGLEN15"), + pytest.param(jcb, "4242424242424241", False, id="ISP-JCB-ACOC-FAIL-WRONGPFX"), + pytest.param(jcb, "400000000000000", False, id="ISP-JCB-FAIL-WRONGLEN-WRONGPFX"), + # ---- discover (len=16, ^(60|64|65)) ---- + pytest.param(discover, "6011111111111117", True, id="LC-DISC-CACC-TTT_ISP-ACOC-PASS-OK"), + pytest.param(discover, "6011111111111116", False, id="LC-DISC-CACC-FTT_ISP-ACOC-FAIL-OK"), + pytest.param(discover, "600000000000004", False, id="LC-DISC-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), + pytest.param(discover, "4242424242424242", False, id="LC-DISC-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), + pytest.param(discover, "600000000000003", False, id="ISP-DISC-ACOC-FAIL-WRONGLEN15"), + pytest.param(discover, "4242424242424241", False, id="ISP-DISC-ACOC-FAIL-WRONGPFX"), + pytest.param(discover, "400000000000000", False, id="ISP-DISC-FAIL-WRONGLEN-WRONGPFX"), + # ---- mir (len=16, ^(220[0-4])) ---- + pytest.param(mir, "2200123456789019", True, id="LC-MIR-CACC-TTT_ISP-ACOC-PASS-OK"), + pytest.param(mir, "2200123456789018", False, id="LC-MIR-CACC-FTT_ISP-ACOC-FAIL-OK"), + pytest.param(mir, "220000000000004", False, id="LC-MIR-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), + pytest.param(mir, "4242424242424242", False, id="LC-MIR-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), + pytest.param(mir, "220000000000003", False, id="ISP-MIR-ACOC-FAIL-WRONGLEN15"), + pytest.param(mir, "4242424242424241", False, id="ISP-MIR-ACOC-FAIL-WRONGPFX"), + pytest.param(mir, "400000000000000", False, id="ISP-MIR-FAIL-WRONGLEN-WRONGPFX"), + ], +) +def test_issuer_acoc_and_cacc(func, value, expected_valid): + """Verify ACoC and CACC requirements for each issuer validator.""" + result = func(value) + assert_valid(result) if expected_valid else assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 3. Boundary & Regex Alternative Coverage +# --------------------------------------------------------------------------- +@pytest.mark.parametrize( + "func, value, expected_valid", + [ + # visa length upper boundary (17) and prefix boundary (3, 5) + pytest.param(visa, "4000000000000002", True, id="BND-VISA-LEN16"), + pytest.param(visa, "40000000000000006", False, id="BND-VISA-LEN17"), + pytest.param(visa, "3500000000000009", False, id="BND-VISA-PFX35"), + # mastercard BIN alternatives & boundaries (51-55, 2221-2720) + pytest.param(mastercard, "5100000000000008", True, id="BND-MC-51-LOWER"), + pytest.param(mastercard, "5500000000000004", True, id="BND-MC-55-UPPER"), + pytest.param(mastercard, "5000000000000009", False, id="BND-MC-50-BELOW"), + pytest.param(mastercard, "5600000000000003", False, id="BND-MC-56-ABOVE"), + pytest.param(mastercard, "2221000000000009", True, id="BND-MC-2221-LOWER"), + pytest.param(mastercard, "2220000000000000", False, id="BND-MC-2220-BELOW"), + pytest.param(mastercard, "2230000000000008", True, id="BND-MC-223X"), + pytest.param(mastercard, "2300000000000003", True, id="BND-MC-23XX"), + pytest.param(mastercard, "2710000000000007", True, id="BND-MC-271X"), + pytest.param(mastercard, "2720000000000005", True, id="BND-MC-2720-UPPER"), + pytest.param(mastercard, "2721000000000004", False, id="BND-MC-2721-ABOVE"), + pytest.param(mastercard, "51000000000000003", False, id="BND-MC-LEN17"), + # amex alternatives (34, 37) and boundaries (33, 38, len 16) + pytest.param(amex, "340000000000009", True, id="BND-AMEX-PFX34"), + pytest.param(amex, "380000000000000", False, id="BND-AMEX-PFX38"), + pytest.param(amex, "3400000000000000", False, id="BND-AMEX-LEN16"), + # unionpay boundaries (61, 63, len 17) + pytest.param(unionpay, "6100000000000006", False, id="BND-UP-PFX61"), + pytest.param(unionpay, "6300000000000004", False, id="BND-UP-PFX63"), + pytest.param(unionpay, "62000000000000000", False, id="BND-UP-LEN17"), + # diners lengths {14, 16} + boundaries {13, 15, 17} + prefixes {30, 36, 38, 39} + pytest.param(diners, "30000000000004", True, id="BND-DINERS-LEN14-PFX30"), + pytest.param(diners, "36000000000008", True, id="BND-DINERS-LEN14-PFX36"), + pytest.param(diners, "38000000000006", True, id="BND-DINERS-LEN14-PFX38"), + pytest.param(diners, "39000000000005", True, id="BND-DINERS-LEN14-PFX39"), + pytest.param(diners, "3600000000000008", True, id="BND-DINERS-LEN16-PFX36"), + pytest.param(diners, "30000000000003", False, id="BND-DINERS-LEN14-FAILLUHN"), + pytest.param(diners, "3000000000007", False, id="BND-DINERS-LEN13"), + pytest.param(diners, "30000000000000007", False, id="BND-DINERS-LEN17"), + pytest.param(diners, "35000000000009", False, id="BND-DINERS-LEN14-PFX35"), + pytest.param(diners, "3700000000000007", False, id="BND-DINERS-LEN16-PFX37"), + # jcb boundaries (34, 36, len 17) + pytest.param(jcb, "3400000000000000", False, id="BND-JCB-PFX34"), + pytest.param(jcb, "3600000000000008", False, id="BND-JCB-PFX36"), + pytest.param(jcb, "35000000000000006", False, id="BND-JCB-LEN17"), + # discover alternatives (60, 64, 65) and misses (62, 63, 66, len 17) + pytest.param(discover, "6400000000000003", True, id="BND-DISC-PFX64"), + pytest.param(discover, "6500000000000002", True, id="BND-DISC-PFX65"), + pytest.param(discover, "6200000000000005", False, id="BND-DISC-PFX62"), + pytest.param(discover, "6300000000000004", False, id="BND-DISC-PFX63"), + pytest.param(discover, "6600000000000001", False, id="BND-DISC-PFX66"), + pytest.param(discover, "60000000000000004", False, id="BND-DISC-LEN17"), + # mir boundaries (2199, 2200, 2204, 2205, len 17) + pytest.param(mir, "2200000000000004", True, id="BND-MIR-2200-LOWER"), + pytest.param(mir, "2204000000000000", True, id="BND-MIR-2204-UPPER"), + pytest.param(mir, "2199000000000007", False, id="BND-MIR-2199-BELOW"), + pytest.param(mir, "2205000000000009", False, id="BND-MIR-2205-ABOVE"), + pytest.param(mir, "22000000000000004", False, id="BND-MIR-LEN17"), + ], +) +def test_issuer_boundaries(func, value, expected_valid): + """Verify exact length and BIN/prefix boundaries for all issuers.""" + result = func(value) + assert_valid(result) if expected_valid else assert_invalid(result) diff --git a/tests/test.py b/tests/test.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/test_cmdline_running.md b/tests/test_cmdline_running.md new file mode 100644 index 00000000..a34fd292 --- /dev/null +++ b/tests/test_cmdline_running.md @@ -0,0 +1,17 @@ + +## Using card as a example: + +``` +pytest ./tests/card_test.py -v +``` + +### Check Code coverage: + +``` +coverage run --branch --source=validators.card -m pytest ./tests/card_test.py +coverage report -m +``` + +Need to change the source to be the appropriate validator in the folder + +Will need to install pytest and coverage in order to run this code. From af447371517987cd69fdb8ee299aabbdef0de8ae Mon Sep 17 00:00:00 2001 From: Daana Honarmand <68249577+DaanaH-dev@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:49:59 +0000 Subject: [PATCH 04/12] Update card_test.py --- tests/card_test.py | 268 ++++++++++++++++++++++----------------------- 1 file changed, 134 insertions(+), 134 deletions(-) diff --git a/tests/card_test.py b/tests/card_test.py index bc415eec..9014c947 100644 --- a/tests/card_test.py +++ b/tests/card_test.py @@ -61,12 +61,12 @@ def assert_invalid(result) -> None: @pytest.mark.parametrize( "value", [ - pytest.param(None, id="ISP-CARD-TYPE-NONE"), - pytest.param(123, id="ISP-CARD-TYPE-INT"), - pytest.param(4242424242424242, id="ISP-CARD-TYPE-VALID-LUHN-INT"), - pytest.param(b"4242424242424242", id="ISP-CARD-TYPE-BYTES"), - pytest.param(b"", id="ISP-CARD-TYPE-EMPTY-BYTES"), - pytest.param("", id="ISP-CARD-TYPE-EMPTY-STR"), + pytest.param(None, id="ISP type: None"), + pytest.param(123, id="ISP type: int (small number)"), + pytest.param(4242424242424242, id="ISP type: int (16-digit valid Luhn)"), + pytest.param(b"4242424242424242", id="ISP type: bytes (non-empty)"), + pytest.param(b"", id="ISP type: bytes (empty)"), + pytest.param("", id="ISP type: str (empty)"), ], ) def test_non_string_and_empty_argument_types(func, value): @@ -78,18 +78,18 @@ def test_non_string_and_empty_argument_types(func, value): "value, expected_valid", [ # Luhn passes (str) - pytest.param("4242424242424242", True, id="ISP-CARDNUM-LUHN-PASS-16"), - pytest.param("0", True, id="ISP-CARDNUM-LUHN-PASS-SINGLE-ZERO"), - pytest.param("42", True, id="ISP-CARDNUM-LUHN-PASS-2DIGIT"), + pytest.param("4242424242424242", True, id="valid Luhn: 16 digits"), + pytest.param("0", True, id="valid Luhn: single zero"), + pytest.param("42", True, id="valid Luhn: 2 digits"), # Luhn fails (str) - pytest.param("4242424242424241", False, id="ISP-CARDNUM-LUHN-FAIL-16"), - pytest.param("7", False, id="ISP-CARDNUM-LUHN-FAIL-SINGLE"), - pytest.param("41", False, id="ISP-CARDNUM-LUHN-FAIL-2DIGIT"), + pytest.param("4242424242424241", False, id="invalid Luhn: 16 digits"), + pytest.param("7", False, id="invalid Luhn: single digit"), + pytest.param("41", False, id="invalid Luhn: 2 digits"), # ValueError branch inside card_number (non-digit characters) - pytest.param("424242424242424a", False, id="ISP-CARDNUM-NONDIGIT-ALPHA"), - pytest.param("4242-4242-4242-4242", False, id="ISP-CARDNUM-NONDIGIT-HYPHEN"), - pytest.param("4242 4242 4242 4242", False, id="ISP-CARDNUM-NONDIGIT-SPACE"), - pytest.param("42.42", False, id="ISP-CARDNUM-NONDIGIT-DOT"), + pytest.param("424242424242424a", False, id="non-digit char: letter"), + pytest.param("4242-4242-4242-4242", False, id="non-digit char: hyphen"), + pytest.param("4242 4242 4242 4242", False, id="non-digit char: space"), + pytest.param("42.42", False, id="non-digit char: decimal dot"), ], ) def test_card_number_luhn_and_format(value, expected_valid): @@ -104,70 +104,70 @@ def test_card_number_luhn_and_format(value, expected_valid): @pytest.mark.parametrize( "func, value, expected_valid", [ - # ---- visa (len=16, ^4) ---- - pytest.param(visa, "4242424242424242", True, id="LC-VISA-CACC-TTT_ISP-ACOC-PASS-OK"), - pytest.param(visa, "4242424242424241", False, id="LC-VISA-CACC-FTT_ISP-ACOC-FAIL-OK"), - pytest.param(visa, "400000000000006", False, id="LC-VISA-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), - pytest.param(visa, "5100000000000008", False, id="LC-VISA-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), - pytest.param(visa, "400000000000005", False, id="ISP-VISA-ACOC-FAIL-WRONGLEN15"), - pytest.param(visa, "5100000000000007", False, id="ISP-VISA-ACOC-FAIL-WRONGPFX"), - pytest.param(visa, "510000000000000", False, id="ISP-VISA-FAIL-WRONGLEN-WRONGPFX"), - # ---- mastercard (len=16, ^(5[1-5]|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)) ---- - pytest.param(mastercard, "5555555555554444", True, id="LC-MC-CACC-TTT_ISP-ACOC-PASS-OK"), - pytest.param(mastercard, "5555555555554443", False, id="LC-MC-CACC-FTT_ISP-ACOC-FAIL-OK"), - pytest.param(mastercard, "510000000000003", False, id="LC-MC-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), - pytest.param(mastercard, "4242424242424242", False, id="LC-MC-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), - pytest.param(mastercard, "510000000000002", False, id="ISP-MC-ACOC-FAIL-WRONGLEN15"), - pytest.param(mastercard, "4242424242424241", False, id="ISP-MC-ACOC-FAIL-WRONGPFX"), - pytest.param(mastercard, "400000000000000", False, id="ISP-MC-FAIL-WRONGLEN-WRONGPFX"), - # ---- amex (len=15, ^(34|37)) ---- - pytest.param(amex, "378282246310005", True, id="LC-AMEX-CACC-TTT_ISP-ACOC-PASS-OK"), - pytest.param(amex, "378282246310004", False, id="LC-AMEX-CACC-FTT_ISP-ACOC-FAIL-OK"), - pytest.param(amex, "34000000000000", False, id="LC-AMEX-CACC-TFT_ISP-ACOC-PASS-WRONGLEN14"), - pytest.param(amex, "350000000000006", False, id="LC-AMEX-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), - pytest.param(amex, "34000000000001", False, id="ISP-AMEX-ACOC-FAIL-WRONGLEN14"), - pytest.param(amex, "350000000000005", False, id="ISP-AMEX-ACOC-FAIL-WRONGPFX"), - pytest.param(amex, "4242424242424241", False, id="ISP-AMEX-FAIL-WRONGLEN-WRONGPFX"), - # ---- unionpay (len=16, ^62) ---- - pytest.param(unionpay, "6200000000000005", True, id="LC-UP-CACC-TTT_ISP-ACOC-PASS-OK"), - pytest.param(unionpay, "6200000000000004", False, id="LC-UP-CACC-FTT_ISP-ACOC-FAIL-OK"), - pytest.param(unionpay, "620000000000000", False, id="LC-UP-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), - pytest.param(unionpay, "4242424242424242", False, id="LC-UP-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), - pytest.param(unionpay, "620000000000001", False, id="ISP-UP-ACOC-FAIL-WRONGLEN15"), - pytest.param(unionpay, "4242424242424241", False, id="ISP-UP-ACOC-FAIL-WRONGPFX"), - pytest.param(unionpay, "400000000000000", False, id="ISP-UP-FAIL-WRONGLEN-WRONGPFX"), - # ---- diners (len in {14, 16}, ^(30|36|38|39)) ---- - pytest.param(diners, "3056930009020004", True, id="LC-DINERS-CACC-TTT_ISP-ACOC-PASS-OK"), - pytest.param(diners, "3056930009020003", False, id="LC-DINERS-CACC-FTT_ISP-ACOC-FAIL-OK"), - pytest.param(diners, "300000000000007", False, id="LC-DINERS-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), - pytest.param(diners, "4242424242424242", False, id="LC-DINERS-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), - pytest.param(diners, "300000000000006", False, id="ISP-DINERS-ACOC-FAIL-WRONGLEN15"), - pytest.param(diners, "4242424242424241", False, id="ISP-DINERS-ACOC-FAIL-WRONGPFX"), - pytest.param(diners, "400000000000000", False, id="ISP-DINERS-FAIL-WRONGLEN-WRONGPFX"), - # ---- jcb (len=16, ^35) ---- - pytest.param(jcb, "3566002020360505", True, id="LC-JCB-CACC-TTT_ISP-ACOC-PASS-OK"), - pytest.param(jcb, "3566002020360504", False, id="LC-JCB-CACC-FTT_ISP-ACOC-FAIL-OK"), - pytest.param(jcb, "350000000000006", False, id="LC-JCB-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), - pytest.param(jcb, "4242424242424242", False, id="LC-JCB-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), - pytest.param(jcb, "350000000000005", False, id="ISP-JCB-ACOC-FAIL-WRONGLEN15"), - pytest.param(jcb, "4242424242424241", False, id="ISP-JCB-ACOC-FAIL-WRONGPFX"), - pytest.param(jcb, "400000000000000", False, id="ISP-JCB-FAIL-WRONGLEN-WRONGPFX"), - # ---- discover (len=16, ^(60|64|65)) ---- - pytest.param(discover, "6011111111111117", True, id="LC-DISC-CACC-TTT_ISP-ACOC-PASS-OK"), - pytest.param(discover, "6011111111111116", False, id="LC-DISC-CACC-FTT_ISP-ACOC-FAIL-OK"), - pytest.param(discover, "600000000000004", False, id="LC-DISC-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), - pytest.param(discover, "4242424242424242", False, id="LC-DISC-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), - pytest.param(discover, "600000000000003", False, id="ISP-DISC-ACOC-FAIL-WRONGLEN15"), - pytest.param(discover, "4242424242424241", False, id="ISP-DISC-ACOC-FAIL-WRONGPFX"), - pytest.param(discover, "400000000000000", False, id="ISP-DISC-FAIL-WRONGLEN-WRONGPFX"), - # ---- mir (len=16, ^(220[0-4])) ---- - pytest.param(mir, "2200123456789019", True, id="LC-MIR-CACC-TTT_ISP-ACOC-PASS-OK"), - pytest.param(mir, "2200123456789018", False, id="LC-MIR-CACC-FTT_ISP-ACOC-FAIL-OK"), - pytest.param(mir, "220000000000004", False, id="LC-MIR-CACC-TFT_ISP-ACOC-PASS-WRONGLEN15"), - pytest.param(mir, "4242424242424242", False, id="LC-MIR-CACC-TTF_ISP-ACOC-PASS-WRONGPFX"), - pytest.param(mir, "220000000000003", False, id="ISP-MIR-ACOC-FAIL-WRONGLEN15"), - pytest.param(mir, "4242424242424241", False, id="ISP-MIR-ACOC-FAIL-WRONGPFX"), - pytest.param(mir, "400000000000000", False, id="ISP-MIR-FAIL-WRONGLEN-WRONGPFX"), + # ---- visa ---- + pytest.param(visa, "4242424242424242", True, id="visa: valid card (CACC TTT, ACoC)"), + pytest.param(visa, "4242424242424241", False, id="visa: fails Luhn (CACC FTT, ACoC)"), + pytest.param(visa, "400000000000006", False, id="visa: wrong length 15 (CACC TFT, ACoC)"), + pytest.param(visa, "5100000000000008", False, id="visa: wrong prefix 51 (CACC TTF, ACoC)"), + pytest.param(visa, "400000000000005", False, id="visa: fails Luhn and wrong length 15 (ACoC)"), + pytest.param(visa, "5100000000000007", False, id="visa: fails Luhn and wrong prefix 51 (ACoC)"), + pytest.param(visa, "510000000000000", False, id="visa: fails Luhn, wrong length 15, wrong prefix 51"), + # ---- mastercard ---- + pytest.param(mastercard, "5555555555554444", True, id="mastercard: valid card (CACC TTT, ACoC)"), + pytest.param(mastercard, "5555555555554443", False, id="mastercard: fails Luhn (CACC FTT, ACoC)"), + pytest.param(mastercard, "510000000000003", False, id="mastercard: wrong length 15 (CACC TFT, ACoC)"), + pytest.param(mastercard, "4242424242424242", False, id="mastercard: wrong prefix 42 (CACC TTF, ACoC)"), + pytest.param(mastercard, "510000000000002", False, id="mastercard: fails Luhn and wrong length 15 (ACoC)"), + pytest.param(mastercard, "4242424242424241", False, id="mastercard: fails Luhn and wrong prefix 42 (ACoC)"), + pytest.param(mastercard, "400000000000000", False, id="mastercard: fails Luhn, wrong length 15, wrong prefix 40"), + # ---- amex ---- + pytest.param(amex, "378282246310005", True, id="amex: valid card (CACC TTT, ACoC)"), + pytest.param(amex, "378282246310004", False, id="amex: fails Luhn (CACC FTT, ACoC)"), + pytest.param(amex, "34000000000000", False, id="amex: wrong length 14 (CACC TFT, ACoC)"), + pytest.param(amex, "350000000000006", False, id="amex: wrong prefix 35 (CACC TTF, ACoC)"), + pytest.param(amex, "34000000000001", False, id="amex: fails Luhn and wrong length 14 (ACoC)"), + pytest.param(amex, "350000000000005", False, id="amex: fails Luhn and wrong prefix 35 (ACoC)"), + pytest.param(amex, "4242424242424241", False, id="amex: fails Luhn, wrong length 16, wrong prefix 42"), + # ---- unionpay ---- + pytest.param(unionpay, "6200000000000005", True, id="unionpay: valid card (CACC TTT, ACoC)"), + pytest.param(unionpay, "6200000000000004", False, id="unionpay: fails Luhn (CACC FTT, ACoC)"), + pytest.param(unionpay, "620000000000000", False, id="unionpay: wrong length 15 (CACC TFT, ACoC)"), + pytest.param(unionpay, "4242424242424242", False, id="unionpay: wrong prefix 42 (CACC TTF, ACoC)"), + pytest.param(unionpay, "620000000000001", False, id="unionpay: fails Luhn and wrong length 15 (ACoC)"), + pytest.param(unionpay, "4242424242424241", False, id="unionpay: fails Luhn and wrong prefix 42 (ACoC)"), + pytest.param(unionpay, "400000000000000", False, id="unionpay: fails Luhn, wrong length 15, wrong prefix 40"), + # ---- diners ---- + pytest.param(diners, "3056930009020004", True, id="diners: valid card (CACC TTT, ACoC)"), + pytest.param(diners, "3056930009020003", False, id="diners: fails Luhn (CACC FTT, ACoC)"), + pytest.param(diners, "300000000000007", False, id="diners: wrong length 15 (CACC TFT, ACoC)"), + pytest.param(diners, "4242424242424242", False, id="diners: wrong prefix 42 (CACC TTF, ACoC)"), + pytest.param(diners, "300000000000006", False, id="diners: fails Luhn and wrong length 15 (ACoC)"), + pytest.param(diners, "4242424242424241", False, id="diners: fails Luhn and wrong prefix 42 (ACoC)"), + pytest.param(diners, "400000000000000", False, id="diners: fails Luhn, wrong length 15, wrong prefix 40"), + # ---- jcb ---- + pytest.param(jcb, "3566002020360505", True, id="jcb: valid card (CACC TTT, ACoC)"), + pytest.param(jcb, "3566002020360504", False, id="jcb: fails Luhn (CACC FTT, ACoC)"), + pytest.param(jcb, "350000000000006", False, id="jcb: wrong length 15 (CACC TFT, ACoC)"), + pytest.param(jcb, "4242424242424242", False, id="jcb: wrong prefix 42 (CACC TTF, ACoC)"), + pytest.param(jcb, "350000000000005", False, id="jcb: fails Luhn and wrong length 15 (ACoC)"), + pytest.param(jcb, "4242424242424241", False, id="jcb: fails Luhn and wrong prefix 42 (ACoC)"), + pytest.param(jcb, "400000000000000", False, id="jcb: fails Luhn, wrong length 15, wrong prefix 40"), + # ---- discover ---- + pytest.param(discover, "6011111111111117", True, id="discover: valid card (CACC TTT, ACoC)"), + pytest.param(discover, "6011111111111116", False, id="discover: fails Luhn (CACC FTT, ACoC)"), + pytest.param(discover, "600000000000004", False, id="discover: wrong length 15 (CACC TFT, ACoC)"), + pytest.param(discover, "4242424242424242", False, id="discover: wrong prefix 42 (CACC TTF, ACoC)"), + pytest.param(discover, "600000000000003", False, id="discover: fails Luhn and wrong length 15 (ACoC)"), + pytest.param(discover, "4242424242424241", False, id="discover: fails Luhn and wrong prefix 42 (ACoC)"), + pytest.param(discover, "400000000000000", False, id="discover: fails Luhn, wrong length 15, wrong prefix 40"), + # ---- mir ---- + pytest.param(mir, "2200123456789019", True, id="mir: valid card (CACC TTT, ACoC)"), + pytest.param(mir, "2200123456789018", False, id="mir: fails Luhn (CACC FTT, ACoC)"), + pytest.param(mir, "220000000000004", False, id="mir: wrong length 15 (CACC TFT, ACoC)"), + pytest.param(mir, "4242424242424242", False, id="mir: wrong prefix 42 (CACC TTF, ACoC)"), + pytest.param(mir, "220000000000003", False, id="mir: fails Luhn and wrong length 15 (ACoC)"), + pytest.param(mir, "4242424242424241", False, id="mir: fails Luhn and wrong prefix 42 (ACoC)"), + pytest.param(mir, "400000000000000", False, id="mir: fails Luhn, wrong length 15, wrong prefix 40"), ], ) def test_issuer_acoc_and_cacc(func, value, expected_valid): @@ -182,62 +182,62 @@ def test_issuer_acoc_and_cacc(func, value, expected_valid): @pytest.mark.parametrize( "func, value, expected_valid", [ - # visa length upper boundary (17) and prefix boundary (3, 5) - pytest.param(visa, "4000000000000002", True, id="BND-VISA-LEN16"), - pytest.param(visa, "40000000000000006", False, id="BND-VISA-LEN17"), - pytest.param(visa, "3500000000000009", False, id="BND-VISA-PFX35"), - # mastercard BIN alternatives & boundaries (51-55, 2221-2720) - pytest.param(mastercard, "5100000000000008", True, id="BND-MC-51-LOWER"), - pytest.param(mastercard, "5500000000000004", True, id="BND-MC-55-UPPER"), - pytest.param(mastercard, "5000000000000009", False, id="BND-MC-50-BELOW"), - pytest.param(mastercard, "5600000000000003", False, id="BND-MC-56-ABOVE"), - pytest.param(mastercard, "2221000000000009", True, id="BND-MC-2221-LOWER"), - pytest.param(mastercard, "2220000000000000", False, id="BND-MC-2220-BELOW"), - pytest.param(mastercard, "2230000000000008", True, id="BND-MC-223X"), - pytest.param(mastercard, "2300000000000003", True, id="BND-MC-23XX"), - pytest.param(mastercard, "2710000000000007", True, id="BND-MC-271X"), - pytest.param(mastercard, "2720000000000005", True, id="BND-MC-2720-UPPER"), - pytest.param(mastercard, "2721000000000004", False, id="BND-MC-2721-ABOVE"), - pytest.param(mastercard, "51000000000000003", False, id="BND-MC-LEN17"), - # amex alternatives (34, 37) and boundaries (33, 38, len 16) - pytest.param(amex, "340000000000009", True, id="BND-AMEX-PFX34"), - pytest.param(amex, "380000000000000", False, id="BND-AMEX-PFX38"), - pytest.param(amex, "3400000000000000", False, id="BND-AMEX-LEN16"), - # unionpay boundaries (61, 63, len 17) - pytest.param(unionpay, "6100000000000006", False, id="BND-UP-PFX61"), - pytest.param(unionpay, "6300000000000004", False, id="BND-UP-PFX63"), - pytest.param(unionpay, "62000000000000000", False, id="BND-UP-LEN17"), - # diners lengths {14, 16} + boundaries {13, 15, 17} + prefixes {30, 36, 38, 39} - pytest.param(diners, "30000000000004", True, id="BND-DINERS-LEN14-PFX30"), - pytest.param(diners, "36000000000008", True, id="BND-DINERS-LEN14-PFX36"), - pytest.param(diners, "38000000000006", True, id="BND-DINERS-LEN14-PFX38"), - pytest.param(diners, "39000000000005", True, id="BND-DINERS-LEN14-PFX39"), - pytest.param(diners, "3600000000000008", True, id="BND-DINERS-LEN16-PFX36"), - pytest.param(diners, "30000000000003", False, id="BND-DINERS-LEN14-FAILLUHN"), - pytest.param(diners, "3000000000007", False, id="BND-DINERS-LEN13"), - pytest.param(diners, "30000000000000007", False, id="BND-DINERS-LEN17"), - pytest.param(diners, "35000000000009", False, id="BND-DINERS-LEN14-PFX35"), - pytest.param(diners, "3700000000000007", False, id="BND-DINERS-LEN16-PFX37"), - # jcb boundaries (34, 36, len 17) - pytest.param(jcb, "3400000000000000", False, id="BND-JCB-PFX34"), - pytest.param(jcb, "3600000000000008", False, id="BND-JCB-PFX36"), - pytest.param(jcb, "35000000000000006", False, id="BND-JCB-LEN17"), - # discover alternatives (60, 64, 65) and misses (62, 63, 66, len 17) - pytest.param(discover, "6400000000000003", True, id="BND-DISC-PFX64"), - pytest.param(discover, "6500000000000002", True, id="BND-DISC-PFX65"), - pytest.param(discover, "6200000000000005", False, id="BND-DISC-PFX62"), - pytest.param(discover, "6300000000000004", False, id="BND-DISC-PFX63"), - pytest.param(discover, "6600000000000001", False, id="BND-DISC-PFX66"), - pytest.param(discover, "60000000000000004", False, id="BND-DISC-LEN17"), - # mir boundaries (2199, 2200, 2204, 2205, len 17) - pytest.param(mir, "2200000000000004", True, id="BND-MIR-2200-LOWER"), - pytest.param(mir, "2204000000000000", True, id="BND-MIR-2204-UPPER"), - pytest.param(mir, "2199000000000007", False, id="BND-MIR-2199-BELOW"), - pytest.param(mir, "2205000000000009", False, id="BND-MIR-2205-ABOVE"), - pytest.param(mir, "22000000000000004", False, id="BND-MIR-LEN17"), + # visa length upper boundary and prefix boundary + pytest.param(visa, "4000000000000002", True, id="visa: valid length 16"), + pytest.param(visa, "40000000000000006", False, id="visa: wrong length 17 (too long)"), + pytest.param(visa, "3500000000000009", False, id="visa: wrong prefix 35"), + # mastercard BIN alternatives and boundaries + pytest.param(mastercard, "5100000000000008", True, id="mastercard: prefix 51 lower bound (valid)"), + pytest.param(mastercard, "5500000000000004", True, id="mastercard: prefix 55 upper bound (valid)"), + pytest.param(mastercard, "5000000000000009", False, id="mastercard: prefix 50 below range (invalid)"), + pytest.param(mastercard, "5600000000000003", False, id="mastercard: prefix 56 above range (invalid)"), + pytest.param(mastercard, "2221000000000009", True, id="mastercard: prefix 2221 lower bound (valid)"), + pytest.param(mastercard, "2220000000000000", False, id="mastercard: prefix 2220 below range (invalid)"), + pytest.param(mastercard, "2230000000000008", True, id="mastercard: prefix 2230 mid-range (valid)"), + pytest.param(mastercard, "2300000000000003", True, id="mastercard: prefix 2300 mid-range (valid)"), + pytest.param(mastercard, "2710000000000007", True, id="mastercard: prefix 2710 mid-range (valid)"), + pytest.param(mastercard, "2720000000000005", True, id="mastercard: prefix 2720 upper bound (valid)"), + pytest.param(mastercard, "2721000000000004", False, id="mastercard: prefix 2721 above range (invalid)"), + pytest.param(mastercard, "51000000000000003", False, id="mastercard: wrong length 17 (too long)"), + # amex alternatives and boundaries + pytest.param(amex, "340000000000009", True, id="amex: valid prefix 34"), + pytest.param(amex, "380000000000000", False, id="amex: wrong prefix 38"), + pytest.param(amex, "3400000000000000", False, id="amex: wrong length 16 (too long)"), + # unionpay boundaries + pytest.param(unionpay, "6100000000000006", False, id="unionpay: wrong prefix 61 (below 62)"), + pytest.param(unionpay, "6300000000000004", False, id="unionpay: wrong prefix 63 (above 62)"), + pytest.param(unionpay, "62000000000000000", False, id="unionpay: wrong length 17 (too long)"), + # diners lengths, boundaries, and prefixes + pytest.param(diners, "30000000000004", True, id="diners: valid length 14 with prefix 30"), + pytest.param(diners, "36000000000008", True, id="diners: valid length 14 with prefix 36"), + pytest.param(diners, "38000000000006", True, id="diners: valid length 14 with prefix 38"), + pytest.param(diners, "39000000000005", True, id="diners: valid length 14 with prefix 39"), + pytest.param(diners, "3600000000000008", True, id="diners: valid length 16 with prefix 36"), + pytest.param(diners, "30000000000003", False, id="diners: length 14 failing Luhn (invalid)"), + pytest.param(diners, "3000000000007", False, id="diners: wrong length 13 (too short)"), + pytest.param(diners, "30000000000000007", False, id="diners: wrong length 17 (too long)"), + pytest.param(diners, "35000000000009", False, id="diners: length 14 wrong prefix 35"), + pytest.param(diners, "3700000000000007", False, id="diners: length 16 wrong prefix 37"), + # jcb boundaries + pytest.param(jcb, "3400000000000000", False, id="jcb: wrong prefix 34 (below 35)"), + pytest.param(jcb, "3600000000000008", False, id="jcb: wrong prefix 36 (above 35)"), + pytest.param(jcb, "35000000000000006", False, id="jcb: wrong length 17 (too long)"), + # discover alternatives and misses + pytest.param(discover, "6400000000000003", True, id="discover: valid prefix 64"), + pytest.param(discover, "6500000000000002", True, id="discover: valid prefix 65"), + pytest.param(discover, "6200000000000005", False, id="discover: wrong prefix 62"), + pytest.param(discover, "6300000000000004", False, id="discover: wrong prefix 63"), + pytest.param(discover, "6600000000000001", False, id="discover: wrong prefix 66"), + pytest.param(discover, "60000000000000004", False, id="discover: wrong length 17 (too long)"), + # mir boundaries + pytest.param(mir, "2200000000000004", True, id="mir: prefix 2200 lower bound (valid)"), + pytest.param(mir, "2204000000000000", True, id="mir: prefix 2204 upper bound (valid)"), + pytest.param(mir, "2199000000000007", False, id="mir: prefix 2199 below range (invalid)"), + pytest.param(mir, "2205000000000009", False, id="mir: prefix 2205 above range (invalid)"), + pytest.param(mir, "22000000000000004", False, id="mir: wrong length 17 (too long)"), ], ) def test_issuer_boundaries(func, value, expected_valid): """Verify exact length and BIN/prefix boundaries for all issuers.""" result = func(value) - assert_valid(result) if expected_valid else assert_invalid(result) + assert_valid(result) if expected_valid else assert_invalid(result) \ No newline at end of file From ff87445d78ef6dfe850107051ed5f6be28ba4cc4 Mon Sep 17 00:00:00 2001 From: Daana Honarmand <68249577+DaanaH-dev@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:10:40 -0500 Subject: [PATCH 05/12] Updated card test and added country test --- tests/card_test.py | 596 ++++++++++++++++++++++++++++-------------- tests/country_test.py | 563 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 961 insertions(+), 198 deletions(-) create mode 100644 tests/country_test.py diff --git a/tests/card_test.py b/tests/card_test.py index 9014c947..38ca1624 100644 --- a/tests/card_test.py +++ b/tests/card_test.py @@ -1,5 +1,3 @@ -"""ISP and Logic Coverage tests for validators.card.""" - import pytest from validators.card import ( @@ -15,229 +13,431 @@ ) from validators.utils import ValidationError +_BYTES_LUHN_TRUE_XFAIL = pytest.mark.xfail( + raises=AssertionError, + strict=True, + reason=( + "Defect in validators.card.card_number: map(int, bytes) converts ASCII " + "byte values into ints, allowing bytes whose ASCII Luhn sum % 10 == 0 " + "to return True instead of ValidationError." + ), +) -# --------------------------------------------------------------------------- -# Test Oracles -# --------------------------------------------------------------------------- -def assert_valid(result) -> None: - """Assert strict boolean True for valid inputs.""" - assert result is True +def _assert_result(result, expected_valid: bool) -> None: + if expected_valid: + assert result is True + else: + assert isinstance(result, ValidationError) + assert bool(result) is False -def assert_invalid(result) -> None: - """Assert falsy ValidationError object for invalid inputs.""" - assert not result - assert isinstance(result, ValidationError) +# =========================================================================== +# 1. Input Space Partitioning (ISP) - Section 2.3 & Table 2 +# =========================================================================== -ALL_VALIDATORS = [ - card_number, - visa, - mastercard, - amex, - unionpay, - diners, - jcb, - discover, - mir, -] -ISSUER_VALIDATORS = [ - visa, - mastercard, - amex, - unionpay, - diners, - jcb, - discover, - mir, -] +@pytest.mark.parametrize( + ("func", "value", "expected_valid"), + [ + # Table 2: All validators -> Argument type (str; None; int; bytes) + pytest.param(card_number, "4242424242424242", True, id="card_number-str_valid"), + pytest.param(card_number, None, False, id="card_number-none"), + pytest.param(card_number, 4242424242424242, False, id="card_number-int"), + pytest.param(card_number, b"4242424242424242", False, id="card_number-bytes"), + pytest.param(visa, "4242424242424242", True, id="visa-str_valid"), + pytest.param(visa, None, False, id="visa-none"), + pytest.param(visa, 123, False, id="visa-int"), + pytest.param(visa, b"4242424242424242", False, id="visa-bytes"), + pytest.param(mastercard, "5555555555554444", True, id="mastercard-str_valid"), + pytest.param(mastercard, None, False, id="mastercard-none"), + pytest.param(mastercard, 123, False, id="mastercard-int"), + pytest.param(mastercard, b"5555555555554444", False, id="mastercard-bytes"), + pytest.param(amex, "378282246310005", True, id="amex-str_valid"), + pytest.param(amex, None, False, id="amex-none"), + pytest.param(amex, 123, False, id="amex-int"), + pytest.param(amex, b"378282246310005", False, id="amex-bytes"), + pytest.param(unionpay, "6200000000000005", True, id="unionpay-str_valid"), + pytest.param(unionpay, None, False, id="unionpay-none"), + pytest.param(unionpay, 123, False, id="unionpay-int"), + pytest.param(unionpay, b"6200000000000005", False, id="unionpay-bytes"), + pytest.param(diners, "3056930009020004", True, id="diners-str_valid"), + pytest.param(diners, None, False, id="diners-none"), + pytest.param(diners, 123, False, id="diners-int"), + pytest.param(diners, b"3056930009020004", False, id="diners-bytes"), + pytest.param(jcb, "3566002020360505", True, id="jcb-str_valid"), + pytest.param(jcb, None, False, id="jcb-none"), + pytest.param(jcb, 123, False, id="jcb-int"), + pytest.param(jcb, b"3566002020360505", False, id="jcb-bytes"), + pytest.param(discover, "6011111111111117", True, id="discover-str_valid"), + pytest.param(discover, None, False, id="discover-none"), + pytest.param(discover, 123, False, id="discover-int"), + pytest.param(discover, b"6011111111111117", False, id="discover-bytes"), + pytest.param(mir, "2200123456789019", True, id="mir-str_valid"), + pytest.param(mir, None, False, id="mir-none"), + pytest.param(mir, 123, False, id="mir-int"), + pytest.param(mir, b"2200123456789019", False, id="mir-bytes"), + ], +) +def test_all_card_validators_argument_types(func, value, expected_valid: bool) -> None: + """TR-ISP-TYPE: Verify str, None, int, and bytes across all card validators.""" + _assert_result(func(value), expected_valid) + + +@pytest.mark.parametrize( + ("value", "expected_valid"), + [ + # card_number -> ACoC (<= 20 tests) + # Table 2 characteristic: Luhn checksum (Passes; fails) + emptiness/non-digits + pytest.param("", False, id="str-empty"), + pytest.param("0", True, id="str-single_zero_luhn_pass"), + pytest.param("5", False, id="str-single_nonzero_luhn_fail"), + pytest.param("18", True, id="str-two_digits_luhn_pass"), + pytest.param("81", False, id="str-two_digits_luhn_fail"), + pytest.param("4242424242424242", True, id="str-16_digits_luhn_pass"), + pytest.param("4242424242424241", False, id="str-16_digits_luhn_fail"), + pytest.param("424242424242424a", False, id="str-contains_letter"), + pytest.param("4242-4242-4242-4242", False, id="str-contains_hyphens"), + pytest.param("4242 4242 4242 4242", False, id="str-contains_spaces"), + pytest.param(None, False, id="none"), + pytest.param(123, False, id="int"), + pytest.param(b"4242424242424242", False, id="bytes-luhn_fail"), + ], +) +def test_card_number_isp_acoc(value, expected_valid: bool) -> None: + """TR-ISP-CARD-NUMBER-ACoC: All feasible blocks/combinations for card_number.""" + _assert_result(card_number(value), expected_valid) + + +# Table 2: amex, diners, visa -> Length and prefix x Luhn checksum (2 x 2 x 2 = 8 <= 20 -> ACoC) +@pytest.mark.parametrize( + ("func", "value", "expected_valid"), + [ + # visa: Luhn x Length (16) x Prefix (^4) + pytest.param(visa, "4242424242424242", True, id="visa-luhn_pass-len_valid-prefix_valid"), + pytest.param(visa, "5000000000000009", False, id="visa-luhn_pass-len_valid-prefix_wrong"), + pytest.param(visa, "400000000000006", False, id="visa-luhn_pass-len_wrong-prefix_valid"), + pytest.param(visa, "550000000000004", False, id="visa-luhn_pass-len_wrong-prefix_wrong"), + pytest.param(visa, "4242424242424241", False, id="visa-luhn_fail-len_valid-prefix_valid"), + pytest.param(visa, "5000000000000008", False, id="visa-luhn_fail-len_valid-prefix_wrong"), + pytest.param(visa, "400000000000005", False, id="visa-luhn_fail-len_wrong-prefix_valid"), + pytest.param(visa, "550000000000003", False, id="visa-luhn_fail-len_wrong-prefix_wrong"), + # amex: Luhn x Length (15) x Prefix (^(34|37)) + pytest.param(amex, "378282246310005", True, id="amex-luhn_pass-len_valid-prefix_valid"), + pytest.param(amex, "350000000000006", False, id="amex-luhn_pass-len_valid-prefix_wrong"), + pytest.param(amex, "3400000000000000", False, id="amex-luhn_pass-len_wrong-prefix_valid"), + pytest.param(amex, "4242424242424242", False, id="amex-luhn_pass-len_wrong-prefix_wrong"), + pytest.param(amex, "378282246310004", False, id="amex-luhn_fail-len_valid-prefix_valid"), + pytest.param(amex, "350000000000005", False, id="amex-luhn_fail-len_valid-prefix_wrong"), + pytest.param(amex, "3400000000000001", False, id="amex-luhn_fail-len_wrong-prefix_valid"), + pytest.param(amex, "4242424242424241", False, id="amex-luhn_fail-len_wrong-prefix_wrong"), + # diners: Luhn x Length ({14, 16}) x Prefix (^(30|36|38|39)) + pytest.param(diners, "3056930009020004", True, id="diners-luhn_pass-len_valid-prefix_valid"), + pytest.param(diners, "3100000000000003", False, id="diners-luhn_pass-len_valid-prefix_wrong"), + pytest.param(diners, "300000000000007", False, id="diners-luhn_pass-len_wrong-prefix_valid"), + pytest.param(diners, "378282246310005", False, id="diners-luhn_pass-len_wrong-prefix_wrong"), + pytest.param(diners, "3056930009020003", False, id="diners-luhn_fail-len_valid-prefix_valid"), + pytest.param(diners, "3100000000000002", False, id="diners-luhn_fail-len_valid-prefix_wrong"), + pytest.param(diners, "300000000000006", False, id="diners-luhn_fail-len_wrong-prefix_valid"), + pytest.param(diners, "378282246310004", False, id="diners-luhn_fail-len_wrong-prefix_wrong"), + ], +) +def test_table2_issuers_isp_acoc(func, value: str, expected_valid: bool) -> None: + """TR-ISP-ISSUERS-ACoC: All combinations of Luhn, length, and prefix for amex/diners/visa.""" + _assert_result(func(value), expected_valid) + + +# =========================================================================== +# 2. Logic Coverage (PC, CC, CACC) - Section 2.4 +# =========================================================================== + + +@pytest.mark.parametrize( + ("value", "expected_valid"), + [ + # Predicate 1 (card_number): if not value + pytest.param("", False, id="empty_true"), + # Predicate 2 (card_number): ValueError exception vs normal return + pytest.param("424242424242424a", False, id="value_error_raised_non_digit"), + # Predicate 3 (card_number): (odd_sum + even_sum) % 10 == 0 + pytest.param("4242424242424242", True, id="luhn_mod10_true"), + pytest.param("4242424242424241", False, id="luhn_mod10_false"), + ], +) +def test_card_number_logic_coverage(value: str, expected_valid: bool) -> None: + """TR-LC-CARD-NUMBER: PC/CC for empty check, ValueError branch, and Luhn predicate.""" + _assert_result(card_number(value), expected_valid) + + +# Compound Predicate for all 8 card issuers: +# P = card_number(value) and len_check(value) and pattern.match(value) +# +# Clauses: +# c1: bool(card_number(value)) [Luhn checksum passes] +# c2: len(value) == L (or in {14,16}) [Issuer-specific length] +# c3: bool(pattern.match(value)) [Issuer-specific BIN prefix] +# +# Truth Table (8 rows): +# Row 1: c1=T, c2=T, c3=T -> P=T +# Row 2: c1=T, c2=T, c3=F -> P=F +# Row 3: c1=T, c2=F, c3=T -> P=F (c3 short-circuited by c2=F) +# Row 4: c1=T, c2=F, c3=F -> P=F (c3 short-circuited by c2=F) +# Row 5: c1=F, c2=T, c3=T -> P=F (c2, c3 short-circuited by c1=F) +# Row 6: c1=F, c2=T, c3=F -> P=F (c2, c3 short-circuited by c1=F) +# Row 7: c1=F, c2=F, c3=T -> P=F (c2, c3 short-circuited by c1=F) +# Row 8: c1=F, c2=F, c3=F -> P=F (c2, c3 short-circuited by c1=F) +# +# CACC pairs: +# - Active c1 (c2=T, c3=T): Row 1 vs Row 5 +# - Active c2 (c1=T, c3=T): Row 1 vs Row 3 +# - Active c3 (c1=T, c2=T): Row 1 vs Row 2 +@pytest.mark.parametrize( + ("func", "value", "expected_valid"), + [ + # visa + pytest.param(visa, "4242424242424242", True, id="visa-row1-luhn_true-len_true-prefix_true"), + pytest.param(visa, "5000000000000009", False, id="visa-row2-luhn_true-len_true-prefix_false"), + pytest.param(visa, "400000000000006", False, id="visa-row3-luhn_true-len_false-prefix_true"), + pytest.param(visa, "4242424242424241", False, id="visa-row5-luhn_false-len_true-prefix_true"), + # mastercard + pytest.param(mastercard, "5555555555554444", True, id="mastercard-row1-luhn_true-len_true-prefix_true"), + pytest.param(mastercard, "5000000000000009", False, id="mastercard-row2-luhn_true-len_true-prefix_false"), + pytest.param(mastercard, "550000000000004", False, id="mastercard-row3-luhn_true-len_false-prefix_true"), + pytest.param(mastercard, "5555555555554443", False, id="mastercard-row5-luhn_false-len_true-prefix_true"), + # amex + pytest.param(amex, "378282246310005", True, id="amex-row1-luhn_true-len_true-prefix_true"), + pytest.param(amex, "350000000000006", False, id="amex-row2-luhn_true-len_true-prefix_false"), + pytest.param(amex, "3400000000000000", False, id="amex-row3-luhn_true-len_false-prefix_true"), + pytest.param(amex, "378282246310004", False, id="amex-row5-luhn_false-len_true-prefix_true"), + # unionpay + pytest.param(unionpay, "6200000000000005", True, id="unionpay-row1-luhn_true-len_true-prefix_true"), + pytest.param(unionpay, "6100000000000006", False, id="unionpay-row2-luhn_true-len_true-prefix_false"), + pytest.param(unionpay, "620000000000000", False, id="unionpay-row3-luhn_true-len_false-prefix_true"), + pytest.param(unionpay, "6200000000000004", False, id="unionpay-row5-luhn_false-len_true-prefix_true"), + # diners + pytest.param(diners, "3056930009020004", True, id="diners-row1-luhn_true-len_true-prefix_true"), + pytest.param(diners, "3100000000000003", False, id="diners-row2-luhn_true-len_true-prefix_false"), + pytest.param(diners, "300000000000007", False, id="diners-row3-luhn_true-len_false-prefix_true"), + pytest.param(diners, "3056930009020003", False, id="diners-row5-luhn_false-len_true-prefix_true"), + # jcb + pytest.param(jcb, "3566002020360505", True, id="jcb-row1-luhn_true-len_true-prefix_true"), + pytest.param(jcb, "3400000000000000", False, id="jcb-row2-luhn_true-len_true-prefix_false"), + pytest.param(jcb, "350000000000006", False, id="jcb-row3-luhn_true-len_false-prefix_true"), + pytest.param(jcb, "3566002020360504", False, id="jcb-row5-luhn_false-len_true-prefix_true"), + # discover + pytest.param(discover, "6011111111111117", True, id="discover-row1-luhn_true-len_true-prefix_true"), + pytest.param(discover, "5900000000000000", False, id="discover-row2-luhn_true-len_true-prefix_false"), + pytest.param(discover, "600000000000004", False, id="discover-row3-luhn_true-len_false-prefix_true"), + pytest.param(discover, "6011111111111116", False, id="discover-row5-luhn_false-len_true-prefix_true"), + # mir + pytest.param(mir, "2200123456789019", True, id="mir-row1-luhn_true-len_true-prefix_true"), + pytest.param(mir, "2205000000000009", False, id="mir-row2-luhn_true-len_true-prefix_false"), + pytest.param(mir, "220000000000004", False, id="mir-row3-luhn_true-len_false-prefix_true"), + pytest.param(mir, "2200123456789018", False, id="mir-row5-luhn_false-len_true-prefix_true"), + ], +) +def test_all_issuers_compound_predicate_cacc( + func, value: str, expected_valid: bool +) -> None: + """TR-LC-ISSUERS: PC, CC, and CACC for `card_number and len_check and pattern.match`.""" + _assert_result(func(value), expected_valid) + + +@pytest.mark.parametrize( + ("value", "expected_valid"), + [ + # Remaining short-circuited rows (Rows 4, 6, 7, 8) for complete 8-row coverage + pytest.param("550000000000004", False, id="row4-luhn_true-len_false-prefix_false"), + pytest.param("5000000000000008", False, id="row6-luhn_false-len_true-prefix_false"), + pytest.param("400000000000005", False, id="row7-luhn_false-len_false-prefix_true"), + pytest.param("550000000000003", False, id="row8-luhn_false-len_false-prefix_false"), + ], +) +def test_visa_truth_table_short_circuit_rows(value: str, expected_valid: bool) -> None: + """TR-LC-VISA-TT: Completes all 8 truth-table combinations including short-circuited rows.""" + _assert_result(visa(value), expected_valid) + + +# =========================================================================== +# 3. Branch Coverage, Mutation Testing & ValidationError Contract - Sec 2.1/2.2 +# =========================================================================== -# --------------------------------------------------------------------------- -# 1. ISP: Argument Type (ECC across all validators) + card_number Edge Cases -# --------------------------------------------------------------------------- -@pytest.mark.parametrize("func", ALL_VALIDATORS, ids=lambda f: f.__name__) @pytest.mark.parametrize( - "value", + ("func", "bad_input"), [ - pytest.param(None, id="ISP type: None"), - pytest.param(123, id="ISP type: int (small number)"), - pytest.param(4242424242424242, id="ISP type: int (16-digit valid Luhn)"), - pytest.param(b"4242424242424242", id="ISP type: bytes (non-empty)"), - pytest.param(b"", id="ISP type: bytes (empty)"), - pytest.param("", id="ISP type: str (empty)"), + pytest.param(card_number, None, id="card_number-none"), + pytest.param(card_number, 123, id="card_number-int"), + pytest.param(card_number, 12.34, id="card_number-float"), + pytest.param(card_number, b"4242424242424242", id="card_number-bytes_luhn_fail"), + pytest.param( + card_number, + b"4242424242424240", + id="card_number-bytes_ascii_luhn_pass_16digit", + marks=_BYTES_LUHN_TRUE_XFAIL, + ), + pytest.param( + card_number, + b"22", + id="card_number-bytes_ascii_luhn_pass_2digit", + marks=_BYTES_LUHN_TRUE_XFAIL, + ), + pytest.param(card_number, [], id="card_number-empty_list"), + pytest.param(card_number, {}, id="card_number-empty_dict"), + pytest.param(visa, None, id="visa-none"), + pytest.param(visa, 4242424242424242, id="visa-int"), + pytest.param(visa, b"4242424242424240", id="visa-bytes_luhn_true_regex_type_error"), + pytest.param(mastercard, b"5555555555554444", id="mastercard-bytes"), + pytest.param(amex, b"378282246310005", id="amex-bytes"), + pytest.param(unionpay, b"6200000000000005", id="unionpay-bytes"), + pytest.param(diners, b"3056930009020004", id="diners-bytes"), + pytest.param(jcb, b"3566002020360505", id="jcb-bytes"), + pytest.param(discover, b"6011111111111117", id="discover-bytes"), + pytest.param(mir, b"2200123456789019", id="mir-bytes"), ], ) -def test_non_string_and_empty_argument_types(func, value): - """Non-str argument types and empty strings must return ValidationError.""" - assert_invalid(func(value)) +def test_invalid_types_return_validation_error(func, bad_input) -> None: + """Confirm decorator-caught/falsy non-str inputs return falsy ValidationError.""" + result = func(bad_input) + _assert_result(result, False) + assert result.func.__name__ == func.__name__ @pytest.mark.parametrize( - "value, expected_valid", + ("value", "expected_valid"), [ - # Luhn passes (str) - pytest.param("4242424242424242", True, id="valid Luhn: 16 digits"), - pytest.param("0", True, id="valid Luhn: single zero"), - pytest.param("42", True, id="valid Luhn: 2 digits"), - # Luhn fails (str) - pytest.param("4242424242424241", False, id="invalid Luhn: 16 digits"), - pytest.param("7", False, id="invalid Luhn: single digit"), - pytest.param("41", False, id="invalid Luhn: 2 digits"), - # ValueError branch inside card_number (non-digit characters) - pytest.param("424242424242424a", False, id="non-digit char: letter"), - pytest.param("4242-4242-4242-4242", False, id="non-digit char: hyphen"), - pytest.param("4242 4242 4242 4242", False, id="non-digit char: space"), - pytest.param("42.42", False, id="non-digit char: decimal dot"), + # Luhn slice / carry / modulo mutation killers + pytest.param("0000000000000000", True, id="all_zeros"), + pytest.param("4000000000000002", True, id="even_len_ends_only"), + pytest.param("0400000000000006", True, id="even_len_odd_positions_only"), + pytest.param("400000000000006", True, id="odd_len_15_first_and_last"), + pytest.param("18", True, id="two_digit_valid_18"), + pytest.param("81", False, id="two_digit_swapped_81"), + pytest.param("91", True, id="divmod_carry_valid_91"), + pytest.param("92", False, id="divmod_carry_invalid_92"), + pytest.param("+4242424242424242", False, id="leading_plus_sign"), + pytest.param("-4242424242424242", False, id="leading_minus_sign"), + pytest.param(" 4242424242424242", False, id="leading_space"), + pytest.param("4242424242424242 ", False, id="trailing_space"), + pytest.param("4242424242424242\n", False, id="trailing_newline"), ], ) -def test_card_number_luhn_and_format(value, expected_valid): - """Test card_number valid/invalid Luhn checksums and ValueError exception path.""" - result = card_number(value) - assert_valid(result) if expected_valid else assert_invalid(result) +def test_card_number_luhn_boundaries_and_mutations( + value: str, expected_valid: bool +) -> None: + """Kills slice-step, doubling, divmod, modulo, and sign mutants in card_number.""" + _assert_result(card_number(value), expected_valid) -# --------------------------------------------------------------------------- -# 2. ISP (ACoC) + Logic Coverage (CACC) for Compound Predicates in Issuers -# --------------------------------------------------------------------------- @pytest.mark.parametrize( - "func, value, expected_valid", + ("func", "value"), [ - # ---- visa ---- - pytest.param(visa, "4242424242424242", True, id="visa: valid card (CACC TTT, ACoC)"), - pytest.param(visa, "4242424242424241", False, id="visa: fails Luhn (CACC FTT, ACoC)"), - pytest.param(visa, "400000000000006", False, id="visa: wrong length 15 (CACC TFT, ACoC)"), - pytest.param(visa, "5100000000000008", False, id="visa: wrong prefix 51 (CACC TTF, ACoC)"), - pytest.param(visa, "400000000000005", False, id="visa: fails Luhn and wrong length 15 (ACoC)"), - pytest.param(visa, "5100000000000007", False, id="visa: fails Luhn and wrong prefix 51 (ACoC)"), - pytest.param(visa, "510000000000000", False, id="visa: fails Luhn, wrong length 15, wrong prefix 51"), - # ---- mastercard ---- - pytest.param(mastercard, "5555555555554444", True, id="mastercard: valid card (CACC TTT, ACoC)"), - pytest.param(mastercard, "5555555555554443", False, id="mastercard: fails Luhn (CACC FTT, ACoC)"), - pytest.param(mastercard, "510000000000003", False, id="mastercard: wrong length 15 (CACC TFT, ACoC)"), - pytest.param(mastercard, "4242424242424242", False, id="mastercard: wrong prefix 42 (CACC TTF, ACoC)"), - pytest.param(mastercard, "510000000000002", False, id="mastercard: fails Luhn and wrong length 15 (ACoC)"), - pytest.param(mastercard, "4242424242424241", False, id="mastercard: fails Luhn and wrong prefix 42 (ACoC)"), - pytest.param(mastercard, "400000000000000", False, id="mastercard: fails Luhn, wrong length 15, wrong prefix 40"), - # ---- amex ---- - pytest.param(amex, "378282246310005", True, id="amex: valid card (CACC TTT, ACoC)"), - pytest.param(amex, "378282246310004", False, id="amex: fails Luhn (CACC FTT, ACoC)"), - pytest.param(amex, "34000000000000", False, id="amex: wrong length 14 (CACC TFT, ACoC)"), - pytest.param(amex, "350000000000006", False, id="amex: wrong prefix 35 (CACC TTF, ACoC)"), - pytest.param(amex, "34000000000001", False, id="amex: fails Luhn and wrong length 14 (ACoC)"), - pytest.param(amex, "350000000000005", False, id="amex: fails Luhn and wrong prefix 35 (ACoC)"), - pytest.param(amex, "4242424242424241", False, id="amex: fails Luhn, wrong length 16, wrong prefix 42"), - # ---- unionpay ---- - pytest.param(unionpay, "6200000000000005", True, id="unionpay: valid card (CACC TTT, ACoC)"), - pytest.param(unionpay, "6200000000000004", False, id="unionpay: fails Luhn (CACC FTT, ACoC)"), - pytest.param(unionpay, "620000000000000", False, id="unionpay: wrong length 15 (CACC TFT, ACoC)"), - pytest.param(unionpay, "4242424242424242", False, id="unionpay: wrong prefix 42 (CACC TTF, ACoC)"), - pytest.param(unionpay, "620000000000001", False, id="unionpay: fails Luhn and wrong length 15 (ACoC)"), - pytest.param(unionpay, "4242424242424241", False, id="unionpay: fails Luhn and wrong prefix 42 (ACoC)"), - pytest.param(unionpay, "400000000000000", False, id="unionpay: fails Luhn, wrong length 15, wrong prefix 40"), - # ---- diners ---- - pytest.param(diners, "3056930009020004", True, id="diners: valid card (CACC TTT, ACoC)"), - pytest.param(diners, "3056930009020003", False, id="diners: fails Luhn (CACC FTT, ACoC)"), - pytest.param(diners, "300000000000007", False, id="diners: wrong length 15 (CACC TFT, ACoC)"), - pytest.param(diners, "4242424242424242", False, id="diners: wrong prefix 42 (CACC TTF, ACoC)"), - pytest.param(diners, "300000000000006", False, id="diners: fails Luhn and wrong length 15 (ACoC)"), - pytest.param(diners, "4242424242424241", False, id="diners: fails Luhn and wrong prefix 42 (ACoC)"), - pytest.param(diners, "400000000000000", False, id="diners: fails Luhn, wrong length 15, wrong prefix 40"), - # ---- jcb ---- - pytest.param(jcb, "3566002020360505", True, id="jcb: valid card (CACC TTT, ACoC)"), - pytest.param(jcb, "3566002020360504", False, id="jcb: fails Luhn (CACC FTT, ACoC)"), - pytest.param(jcb, "350000000000006", False, id="jcb: wrong length 15 (CACC TFT, ACoC)"), - pytest.param(jcb, "4242424242424242", False, id="jcb: wrong prefix 42 (CACC TTF, ACoC)"), - pytest.param(jcb, "350000000000005", False, id="jcb: fails Luhn and wrong length 15 (ACoC)"), - pytest.param(jcb, "4242424242424241", False, id="jcb: fails Luhn and wrong prefix 42 (ACoC)"), - pytest.param(jcb, "400000000000000", False, id="jcb: fails Luhn, wrong length 15, wrong prefix 40"), - # ---- discover ---- - pytest.param(discover, "6011111111111117", True, id="discover: valid card (CACC TTT, ACoC)"), - pytest.param(discover, "6011111111111116", False, id="discover: fails Luhn (CACC FTT, ACoC)"), - pytest.param(discover, "600000000000004", False, id="discover: wrong length 15 (CACC TFT, ACoC)"), - pytest.param(discover, "4242424242424242", False, id="discover: wrong prefix 42 (CACC TTF, ACoC)"), - pytest.param(discover, "600000000000003", False, id="discover: fails Luhn and wrong length 15 (ACoC)"), - pytest.param(discover, "4242424242424241", False, id="discover: fails Luhn and wrong prefix 42 (ACoC)"), - pytest.param(discover, "400000000000000", False, id="discover: fails Luhn, wrong length 15, wrong prefix 40"), - # ---- mir ---- - pytest.param(mir, "2200123456789019", True, id="mir: valid card (CACC TTT, ACoC)"), - pytest.param(mir, "2200123456789018", False, id="mir: fails Luhn (CACC FTT, ACoC)"), - pytest.param(mir, "220000000000004", False, id="mir: wrong length 15 (CACC TFT, ACoC)"), - pytest.param(mir, "4242424242424242", False, id="mir: wrong prefix 42 (CACC TTF, ACoC)"), - pytest.param(mir, "220000000000003", False, id="mir: fails Luhn and wrong length 15 (ACoC)"), - pytest.param(mir, "4242424242424241", False, id="mir: fails Luhn and wrong prefix 42 (ACoC)"), - pytest.param(mir, "400000000000000", False, id="mir: fails Luhn, wrong length 15, wrong prefix 40"), + # visa (prefix ^4, len 16) + pytest.param(visa, "4000000000000002", id="visa-prefix_4000_min"), + pytest.param(visa, "4999999999999996", id="visa-prefix_4999_max"), + # mastercard (51-55, 2221-2720, len 16) + pytest.param(mastercard, "5100000000000008", id="mastercard-prefix_51_min"), + pytest.param(mastercard, "5500000000000004", id="mastercard-prefix_55_max"), + pytest.param(mastercard, "2221000000000009", id="mastercard-prefix_2221_min"), + pytest.param(mastercard, "2229000000000001", id="mastercard-prefix_2229_max"), + pytest.param(mastercard, "2230000000000008", id="mastercard-prefix_2230_min"), + pytest.param(mastercard, "2299000000000006", id="mastercard-prefix_2299_max"), + pytest.param(mastercard, "2300000000000003", id="mastercard-prefix_2300_min"), + pytest.param(mastercard, "2699000000000002", id="mastercard-prefix_2699_max"), + pytest.param(mastercard, "2700000000000009", id="mastercard-prefix_2700_min"), + pytest.param(mastercard, "2719000000000008", id="mastercard-prefix_2719_max"), + pytest.param(mastercard, "2720000000000005", id="mastercard-prefix_2720_exact"), + # amex (34, 37, len 15) + pytest.param(amex, "340000000000009", id="amex-prefix_34_len_15"), + pytest.param(amex, "378282246310005", id="amex-prefix_37_len_15"), + # diners (30, 36, 38, 39 at both len 14 and len 16) + pytest.param(diners, "30000000000004", id="diners-prefix_30_len_14"), + pytest.param(diners, "36000000000008", id="diners-prefix_36_len_14"), + pytest.param(diners, "38000000000006", id="diners-prefix_38_len_14"), + pytest.param(diners, "39000000000005", id="diners-prefix_39_len_14"), + pytest.param(diners, "3056930009020004", id="diners-prefix_30_len_16"), + pytest.param(diners, "3600000000000008", id="diners-prefix_36_len_16"), + pytest.param(diners, "3800000000000006", id="diners-prefix_38_len_16"), + pytest.param(diners, "3900000000000005", id="diners-prefix_39_len_16"), + # discover (60, 64, 65, len 16) + pytest.param(discover, "6011111111111117", id="discover-prefix_60"), + pytest.param(discover, "6400000000000003", id="discover-prefix_64"), + pytest.param(discover, "6500000000000002", id="discover-prefix_65"), + # mir (2200-2204, len 16) + pytest.param(mir, "2200123456789019", id="mir-prefix_2200_min"), + pytest.param(mir, "2201000000000003", id="mir-prefix_2201_mid"), + pytest.param(mir, "2204000000000000", id="mir-prefix_2204_max"), ], ) -def test_issuer_acoc_and_cacc(func, value, expected_valid): - """Verify ACoC and CACC requirements for each issuer validator.""" - result = func(value) - assert_valid(result) if expected_valid else assert_invalid(result) +def test_issuer_valid_prefix_and_length_boundaries(func, value: str) -> None: + """Exercise every regex branch and valid length boundary across all issuers.""" + assert func(value) is True -# --------------------------------------------------------------------------- -# 3. Boundary & Regex Alternative Coverage -# --------------------------------------------------------------------------- @pytest.mark.parametrize( - "func, value, expected_valid", + ("func", "value"), [ - # visa length upper boundary and prefix boundary - pytest.param(visa, "4000000000000002", True, id="visa: valid length 16"), - pytest.param(visa, "40000000000000006", False, id="visa: wrong length 17 (too long)"), - pytest.param(visa, "3500000000000009", False, id="visa: wrong prefix 35"), - # mastercard BIN alternatives and boundaries - pytest.param(mastercard, "5100000000000008", True, id="mastercard: prefix 51 lower bound (valid)"), - pytest.param(mastercard, "5500000000000004", True, id="mastercard: prefix 55 upper bound (valid)"), - pytest.param(mastercard, "5000000000000009", False, id="mastercard: prefix 50 below range (invalid)"), - pytest.param(mastercard, "5600000000000003", False, id="mastercard: prefix 56 above range (invalid)"), - pytest.param(mastercard, "2221000000000009", True, id="mastercard: prefix 2221 lower bound (valid)"), - pytest.param(mastercard, "2220000000000000", False, id="mastercard: prefix 2220 below range (invalid)"), - pytest.param(mastercard, "2230000000000008", True, id="mastercard: prefix 2230 mid-range (valid)"), - pytest.param(mastercard, "2300000000000003", True, id="mastercard: prefix 2300 mid-range (valid)"), - pytest.param(mastercard, "2710000000000007", True, id="mastercard: prefix 2710 mid-range (valid)"), - pytest.param(mastercard, "2720000000000005", True, id="mastercard: prefix 2720 upper bound (valid)"), - pytest.param(mastercard, "2721000000000004", False, id="mastercard: prefix 2721 above range (invalid)"), - pytest.param(mastercard, "51000000000000003", False, id="mastercard: wrong length 17 (too long)"), - # amex alternatives and boundaries - pytest.param(amex, "340000000000009", True, id="amex: valid prefix 34"), - pytest.param(amex, "380000000000000", False, id="amex: wrong prefix 38"), - pytest.param(amex, "3400000000000000", False, id="amex: wrong length 16 (too long)"), - # unionpay boundaries - pytest.param(unionpay, "6100000000000006", False, id="unionpay: wrong prefix 61 (below 62)"), - pytest.param(unionpay, "6300000000000004", False, id="unionpay: wrong prefix 63 (above 62)"), - pytest.param(unionpay, "62000000000000000", False, id="unionpay: wrong length 17 (too long)"), - # diners lengths, boundaries, and prefixes - pytest.param(diners, "30000000000004", True, id="diners: valid length 14 with prefix 30"), - pytest.param(diners, "36000000000008", True, id="diners: valid length 14 with prefix 36"), - pytest.param(diners, "38000000000006", True, id="diners: valid length 14 with prefix 38"), - pytest.param(diners, "39000000000005", True, id="diners: valid length 14 with prefix 39"), - pytest.param(diners, "3600000000000008", True, id="diners: valid length 16 with prefix 36"), - pytest.param(diners, "30000000000003", False, id="diners: length 14 failing Luhn (invalid)"), - pytest.param(diners, "3000000000007", False, id="diners: wrong length 13 (too short)"), - pytest.param(diners, "30000000000000007", False, id="diners: wrong length 17 (too long)"), - pytest.param(diners, "35000000000009", False, id="diners: length 14 wrong prefix 35"), - pytest.param(diners, "3700000000000007", False, id="diners: length 16 wrong prefix 37"), - # jcb boundaries - pytest.param(jcb, "3400000000000000", False, id="jcb: wrong prefix 34 (below 35)"), - pytest.param(jcb, "3600000000000008", False, id="jcb: wrong prefix 36 (above 35)"), - pytest.param(jcb, "35000000000000006", False, id="jcb: wrong length 17 (too long)"), - # discover alternatives and misses - pytest.param(discover, "6400000000000003", True, id="discover: valid prefix 64"), - pytest.param(discover, "6500000000000002", True, id="discover: valid prefix 65"), - pytest.param(discover, "6200000000000005", False, id="discover: wrong prefix 62"), - pytest.param(discover, "6300000000000004", False, id="discover: wrong prefix 63"), - pytest.param(discover, "6600000000000001", False, id="discover: wrong prefix 66"), - pytest.param(discover, "60000000000000004", False, id="discover: wrong length 17 (too long)"), - # mir boundaries - pytest.param(mir, "2200000000000004", True, id="mir: prefix 2200 lower bound (valid)"), - pytest.param(mir, "2204000000000000", True, id="mir: prefix 2204 upper bound (valid)"), - pytest.param(mir, "2199000000000007", False, id="mir: prefix 2199 below range (invalid)"), - pytest.param(mir, "2205000000000009", False, id="mir: prefix 2205 above range (invalid)"), - pytest.param(mir, "22000000000000004", False, id="mir: wrong length 17 (too long)"), + # visa: adjacent prefixes, off-by-one/13-digit lengths, unanchored '4' + pytest.param(visa, "3999999999999998", id="visa-prefix_39_below"), + pytest.param(visa, "5000000000000009", id="visa-prefix_50_above"), + pytest.param(visa, "4000000000006", id="visa-len_13"), + pytest.param(visa, "400000000000006", id="visa-len_15"), + pytest.param(visa, "40000000000000006", id="visa-len_17"), + pytest.param(visa, "0400000000000006", id="visa-unanchored_4_at_idx_1"), + # mastercard: adjacent prefixes, off-by-one lengths, unanchored '55' + pytest.param(mastercard, "5000000000000009", id="mastercard-prefix_50_below"), + pytest.param(mastercard, "5600000000000003", id="mastercard-prefix_56_above"), + pytest.param(mastercard, "2220000000000000", id="mastercard-prefix_2220_below"), + pytest.param(mastercard, "2721000000000004", id="mastercard-prefix_2721_above"), + pytest.param(mastercard, "550000000000004", id="mastercard-len_15"), + pytest.param(mastercard, "55000000000000004", id="mastercard-len_17"), + pytest.param(mastercard, "0550000000000004", id="mastercard-unanchored_55_at_idx_1"), + # amex: adjacent prefixes, off-by-one lengths, unanchored '34' + pytest.param(amex, "330000000000001", id="amex-prefix_33"), + pytest.param(amex, "350000000000006", id="amex-prefix_35"), + pytest.param(amex, "360000000000004", id="amex-prefix_36"), + pytest.param(amex, "380000000000000", id="amex-prefix_38"), + pytest.param(amex, "34000000000000", id="amex-len_14"), + pytest.param(amex, "3400000000000000", id="amex-len_16"), + pytest.param(amex, "034000000000000", id="amex-unanchored_34_at_idx_1"), + # unionpay: adjacent prefixes, off-by-one lengths, unanchored '62' + pytest.param(unionpay, "6100000000000006", id="unionpay-prefix_61_below"), + pytest.param(unionpay, "6300000000000004", id="unionpay-prefix_63_above"), + pytest.param(unionpay, "620000000000000", id="unionpay-len_15"), + pytest.param(unionpay, "62000000000000000", id="unionpay-len_17"), + pytest.param(unionpay, "0620000000000000", id="unionpay-unanchored_62_at_idx_1"), + # diners: adjacent prefixes, lengths 13/15/17, unanchored '30' + pytest.param(diners, "2900000000000007", id="diners-prefix_29"), + pytest.param(diners, "3100000000000003", id="diners-prefix_31"), + pytest.param(diners, "3500000000000009", id="diners-prefix_35"), + pytest.param(diners, "3700000000000007", id="diners-prefix_37"), + pytest.param(diners, "4000000000000002", id="diners-prefix_40"), + pytest.param(diners, "3000000000007", id="diners-len_13"), + pytest.param(diners, "300000000000007", id="diners-len_15_between_14_and_16"), + pytest.param(diners, "30000000000000007", id="diners-len_17"), + pytest.param(diners, "0300000000000007", id="diners-unanchored_30_at_idx_1"), + # jcb: adjacent prefixes, off-by-one lengths, unanchored '35' + pytest.param(jcb, "3400000000000000", id="jcb-prefix_34_below"), + pytest.param(jcb, "3600000000000008", id="jcb-prefix_36_above"), + pytest.param(jcb, "350000000000006", id="jcb-len_15"), + pytest.param(jcb, "35000000000000006", id="jcb-len_17"), + pytest.param(jcb, "0350000000000006", id="jcb-unanchored_35_at_idx_1"), + # discover: adjacent prefixes, off-by-one lengths, unanchored '60' + pytest.param(discover, "5900000000000000", id="discover-prefix_59"), + pytest.param(discover, "6100000000000006", id="discover-prefix_61"), + pytest.param(discover, "6300000000000004", id="discover-prefix_63"), + pytest.param(discover, "6600000000000001", id="discover-prefix_66"), + pytest.param(discover, "600000000000004", id="discover-len_15"), + pytest.param(discover, "60000000000000004", id="discover-len_17"), + pytest.param(discover, "0600000000000004", id="discover-unanchored_60_at_idx_1"), + # mir: adjacent prefixes, off-by-one lengths, unanchored '2200' + pytest.param(mir, "2199000000000007", id="mir-prefix_2199_below"), + pytest.param(mir, "2205000000000009", id="mir-prefix_2205_above"), + pytest.param(mir, "220000000000004", id="mir-len_15"), + pytest.param(mir, "22000000000000004", id="mir-len_17"), + pytest.param(mir, "0220000000000004", id="mir-unanchored_2200_at_idx_1"), ], ) -def test_issuer_boundaries(func, value, expected_valid): - """Verify exact length and BIN/prefix boundaries for all issuers.""" - result = func(value) - assert_valid(result) if expected_valid else assert_invalid(result) \ No newline at end of file +def test_issuer_invalid_prefix_length_and_anchor_boundaries(func, value: str) -> None: + """All inputs pass Luhn checksum so rejection isolates prefix, length, or ^ anchor.""" + _assert_result(func(value), False) \ No newline at end of file diff --git a/tests/country_test.py b/tests/country_test.py new file mode 100644 index 00000000..ff438ac8 --- /dev/null +++ b/tests/country_test.py @@ -0,0 +1,563 @@ +import pytest + +from validators.country import _get_code_type, calling_code, country_code, currency +from validators.utils import ValidationError + +_BYTES_AUTO_DETECT_XFAIL = pytest.mark.xfail( + raises=AttributeError, + strict=True, + reason=( + "Defect in validators.country.country_code: bytes of length 2..3 with " + "iso_format='auto' reaches _get_code_type(value).isdecimal() and raises " + "AttributeError, which @validator does not catch." + ), +) + + +def _assert_result(result, expected_valid: bool) -> None: + if expected_valid: + assert result is True + else: + assert isinstance(result, ValidationError) + assert bool(result) is False + + +# =========================================================================== +# 1. Input Space Partitioning (ISP) - Section 2.3 & Table 2 +# =========================================================================== + + +@pytest.mark.parametrize( + ("func", "value", "expected_valid"), + [ + # Table 2: All validators -> Argument type (str; None; int; bytes) + pytest.param(calling_code, "+91", True, id="calling_code-str_valid"), + pytest.param(calling_code, None, False, id="calling_code-none"), + pytest.param(calling_code, 123, False, id="calling_code-int"), + pytest.param(calling_code, b"+91", False, id="calling_code-bytes"), + pytest.param(country_code, "US", True, id="country_code-str_valid"), + pytest.param(country_code, None, False, id="country_code-none"), + pytest.param(country_code, 123, False, id="country_code-int"), + pytest.param( + country_code, + b"US", + False, + id="country_code-bytes", + marks=_BYTES_AUTO_DETECT_XFAIL, + ), + pytest.param(currency, "USD", True, id="currency-str_valid"), + pytest.param(currency, None, False, id="currency-none"), + pytest.param(currency, 123, False, id="currency-int"), + pytest.param(currency, b"USD", False, id="currency-bytes"), + ], +) +def test_all_country_validators_argument_types(func, value, expected_valid: bool) -> None: + """TR-ISP-TYPE: Verify str, None, int, and bytes across all country validators.""" + _assert_result(func(value), expected_valid) + + +@pytest.mark.parametrize( + ("value", "expected_valid"), + [ + # calling_code -> ACoC (<= 20 tests) + pytest.param("", False, id="str-empty"), + pytest.param("+91", True, id="str-valid_simple"), + pytest.param("+1-264", True, id="str-valid_hyphenated"), + pytest.param("-31", False, id="str-invalid_minus_prefix"), + pytest.param("91", False, id="str-invalid_missing_plus"), + pytest.param("+999", False, id="str-invalid_unknown_code"), + pytest.param("+abc", False, id="str-invalid_letters"), + pytest.param(None, False, id="none"), + pytest.param(91, False, id="int"), + pytest.param(b"+91", False, id="bytes"), + ], +) +def test_calling_code_isp_acoc(value, expected_valid: bool) -> None: + """TR-ISP-CALLING-ACoC: All feasible blocks/combinations for calling_code.""" + _assert_result(calling_code(value), expected_valid) + + +# country_code -> PWC (4 iso_format x 5 lengths x 4 case options = 80 > 20) +# Characteristics & Blocks (Table 2): +# - Format option (iso_format): {auto, alpha2, alpha3, numeric} +# - Value length: {Empty (0), 1, 2, 3, more than 3} +# - Case option (ignore_case): {True+lower, True+upper, False+lower, False+upper} +# For non-empty lengths {1, 2, 3, >3}, the 4x4 Latin square below covers all +# feasible (iso_format, length), (iso_format, case), and (length, case) pairs. +@pytest.mark.parametrize( + ("value", "iso_format", "ignore_case", "expected_valid"), + [ + # iso_format = "auto" + pytest.param("u", "auto", True, False, id="auto-len_1-ignore_case_on-lowercase"), + pytest.param("US", "auto", True, True, id="auto-len_2-ignore_case_on-uppercase"), + pytest.param("usa", "auto", False, False, id="auto-len_3-ignore_case_off-lowercase"), + pytest.param("USAA", "auto", False, False, id="auto-len_4plus-ignore_case_off-uppercase"), + pytest.param("", "auto", False, False, id="auto-empty-ignore_case_off"), + # iso_format = "alpha2" + pytest.param("U", "alpha2", True, False, id="alpha2-len_1-ignore_case_on-uppercase"), + pytest.param("us", "alpha2", True, True, id="alpha2-len_2-ignore_case_on-lowercase"), + pytest.param("USA", "alpha2", False, False, id="alpha2-len_3-ignore_case_off-uppercase"), + pytest.param("usaa", "alpha2", False, False, id="alpha2-len_4plus-ignore_case_off-lowercase"), + pytest.param("", "alpha2", True, False, id="alpha2-empty-ignore_case_on"), + # iso_format = "alpha3" + pytest.param("u", "alpha3", False, False, id="alpha3-len_1-ignore_case_off-lowercase"), + pytest.param("GB", "alpha3", False, False, id="alpha3-len_2-ignore_case_off-uppercase"), + pytest.param("usa", "alpha3", True, True, id="alpha3-len_3-ignore_case_on-lowercase"), + pytest.param("USAA", "alpha3", True, False, id="alpha3-len_4plus-ignore_case_on-uppercase"), + pytest.param("", "alpha3", False, False, id="alpha3-empty-ignore_case_off"), + # iso_format = "numeric" + pytest.param("U", "numeric", False, False, id="numeric-len_1-ignore_case_off-uppercase"), + pytest.param("us", "numeric", False, False, id="numeric-len_2-ignore_case_off-lowercase"), + pytest.param("USA", "numeric", True, False, id="numeric-len_3-ignore_case_on-uppercase"), + pytest.param("usaa", "numeric", True, False, id="numeric-len_4plus-ignore_case_on-lowercase"), + pytest.param("", "numeric", True, False, id="numeric-empty-ignore_case_on"), + ], +) +def test_country_code_isp_pwc_matrix( + value: str, iso_format: str, ignore_case: bool, expected_valid: bool +) -> None: + """TR-ISP-COUNTRY-PWC: Pairwise covering array over Table 2 blocks.""" + _assert_result( + country_code(value, iso_format=iso_format, ignore_case=ignore_case), + expected_valid, + ) + + +@pytest.mark.parametrize( + ("value", "iso_format", "ignore_case", "expected_valid"), + [ + pytest.param("US", "auto", False, True, id="valid-alpha2-auto"), + pytest.param("USA", "auto", False, True, id="valid-alpha3-auto"), + pytest.param("840", "auto", False, True, id="valid-numeric-auto"), + pytest.param("840", "auto", True, True, id="valid-numeric-auto-ignore_case_on"), + pytest.param("US", "alpha2", False, True, id="valid-alpha2-explicit"), + pytest.param("USA", "alpha3", False, True, id="valid-alpha3-explicit"), + pytest.param("840", "numeric", False, True, id="valid-numeric-explicit"), + pytest.param("840", "numeric", True, True, id="valid-numeric-explicit-ignore_case_on"), + pytest.param("ZZ", "auto", False, False, id="invalid-alpha2-unknown"), + pytest.param("ZZZ", "auto", False, False, id="invalid-alpha3-unknown"), + pytest.param("999", "auto", False, False, id="invalid-numeric-3digit_unknown"), + pytest.param("84", "numeric", False, False, id="invalid-numeric-2digit"), + pytest.param("U1", "auto", False, False, id="invalid-mixed_alphanumeric-auto"), + ], +) +def test_country_code_isp_code_validity_blocks( + value: str, iso_format: str, ignore_case: bool, expected_valid: bool +) -> None: + """TR-ISP-COUNTRY-CONTENT: Valid/invalid code blocks across all iso_format options.""" + _assert_result( + country_code(value, iso_format=iso_format, ignore_case=ignore_case), + expected_valid, + ) + + +# currency -> ACoC (<= 20 tests) +# Covers Table 2 (skip_symbols and value kind) + ignore_case signature flag. +@pytest.mark.parametrize( + ("value", "skip_symbols", "ignore_case", "expected_valid"), + [ + # Symbol with skip_symbols=True vs False across ignore_case + pytest.param("$", True, False, False, id="symbol-skip_symbols_on-ignore_case_off"), + pytest.param("$", True, True, False, id="symbol-skip_symbols_on-ignore_case_on"), + pytest.param("$", False, False, True, id="symbol-skip_symbols_off-ignore_case_off"), + pytest.param("$", False, True, True, id="symbol-skip_symbols_off-ignore_case_on"), + # Valid 3-letter uppercase code across skip_symbols and ignore_case + pytest.param("USD", True, False, True, id="valid_upper-skip_symbols_on-ignore_case_off"), + pytest.param("USD", True, True, True, id="valid_upper-skip_symbols_on-ignore_case_on"), + pytest.param("USD", False, False, True, id="valid_upper-skip_symbols_off-ignore_case_off"), + pytest.param("USD", False, True, True, id="valid_upper-skip_symbols_off-ignore_case_on"), + # Valid 3-letter lowercase code across skip_symbols and ignore_case + pytest.param("usd", True, False, False, id="valid_lower-skip_symbols_on-ignore_case_off"), + pytest.param("usd", True, True, True, id="valid_lower-skip_symbols_on-ignore_case_on"), + pytest.param("usd", False, False, False, id="valid_lower-skip_symbols_off-ignore_case_off"), + pytest.param("usd", False, True, True, id="valid_lower-skip_symbols_off-ignore_case_on"), + # Other / invalid values across skip_symbols and ignore_case + pytest.param("ZWX", True, False, False, id="other_invalid_upper_3char-skip_symbols_on-ignore_case_off"), + pytest.param("zwx", True, True, False, id="other_invalid_lower_3char-skip_symbols_on-ignore_case_on"), + pytest.param("@", False, False, False, id="other_non_symbol_char-skip_symbols_off-ignore_case_off"), + pytest.param("US", False, True, False, id="other_len_2-skip_symbols_off-ignore_case_on"), + pytest.param("", True, False, False, id="other_empty-skip_symbols_on-ignore_case_off"), + pytest.param("USDD", False, False, False, id="other_len_4-skip_symbols_off-ignore_case_off"), + ], +) +def test_currency_isp_acoc( + value: str, skip_symbols: bool, ignore_case: bool, expected_valid: bool +) -> None: + """TR-ISP-CURRENCY-ACoC: All combinations of skip_symbols, ignore_case, and value kind.""" + _assert_result( + currency(value, skip_symbols=skip_symbols, ignore_case=ignore_case), + expected_valid, + ) + + +# =========================================================================== +# 2. Logic Coverage (PC, CC, CACC) - Section 2.4 +# =========================================================================== + + +# Compound Predicate P1 (country_code): not (1 < len(value) < 4) +# Clauses: c1 = (1 < len(value)), c2 = (len(value) < 4) +# Truth Table (for non-empty strings): +# Row 1: c1=T, c2=T -> P1=F ("US", "USA") [Feasible] +# Row 2: c1=T, c2=F -> P1=T ("USAA") [Feasible] +# Row 3: c1=F, c2=T -> P1=T ("U") [Feasible; c2 short-circuited] +# Row 4: c1=F, c2=F -> P1=T (len<=1 & >=4) [Infeasible] +# CACC pairs: active c1 (Row 1 vs Row 3), active c2 (Row 1 vs Row 2) +@pytest.mark.parametrize( + ("value", "expected_valid"), + [ + pytest.param("US", True, id="row1-gt_1_true-lt_4_true-pred_false-len_2"), + pytest.param("USA", True, id="row1-gt_1_true-lt_4_true-pred_false-len_3"), + pytest.param("USAA", False, id="row2-gt_1_true-lt_4_false-pred_true-len_4"), + pytest.param("U", False, id="row3-gt_1_false-lt_4_true-pred_true-len_1"), + ], +) +def test_country_code_predicate_p1_length_bounds_cacc( + value: str, expected_valid: bool +) -> None: + """TR-LC-P1: PC, CC, and CACC for `not (1 < len(value) < 4)`.""" + _assert_result(country_code(value), expected_valid) + + +# Compound Predicate P2 (country_code): +# iso_format == "auto" and (iso_format := _get_code_type(value)) == "invalid" +# Clauses: c1 = (iso_format == "auto"), c2 = (_get_code_type(value) == "invalid") +# Truth Table: +# Row 1: c1=T, c2=T -> P2=T ("U1", "auto") [Feasible] +# Row 2: c1=T, c2=F -> P2=F ("US", "auto") [Feasible] +# Row 3: c1=F, c2=T -> P2=F ("U1", "alpha2") [c2 short-circuited] +# Row 4: c1=F, c2=F -> P2=F ("US", "alpha2") [c2 short-circuited] +# CACC pairs: active c1 (Row 1 vs Row 3), active c2 (Row 1 vs Row 2) +@pytest.mark.parametrize( + ("value", "iso_format", "expected_valid"), + [ + pytest.param("U1", "auto", False, id="row1-auto_true-invalid_type_true-pred_true"), + pytest.param("US", "auto", True, id="row2-auto_true-invalid_type_false-pred_false-alpha2"), + pytest.param("USA", "auto", True, id="row2-auto_true-invalid_type_false-pred_false-alpha3"), + pytest.param("840", "auto", True, id="row2-auto_true-invalid_type_false-pred_false-numeric"), + pytest.param("U1", "alpha2", False, id="row3-auto_false-short_circuit_invalid-pred_false"), + pytest.param("US", "alpha2", True, id="row4-auto_false-short_circuit_valid-pred_false"), + ], +) +def test_country_code_predicate_p2_auto_detect_cacc( + value: str, iso_format: str, expected_valid: bool +) -> None: + """TR-LC-P2: PC, CC, and CACC for `iso_format == 'auto' and ... == 'invalid'`.""" + _assert_result(country_code(value, iso_format=iso_format), expected_valid) + + +# Compound Predicate P3 (currency - explicitly cited in Section 2.4): +# not skip_symbols and value in _currency_symbols +# Clauses: c1 = (not skip_symbols), c2 = (value in _currency_symbols) +# Truth Table: +# Row 1: c1=T (skip=False), c2=T ("$") -> P3=T [Feasible] +# Row 2: c1=T (skip=False), c2=F ("@") -> P3=F [Feasible; "USD" falls through] +# Row 3: c1=F (skip=True), c2=T ("$") -> P3=F [c2 short-circuited] +# Row 4: c1=F (skip=True), c2=F ("USD") -> P3=F [c2 short-circuited] +# CACC pairs: active c1 (Row 1 vs Row 3), active c2 (Row 1 vs Row 2) +@pytest.mark.parametrize( + ("value", "skip_symbols", "expected_valid"), + [ + pytest.param("$", False, True, id="row1-allow_symbols_true-in_symbols_true-pred_true"), + pytest.param("@", False, False, id="row2-allow_symbols_true-in_symbols_false-pred_false-invalid"), + pytest.param("USD", False, True, id="row2-allow_symbols_true-in_symbols_false-pred_false-valid_code"), + pytest.param("$", True, False, id="row3-allow_symbols_false-short_circuit_symbol-pred_false"), + pytest.param("USD", True, True, id="row4-allow_symbols_false-short_circuit_valid_code-pred_false"), + pytest.param("@", True, False, id="row4-allow_symbols_false-short_circuit_invalid-pred_false"), + ], +) +def test_currency_predicate_p3_symbol_check_cacc( + value: str, skip_symbols: bool, expected_valid: bool +) -> None: + """TR-LC-P3: PC, CC, and CACC for `not skip_symbols and value in _currency_symbols`.""" + _assert_result(currency(value, skip_symbols=skip_symbols), expected_valid) + + +@pytest.mark.parametrize( + ("value", "expected_valid"), + [ + pytest.param("", False, id="empty_true"), + pytest.param("+91", True, id="empty_false-in_calling_codes_true"), + pytest.param("-31", False, id="empty_false-in_calling_codes_false"), + ], +) +def test_calling_code_single_clause_predicates(value: str, expected_valid: bool) -> None: + """TR-LC-CALLING: PC/CC for `if not value` and membership check.""" + _assert_result(calling_code(value), expected_valid) + + +@pytest.mark.parametrize( + ("value", "iso_format", "ignore_case", "expected_valid"), + [ + pytest.param("", "auto", False, False, id="empty_true"), + pytest.param("us", "alpha2", True, True, id="alpha2-ignore_case_true-valid"), + pytest.param("zz", "alpha2", True, False, id="alpha2-ignore_case_true-invalid"), + pytest.param("US", "alpha2", False, True, id="alpha2-ignore_case_false-valid"), + pytest.param("us", "alpha2", False, False, id="alpha2-ignore_case_false-invalid"), + pytest.param("usa", "alpha3", True, True, id="alpha3-ignore_case_true-valid"), + pytest.param("zzz", "alpha3", True, False, id="alpha3-ignore_case_true-invalid"), + pytest.param("USA", "alpha3", False, True, id="alpha3-ignore_case_false-valid"), + pytest.param("usa", "alpha3", False, False, id="alpha3-ignore_case_false-invalid"), + pytest.param("840", "numeric", False, True, id="numeric-valid"), + pytest.param("999", "numeric", False, False, id="numeric-invalid"), + pytest.param("USA", "unsupported", False, False, id="unsupported_format-else_false"), + ], +) +def test_country_code_single_clause_predicates( + value: str, iso_format: str, ignore_case: bool, expected_valid: bool +) -> None: + """TR-LC-COUNTRY-BRANCHES: PC/CC for format branches and ignore_case ternaries.""" + _assert_result( + country_code(value, iso_format=iso_format, ignore_case=ignore_case), + expected_valid, + ) + + +@pytest.mark.parametrize( + ("value", "ignore_case", "expected_valid"), + [ + pytest.param("", False, False, id="empty_true"), + pytest.param("US", False, False, id="len_not_3_true-short"), + pytest.param("USDD", False, False, id="len_not_3_true-long"), + pytest.param("usd", True, True, id="ignore_case_true-valid"), + pytest.param("zwx", True, False, id="ignore_case_true-invalid"), + pytest.param("USD", False, True, id="ignore_case_false-valid"), + pytest.param("usd", False, False, id="ignore_case_false-invalid"), + ], +) +def test_currency_single_clause_predicates( + value: str, ignore_case: bool, expected_valid: bool +) -> None: + """TR-LC-CURRENCY-BRANCHES: PC/CC for empty check, length != 3, and ignore_case ternary.""" + _assert_result(currency(value, ignore_case=ignore_case), expected_valid) + + +@pytest.mark.parametrize( + ("value", "expected_type"), + [ + pytest.param("840", "numeric", id="isdecimal_true-numeric"), + pytest.param("US", "alpha2", id="isalpha_true-len_2-alpha2"), + pytest.param("USA", "alpha3", id="isalpha_true-len_3-alpha3"), + pytest.param("A", "invalid", id="isalpha_true-len_1-invalid"), + pytest.param("ABCD", "invalid", id="isalpha_true-len_4-invalid"), + pytest.param("U1", "invalid", id="isalpha_false-alphanumeric-invalid"), + ], +) +def test_get_code_type_predicates(value: str, expected_type: str) -> None: + """TR-LC-HELPER: PC/CC for every branch in _get_code_type.""" + assert _get_code_type(value) == expected_type + + +# =========================================================================== +# 3. Branch Coverage, Mutation Testing & ValidationError Contract - Sec 2.1/2.2 +# =========================================================================== + + +@pytest.mark.parametrize( + ("func", "bad_input"), + [ + pytest.param(calling_code, None, id="calling_code-none"), + pytest.param(calling_code, 123, id="calling_code-int"), + pytest.param(calling_code, 91.5, id="calling_code-float"), + pytest.param(calling_code, b"+91", id="calling_code-bytes"), + pytest.param(calling_code, [], id="calling_code-empty_list"), + pytest.param(calling_code, {}, id="calling_code-empty_dict"), + pytest.param(country_code, None, id="country_code-none"), + pytest.param(country_code, 123, id="country_code-int"), + pytest.param(country_code, 12.3, id="country_code-float"), + pytest.param(country_code, b"", id="country_code-bytes_empty"), + pytest.param(country_code, b"U", id="country_code-bytes_len_1"), + pytest.param( + country_code, + b"US", + id="country_code-bytes_len_2", + marks=_BYTES_AUTO_DETECT_XFAIL, + ), + pytest.param( + country_code, + b"840", + id="country_code-bytes_len_3_numeric", + marks=_BYTES_AUTO_DETECT_XFAIL, + ), + pytest.param(country_code, b"USAA", id="country_code-bytes_len_4"), + pytest.param(country_code, [], id="country_code-empty_list"), + pytest.param(currency, None, id="currency-none"), + pytest.param(currency, 123, id="currency-int"), + pytest.param(currency, 1.23, id="currency-float"), + pytest.param(currency, b"USD", id="currency-bytes"), + pytest.param(currency, [], id="currency-empty_list"), + ], +) +def test_invalid_types_return_validation_error(func, bad_input) -> None: + """Confirm decorator-caught/falsy non-str inputs return falsy ValidationError.""" + result = func(bad_input) + _assert_result(result, False) + assert result.func.__name__ == func.__name__ + + +@pytest.mark.parametrize( + ("value", "iso_format", "ignore_case"), + [ + pytest.param(b"US", "alpha2", False, id="bytes-alpha2-ignore_case_off"), + pytest.param(b"us", "alpha2", True, id="bytes-alpha2-ignore_case_on"), + pytest.param(b"USA", "alpha3", False, id="bytes-alpha3"), + pytest.param(b"840", "numeric", False, id="bytes-numeric"), + ], +) +def test_country_code_bytes_explicit_format_returns_validation_error( + value: bytes, iso_format: str, ignore_case: bool +) -> None: + """When iso_format != 'auto', _get_code_type is bypassed and bytes return ValidationError.""" + _assert_result( + country_code(value, iso_format=iso_format, ignore_case=ignore_case), + False, + ) + + +def test_currency_invalid_type_with_skip_symbols_false() -> None: + """Ensure int/bytes with skip_symbols=False return ValidationError instead of crashing.""" + _assert_result(currency(123, skip_symbols=False), False) + _assert_result(currency(b"$", skip_symbols=False), False) + + +@pytest.mark.parametrize( + "value", + [ + pytest.param("+297", id="first_entry_abw"), + pytest.param("+1", id="single_digit_nanp"), + pytest.param("+1-264", id="hyphenated_aia"), + pytest.param("+44-1481", id="hyphenated_ggy"), + pytest.param("+263", id="last_entry_zwe"), + ], +) +def test_calling_code_valid_boundaries(value: str) -> None: + assert calling_code(value) is True + + +@pytest.mark.parametrize( + "value", + [ + pytest.param(" +91", id="leading_space"), + pytest.param("+91 ", id="trailing_space"), + pytest.param("+0", id="zero"), + pytest.param("+00", id="double_zero"), + pytest.param("+1-", id="trailing_hyphen"), + pytest.param("-1", id="minus_prefix"), + pytest.param("1-264", id="missing_plus_hyphenated"), + pytest.param("+1 264", id="space_instead_of_hyphen"), + ], +) +def test_calling_code_invalid_formatting(value: str) -> None: + _assert_result(calling_code(value), False) + + +def test_country_code_defaults_are_auto_and_case_sensitive() -> None: + """Kills mutants flipping default iso_format='auto' or ignore_case=False.""" + assert country_code("US") is True + assert country_code("USA") is True + assert country_code("840") is True + _assert_result(country_code("us"), False) + _assert_result(country_code("usa"), False) + _assert_result(country_code("iN"), False) + + +@pytest.mark.parametrize( + ("value", "iso_format", "ignore_case"), + [ + pytest.param("AW", "alpha2", False, id="alpha2-first_entry_aw"), + pytest.param("ZW", "alpha2", False, id="alpha2-last_entry_zw"), + pytest.param("Us", "alpha2", True, id="alpha2-mixed_case"), + pytest.param("ABW", "alpha3", False, id="alpha3-first_entry_abw"), + pytest.param("ZWE", "alpha3", False, id="alpha3-last_entry_zwe"), + pytest.param("uSa", "alpha3", True, id="alpha3-mixed_case"), + pytest.param("004", "numeric", False, id="numeric-first_entry_004"), + pytest.param("894", "numeric", False, id="numeric-last_entry_894"), + pytest.param("us", "auto", True, id="auto-alpha2_lower_ignore_case"), + pytest.param("usa", "auto", True, id="auto-alpha3_lower_ignore_case"), + ], +) +def test_country_code_valid_boundaries_and_case( + value: str, iso_format: str, ignore_case: bool +) -> None: + assert country_code(value, iso_format=iso_format, ignore_case=ignore_case) is True + + +@pytest.mark.parametrize( + ("value", "iso_format", "ignore_case"), + [ + pytest.param("GB", "alpha3", False, id="alpha2_code_with_alpha3_format"), + pytest.param("USA", "alpha2", False, id="alpha3_code_with_alpha2_format"), + pytest.param("840", "alpha2", False, id="numeric_code_with_alpha2_format"), + pytest.param("840", "alpha3", False, id="numeric_code_with_alpha3_format"), + pytest.param("US", "numeric", False, id="alpha2_code_with_numeric_format"), + pytest.param("USA", "numeric", False, id="alpha3_code_with_numeric_format"), + pytest.param("0840", "numeric", False, id="numeric_4_digits"), + pytest.param("000", "numeric", False, id="numeric_000_not_in_table"), + pytest.param("1", "numeric", False, id="numeric_1_digit"), + pytest.param("USA", "ALPHA3", False, id="uppercase_format_name_ALPHA3"), + pytest.param("840", "invalid", False, id="unknown_format_invalid"), + pytest.param("US", "", False, id="empty_format_name"), + pytest.param("²³", "auto", False, id="superscript_digits"), + pytest.param("½", "auto", False, id="vulgar_fraction"), + pytest.param("١٢٣", "auto", False, id="arabic_indic_digits"), + pytest.param(" US", "auto", False, id="leading_space"), + pytest.param("US ", "auto", False, id="trailing_space"), + ], +) +def test_country_code_invalid_cross_format_and_edge_cases( + value: str, iso_format: str, ignore_case: bool +) -> None: + _assert_result( + country_code(value, iso_format=iso_format, ignore_case=ignore_case), + False, + ) + + +def test_currency_defaults_skip_symbols_and_case_sensitive() -> None: + """Kills mutants flipping default skip_symbols=True or ignore_case=False.""" + assert currency("USD") is True + _assert_result(currency("$"), False) + _assert_result(currency("usd"), False) + _assert_result(currency("Usd"), False) + + +@pytest.mark.parametrize( + ("value", "skip_symbols", "ignore_case"), + [ + pytest.param("AED", True, False, id="iso4217-first_entry_aed"), + pytest.param("ZWL", True, False, id="iso4217-last_entry_zwl"), + pytest.param("Cad", True, True, id="iso4217-mixed_case"), + pytest.param("؋", False, False, id="symbol-first_entry_afghani"), + pytest.param("€", False, False, id="symbol-euro"), + pytest.param("₹", False, False, id="symbol-rupee"), + pytest.param("Rs", False, False, id="symbol-two_char_Rs"), + pytest.param("Rs", False, True, id="symbol-two_char_Rs_ignore_case_on"), + pytest.param("¤", False, False, id="symbol-last_entry_generic"), + ], +) +def test_currency_valid_boundaries_and_symbols( + value: str, skip_symbols: bool, ignore_case: bool +) -> None: + assert currency(value, skip_symbols=skip_symbols, ignore_case=ignore_case) is True + + +@pytest.mark.parametrize( + ("value", "skip_symbols", "ignore_case"), + [ + pytest.param("Rs", True, False, id="two_char_Rs_with_skip_symbols_on"), + pytest.param("rs", False, True, id="lowercase_rs_symbol_case_sensitive"), + pytest.param("RS", False, True, id="uppercase_RS_not_symbol_or_code"), + pytest.param(" USD", True, False, id="leading_space"), + pytest.param("USD ", True, False, id="trailing_space"), + pytest.param("123", False, False, id="three_digits"), + pytest.param("U$D", False, False, id="embedded_dollar_sign"), + pytest.param("$$$", False, False, id="repeated_dollar_signs"), + ], +) +def test_currency_invalid_edge_cases( + value: str, skip_symbols: bool, ignore_case: bool +) -> None: + _assert_result( + currency(value, skip_symbols=skip_symbols, ignore_case=ignore_case), + False, + ) \ No newline at end of file From 324f01919733e4508c81fac9ac58c95c8287306a Mon Sep 17 00:00:00 2001 From: Daana Honarmand <68249577+DaanaH-dev@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:33:54 -0500 Subject: [PATCH 06/12] Making the test files for the other tests --- tests/domain_test.py | 1 + tests/email_test.py | 1 + tests/ip_address_test.py | 1 + tests/length_test.py | 1 + tests/mac_address_test.py | 1 + tests/url_test.py | 1 + 6 files changed, 6 insertions(+) create mode 100644 tests/domain_test.py create mode 100644 tests/email_test.py create mode 100644 tests/ip_address_test.py create mode 100644 tests/length_test.py create mode 100644 tests/mac_address_test.py create mode 100644 tests/url_test.py diff --git a/tests/domain_test.py b/tests/domain_test.py new file mode 100644 index 00000000..e9691f24 --- /dev/null +++ b/tests/domain_test.py @@ -0,0 +1 @@ +#init \ No newline at end of file diff --git a/tests/email_test.py b/tests/email_test.py new file mode 100644 index 00000000..e9691f24 --- /dev/null +++ b/tests/email_test.py @@ -0,0 +1 @@ +#init \ No newline at end of file diff --git a/tests/ip_address_test.py b/tests/ip_address_test.py new file mode 100644 index 00000000..e9691f24 --- /dev/null +++ b/tests/ip_address_test.py @@ -0,0 +1 @@ +#init \ No newline at end of file diff --git a/tests/length_test.py b/tests/length_test.py new file mode 100644 index 00000000..e9691f24 --- /dev/null +++ b/tests/length_test.py @@ -0,0 +1 @@ +#init \ No newline at end of file diff --git a/tests/mac_address_test.py b/tests/mac_address_test.py new file mode 100644 index 00000000..e9691f24 --- /dev/null +++ b/tests/mac_address_test.py @@ -0,0 +1 @@ +#init \ No newline at end of file diff --git a/tests/url_test.py b/tests/url_test.py new file mode 100644 index 00000000..e9691f24 --- /dev/null +++ b/tests/url_test.py @@ -0,0 +1 @@ +#init \ No newline at end of file From 8032ad0be7cc6efe97cfb24250341ceff2e6ed6a Mon Sep 17 00:00:00 2001 From: Daana Honarmand <68249577+DaanaH-dev@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:07:42 -0500 Subject: [PATCH 07/12] Added temp tests for domain and emails --- tests/domain_test.py | 359 +++++++++++++++++++++++++++++++++- tests/email_test.py | 453 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 810 insertions(+), 2 deletions(-) diff --git a/tests/domain_test.py b/tests/domain_test.py index e9691f24..fbaf5040 100644 --- a/tests/domain_test.py +++ b/tests/domain_test.py @@ -1 +1,358 @@ -#init \ No newline at end of file +import pytest + +from validators.domain import _IanaTLD, domain +from validators.utils import ValidationError + + +def _assert_invalid(result) -> None: + """Confirm invalid validations return a falsy ValidationError.""" + assert isinstance(result, ValidationError) + assert not result + + +# --------------------------------------------------------------------------- +# 1. ISP: Argument type (Table 2 - All validators) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + pytest.param("example.com", True, id="str_valid"), + pytest.param("", False, id="str_empty"), + pytest.param(None, False, id="none"), + pytest.param(0, False, id="int_zero"), + pytest.param(b"example.com", False, id="bytes_ascii"), + pytest.param(b"", False, id="bytes_empty"), + ], +) +def test_domain_argument_types(value, is_valid): + """Cover non-raising argument types from Table 2 (str, None, int, bytes).""" + result = domain(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +def test_domain_truthy_int_defect(): + """Document Section 2.2 defect: truthy int raises AttributeError instead of ValidationError.""" + with pytest.raises(AttributeError): + domain(123) + + +# --------------------------------------------------------------------------- +# 2. ISP: Pairwise Coverage (PWC) & Option Flag Matching (Table 2 - domain) +# --------------------------------------------------------------------------- +# Because ACoC across (Character set [3] x Label length [2] x Total length [2] +# x consider_tld [2] x rfc_1034 [2] x rfc_2782 [2]) yields 96 combinations (> 20), +# these 8 tests form a Pairwise Covering Array covering all 70 parameter pairs: +# +# ID | Char set | Label | Total | consider_tld | rfc_1034 | rfc_2782 +# ------+-------------+-------+-------+--------------+----------+--------- +# pwc1 | mapped IDN | <=63 | <=253 | False | False | False +# pwc2 | mapped IDN | >=64 | >=254 | True | True | True +# pwc3 | direct IDN | <=63 | >=254 | False | True | False +# pwc4 | direct IDN | >=64 | <=253 | True | False | True +# pwc5 | ASCII | <=63 | <=253 | True | False | True +# pwc6 | ASCII | >=64 | >=254 | False | True | False +# pwc7 | ASCII | <=63 | >=254 | True | False | False +# pwc8 | direct IDN | >=64 | <=253 | False | True | True + + +@pytest.mark.parametrize( + ("value", "consider_tld", "rfc_1034", "rfc_2782", "is_valid"), + [ + pytest.param( + "\uff45\uff58\uff41\uff4d\uff50\uff4c\uff45.com", + False, + False, + False, + False, + id="pwc1_mapped_short", + ), + pytest.param( + "_srv." + ("\uff45" * 64) + "." + ("a" * 62 + ".") * 3 + "com.", + True, + True, + True, + False, + id="pwc2_mapped_long_label_and_total", + ), + pytest.param( + "m\u00fcnchen." + ("a" * 62 + ".") * 3 + ("b" * 60 + ".") + "notatld.", + False, + True, + False, + False, + id="pwc3_direct_long_total", + ), + pytest.param( + "_srv.\u00fc" + ("a" * 63) + ".de", + True, + False, + True, + False, + id="pwc4_direct_long_label", + ), + pytest.param( + "_http._tcp.example.com", + True, + False, + True, + True, + id="pwc5_ascii_valid_service", + ), + pytest.param( + ("a" * 64 + ".") + ("b" * 62 + ".") * 3 + "notatld.", + False, + True, + False, + False, + id="pwc6_ascii_long_label_and_total", + ), + pytest.param( + ("a" * 62 + ".") * 4 + "com", + True, + False, + False, + False, + id="pwc7_ascii_long_total", + ), + pytest.param( + "_srv.\u00fc" + ("a" * 63) + ".notatld.", + False, + True, + True, + False, + id="pwc8_direct_long_label_service_dot", + ), + ], +) +def test_domain_isp_pairwise(value, consider_tld, rfc_1034, rfc_2782, is_valid): + """Verify Pairwise Coverage (PWC) across all domain ISP characteristics.""" + result = domain( + value, + consider_tld=consider_tld, + rfc_1034=rfc_1034, + rfc_2782=rfc_2782, + ) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "consider_tld", "rfc_1034", "rfc_2782", "is_valid"), + [ + pytest.param("example.com", True, False, False, True, id="consider_tld_on_popular"), + pytest.param("example.io", True, False, False, True, id="consider_tld_on_iana"), + pytest.param("example.notatld", True, False, False, False, id="consider_tld_on_unknown"), + pytest.param("example.notatld", False, False, False, True, id="consider_tld_off_unknown"), + pytest.param("example.com.", False, True, False, True, id="rfc1034_on_trailing_dot"), + pytest.param("example.com.", False, False, False, False, id="rfc1034_off_trailing_dot"), + pytest.param("_http._tcp.example.com", False, False, True, True, id="rfc2782_on_underscore"), + pytest.param("_http._tcp.example.com", False, False, False, False, id="rfc2782_off_underscore"), + pytest.param("m\u00fcnchen.de", False, False, False, True, id="direct_idn_valid"), + pytest.param("_http._tcp.m\u00fcnchen.de.", True, True, True, True, id="all_flags_on_direct_idn"), + ], +) +def test_domain_isp_option_flags(value, consider_tld, rfc_1034, rfc_2782, is_valid): + """Ensure each option flag on/off is tested with a matching valid/invalid input.""" + result = domain( + value, + consider_tld=consider_tld, + rfc_1034=rfc_1034, + rfc_2782=rfc_2782, + ) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 3. Logic Coverage (PC, CC, CACC) for compound predicates +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + # Predicate P1 (_relies_on_idna_mapping): + # A and (B or any(D or E for char in value)) + # A: not value.isascii() + # B: normalize("NFKC", value) != value + # D: in_table_b1(char) + # E: char in "\u3002\uff0e\uff61" + # + # Note: When A is False (ASCII), B, D, and E are structurally False and + # short-circuited. Similarly, D and E cannot both be True on the same char. + pytest.param("example.com", True, id="ascii_short_circuit"), # A=F -> P1=F + pytest.param("m\u00fcnchen.de", True, id="direct_non_ascii_valid"), # A=T, B=F, D=F, E=F -> P1=F + pytest.param("caf\u00e9.com", True, id="nfc_non_ascii_valid"), # A=T, B=F, D=F, E=F -> P1=F + pytest.param("\uff45\uff58\uff41\uff4d\uff50\uff4c\uff45.com", False, id="nfkc_fullwidth_letters"), # A=T, B=T, D=F, E=F -> P1=T + pytest.param("cafe\u0301.com", False, id="nfkc_decomposed_accent"), # A=T, B=T, D=F, E=F -> P1=T + pytest.param("exa\u00admple.com", False, id="table_b1_soft_hyphen"), # A=T, B=F, D=T, E=F -> P1=T + pytest.param("example\u3002com", False, id="special_dot_u3002"), # A=T, B=F, D=F, E=T -> P1=T + pytest.param("example\uff0ecom", False, id="special_dot_uff0e"), + pytest.param("example\uff61com", False, id="special_dot_uff61"), + ], +) +def test_logic_coverage_idna_mapping_predicate(value, is_valid): + """CACC/CC/PC for _relies_on_idna_mapping(value).""" + result = domain(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "consider_tld", "is_valid"), + [ + # Predicate P2: F and G + # F: consider_tld + # G: not _IanaTLD.check(...) + pytest.param("example.notatld", True, False, id="flag_on_unknown_tld"), # F=T, G=T -> P2=T + pytest.param("example.notatld", False, True, id="flag_off_unknown_tld"), # F=F, G=T -> P2=F + pytest.param("example.com", True, True, id="flag_on_valid_tld"), # F=T, G=F -> P2=F + pytest.param("example.com", False, True, id="flag_off_valid_tld"), # F=F, G=F -> P2=F + ], +) +def test_logic_coverage_consider_tld_predicate(value, consider_tld, is_valid): + """CACC/CC/PC for the consider_tld compound condition.""" + result = domain(value, consider_tld=consider_tld) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "rfc_2782", "is_valid"), + [ + # Predicate P3: H and I + # H: not re.search(r"\s|__+", value) + # I: bool(re.match(..., encoded, re.IGNORECASE)) + # + # Note: "example.com\n" matches regex $ before trailing newline (I=T) + # and "__http._tcp.example.com" with rfc_2782=True matches regex (I=T), + # so both make H=F while keeping I=T. + pytest.param("example.com", False, True, id="valid_chars_and_format"), # H=T, I=T -> P3=T + pytest.param("example.com\n", False, False, id="trailing_newline_caught_by_search"), # H=F, I=T -> P3=F + pytest.param("__http._tcp.example.com", True, False, id="double_underscore_caught_by_search"), # H=F, I=T -> P3=F + pytest.param("-example.com", False, False, id="leading_hyphen_caught_by_regex"), # H=T, I=F -> P3=F + pytest.param("exa mple", False, False, id="space_and_missing_tld"), # H=F, I=F -> P3=F + ], +) +def test_logic_coverage_final_return_predicate(value, rfc_2782, is_valid): + """CACC/CC/PC for the final whitespace/underscore and regex predicate.""" + result = domain(value, rfc_2782=rfc_2782) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 4. Boundary, Branch, and Mutation-Killing Tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "rfc_1034", "rfc_2782", "is_valid"), + [ + # Label length boundaries (1, 2, 63 vs 64, and punycode expansion > 63) + pytest.param("a.com", False, False, True, id="sub_1_char"), + pytest.param("ab.com", False, False, True, id="sub_2_chars"), + pytest.param(("a" * 63) + ".com", False, False, True, id="sub_63_chars"), + pytest.param(("a" * 64) + ".com", False, False, False, id="sub_64_chars"), + pytest.param("example.co", False, False, True, id="tld_2_chars"), + pytest.param("example.a", False, False, False, id="tld_1_char"), + pytest.param("example." + ("a" * 63), False, False, True, id="tld_63_chars"), + pytest.param("example." + ("a" * 64), False, False, False, id="tld_64_chars"), + pytest.param("\u00fc" + ("a" * 56) + ".com", False, False, False, id="encoded_label_over_63"), + # Total length boundaries (253 vs 254, with/without trailing dot, punycode > 253) + pytest.param(("a" * 63 + ".") * 3 + ("b" * 57) + ".com", False, False, True, id="total_253_chars"), + pytest.param(("a" * 63 + ".") * 3 + ("b" * 57) + ".com.", True, False, True, id="total_253_with_trailing_dot"), + pytest.param(("a" * 63 + ".") * 3 + ("b" * 58) + ".com", False, False, False, id="total_254_chars"), + pytest.param(("a" * 63 + ".") * 3 + ("b" * 58) + ".com.", True, False, False, id="total_254_with_trailing_dot"), + pytest.param("m\u00fcnchen." * 17 + "de", False, False, False, id="encoded_total_over_253"), + # Numeric TLD checks (ASCII and IDN all-decimal TLDs) + pytest.param("example.123", False, False, False, id="numeric_tld"), + pytest.param("example.123.", True, False, False, id="numeric_tld_trailing_dot"), + pytest.param("example.\u0661", False, False, False, id="numeric_idn_tld"), + pytest.param("example.\u0661.", True, False, False, id="numeric_idn_tld_trailing_dot"), + pytest.param("123.example.com", False, False, True, id="numeric_subdomain"), + pytest.param("123", False, False, False, id="numeric_only"), + # Case, hyphens, digits, structural errors, and UnicodeError paths + pytest.param("EXAMPLE.COM", False, False, True, id="uppercase_domain"), + pytest.param("my-host-1.sub-2.example.com", False, False, True, id="hyphen_in_middle"), + pytest.param("example.x1y", False, False, True, id="digit_in_tld"), + pytest.param("example.1ab", False, False, True, id="leading_digit_in_tld"), + pytest.param("example.ab1", False, False, False, id="trailing_digit_in_tld"), + pytest.param("-example.com", False, False, False, id="leading_hyphen"), + pytest.param("example-.com", False, False, False, id="trailing_hyphen"), + pytest.param("example.-com", False, False, False, id="tld_leading_hyphen"), + pytest.param("example.com-", False, False, False, id="tld_trailing_hyphen"), + pytest.param("localhost", False, False, False, id="single_label"), + pytest.param(".", False, False, False, id="only_dot"), + pytest.param(".example.com", False, False, False, id="leading_dot"), + pytest.param("example..com", False, False, False, id="double_dot"), + pytest.param("example.com..", True, False, False, id="double_trailing_dot"), + pytest.param(" example.com", False, False, False, id="leading_space"), + pytest.param("example.com ", False, False, False, id="trailing_space"), + pytest.param("exa mple.com", False, False, False, id="internal_space"), + pytest.param("example\t.com", False, False, False, id="tab_char"), + # Service record underscore edge cases (rfc_2782) + pytest.param("sub_1.example.com", False, True, True, id="srv_middle_underscore"), + pytest.param("sub_.example.com", False, True, True, id="srv_trailing_underscore"), + pytest.param("___http.example.com", False, True, False, id="srv_triple_underscore"), + pytest.param("example.c_m", False, True, False, id="srv_underscore_in_tld"), + # Non-domain punctuation + pytest.param("example.com/", False, False, False, id="trailing_slash"), + pytest.param("user@example.com", False, False, False, id="at_symbol"), + pytest.param("example!.com", False, False, False, id="exclamation_mark"), + ], +) +def test_domain_boundaries_and_structure(value, rfc_1034, rfc_2782, is_valid): + """Test length boundaries, numeric TLDs, IDNA UnicodeErrors, and regex edge cases.""" + result = domain(value, rfc_1034=rfc_1034, rfc_2782=rfc_2782) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "rfc_1034", "is_valid"), + [ + pytest.param("example.onion", False, True, id="tld_popular_onion"), + pytest.param("example.Io", False, True, id="tld_case_insensitive"), + pytest.param("example.io.", True, True, id="tld_iana_trailing_dot"), + pytest.param("\u043f\u0440\u0438\u043c\u0435\u0440.\u0440\u0444", False, True, id="tld_idn_punycode"), + ], +) +def test_domain_iana_tld_lookup_variants(value, rfc_1034, is_valid): + """Verify popular cache, mixed-case normalization, trailing dots, and IDN punycode TLDs.""" + result = domain(value, consider_tld=True, rfc_1034=rfc_1034) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +def test_domain_iana_tld_full_cache_enabled(monkeypatch): + """Cover _IanaTLD._full_cache population and cache-hit branches via PYVLD_CACHE_TLD.""" + monkeypatch.setenv("PYVLD_CACHE_TLD", "True") + monkeypatch.setattr(_IanaTLD, "_full_cache", None) + + # First non-popular TLD lookup populates _full_cache + assert domain("example.ca", consider_tld=True) is True + assert _IanaTLD._full_cache is not None + + # Subsequent lookups hit populated _full_cache directly + assert domain("example.edu", consider_tld=True) is True + _assert_invalid(domain("example.notatld", consider_tld=True)) \ No newline at end of file diff --git a/tests/email_test.py b/tests/email_test.py index e9691f24..a2c5ecb1 100644 --- a/tests/email_test.py +++ b/tests/email_test.py @@ -1 +1,452 @@ -#init \ No newline at end of file +import pytest + +from validators.email import email +from validators.utils import ValidationError + + +def _assert_invalid(result) -> None: + """Confirm invalid validations return a falsy ValidationError.""" + assert isinstance(result, ValidationError) + assert not result + + +# --------------------------------------------------------------------------- +# 1. ISP: Argument type (Table 2 - All validators) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + pytest.param("someone@example.com", True, id="str_valid"), + pytest.param("", False, id="str_empty"), + pytest.param(None, False, id="none"), + pytest.param(0, False, id="int_zero"), + pytest.param(b"someone@example.com", False, id="bytes_email"), + pytest.param(b"", False, id="bytes_empty"), + ], +) +def test_email_argument_types(value, is_valid): + """Cover non-raising argument types from Table 2 (str, None, int, bytes).""" + result = email(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +def test_email_truthy_int_defect(): + """Document Section 2.2 defect: truthy int raises AttributeError instead of ValidationError.""" + with pytest.raises(AttributeError): + email(123) + + +# --------------------------------------------------------------------------- +# 2. ISP: Pairwise Coverage (PWC) & Option Flag Matching (Table 2 - email) +# --------------------------------------------------------------------------- +# Because ACoC across (Number of @ signs [3] x Domain form [3] x Local len [2] +# x Domain len [2] x ipv4 [2] x ipv6 [2] x simple_host [2] x rfc_1034 [2] +# x rfc_2782 [2]) yields 1,152 combinations (> 20), these 10 tests form a +# Pairwise Covering Array covering all pairs across all 9 parameters: +# +# ID | @ count | Form | Local | Domain | ipv4 | ipv6 | simple | 1034 | 2782 +# ------+---------+------+-------+--------+------+------+--------+------+------ +# pwc1 | 1 | host | <=64 | <=253 | F | F | F | F | F +# pwc2 | 1 | [ip] | <=64 | <=253 | T | F | T | T | T +# pwc3 | 1 | ip | >=65 | >=254 | F | T | F | T | F +# pwc4 | 0 | host | <=64 | >=254 | T | T | T | F | T +# pwc5 | 0 | [ip] | >=65 | <=253 | F | F | F | T | F +# pwc6 | 0 | ip | <=64 | <=253 | T | F | T | F | T +# pwc7 | >1 | host | >=65 | <=253 | F | T | T | T | F +# pwc8 | >1 | [ip] | <=64 | >=254 | F | T | F | F | T +# pwc9 | >1 | ip | >=65 | >=254 | T | T | F | F | F +# pwc10 | >1 | host | >=65 | >=254 | F | F | F | T | T + + +@pytest.mark.parametrize( + ("value", "ipv4_address", "ipv6_address", "simple_host", "rfc_1034", "rfc_2782", "is_valid"), + [ + pytest.param( + "someone@example.com", + False, + False, + False, + False, + False, + True, + id="pwc1_valid_hostname", + ), + pytest.param( + "someone@[127.0.0.1]", + True, + False, + True, + True, + True, + True, + id="pwc2_valid_bracketed_ipv4", + ), + pytest.param( + ("a" * 65) + "@127.0.0." + ("1" * 246), + False, + True, + False, + True, + False, + False, + id="pwc3_long_local_unbracketed_ip_len", + ), + pytest.param( + ("a" * 63 + ".") * 3 + ("b" * 58) + ".com", + True, + True, + True, + False, + True, + False, + id="pwc4_zero_at_long_hostname", + ), + pytest.param( + ("a" * 65) + "[127.0.0.1]", + False, + False, + False, + True, + False, + False, + id="pwc5_zero_at_bracketed_ip", + ), + pytest.param( + "127.0.0.1", + True, + False, + True, + False, + True, + False, + id="pwc6_zero_at_unbracketed_ip", + ), + pytest.param( + "a@" + ("b" * 65) + "@example.com", + False, + True, + True, + True, + False, + False, + id="pwc7_multi_at_long_local_host", + ), + pytest.param( + "a@b@[::" + ("1" * 251) + "]", + False, + True, + False, + False, + True, + False, + id="pwc8_multi_at_long_bracketed_ipv6", + ), + pytest.param( + ("a" * 64) + "@b@127.0.0." + ("1" * 246), + True, + True, + False, + False, + False, + False, + id="pwc9_multi_at_long_unbracketed_ip", + ), + pytest.param( + ("a" * 65) + "@b@" + ("c" * 63 + ".") * 3 + ("d" * 58) + ".com", + False, + False, + False, + True, + True, + False, + id="pwc10_multi_at_long_local_and_host", + ), + ], +) +def test_email_isp_pairwise( + value, + ipv4_address, + ipv6_address, + simple_host, + rfc_1034, + rfc_2782, + is_valid, +): + """Verify Pairwise Coverage (PWC) across all email ISP characteristics and option flags.""" + result = email( + value, + ipv4_address=ipv4_address, + ipv6_address=ipv6_address, + simple_host=simple_host, + rfc_1034=rfc_1034, + rfc_2782=rfc_2782, + ) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "kwargs", "is_valid"), + [ + pytest.param("someone@[127.0.0.1]", {"ipv4_address": True}, True, id="ipv4_on_bracketed"), + pytest.param("someone@[127.0.0.1]", {"ipv4_address": False}, False, id="ipv4_off_bracketed"), + pytest.param("someone@127.0.0.1", {"ipv4_address": True}, False, id="ipv4_on_unbracketed"), + pytest.param("someone@[127.0.0.1]", {"ipv6_address": True}, False, id="ipv4_literal_with_ipv6_flag"), + pytest.param("someone@example.com", {"ipv4_address": True}, False, id="ipv4_on_plain_hostname"), + pytest.param("someone@[::1]", {"ipv6_address": True}, True, id="ipv6_on_bracketed"), + pytest.param("someone@[2001:db8::1]", {"ipv6_address": True}, True, id="ipv6_on_full_bracketed"), + pytest.param("someone@[::1]", {"ipv6_address": False}, False, id="ipv6_off_bracketed"), + pytest.param("someone@::1", {"ipv6_address": True}, False, id="ipv6_on_unbracketed"), + pytest.param("someone@[::1]", {"ipv4_address": True}, False, id="ipv6_literal_with_ipv4_flag"), + pytest.param("someone@example.com", {"ipv6_address": True}, False, id="ipv6_on_plain_hostname"), + pytest.param( + "someone@[127.0.0.1]", + {"ipv4_address": True, "ipv6_address": True}, + True, + id="both_ip_flags_on_ipv4", + ), + pytest.param( + "someone@[::1]", + {"ipv4_address": True, "ipv6_address": True}, + True, + id="both_ip_flags_on_ipv6", + ), + pytest.param("someone@localhost", {"simple_host": True}, True, id="simple_host_on_localhost"), + pytest.param("someone@my-host-1", {"simple_host": True}, True, id="simple_host_on_hyphenated"), + pytest.param("someone@localhost", {"simple_host": False}, False, id="simple_host_off_localhost"), + pytest.param("someone@example.com.", {"rfc_1034": True}, True, id="rfc1034_on_trailing_dot"), + pytest.param("someone@example.com.", {"rfc_1034": False}, False, id="rfc1034_off_trailing_dot"), + pytest.param("someone@_http._tcp.example.com", {"rfc_2782": True}, True, id="rfc2782_on_underscore"), + pytest.param("someone@_http._tcp.example.com", {"rfc_2782": False}, False, id="rfc2782_off_underscore"), + pytest.param( + "someone@_http._tcp.example.com.", + {"simple_host": True, "rfc_1034": True, "rfc_2782": True}, + True, + id="combined_simple_dot_service", + ), + ], +) +def test_email_isp_option_flags(value, kwargs, is_valid): + """Ensure every option flag toggles matching valid and invalid domain forms.""" + result = email(value, **kwargs) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 3. Logic Coverage (PC, CC, CACC) for compound predicates +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + # Predicate P1: A or B + # A: not value + # B: value.count("@") != 1 + # + # Note: (A=T, B=F) is infeasible because an empty string cannot contain "@". + # A satisfies PC and CC; B satisfies CACC via (A=F, B=T) vs (A=F, B=F). + pytest.param("", False, id="empty_string"), # A=T (short-circuits B) -> P1=T + pytest.param("someone.example.com", False, id="zero_at_signs"), # A=F, B=T -> P1=T + pytest.param("a@b@example.com", False, id="two_at_signs"), # A=F, B=T -> P1=T + pytest.param("someone@example.com", True, id="one_at_sign"), # A=F, B=F -> P1=F + ], +) +def test_logic_coverage_empty_and_at_count_predicate(value, is_valid): + """CACC/CC/PC for the emptiness and '@' count input predicate.""" + result = email(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + # Predicate P2: C or D + # C: len(username_part) > 64 + # D: len(domain_part) > 253 + pytest.param( + ("a" * 64) + "@" + ("b" * 63 + ".") * 3 + ("c" * 57) + ".com", + True, + id="both_within_limits", + ), # C=F, D=F -> P2=F + pytest.param( + ("a" * 65) + "@example.com", + False, + id="local_over_64_only", + ), # C=T, D=F -> P2=T + pytest.param( + "someone@" + ("b" * 63 + ".") * 3 + ("c" * 58) + ".com", + False, + id="domain_over_253_only", + ), # C=F, D=T -> P2=T + pytest.param( + ("a" * 65) + "@" + ("b" * 63 + ".") * 3 + ("c" * 58) + ".com", + False, + id="both_over_limits", + ), # C=T, D=T -> P2=T + ], +) +def test_logic_coverage_length_predicate(value, is_valid): + """CACC/CC/PC for the local-part and domain-part length predicate.""" + result = email(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "ipv6_address", "ipv4_address", "is_valid"), + [ + # Predicate P3: E or F + # E: ipv6_address + # F: ipv4_address + pytest.param("someone@[127.0.0.1]", False, False, False, id="both_flags_off_ipv4_fails"), # E=F, F=F -> P3=F + pytest.param("someone@[127.0.0.1]", False, True, True, id="ipv4_flag_on_valid"), # E=F, F=T -> P3=T + pytest.param("someone@[::1]", False, False, False, id="both_flags_off_ipv6_fails"), # E=F, F=F -> P3=F + pytest.param("someone@[::1]", True, False, True, id="ipv6_flag_on_valid"), # E=T, F=F -> P3=T + pytest.param("someone@[127.0.0.1]", True, True, True, id="both_flags_on_ipv4_valid"), # E=T, F=T -> P3=T + pytest.param("someone@[::1]", True, True, True, id="both_flags_on_ipv6_valid"), # E=T, F=T -> P3=T + ], +) +def test_logic_coverage_ip_flag_predicate(value, ipv6_address, ipv4_address, is_valid): + """CACC/CC/PC for the ipv6_address or ipv4_address predicate.""" + result = email(value, ipv6_address=ipv6_address, ipv4_address=ipv4_address) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + # Predicate P4: G and H + # G: domain_part.startswith("[") + # H: domain_part.endswith("]") + pytest.param("someone@[127.0.0.1]", True, id="both_brackets_present"), # G=T, H=T -> P4=T + pytest.param("someone@[127.0.0.1", False, id="missing_closing_bracket"), # G=T, H=F -> P4=F + pytest.param("someone@127.0.0.1]", False, id="missing_opening_bracket"), # G=F, H=T -> P4=F + pytest.param("someone@127.0.0.1", False, id="both_brackets_missing"), # G=F, H=F -> P4=F + ], +) +def test_logic_coverage_bracket_predicate(value, is_valid): + """CACC/CC/PC for the bracketed IP literal check.""" + result = email(value, ipv4_address=True) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 4. Boundary, Branch, and Mutation-Killing Tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "kwargs", "is_valid"), + [ + # Length boundaries + pytest.param("a@example.com", {}, True, id="local_1_char"), + pytest.param(("a" * 64) + "@example.com", {}, True, id="local_64_chars"), + pytest.param(("a" * 65) + "@example.com", {}, False, id="local_65_chars"), + pytest.param( + "someone@" + ("b" * 63 + ".") * 3 + ("c" * 57) + ".com", + {}, + True, + id="domain_253_chars", + ), + pytest.param( + "someone@" + ("b" * 63 + ".") * 3 + ("c" * 56) + ".com.", + {"rfc_1034": True}, + True, + id="domain_253_chars_with_dot", + ), + pytest.param( + "someone@" + ("b" * 63 + ".") * 3 + ("c" * 58) + ".com", + {}, + False, + id="domain_254_chars", + ), + pytest.param( + "someone@" + ("b" * 63 + ".") * 3 + ("c" * 57) + ".com.", + {"rfc_1034": True}, + False, + id="domain_253_plus_dot_over_253", + ), + # Split & @-sign structure + pytest.param("@example.com", {}, False, id="empty_local_part"), + pytest.param("someone@", {}, False, id="empty_domain_part"), + pytest.param("@", {}, False, id="only_at_sign"), + pytest.param('"user@inner"@example.com', {}, False, id="quoted_extra_at_sign"), + # IP literal & hostname delegation checks (may_have_port=False, cidr=False) + pytest.param("someone@[]", {"ipv4_address": True}, False, id="empty_brackets"), + pytest.param("someone@[999.0.0.1]", {"ipv4_address": True}, False, id="invalid_ipv4_literal"), + pytest.param("someone@[127.0.0.1/24]", {"ipv4_address": True}, False, id="ipv4_cidr_rejected"), + pytest.param("someone@example.com:8080", {}, False, id="port_on_hostname"), + pytest.param("someone@[127.0.0.1]:8080", {"ipv4_address": True}, False, id="port_outside_brackets"), + pytest.param("someone@[127.0.0.1:8080]", {"ipv4_address": True}, False, id="port_inside_brackets"), + # Local-part branch 1 & 2: Extended Latin and fullmatch vs match killers + pytest.param("\u00e9@example.com", {}, True, id="ext_latin_single_u00e9"), + pytest.param("\u0100@example.com", {}, True, id="ext_latin_single_u0100"), + pytest.param("\u0180@example.com", {}, True, id="ext_latin_single_u0180"), + pytest.param("jos\u00e9@example.com", {}, True, id="ext_latin_multi_char"), + pytest.param("\u00e9 space@example.com", {}, False, id="ext_latin_trailing_space_fullmatch"), + pytest.param("\u00e9\n@example.com", {}, False, id="ext_latin_trailing_newline_fullmatch"), + pytest.param("\u043f\u0440\u0438\u0432\u0435\u0442@example.com", {}, False, id="cyrillic_local_rejected"), + pytest.param("someone@m\u00fcnchen.de", {}, True, id="idn_domain_valid"), + # Local-part branch 2: Dot-atom characters and invalid delimiters + pytest.param("UPPER.Case_123@example.com", {}, True, id="uppercase_dot_atom"), + pytest.param("first.middle.last@example.com", {}, True, id="multiple_dots"), + pytest.param("a!#$%&'*+/=?^_`{|}~-z@example.com", {}, True, id="all_atext_specials"), + pytest.param(".leadingdot@example.com", {}, False, id="leading_dot"), + pytest.param("trailingdot.@example.com", {}, False, id="trailing_dot"), + pytest.param("double..dot@example.com", {}, False, id="consecutive_dots"), + pytest.param("has space@example.com", {}, False, id="internal_space"), + pytest.param("someone\n@example.com", {}, False, id="trailing_newline"), + pytest.param("bad(paren)@example.com", {}, False, id="paren_in_dot_atom"), + pytest.param("bad,comma@example.com", {}, False, id="comma_in_dot_atom"), + pytest.param("bad:colon@example.com", {}, False, id="colon_in_dot_atom"), + pytest.param("bad;semi@example.com", {}, False, id="semicolon_in_dot_atom"), + pytest.param("bad@example.com", {}, False, id="angle_brackets_in_dot_atom"), + pytest.param("bad[bracket]@example.com", {}, False, id="square_brackets_in_dot_atom"), + pytest.param("bad\\slash@example.com", {}, False, id="backslash_in_dot_atom"), + # Local-part branch 3: Quoted-string rules + pytest.param('""@example.com', {}, True, id="quoted_empty"), + pytest.param('"simple"@example.com', {}, True, id="quoted_simple"), + pytest.param('"john..doe"@example.com', {}, True, id="quoted_consecutive_dots"), + pytest.param('"first.last."@example.com', {}, True, id="quoted_trailing_dot"), + pytest.param('"(parens),:;<>[text]"@example.com', {}, True, id="quoted_special_chars"), + pytest.param('"caf\u00e9"@example.com', {}, True, id="quoted_ext_latin"), + pytest.param(r'"escaped\."@example.com', {}, True, id="quoted_escaped_dot"), + pytest.param('"escaped\\\t"@example.com', {}, True, id="quoted_escaped_tab"), + pytest.param('"unclosed@example.com', {}, False, id="quoted_unclosed"), + pytest.param('unopened"@example.com', {}, False, id="quoted_unopened"), + pytest.param('"outer"extra@example.com', {}, False, id="quoted_trailing_text"), + pytest.param('extra"inner"@example.com', {}, False, id="quoted_leading_text"), + pytest.param('"has space"@example.com', {}, False, id="quoted_space_rejected"), + pytest.param(r'"has\"quote"@example.com', {}, False, id="quoted_escaped_quote_rejected"), + pytest.param(r'"has\a"@example.com', {}, False, id="quoted_escaped_letter_rejected"), + ], +) +def test_email_boundaries_and_local_part_regex(value, kwargs, is_valid): + """Test length boundaries, IP/hostname delegation limits, and all local-part regex branches.""" + result = email(value, **kwargs) + if is_valid: + assert result is True + else: + _assert_invalid(result) \ No newline at end of file From 7586acd65a5be8a0a7745c2e0a073a57bfdb8414 Mon Sep 17 00:00:00 2001 From: Daana Honarmand <68249577+DaanaH-dev@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:11:41 -0500 Subject: [PATCH 08/12] added base files for all other tests and did some work on domain --- tests/domain_test.py | 663 ++++++++++++++++++++++++++-------- tests/email_test.py | 1 + tests/ip_address_test.py | 397 +++++++++++++++++++- tests/length_test.py | 219 ++++++++++- tests/mac_address_test.py | 203 ++++++++++- tests/test_cmdline_running.md | 15 + tests/url_test.py | 350 +++++++++++++++++- 7 files changed, 1700 insertions(+), 148 deletions(-) diff --git a/tests/domain_test.py b/tests/domain_test.py index fbaf5040..0c288219 100644 --- a/tests/domain_test.py +++ b/tests/domain_test.py @@ -1,3 +1,4 @@ +#TODO import pytest from validators.domain import _IanaTLD, domain @@ -10,11 +11,7 @@ def _assert_invalid(result) -> None: assert not result -# --------------------------------------------------------------------------- -# 1. ISP: Argument type (Table 2 - All validators) -# --------------------------------------------------------------------------- - - +# ISP @pytest.mark.parametrize( ("value", "is_valid"), [ @@ -41,25 +38,7 @@ def test_domain_truthy_int_defect(): domain(123) -# --------------------------------------------------------------------------- -# 2. ISP: Pairwise Coverage (PWC) & Option Flag Matching (Table 2 - domain) -# --------------------------------------------------------------------------- -# Because ACoC across (Character set [3] x Label length [2] x Total length [2] -# x consider_tld [2] x rfc_1034 [2] x rfc_2782 [2]) yields 96 combinations (> 20), -# these 8 tests form a Pairwise Covering Array covering all 70 parameter pairs: -# -# ID | Char set | Label | Total | consider_tld | rfc_1034 | rfc_2782 -# ------+-------------+-------+-------+--------------+----------+--------- -# pwc1 | mapped IDN | <=63 | <=253 | False | False | False -# pwc2 | mapped IDN | >=64 | >=254 | True | True | True -# pwc3 | direct IDN | <=63 | >=254 | False | True | False -# pwc4 | direct IDN | >=64 | <=253 | True | False | True -# pwc5 | ASCII | <=63 | <=253 | True | False | True -# pwc6 | ASCII | >=64 | >=254 | False | True | False -# pwc7 | ASCII | <=63 | >=254 | True | False | False -# pwc8 | direct IDN | >=64 | <=253 | False | True | True - - +# 2. ISP: Pairwise Coverage (PWC) & Option Flag Matching @pytest.mark.parametrize( ("value", "consider_tld", "rfc_1034", "rfc_2782", "is_valid"), [ @@ -146,16 +125,87 @@ def test_domain_isp_pairwise(value, consider_tld, rfc_1034, rfc_2782, is_valid): @pytest.mark.parametrize( ("value", "consider_tld", "rfc_1034", "rfc_2782", "is_valid"), [ - pytest.param("example.com", True, False, False, True, id="consider_tld_on_popular"), - pytest.param("example.io", True, False, False, True, id="consider_tld_on_iana"), - pytest.param("example.notatld", True, False, False, False, id="consider_tld_on_unknown"), - pytest.param("example.notatld", False, False, False, True, id="consider_tld_off_unknown"), - pytest.param("example.com.", False, True, False, True, id="rfc1034_on_trailing_dot"), - pytest.param("example.com.", False, False, False, False, id="rfc1034_off_trailing_dot"), - pytest.param("_http._tcp.example.com", False, False, True, True, id="rfc2782_on_underscore"), - pytest.param("_http._tcp.example.com", False, False, False, False, id="rfc2782_off_underscore"), - pytest.param("m\u00fcnchen.de", False, False, False, True, id="direct_idn_valid"), - pytest.param("_http._tcp.m\u00fcnchen.de.", True, True, True, True, id="all_flags_on_direct_idn"), + pytest.param( + "example.com", + True, + False, + False, + True, + id="consider_tld_on_popular", + ), + pytest.param( + "example.io", + True, + False, + False, + True, + id="consider_tld_on_iana", + ), + pytest.param( + "example.notatld", + True, + False, + False, + False, + id="consider_tld_on_unknown", + ), + pytest.param( + "example.notatld", + False, + False, + False, + True, + id="consider_tld_off_unknown", + ), + pytest.param( + "example.com.", + False, + True, + False, + True, + id="rfc1034_on_trailing_dot", + ), + pytest.param( + "example.com.", + False, + False, + False, + False, + id="rfc1034_off_trailing_dot", + ), + pytest.param( + "_http._tcp.example.com", + False, + False, + True, + True, + id="rfc2782_on_underscore", + ), + pytest.param( + "_http._tcp.example.com", + False, + False, + False, + False, + id="rfc2782_off_underscore", + ), + pytest.param( + "m\u00fcnchen.de", + False, + False, + False, + True, + id="direct_idn_valid", + ), + pytest.param( + "_http._tcp.m\u00fcnchen.de.", + True, + True, + True, + True, + id="all_flags_on_direct_idn", + ), + ], ) def test_domain_isp_option_flags(value, consider_tld, rfc_1034, rfc_2782, is_valid): @@ -172,32 +222,56 @@ def test_domain_isp_option_flags(value, consider_tld, rfc_1034, rfc_2782, is_val _assert_invalid(result) -# --------------------------------------------------------------------------- # 3. Logic Coverage (PC, CC, CACC) for compound predicates -# --------------------------------------------------------------------------- - @pytest.mark.parametrize( ("value", "is_valid"), [ - # Predicate P1 (_relies_on_idna_mapping): - # A and (B or any(D or E for char in value)) - # A: not value.isascii() - # B: normalize("NFKC", value) != value - # D: in_table_b1(char) - # E: char in "\u3002\uff0e\uff61" - # - # Note: When A is False (ASCII), B, D, and E are structurally False and - # short-circuited. Similarly, D and E cannot both be True on the same char. - pytest.param("example.com", True, id="ascii_short_circuit"), # A=F -> P1=F - pytest.param("m\u00fcnchen.de", True, id="direct_non_ascii_valid"), # A=T, B=F, D=F, E=F -> P1=F - pytest.param("caf\u00e9.com", True, id="nfc_non_ascii_valid"), # A=T, B=F, D=F, E=F -> P1=F - pytest.param("\uff45\uff58\uff41\uff4d\uff50\uff4c\uff45.com", False, id="nfkc_fullwidth_letters"), # A=T, B=T, D=F, E=F -> P1=T - pytest.param("cafe\u0301.com", False, id="nfkc_decomposed_accent"), # A=T, B=T, D=F, E=F -> P1=T - pytest.param("exa\u00admple.com", False, id="table_b1_soft_hyphen"), # A=T, B=F, D=T, E=F -> P1=T - pytest.param("example\u3002com", False, id="special_dot_u3002"), # A=T, B=F, D=F, E=T -> P1=T - pytest.param("example\uff0ecom", False, id="special_dot_uff0e"), - pytest.param("example\uff61com", False, id="special_dot_uff61"), + pytest.param( + "example.com", + True, + id="ascii_short_circuit", + ), + pytest.param( + "m\u00fcnchen.de", + True, + id="direct_non_ascii_valid", + ), + pytest.param( + "caf\u00e9.com", + True, + id="nfc_non_ascii_valid", + ), + pytest.param( + "\uff45\uff58\uff41\uff4d\uff50\uff4c\uff45.com", + False, + id="nfkc_fullwidth_letters", + ), + pytest.param( + "cafe\u0301.com", + False, + id="nfkc_decomposed_accent", + ), + pytest.param( + "exa\u00admple.com", + False, + id="table_b1_soft_hyphen", + ), + pytest.param( + "example\u3002com", + False, + id="special_dot_u3002", + ), + pytest.param( + "example\uff0ecom", + False, + id="special_dot_uff0e", + ), + pytest.param( + "example\uff61com", + False, + id="special_dot_uff61", + ), ], ) def test_logic_coverage_idna_mapping_predicate(value, is_valid): @@ -212,13 +286,26 @@ def test_logic_coverage_idna_mapping_predicate(value, is_valid): @pytest.mark.parametrize( ("value", "consider_tld", "is_valid"), [ - # Predicate P2: F and G - # F: consider_tld - # G: not _IanaTLD.check(...) - pytest.param("example.notatld", True, False, id="flag_on_unknown_tld"), # F=T, G=T -> P2=T - pytest.param("example.notatld", False, True, id="flag_off_unknown_tld"), # F=F, G=T -> P2=F - pytest.param("example.com", True, True, id="flag_on_valid_tld"), # F=T, G=F -> P2=F - pytest.param("example.com", False, True, id="flag_off_valid_tld"), # F=F, G=F -> P2=F + pytest.param( + "example.notatld", + True, + False, + id="flag_on_unknown_tld"), + pytest.param( + "example.notatld", + False, + True, + id="flag_off_unknown_tld"), + pytest.param( + "example.com", + True, + True, + id="flag_on_valid_tld"), + pytest.param( + "example.com", + False, + True, + id="flag_off_valid_tld"), ], ) def test_logic_coverage_consider_tld_predicate(value, consider_tld, is_valid): @@ -233,18 +320,36 @@ def test_logic_coverage_consider_tld_predicate(value, consider_tld, is_valid): @pytest.mark.parametrize( ("value", "rfc_2782", "is_valid"), [ - # Predicate P3: H and I - # H: not re.search(r"\s|__+", value) - # I: bool(re.match(..., encoded, re.IGNORECASE)) - # - # Note: "example.com\n" matches regex $ before trailing newline (I=T) - # and "__http._tcp.example.com" with rfc_2782=True matches regex (I=T), - # so both make H=F while keeping I=T. - pytest.param("example.com", False, True, id="valid_chars_and_format"), # H=T, I=T -> P3=T - pytest.param("example.com\n", False, False, id="trailing_newline_caught_by_search"), # H=F, I=T -> P3=F - pytest.param("__http._tcp.example.com", True, False, id="double_underscore_caught_by_search"), # H=F, I=T -> P3=F - pytest.param("-example.com", False, False, id="leading_hyphen_caught_by_regex"), # H=T, I=F -> P3=F - pytest.param("exa mple", False, False, id="space_and_missing_tld"), # H=F, I=F -> P3=F + pytest.param( + "example.com", + False, + True, + id="valid_chars_and_format", + ), + pytest.param( + "example.com\n", + False, + False, + id="trailing_newline_caught_by_search", + ), + pytest.param( + "__http._tcp.example.com", + True, + False, + id="double_underscore_caught_by_search", + ), + pytest.param( + "-example.com", + False, + False, + id="leading_hyphen_caught_by_regex", + ), + pytest.param( + "exa mple", + False, + False, + id="space_and_missing_tld", + ), ], ) def test_logic_coverage_final_return_predicate(value, rfc_2782, is_valid): @@ -256,65 +361,329 @@ def test_logic_coverage_final_return_predicate(value, rfc_2782, is_valid): _assert_invalid(result) -# --------------------------------------------------------------------------- # 4. Boundary, Branch, and Mutation-Killing Tests -# --------------------------------------------------------------------------- @pytest.mark.parametrize( ("value", "rfc_1034", "rfc_2782", "is_valid"), [ - # Label length boundaries (1, 2, 63 vs 64, and punycode expansion > 63) - pytest.param("a.com", False, False, True, id="sub_1_char"), - pytest.param("ab.com", False, False, True, id="sub_2_chars"), - pytest.param(("a" * 63) + ".com", False, False, True, id="sub_63_chars"), - pytest.param(("a" * 64) + ".com", False, False, False, id="sub_64_chars"), - pytest.param("example.co", False, False, True, id="tld_2_chars"), - pytest.param("example.a", False, False, False, id="tld_1_char"), - pytest.param("example." + ("a" * 63), False, False, True, id="tld_63_chars"), - pytest.param("example." + ("a" * 64), False, False, False, id="tld_64_chars"), - pytest.param("\u00fc" + ("a" * 56) + ".com", False, False, False, id="encoded_label_over_63"), - # Total length boundaries (253 vs 254, with/without trailing dot, punycode > 253) - pytest.param(("a" * 63 + ".") * 3 + ("b" * 57) + ".com", False, False, True, id="total_253_chars"), - pytest.param(("a" * 63 + ".") * 3 + ("b" * 57) + ".com.", True, False, True, id="total_253_with_trailing_dot"), - pytest.param(("a" * 63 + ".") * 3 + ("b" * 58) + ".com", False, False, False, id="total_254_chars"), - pytest.param(("a" * 63 + ".") * 3 + ("b" * 58) + ".com.", True, False, False, id="total_254_with_trailing_dot"), - pytest.param("m\u00fcnchen." * 17 + "de", False, False, False, id="encoded_total_over_253"), - # Numeric TLD checks (ASCII and IDN all-decimal TLDs) - pytest.param("example.123", False, False, False, id="numeric_tld"), - pytest.param("example.123.", True, False, False, id="numeric_tld_trailing_dot"), - pytest.param("example.\u0661", False, False, False, id="numeric_idn_tld"), - pytest.param("example.\u0661.", True, False, False, id="numeric_idn_tld_trailing_dot"), - pytest.param("123.example.com", False, False, True, id="numeric_subdomain"), - pytest.param("123", False, False, False, id="numeric_only"), - # Case, hyphens, digits, structural errors, and UnicodeError paths - pytest.param("EXAMPLE.COM", False, False, True, id="uppercase_domain"), - pytest.param("my-host-1.sub-2.example.com", False, False, True, id="hyphen_in_middle"), - pytest.param("example.x1y", False, False, True, id="digit_in_tld"), - pytest.param("example.1ab", False, False, True, id="leading_digit_in_tld"), - pytest.param("example.ab1", False, False, False, id="trailing_digit_in_tld"), - pytest.param("-example.com", False, False, False, id="leading_hyphen"), - pytest.param("example-.com", False, False, False, id="trailing_hyphen"), - pytest.param("example.-com", False, False, False, id="tld_leading_hyphen"), - pytest.param("example.com-", False, False, False, id="tld_trailing_hyphen"), - pytest.param("localhost", False, False, False, id="single_label"), - pytest.param(".", False, False, False, id="only_dot"), - pytest.param(".example.com", False, False, False, id="leading_dot"), - pytest.param("example..com", False, False, False, id="double_dot"), - pytest.param("example.com..", True, False, False, id="double_trailing_dot"), - pytest.param(" example.com", False, False, False, id="leading_space"), - pytest.param("example.com ", False, False, False, id="trailing_space"), - pytest.param("exa mple.com", False, False, False, id="internal_space"), - pytest.param("example\t.com", False, False, False, id="tab_char"), - # Service record underscore edge cases (rfc_2782) - pytest.param("sub_1.example.com", False, True, True, id="srv_middle_underscore"), - pytest.param("sub_.example.com", False, True, True, id="srv_trailing_underscore"), - pytest.param("___http.example.com", False, True, False, id="srv_triple_underscore"), - pytest.param("example.c_m", False, True, False, id="srv_underscore_in_tld"), + + pytest.param( + "a.com", + False, + False, + True, + id="sub_1_char", + ), + pytest.param( + "ab.com", + False, + False, + True, + id="sub_2_chars", + ), + pytest.param( + ("a" * 63) + ".com", + False, + False, + True, + id="sub_63_chars", + ), + pytest.param( + ("a" * 64) + ".com", + False, + False, + False, + id="sub_64_chars", + ), + pytest.param( + "example.co", + False, + False, + True, + id="tld_2_chars", + ), + pytest.param( + "example.a", + False, + False, + False, + id="tld_1_char", + ), + pytest.param( + "example." + ("a" * 63), + False, + False, + True, + id="tld_63_chars", + ), + pytest.param( + "example." + ("a" * 64), + False, + False, + False, + id="tld_64_chars", + ), + pytest.param( + "\u00fc" + ("a" * 56) + ".com", + False, + False, + False, + id="encoded_label_over_63", + ), + pytest.param( + ("a" * 63 + ".") * 3 + ("b" * 57) + ".com", + False, + False, + True, + id="total_253_chars", + ), + pytest.param( + ("a" * 63 + ".") * 3 + ("b" * 57) + ".com.", + True, + False, + True, + id="total_253_with_trailing_dot", + ), + pytest.param( + ("a" * 63 + ".") * 3 + ("b" * 58) + ".com", + False, + False, + False, + id="total_254_chars", + ), + pytest.param( + ("a" * 63 + ".") * 3 + ("b" * 58) + ".com.", + True, + False, + False, + id="total_254_with_trailing_dot", + ), + pytest.param( + "m\u00fcnchen." * 17 + "de", + False, + False, + False, + id="encoded_total_over_253", + ), + pytest.param( + "example.123", + False, + False, + False, + id="numeric_tld", + ), + pytest.param( + "example.123.", + True, + False, + False, + id="numeric_tld_trailing_dot", + ), + pytest.param( + "example.\u0661", + False, + False, + False, + id="numeric_idn_tld", + ), + pytest.param( + "example.\u0661.", + True, + False, + False, + id="numeric_idn_tld_trailing_dot", + ), + pytest.param( + "123.example.com", + False, + False, + True, + id="numeric_subdomain", + ), + pytest.param( + "123", + False, + False, + False, + id="numeric_only", + ), + pytest.param( + "EXAMPLE.COM", + False, + False, + True, + id="uppercase_domain", + ), + pytest.param( + "my-host-1.sub-2.example.com", + False, + False, + True, + id="hyphen_in_middle", + ), + pytest.param( + "example.x1y", + False, + False, + True, + id="digit_in_tld", + ), + pytest.param( + "example.1ab", + False, + False, + True, + id="leading_digit_in_tld", + ), + pytest.param( + "example.ab1", + False, + False, + False, + id="trailing_digit_in_tld", + ), + pytest.param( + "-example.com", + False, + False, + False, + id="leading_hyphen", + ), + pytest.param( + "example-.com", + False, + False, + False, + id="trailing_hyphen", + ), + pytest.param( + "example.-com", + False, + False, + False, + id="tld_leading_hyphen", + ), + pytest.param( + "example.com-", + False, + False, + False, + id="tld_trailing_hyphen", + ), + pytest.param( + "localhost", + False, + False, + False, + id="single_label", + ), + pytest.param( + ".", + False, + False, + False, + id="only_dot", + ), + pytest.param( + ".example.com", + False, + False, + False, + id="leading_dot", + ), + pytest.param( + "example..com", + False, + False, + False, + id="double_dot", + ), + pytest.param( + "example.com..", + True, + False, + False, + id="double_trailing_dot", + ), + pytest.param( + " example.com", + False, + False, + False, + id="leading_space", + ), + pytest.param( + "example.com ", + False, + False, + False, + id="trailing_space", + ), + pytest.param( + "exa mple.com", + False, + False, + False, + id="internal_space", + ), + pytest.param( + "example\t.com", + False, + False, + False, + id="tab_char", + ), + pytest.param( + "sub_1.example.com", + False, + True, + True, + id="srv_middle_underscore", + ), + pytest.param( + "sub_.example.com", + False, + True, + True, + id="srv_trailing_underscore", + ), + pytest.param( + "___http.example.com", + False, + True, + False, + id="srv_triple_underscore", + ), + pytest.param( + "example.c_m", + False, + True, + False, + id="srv_underscore_in_tld", + ), # Non-domain punctuation - pytest.param("example.com/", False, False, False, id="trailing_slash"), - pytest.param("user@example.com", False, False, False, id="at_symbol"), - pytest.param("example!.com", False, False, False, id="exclamation_mark"), + pytest.param( + "example.com/", + False, + False, + False, + id="trailing_slash", + ), + pytest.param( + "user@example.com", + False, + False, + False, + id="at_symbol", + ), + pytest.param( + "example!.com", + False, + False, + False, + id="exclamation_mark", + ), ], ) def test_domain_boundaries_and_structure(value, rfc_1034, rfc_2782, is_valid): @@ -329,10 +698,30 @@ def test_domain_boundaries_and_structure(value, rfc_1034, rfc_2782, is_valid): @pytest.mark.parametrize( ("value", "rfc_1034", "is_valid"), [ - pytest.param("example.onion", False, True, id="tld_popular_onion"), - pytest.param("example.Io", False, True, id="tld_case_insensitive"), - pytest.param("example.io.", True, True, id="tld_iana_trailing_dot"), - pytest.param("\u043f\u0440\u0438\u043c\u0435\u0440.\u0440\u0444", False, True, id="tld_idn_punycode"), + pytest.param( + "example.onion", + False, + True, + id="tld_popular_onion", + ), + pytest.param( + "example.Io", + False, + True, + id="tld_case_insensitive", + ), + pytest.param( + "example.io.", + True, + True, + id="tld_iana_trailing_dot", + ), + pytest.param( + "\u043f\u0440\u0438\u043c\u0435\u0440.\u0440\u0444", + False, + True, + id="tld_idn_punycode", + ), ], ) def test_domain_iana_tld_lookup_variants(value, rfc_1034, is_valid): @@ -342,17 +731,3 @@ def test_domain_iana_tld_lookup_variants(value, rfc_1034, is_valid): assert result is True else: _assert_invalid(result) - - -def test_domain_iana_tld_full_cache_enabled(monkeypatch): - """Cover _IanaTLD._full_cache population and cache-hit branches via PYVLD_CACHE_TLD.""" - monkeypatch.setenv("PYVLD_CACHE_TLD", "True") - monkeypatch.setattr(_IanaTLD, "_full_cache", None) - - # First non-popular TLD lookup populates _full_cache - assert domain("example.ca", consider_tld=True) is True - assert _IanaTLD._full_cache is not None - - # Subsequent lookups hit populated _full_cache directly - assert domain("example.edu", consider_tld=True) is True - _assert_invalid(domain("example.notatld", consider_tld=True)) \ No newline at end of file diff --git a/tests/email_test.py b/tests/email_test.py index a2c5ecb1..a39221f7 100644 --- a/tests/email_test.py +++ b/tests/email_test.py @@ -1,3 +1,4 @@ +#TODO import pytest from validators.email import email diff --git a/tests/ip_address_test.py b/tests/ip_address_test.py index e9691f24..d8e5d39c 100644 --- a/tests/ip_address_test.py +++ b/tests/ip_address_test.py @@ -1 +1,396 @@ -#init \ No newline at end of file +#TODO + +"""Tests for validators.ip_address (ipv4 and ipv6) using ISP, Logic Coverage, and boundary checks.""" + +import pytest + +from validators.ip_address import ipv4, ipv6 +from validators.utils import ValidationError + + +def _assert_invalid(result) -> None: + """Confirm invalid validations return a falsy ValidationError.""" + assert isinstance(result, ValidationError) + assert not result + + +# --------------------------------------------------------------------------- +# 1. ISP: Argument type (Table 2 - All validators) & Section 2.2 Defects +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("func", "value", "is_valid"), + [ + pytest.param(ipv4, "192.0.2.1", True, id="ipv4_str"), + pytest.param(ipv4, "", False, id="ipv4_empty"), + pytest.param(ipv4, None, False, id="ipv4_none"), + pytest.param(ipv4, 0, False, id="ipv4_int_zero"), + pytest.param(ipv4, b"192.0.2.1", False, id="ipv4_bytes_str"), + pytest.param(ipv4, b"", False, id="ipv4_bytes_empty"), + pytest.param(ipv6, "2001:db8::1", True, id="ipv6_str"), + pytest.param(ipv6, "", False, id="ipv6_empty"), + pytest.param(ipv6, None, False, id="ipv6_none"), + pytest.param(ipv6, 0, False, id="ipv6_int_zero"), + pytest.param(ipv6, b"2001:db8::1", False, id="ipv6_bytes_str"), + pytest.param(ipv6, b"", False, id="ipv6_bytes_empty"), + ], +) +def test_ip_argument_types(func, value, is_valid): + """Cover non-defect argument types from Table 2 (str, None, falsy int, bytes).""" + result = func(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("func", "value"), + [ + pytest.param(ipv4, 123, id="ipv4_int_123_returns_true"), + pytest.param(ipv6, 123, id="ipv6_int_123_returns_true"), + ], +) +def test_ip_truthy_int_accepted_defect(func, value): + """Document Section 2.2 defect: ipaddress accepts positive integers as valid addresses.""" + assert func(value) is True + + +@pytest.mark.parametrize( + ("func", "kwargs"), + [ + pytest.param(ipv4, {"strict": True}, id="ipv4_int_123_strict"), + pytest.param(ipv4, {"private": True}, id="ipv4_int_123_private"), + pytest.param(ipv6, {"strict": True}, id="ipv6_int_123_strict"), + ], +) +def test_ip_truthy_int_attribute_error_defect(func, kwargs): + """Document Section 2.2 defect: string methods on int input raise AttributeError.""" + with pytest.raises(AttributeError): + func(123, **kwargs) + + +# --------------------------------------------------------------------------- +# 2. ISP: Pairwise Coverage (PWC) & Option Flag Matching (Table 2 - ipv4 / ipv6) +# --------------------------------------------------------------------------- +# Because ACoC across ipv4 characteristics (Octet count [3] x private flag [3] +# x Octet value [2] x Address class [2] x cidr [2] x strict [2] x host_bit [2]) +# yields 288 combinations (> 20), these 9 tests form a Pairwise Covering Array +# covering every parameter pair across all 7 ipv4 characteristics: +# +# ID | Octets | private | Value | Class | cidr | strict | host_bit +# -----+--------+---------+-------+-------+------+--------+--------- +# pwc1 | few | None | 0-255 | priv | T | T | T +# pwc2 | few | True | 256+ | pub | F | T | T +# pwc3 | few | False | 0-255 | priv | F | F | F +# pwc4 | four | None | 0-255 | pub | F | F | F +# pwc5 | four | True | 0-255 | priv | T | T | F +# pwc6 | four | False | 256+ | priv | T | T | T +# pwc7 | many | None | 256+ | priv | T | T | F +# pwc8 | many | True | 0-255 | priv | F | F | T +# pwc9 | many | False | 256+ | pub | T | F | F + + +@pytest.mark.parametrize( + ("value", "private", "cidr", "strict", "host_bit", "is_valid"), + [ + pytest.param("10.0.1/24", None, True, True, True, False, id="pwc1_few_priv_cidr_strict"), + pytest.param("300.1.1", True, False, True, True, False, id="pwc2_few_256plus_noncidr"), + pytest.param("192.168.1", False, False, False, False, False, id="pwc3_few_priv_noncidr"), + pytest.param("8.8.8.8", None, False, False, False, True, id="pwc4_valid_public_noncidr"), + pytest.param("10.0.0.0/8", True, True, True, False, True, id="pwc5_valid_priv_cidr_strict"), + pytest.param("192.168.300.1/24", False, True, True, True, False, id="pwc6_four_256plus_cidr"), + pytest.param("10.0.0.1.256/24", None, True, True, False, False, id="pwc7_many_256plus_cidr"), + pytest.param("127.0.0.1.1", True, False, False, True, False, id="pwc8_many_priv_noncidr"), + pytest.param("8.8.8.8.999", False, True, False, False, False, id="pwc9_many_256plus_public"), + ], +) +def test_ipv4_isp_pairwise(value, private, cidr, strict, host_bit, is_valid): + """Verify Pairwise Coverage (PWC) across all ipv4 ISP characteristics.""" + result = ipv4( + value, + cidr=cidr, + strict=strict, + private=private, + host_bit=host_bit, + ) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "kwargs", "is_valid"), + [ + pytest.param("192.0.2.0/24", {"cidr": True}, True, id="cidr_on_with_prefix"), + pytest.param("192.0.2.0/24", {"cidr": False}, False, id="cidr_off_with_prefix"), + pytest.param("192.0.2.1", {"cidr": False}, True, id="cidr_off_plain_ip"), + pytest.param("192.0.2.0/24", {"strict": True}, True, id="strict_on_with_prefix"), + pytest.param("192.0.2.1", {"strict": True}, False, id="strict_on_without_prefix"), + pytest.param("192.0.2.1", {"strict": False}, True, id="strict_off_without_prefix"), + pytest.param("192.0.2.1", {"cidr": False, "strict": True}, True, id="strict_ignored_when_cidr_off"), + pytest.param("192.0.2.1/24", {"host_bit": True}, True, id="host_bit_on_with_host_bits"), + pytest.param("192.0.2.1/24", {"host_bit": False}, False, id="host_bit_off_with_host_bits"), + pytest.param("192.0.2.0/24", {"host_bit": False}, True, id="host_bit_off_network_addr"), + pytest.param("192.0.2.1/32", {"host_bit": False}, True, id="host_bit_off_slash_32"), + pytest.param("192.0.2.1", {"host_bit": False}, True, id="host_bit_off_plain_ip"), + pytest.param("10.0.0.1", {"private": None}, True, id="private_none_allows_private"), + pytest.param("8.8.8.8", {"private": None}, True, id="private_none_allows_public"), + pytest.param("10.0.0.1", {"private": True}, True, id="private_true_allows_private"), + pytest.param("8.8.8.8", {"private": True}, False, id="private_true_rejects_public"), + pytest.param("10.0.0.1", {"private": False}, False, id="private_false_rejects_private"), + pytest.param("8.8.8.8", {"private": False}, True, id="private_false_allows_public"), + ], +) +def test_ipv4_isp_option_flags(value, kwargs, is_valid): + """Ensure every ipv4 option flag toggles matching valid and invalid inputs.""" + result = ipv4(value, **kwargs) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# Because ipv6 (Hex group form [4] x cidr [2] x strict [2] x host_bit [2]) yields +# 32 combinations (> 20), these 8 tests provide Pairwise Coverage (PWC) for ipv6: +# +# ID | Form | cidr | strict | host_bit +# -----+------------------+------+--------+--------- +# pwc1 | compressed hex | T | F | T +# pwc2 | compressed hex | F | T | F +# pwc3 | ipv4-mapped | T | T | F +# pwc4 | ipv4-mapped | F | F | T +# pwc5 | too few groups | T | T | T +# pwc6 | too few groups | F | F | F +# pwc7 | too many groups | T | F | F +# pwc8 | non-hex digit | F | T | T + + +@pytest.mark.parametrize( + ("value", "cidr", "strict", "host_bit", "is_valid"), + [ + pytest.param("::1", True, False, True, True, id="pwc1_compressed_cidr"), + pytest.param("2001:db8::1", False, True, False, True, id="pwc2_compressed_noncidr"), + pytest.param("::ffff:192.0.2.0/120", True, True, False, True, id="pwc3_ipv4_mapped_cidr"), + pytest.param("::ffff:192.0.2.128", False, False, True, True, id="pwc4_ipv4_mapped_noncidr"), + pytest.param("2001:db8:1/64", True, True, True, False, id="pwc5_too_few_cidr"), + pytest.param("2001:db8:1", False, False, False, False, id="pwc6_too_few_noncidr"), + pytest.param("1:2:3:4:5:6:7:8:9", True, False, False, False, id="pwc7_too_many_cidr"), + pytest.param("2001:db8::g", False, True, True, False, id="pwc8_bad_hex_noncidr"), + ], +) +def test_ipv6_isp_pairwise(value, cidr, strict, host_bit, is_valid): + """Verify Pairwise Coverage (PWC) across ipv6 formats and option flags.""" + result = ipv6(value, cidr=cidr, strict=strict, host_bit=host_bit) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "kwargs", "is_valid"), + [ + pytest.param("2001:db8::/32", {"cidr": True}, True, id="cidr_on_with_prefix"), + pytest.param("2001:db8::/32", {"cidr": False}, False, id="cidr_off_with_prefix"), + pytest.param("2001:db8::1", {"cidr": False}, True, id="cidr_off_plain_ip"), + pytest.param("2001:db8::/32", {"strict": True}, True, id="strict_on_with_prefix"), + pytest.param("2001:db8::1", {"strict": True}, False, id="strict_on_without_prefix"), + pytest.param("2001:db8::1", {"strict": False}, True, id="strict_off_without_prefix"), + pytest.param("2001:db8::1", {"cidr": False, "strict": True}, True, id="strict_ignored_when_cidr_off"), + pytest.param("2001:db8::1/64", {"host_bit": True}, True, id="host_bit_on_with_host_bits"), + pytest.param("2001:db8::1/64", {"host_bit": False}, False, id="host_bit_off_with_host_bits"), + pytest.param("2001:db8::/64", {"host_bit": False}, True, id="host_bit_off_network_addr"), + pytest.param("2001:db8::1/128", {"host_bit": False}, True, id="host_bit_off_slash_128"), + pytest.param("2001:db8::1", {"host_bit": False}, True, id="host_bit_off_plain_ip"), + ], +) +def test_ipv6_isp_option_flags(value, kwargs, is_valid): + """Ensure every ipv6 option flag toggles matching valid and invalid inputs.""" + result = ipv6(value, **kwargs) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 3. Logic Coverage (PC, CC, CACC) for compound predicates +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "private", "is_valid"), + [ + # Predicate P1 (_check_private_ip): A or B or C + # A: any(value.startswith(l_bit) for l_bit in {"10.", "192.168.", "169.254.", "127.", "0.0.0.0"}) + # B: re.match(r"^172\.(?:1[6-9]|2\d|3[0-1])\.", value) + # C: re.match(r"^(?:22[4-9]|23[0-9]|24[0-9]|25[0-5])\.", value) + # + # Note: A, B, and C check disjoint leading octets, so at most one clause + # can be True for any given IPv4 address. + pytest.param("10.0.0.1", True, True, id="prefix_10_private"), # A=T, B=F, C=F -> P1=T + pytest.param("10.0.0.1", False, False, id="prefix_10_rejected_as_public"), + pytest.param("192.168.1.1", True, True, id="prefix_192_168_private"), # A=T, B=F, C=F -> P1=T + pytest.param("169.254.1.1", True, True, id="prefix_169_254_link_local"), # A=T, B=F, C=F -> P1=T + pytest.param("127.0.0.1", True, True, id="prefix_127_localhost"), # A=T, B=F, C=F -> P1=T + pytest.param("0.0.0.0", True, True, id="prefix_0_0_0_0_loopback"), # A=T, B=F, C=F -> P1=T + pytest.param("172.16.0.1", True, True, id="range_172_16_private"), # A=F, B=T, C=F -> P1=T + pytest.param("172.31.255.255", True, True, id="range_172_31_private"), # A=F, B=T, C=F -> P1=T + pytest.param("172.16.0.1", False, False, id="range_172_16_rejected_as_public"), + pytest.param("224.0.0.1", True, True, id="range_224_broadcast"), # A=F, B=F, C=T -> P1=T + pytest.param("255.255.255.255", True, True, id="range_255_broadcast"), # A=F, B=F, C=T -> P1=T + pytest.param("224.0.0.1", False, False, id="range_224_rejected_as_public"), + pytest.param("8.8.8.8", False, True, id="public_ip_valid"), # A=F, B=F, C=F -> P1=F + pytest.param("8.8.8.8", True, False, id="public_ip_rejected_as_private"), + ], +) +def test_logic_coverage_private_ip_predicate(value, private, is_valid): + """CACC/CC/PC for _check_private_ip's compound range predicate.""" + result = ipv4(value, private=private) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("func", "value", "strict", "is_valid"), + [ + # Predicate P2 (Section 2.4): D and E + # D: strict + # E: value.count("/") != 1 + pytest.param(ipv4, "192.0.2.1", True, False, id="ipv4_strict_on_no_slash"), # D=T, E=T -> P2=T + pytest.param(ipv4, "192.0.2.0/24/8", True, False, id="ipv4_strict_on_two_slashes"), # D=T, E=T -> P2=T + pytest.param(ipv4, "192.0.2.1", False, True, id="ipv4_strict_off_no_slash"), # D=F, E=T -> P2=F + pytest.param(ipv4, "192.0.2.0/24", True, True, id="ipv4_strict_on_one_slash"), # D=T, E=F -> P2=F + pytest.param(ipv4, "192.0.2.0/24", False, True, id="ipv4_strict_off_one_slash"), # D=F, E=F -> P2=F + pytest.param(ipv6, "2001:db8::1", True, False, id="ipv6_strict_on_no_slash"), # D=T, E=T -> P2=T + pytest.param(ipv6, "2001:db8::/32/64", True, False, id="ipv6_strict_on_two_slashes"),# D=T, E=T -> P2=T + pytest.param(ipv6, "2001:db8::1", False, True, id="ipv6_strict_off_no_slash"), # D=F, E=T -> P2=F + pytest.param(ipv6, "2001:db8::/32", True, True, id="ipv6_strict_on_one_slash"), # D=T, E=F -> P2=F + pytest.param(ipv6, "2001:db8::/32", False, True, id="ipv6_strict_off_one_slash"), # D=F, E=F -> P2=F + ], +) +def test_logic_coverage_strict_cidr_predicate(func, value, strict, is_valid): + """CACC/CC/PC for the strict and value.count('/') != 1 condition in ipv4 and ipv6.""" + result = func(value, cidr=True, strict=strict) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "cidr", "private", "host_bit", "is_valid"), + [ + # Predicate P3 / P4: IPv4Network/IPv4Address(...) and _check_private_ip(value, private) + # Note: IPv4Network/IPv4Address either returns a truthy object or raises an + # exception (caught and turned into False), short-circuiting the right-hand side. + pytest.param("10.0.0.0/8", True, True, False, True, id="cidr_valid_and_private_true"), + pytest.param("10.0.0.0/8", True, False, False, False, id="cidr_valid_and_private_false"), + pytest.param("10.0.0.1/8", True, True, False, False, id="cidr_host_bits_rejected"), + pytest.param("999.0.0.1/8", True, True, True, False, id="cidr_invalid_octet_rejected"), + pytest.param("10.0.0.1", False, True, True, True, id="noncidr_valid_and_private_true"), + pytest.param("10.0.0.1", False, False, True, False, id="noncidr_valid_and_private_false"), + pytest.param("10.0.0.0/8", False, True, True, False, id="noncidr_prefix_rejected"), + pytest.param("999.0.0.1", False, False, True, False, id="noncidr_invalid_octet_rejected"), + ], +) +def test_logic_coverage_ipv4_return_predicates(value, cidr, private, host_bit, is_valid): + """Exercise both sides of the short-circuiting return conjunctions in ipv4.""" + result = ipv4(value, cidr=cidr, private=private, host_bit=host_bit) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 4. Boundary, Branch, and Mutation-Killing Tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "kwargs", "is_valid"), + [ + # Octet value & leading zero boundaries + pytest.param("0.0.0.0", {}, True, id="all_zeros"), + pytest.param("255.255.255.255", {}, True, id="all_255s"), + pytest.param("256.0.0.1", {}, False, id="octet_256"), + pytest.param("192.0.2.-1", {}, False, id="negative_octet"), + pytest.param("01.02.03.04", {}, False, id="leading_zeros_all_octets"), + pytest.param("192.168.01.1", {}, False, id="leading_zero_single_octet"), + # CIDR prefix & netmask boundaries + pytest.param("0.0.0.0/0", {}, True, id="prefix_0"), + pytest.param("192.0.2.1/32", {}, True, id="prefix_32"), + pytest.param("192.0.2.0/255.255.255.0", {}, True, id="dotted_netmask"), + pytest.param("192.0.2.0/33", {}, False, id="prefix_33"), + pytest.param("192.0.2.0/-1", {}, False, id="prefix_negative"), + pytest.param("192.0.2.1/", {}, False, id="trailing_slash"), + pytest.param("192.0.2.1/24/8", {}, False, id="multiple_slashes"), + # Private / local / loopback / broadcast regex boundaries + pytest.param("172.15.255.255", {"private": False}, True, id="172_15_is_public"), + pytest.param("172.16.0.0", {"private": True}, True, id="172_16_lower_bound"), + pytest.param("172.20.0.1", {"private": True}, True, id="172_20_mid_range"), + pytest.param("172.31.255.255", {"private": True}, True, id="172_31_upper_bound"), + pytest.param("172.32.0.0", {"private": False}, True, id="172_32_is_public"), + pytest.param("172.160.0.1", {"private": False}, True, id="172_160_dot_required"), + pytest.param("223.255.255.255", {"private": False}, True, id="223_is_public"), + pytest.param("224.0.0.0", {"private": True}, True, id="224_lower_bound"), + pytest.param("235.0.0.1", {"private": True}, True, id="235_mid_range"), + pytest.param("245.0.0.1", {"private": True}, True, id="245_upper_mid_range"), + pytest.param("255.255.255.255", {"private": True}, True, id="255_upper_bound"), + pytest.param("100.64.0.1", {"private": False}, True, id="100_not_10_dot"), + pytest.param("192.167.1.1", {"private": False}, True, id="192_167_is_public"), + pytest.param("169.253.1.1", {"private": False}, True, id="169_253_is_public"), + pytest.param("0.0.0.0", {"private": False}, False, id="0_0_0_0_rejected_as_public"), + pytest.param("0.0.0.0/8", {"private": True}, True, id="0_0_0_0_cidr_private"), + # Malformed strings & whitespace + pytest.param(" 192.0.2.1", {}, False, id="leading_space"), + pytest.param("192.0.2.1 ", {}, False, id="trailing_space"), + pytest.param("192.0.2.a", {}, False, id="non_digit_octet"), + pytest.param("192..0.1", {}, False, id="empty_octet"), + ], +) +def test_ipv4_boundaries_and_private_ranges(value, kwargs, is_valid): + """Test IPv4 octet, leading-zero, CIDR netmask, and _check_private_ip regex boundaries.""" + result = ipv4(value, **kwargs) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "kwargs", "is_valid"), + [ + # Valid IPv6 representations + pytest.param("2001:0db8:85a3:0000:0000:8a2e:0370:7334", {}, True, id="full_8_hextets"), + pytest.param("2001:DB8::1", {}, True, id="uppercase_hex"), + pytest.param("::", {}, True, id="unspecified_addr"), + pytest.param("::/0", {}, True, id="prefix_0"), + pytest.param("::1/128", {}, True, id="prefix_128"), + pytest.param("::ffff:192.0.2.128", {}, True, id="ipv4_mapped"), + # Invalid IPv6 representations and boundaries + pytest.param("::ffff:192.0.2.1/120", {"host_bit": False}, False, id="ipv4_mapped_host_bits"), + pytest.param("::ffff:256.0.2.128", {}, False, id="ipv4_mapped_bad_octet"), + pytest.param("::1/129", {}, False, id="prefix_129"), + pytest.param("::1/-1", {}, False, id="prefix_negative"), + pytest.param("2001::db8::1", {}, False, id="multiple_double_colons"), + pytest.param("2001:0db80::1", {}, False, id="hextet_over_4_digits"), + pytest.param("abc.0.0.1", {}, False, id="ipv4_style_non_hex"), + pytest.param(" ::1", {}, False, id="leading_space"), + pytest.param("::1/", {}, False, id="trailing_slash"), + pytest.param("::1/64/32", {}, False, id="multiple_slashes"), + ], +) +def test_ipv6_boundaries_and_structure(value, kwargs, is_valid): + """Test IPv6 hextet counts, prefix bounds, IPv4-mapped forms, and syntax errors.""" + result = ipv6(value, **kwargs) + if is_valid: + assert result is True + else: + _assert_invalid(result) \ No newline at end of file diff --git a/tests/length_test.py b/tests/length_test.py index e9691f24..de75d1ab 100644 --- a/tests/length_test.py +++ b/tests/length_test.py @@ -1 +1,218 @@ -#init \ No newline at end of file +#TODO + +"""Tests for validators.length using ISP, Logic Coverage, and boundary/branch checks.""" + +import pytest + +from validators.length import length +from validators.utils import ValidationError + + +def _assert_invalid(result) -> None: + """Confirm invalid validations return a falsy ValidationError.""" + assert isinstance(result, ValidationError) + assert not result + + +# --------------------------------------------------------------------------- +# 1. ISP: Argument type (Table 2 - All validators) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "kwargs", "is_valid"), + [ + pytest.param("something", {"min_val": 2, "max_val": 10}, True, id="str_valid"), + pytest.param("", {"min_val": 0, "max_val": 5}, True, id="str_empty_valid"), + pytest.param(None, {"min_val": 1}, False, id="none"), + pytest.param(0, {"min_val": 0}, False, id="int_zero"), + pytest.param(123, {"min_val": 1}, False, id="int_positive"), + # length() delegates directly to len(value) without checking isinstance(value, str), + # so bytes values succeed when byte length falls within bounds. + pytest.param(b"hello", {"min_val": 1, "max_val": 5}, True, id="bytes_in_range"), + pytest.param(b"hello", {"max_val": 3}, False, id="bytes_out_of_range"), + pytest.param(b"", {"min_val": 1}, False, id="bytes_empty_rejected"), + ], +) +def test_length_argument_types(value, kwargs, is_valid): + """Cover argument types from Table 2 (str, None, int, bytes).""" + result = length(value, **kwargs) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 2. ISP: Pairwise Coverage (PWC) & String-Against-Bounds (Table 2 - length) +# --------------------------------------------------------------------------- +# Full ACoC across (min_val [4] x max_val [4] x String length [5]) yields 80 +# combinations (> 20), many of which are infeasible (e.g., max_val cannot be +# below an unset min_val, and len(value) cannot be below min_val=0). +# These 16 tests cover all feasible parameter pairs across the three factors: +# +# ID | min_val | max_val | String length vs bounds +# ------+----------+--------------+------------------------ +# pwc1 | Unset | Unset | Between +# pwc2 | Unset | Negative | Above maximum +# pwc3 | Unset | >= min_val | At maximum +# pwc4 | Unset | >= min_val | Above maximum +# pwc5 | Negative | Unset | Between +# pwc6 | Negative | Negative | Above maximum +# pwc7 | Negative | >= min_val | Between +# pwc8 | Zero | Unset | At minimum +# pwc9 | Zero | Negative | Above maximum +# pwc10 | Zero | >= min_val | Between +# pwc11 | Zero | >= min_val | At maximum +# pwc12 | Zero | >= min_val | Above maximum +# pwc13 | Positive | Unset | Below minimum +# pwc14 | Positive | Negative | Above maximum +# pwc15 | Positive | >= min_val | Below minimum +# pwc16 | Positive | < min_val | Between + + +@pytest.mark.parametrize( + ("value", "min_val", "max_val", "is_valid"), + [ + pytest.param("hello", None, None, True, id="pwc1_unset_min_unset_max"), + pytest.param("hello", None, -1, False, id="pwc2_unset_min_neg_max"), + pytest.param("hello", None, 5, True, id="pwc3_unset_min_at_max"), + pytest.param("toolong", None, 5, False, id="pwc4_unset_min_above_max"), + pytest.param("hello", -1, None, False, id="pwc5_neg_min_unset_max"), + pytest.param("hello", -1, -2, False, id="pwc6_neg_min_neg_max"), + pytest.param("hi", -1, 5, False, id="pwc7_neg_min_valid_max"), + pytest.param("", 0, None, True, id="pwc8_zero_min_unset_max_at_min"), + pytest.param("a", 0, -1, False, id="pwc9_zero_min_neg_max"), + pytest.param("abc", 0, 5, True, id="pwc10_zero_min_between"), + pytest.param("hello", 0, 5, True, id="pwc11_zero_min_at_max"), + pytest.param("toolong", 0, 5, False, id="pwc12_zero_min_above_max"), + pytest.param("ab", 3, None, False, id="pwc13_pos_min_unset_max_below"), + pytest.param("abc", 3, -1, False, id="pwc14_pos_min_neg_max"), + pytest.param("ab", 3, 5, False, id="pwc15_pos_min_valid_max_below"), + pytest.param("abc", 5, 2, False, id="pwc16_pos_min_inverted_max"), + ], +) +def test_length_isp_pairwise(value, min_val, max_val, is_valid): + """Verify Pairwise Coverage (PWC) across all feasible length ISP characteristics.""" + result = length(value, min_val=min_val, max_val=max_val) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + pytest.param("ab", False, id="below_minimum"), + pytest.param("abc", True, id="at_minimum"), + pytest.param("abcd", True, id="between_bounds"), + pytest.param("abcde", True, id="at_maximum"), + pytest.param("abcdef", False, id="above_maximum"), + ], +) +def test_length_isp_string_against_bounds(value, is_valid): + """Cover all five string-length blocks (below, at min, between, at max, above) for [3, 5].""" + result = length(value, min_val=3, max_val=5) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 3. Logic Coverage (PC, CC, CACC) for compound predicates +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "min_val", "is_valid"), + [ + # Predicate P1 (Section 2.4 example): A and B + # A: min_val is not None + # B: min_val < 0 + # + # Infeasible row: (A=F, B=T) is impossible because min_val < 0 cannot be + # true when min_val is None (and short-circuits in Python). As noted in + # Section 2.4, Predicate Coverage and Clause Coverage cover A while CACC + # covers B via (T, T) vs (T, F). + pytest.param("hello", -1, False, id="min_val_negative"), # A=T, B=T -> P1=T + pytest.param("hello", 0, True, id="min_val_zero"), # A=T, B=F -> P1=F + pytest.param("hello", 2, True, id="min_val_positive"), # A=T, B=F -> P1=F + pytest.param("hello", None, True, id="min_val_none"), # A=F (short-circuits B) -> P1=F + ], +) +def test_logic_coverage_min_val_predicate(value, min_val, is_valid): + """CACC/CC/PC for (min_val is not None and min_val < 0).""" + result = length(value, min_val=min_val, max_val=10) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "max_val", "is_valid"), + [ + # Predicate P2: C and D + # C: max_val is not None + # D: max_val < 0 + # + # Infeasible row: (C=F, D=T) is impossible because max_val < 0 cannot be + # true when max_val is None. + pytest.param("hello", -1, False, id="max_val_negative"), # C=T, D=T -> P2=T + pytest.param("", 0, True, id="max_val_zero"), # C=T, D=F -> P2=F + pytest.param("hello", 5, True, id="max_val_positive"), # C=T, D=F -> P2=F + pytest.param("hello", None, True, id="max_val_none"), # C=F (short-circuits D) -> P2=F + ], +) +def test_logic_coverage_max_val_predicate(value, max_val, is_valid): + """CACC/CC/PC for (max_val is not None and max_val < 0).""" + result = length(value, min_val=0, max_val=max_val) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 4. Boundary, Branch, and Mutation-Killing Tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "min_val", "max_val", "is_valid"), + [ + # Zero-length & zero-bound boundaries (kill `< 0` -> `<= 0` and falsy-zero bugs) + pytest.param("", 0, 0, True, id="empty_exact_zero_bounds"), + pytest.param("", 0, None, True, id="empty_zero_min_only"), + pytest.param("", None, 0, True, id="empty_zero_max_only"), + pytest.param("a", None, 0, False, id="nonempty_zero_max_fails"), + pytest.param("a", 0, None, True, id="min_zero_boundary_not_negative"), + # Negative bound bypass killers (ensure negative check runs before between()) + pytest.param("a", -1, 5, False, id="min_minus_one_with_valid_max"), + pytest.param("a", 0, -1, False, id="max_minus_one_with_valid_min"), + # Exact equal bounds (min_val == max_val) + pytest.param("something", 9, 9, True, id="exact_equal_bounds_match"), + pytest.param("somethin", 9, 9, False, id="exact_equal_bounds_short"), + pytest.param("somethings", 9, 9, False, id="exact_equal_bounds_long"), + # Inverted bounds (min_val > max_val delegated to between()) + pytest.param("abc", 5, 3, False, id="inverted_bounds_equal_to_len"), + pytest.param("abcd", 4, 3, False, id="inverted_bounds_one_apart"), + # Whitespace and Unicode code-point counting via Python len() + pytest.param(" ", 3, 3, True, id="whitespace_counts_as_chars"), + pytest.param("caf\u00e9", 4, 4, True, id="unicode_precomposed_codepoints"), + pytest.param("cafe\u0301", 5, 5, True, id="unicode_decomposed_codepoints"), + pytest.param("\U0001f600", 1, 1, True, id="emoji_single_codepoint"), + # Invalid bound types caught as TypeError -> ValidationError + pytest.param("abc", "2", 5, False, id="non_int_min_val_type_error"), + pytest.param("abc", 1, "5", False, id="non_int_max_val_type_error"), + ], +) +def test_length_boundaries_and_edge_cases(value, min_val, max_val, is_valid): + """Test zero/negative boundaries, equal/inverted bounds, Unicode len(), and bound types.""" + result = length(value, min_val=min_val, max_val=max_val) + if is_valid: + assert result is True + else: + _assert_invalid(result) \ No newline at end of file diff --git a/tests/mac_address_test.py b/tests/mac_address_test.py index e9691f24..58290729 100644 --- a/tests/mac_address_test.py +++ b/tests/mac_address_test.py @@ -1 +1,202 @@ -#init \ No newline at end of file +#TODO + + +"""Tests for validators.mac_address using ISP, Logic Coverage, and boundary/branch checks.""" + +import pytest + +from validators.mac_address import mac_address +from validators.utils import ValidationError + + +def _assert_invalid(result) -> None: + """Confirm invalid validations return a falsy ValidationError.""" + assert isinstance(result, ValidationError) + assert not result + + +# --------------------------------------------------------------------------- +# 1. ISP: Argument type (Table 2 - All validators) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + pytest.param("01:23:45:67:ab:CD", True, id="str_valid"), + pytest.param("", False, id="str_empty"), + pytest.param(None, False, id="none"), + pytest.param(0, False, id="int_zero"), + pytest.param(123, False, id="int_positive"), + pytest.param(b"01:23:45:67:ab:CD", False, id="bytes_mac"), + pytest.param(b"", False, id="bytes_empty"), + ], +) +def test_mac_address_argument_types(value, is_valid): + """Cover argument types from Table 2; non-str types raise TypeError caught as ValidationError.""" + result = mac_address(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 2. ISP: Pairwise Coverage (PWC) & Emptiness (Table 2 - mac_address) +# --------------------------------------------------------------------------- +# Because non-empty ACoC across (Separators [4] x Group count [3] x Hex validity [2]) +# yields 24 combinations (> 20), these 12 tests form a minimal Pairwise Covering +# Array covering every parameter pair, plus the Emptiness block: +# +# ID | Separators | Group count | Hex validity +# -------+-------------+--------------+------------- +# pwc1 | All colons | Too few | All hex +# pwc2 | All colons | Exactly six | Non-hex +# pwc3 | All colons | Too many | All hex +# pwc4 | All hyphens | Too few | Non-hex +# pwc5 | All hyphens | Exactly six | All hex +# pwc6 | All hyphens | Too many | Non-hex +# pwc7 | Mixed | Too few | All hex +# pwc8 | Mixed | Exactly six | Non-hex +# pwc9 | Mixed | Too many | All hex +# pwc10 | None | Too few | Non-hex +# pwc11 | None | Exactly six | All hex +# pwc12 | None | Too many | Non-hex + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + pytest.param("01:23:45:67:ab", False, id="pwc1_colons_few_hex"), + pytest.param("01:23:45:67:ab:zz", False, id="pwc2_colons_six_nonhex"), + pytest.param("01:23:45:67:89:ab:cd", False, id="pwc3_colons_many_hex"), + pytest.param("01-23-45-67-zz", False, id="pwc4_hyphens_few_nonhex"), + pytest.param("01-23-45-67-ab-CD", True, id="pwc5_hyphens_six_hex"), + pytest.param("01-23-45-67-89-ab-zz", False, id="pwc6_hyphens_many_nonhex"), + pytest.param("01:23-45:67-ab", False, id="pwc7_mixed_few_hex"), + pytest.param("01:23:45:67:ab-zz", False, id="pwc8_mixed_six_nonhex"), + pytest.param("01:23:45:67:89:ab-cd", False, id="pwc9_mixed_many_hex"), + pytest.param("01234567gz", False, id="pwc10_none_few_nonhex"), + pytest.param("01234567abCD", False, id="pwc11_none_six_hex"), + pytest.param("0123456789abgz", False, id="pwc12_none_many_nonhex"), + pytest.param("", False, id="empty_string"), + ], +) +def test_mac_address_isp_pairwise_and_empty(value, is_valid): + """Verify Pairwise Coverage (PWC) across mac_address characteristics and Emptiness.""" + result = mac_address(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 3. Logic Coverage (PC, CC, CACC) for compound predicates +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + # Predicate P1 (Section 2.4): A and B + # A: ":" in value + # B: "-" in value + pytest.param("01:23:45:67:89-ab", False, id="both_colon_and_hyphen"), # A=T, B=T -> P1=T + pytest.param("01:23:45:67:ab:CD", True, id="only_colons_valid"), # A=T, B=F -> P1=F + pytest.param("01-23-45-67-ab-CD", True, id="only_hyphens_valid"), # A=F, B=T -> P1=F + pytest.param("01234567abCD", False, id="no_separators"), # A=F, B=F -> P1=F + ], +) +def test_logic_coverage_separator_predicate(value, is_valid): + """CACC/CC/PC for the mixed-separator predicate (':' in value and '-' in value).""" + result = mac_address(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + # Conditional return: re.fullmatch(...) if value else False + pytest.param("", False, id="empty_falsy"), + pytest.param("01:23:45:67:ab:CD", True, id="nonempty_valid_colons"), + pytest.param("01-23-45-67-ab-CD", True, id="nonempty_valid_hyphens"), + pytest.param("01:23:45:67:ab:zz", False, id="nonempty_invalid_format"), + ], +) +def test_logic_coverage_return_condition(value, is_valid): + """Exercise both branches of the conditional return and fullmatch result.""" + result = mac_address(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 4. Boundary, Branch, and Mutation-Killing Tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + # Hex character-class boundaries (0-9, A-F, a-f and adjacent ASCII chars) + pytest.param("00:00:00:00:00:00", True, id="all_zeros"), + pytest.param("99:99:99:99:99:99", True, id="all_nines"), + pytest.param("AA:BB:CC:DD:EE:FF", True, id="uppercase_hex"), + pytest.param("aa:bb:cc:dd:ee:ff", True, id="lowercase_hex"), + pytest.param("01:23:45:67:aB:Cd", True, id="mixed_case_hex"), + pytest.param("/0:00:00:00:00:00", False, id="before_zero_slash"), + pytest.param("0::00:00:00:00:00", False, id="colon_instead_of_digit"), + pytest.param("@0:00:00:00:00:00", False, id="before_upper_a_at"), + pytest.param("G0:00:00:00:00:00", False, id="after_upper_f_g"), + pytest.param("`0:00:00:00:00:00", False, id="before_lower_a_backtick"), + pytest.param("g0:00:00:00:00:00", False, id="after_lower_f_g"), + pytest.param("0g:23:45:67:89:ab", False, id="bad_hex_second_char"), + pytest.param("01:23:45:67:89:G0", False, id="bad_hex_last_group_first"), + pytest.param("01:23:45:67:89:aG", False, id="bad_hex_last_group_second"), + # Group-size {2} and group-count {5} boundaries + pytest.param("1:23:45:67:89:ab", False, id="one_digit_first_group"), + pytest.param("01:2:45:67:89:ab", False, id="one_digit_middle_group"), + pytest.param("01:23:45:67:89:a", False, id="one_digit_last_group"), + pytest.param("012:23:45:67:89:ab", False, id="three_digits_first_group"), + pytest.param("01:23:45:67:89:abc", False, id="three_digits_last_group"), + pytest.param("01:23:45:67:89", False, id="five_groups"), + pytest.param("01:23:45:67:89:ab:cd", False, id="seven_groups"), + pytest.param("01:23:45:67:89:ab:cd:ef", False, id="eui64_eight_groups"), + # Leading, trailing, and repeated separators + pytest.param(":01:23:45:67:89:ab", False, id="leading_colon"), + pytest.param("01:23:45:67:89:ab:", False, id="trailing_colon"), + pytest.param("01:23::45:67:89:ab", False, id="double_colon"), + pytest.param("-01-23-45-67-89-ab", False, id="leading_hyphen"), + pytest.param("01-23-45-67-89-ab-", False, id="trailing_hyphen"), + pytest.param("01-23--45-67-89-ab", False, id="double_hyphen"), + # Unsupported MAC notations + pytest.param("0123.4567.89ab", False, id="cisco_dots"), + pytest.param("0123456789ab", False, id="bare_hex"), + pytest.param("01 23 45 67 89 ab", False, id="spaces"), + pytest.param("01_23_45_67_89_ab", False, id="underscores"), + # Whitespace, newline, and anchor mutation killers (fullmatch vs match) + pytest.param(" 01:23:45:67:89:ab", False, id="leading_space"), + pytest.param("01:23:45:67:89:ab ", False, id="trailing_space"), + pytest.param("01:23:45:67:89:ab\n", False, id="trailing_newline"), + pytest.param("xx01:23:45:67:89:ab", False, id="leading_text"), + pytest.param("01:23:45:67:89:abxx", False, id="trailing_text"), + # Mixed-separator positions + pytest.param("01:23:45:67:89-ab", False, id="mixed_colon_then_hyphen"), + pytest.param("01-23-45-67-89:ab", False, id="mixed_hyphen_then_colon"), + pytest.param("01:23-45:67-89:ab", False, id="mixed_alternating"), + pytest.param("01:23:45:67:89:ab-", False, id="mixed_trailing_hyphen"), + ], +) +def test_mac_address_boundaries_and_format(value, is_valid): + """Test hex bounds, group counts, separator placement, and fullmatch edge cases.""" + result = mac_address(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) \ No newline at end of file diff --git a/tests/test_cmdline_running.md b/tests/test_cmdline_running.md index a34fd292..d49ff982 100644 --- a/tests/test_cmdline_running.md +++ b/tests/test_cmdline_running.md @@ -15,3 +15,18 @@ coverage report -m Need to change the source to be the appropriate validator in the folder Will need to install pytest and coverage in order to run this code. + + +## For domain: + +Need to run with these commands: + +#### 1. Run tests with caching disabled (covers line 38) +coverage run --branch --source=validators.domain -m pytest ./tests/domain_test.py + +#### 2. Run tests with caching enabled (covers line 36 & 39) +PYVLD_CACHE_TLD=True coverage run -a --branch --source=validators.domain -m pytest ./tests/domain_test.py + +#### 3. View combined report +coverage report -m + diff --git a/tests/url_test.py b/tests/url_test.py index e9691f24..f3fe0675 100644 --- a/tests/url_test.py +++ b/tests/url_test.py @@ -1 +1,349 @@ -#init \ No newline at end of file +#TODO +# +# """Tests for validators.url using ISP, Logic Coverage, and boundary/branch checks.""" + +import pytest + +from validators.url import url +from validators.utils import ValidationError + + +def _assert_invalid(result) -> None: + """Confirm invalid validations return a falsy ValidationError.""" + assert isinstance(result, ValidationError) + assert not result + + +# --------------------------------------------------------------------------- +# 1. ISP: Argument type (Table 2 - All validators) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + pytest.param("https://example.com", True, id="str_valid"), + pytest.param("", False, id="str_empty"), + pytest.param(None, False, id="none"), + pytest.param(0, False, id="int_zero"), + pytest.param(123, False, id="int_positive"), + pytest.param(b"https://example.com", False, id="bytes_url"), + pytest.param(b"", False, id="bytes_empty"), + ], +) +def test_url_argument_types(value, is_valid): + """Cover argument types from Table 2; non-str types return ValidationError.""" + result = url(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 2. ISP: Pairwise Coverage (PWC) & Option Flags (Table 2 - url) +# --------------------------------------------------------------------------- +# ACoC across (Scheme [3] x Host form [5] x Whitespace/control [2]) alone yields +# 30 combinations (> 20), before adding option flags. These 15 tests cover every +# pair across all three Table 2 url characteristics: +# +# ID | Scheme | Host form | Whitespace / control +# ------+---------+--------------------+--------------------- +# pwc1 | Valid | Hostname | Absent +# pwc2 | Valid | IPv4 | Absent +# pwc3 | Valid | IPv6 | Present +# pwc4 | Valid | Empty or localhost | Absent +# pwc5 | Valid | Missing | Present +# pwc6 | Invalid | Hostname | Present +# pwc7 | Invalid | IPv4 | Present +# pwc8 | Invalid | IPv6 | Absent +# pwc9 | Invalid | Empty or localhost | Present +# pwc10 | Invalid | Missing | Absent +# pwc11 | file | Hostname | Present +# pwc12 | file | IPv4 | Present +# pwc13 | file | IPv6 | Absent +# pwc14 | file | Empty or localhost | Absent +# pwc15 | file | Missing | Absent + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + pytest.param("https://example.com/path", True, id="pwc1_valid_scheme_hostname"), + pytest.param("http://192.0.2.1/path", True, id="pwc2_valid_scheme_ipv4"), + pytest.param("http://[::1]/path name", False, id="pwc3_valid_scheme_ipv6_space"), + pytest.param("http://localhost/path", False, id="pwc4_valid_scheme_localhost"), + pytest.param("http:///path\t", False, id="pwc5_valid_scheme_missing_tab"), + pytest.param("ftp_bad://example.com/a b", False, id="pwc6_invalid_scheme_host_space"), + pytest.param("javascript://127.0.0.1/\n", False, id="pwc7_invalid_scheme_ipv4_newline"), + pytest.param("gopher://[2001:db8::1]/path", False, id="pwc8_invalid_scheme_ipv6"), + pytest.param("custom://localhost/a b", False, id="pwc9_invalid_scheme_localhost_space"), + pytest.param("example.com/path", False, id="pwc10_missing_scheme_and_host"), + pytest.param("file://example.com/my file", False, id="pwc11_file_hostname_space"), + pytest.param("file://127.0.0.1/\x00", False, id="pwc12_file_ipv4_nul"), + pytest.param("file://[::1]/etc/hosts", True, id="pwc13_file_ipv6"), + pytest.param("file:///etc/hosts", True, id="pwc14_file_empty_host"), + pytest.param("file://:8080/etc/hosts", False, id="pwc15_file_missing_host"), + ], +) +def test_url_isp_pairwise(value, is_valid): + """Verify Pairwise Coverage (PWC) across all Table 2 url characteristics.""" + result = url(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "kwargs", "is_valid"), + [ + pytest.param("http://[::1]", {"skip_ipv6_addr": False}, True, id="skip_ipv6_off"), + pytest.param("http://[::1]", {"skip_ipv6_addr": True}, False, id="skip_ipv6_on"), + pytest.param("http://127.0.0.1", {"skip_ipv4_addr": False}, True, id="skip_ipv4_off"), + pytest.param("http://127.0.0.1", {"skip_ipv4_addr": True}, False, id="skip_ipv4_on"), + pytest.param("http://example.com:8080", {"may_have_port": True}, True, id="may_have_port_on_host"), + pytest.param("http://example.com:8080", {"may_have_port": False}, False, id="may_have_port_off_host"), + pytest.param("http://[::1]:8080", {"may_have_port": True}, True, id="may_have_port_on_ipv6"), + pytest.param("http://[::1]:8080", {"may_have_port": False}, False, id="may_have_port_off_ipv6"), + pytest.param("http://localhost", {"simple_host": True}, True, id="simple_host_on"), + pytest.param("http://localhost", {"simple_host": False}, False, id="simple_host_off"), + pytest.param("https://example.com?a=1&", {"strict_query": False}, True, id="strict_query_off_trailing_amp"), + pytest.param("https://example.com?a=1&", {"strict_query": True}, False, id="strict_query_on_trailing_amp"), + pytest.param("https://example.com", {"consider_tld": True}, True, id="consider_tld_on_valid"), + pytest.param("https://example.notatld", {"consider_tld": True}, False, id="consider_tld_on_unknown"), + pytest.param("https://example.notatld", {"consider_tld": False}, True, id="consider_tld_off_unknown"), + pytest.param("http://10.0.0.1", {"private": True}, True, id="private_true_accepts_private"), + pytest.param("http://10.0.0.1", {"private": False}, False, id="private_false_rejects_private"), + pytest.param("http://8.8.8.8", {"private": False}, True, id="private_false_accepts_public"), + pytest.param("http://8.8.8.8", {"private": True}, False, id="private_true_rejects_public"), + pytest.param("https://example.com.", {"rfc_1034": True}, True, id="rfc1034_on_trailing_dot"), + pytest.param("https://example.com.", {"rfc_1034": False}, False, id="rfc1034_off_trailing_dot"), + pytest.param("https://_http._tcp.example.com", {"rfc_2782": True}, True, id="rfc2782_on_underscore"), + pytest.param("https://_http._tcp.example.com", {"rfc_2782": False}, False, id="rfc2782_off_underscore"), + pytest.param( + "custom://example.com", + {"validate_scheme": lambda s: s == "custom"}, + True, + id="custom_scheme_accepted", + ), + pytest.param( + "https://example.com", + {"validate_scheme": lambda s: s == "custom"}, + False, + id="custom_scheme_rejects_https", + ), + ], +) +def test_url_isp_option_flags(value, kwargs, is_valid): + """Ensure each keyword option flag toggles matching valid and invalid URLs.""" + result = url(value, **kwargs) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 3. Logic Coverage (PC, CC, CACC) for compound predicates +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + # Predicate P1: A or B + # A: not value + # B: re.search(r"[\s\x00-\x1f\x7f]", value) + # + # Note: (A=T, B=T) is infeasible since an empty string has no characters. + pytest.param("", False, id="empty_string"), # A=T -> P1=T + pytest.param("https://example.com/a b", False, id="space_in_url"), # A=F, B=T -> P1=T + pytest.param("https://example.com/\t", False, id="tab_in_url"), # A=F, B=T -> P1=T + pytest.param("https://example.com/\n", False, id="newline_in_url"), # A=F, B=T -> P1=T + pytest.param("https://example.com/\x00", False, id="nul_char_in_url"),# A=F, B=T -> P1=T + pytest.param("https://example.com/\x1f", False, id="unit_sep_in_url"),# A=F, B=T -> P1=T + pytest.param("https://example.com/\x7f", False, id="del_char_in_url"),# A=F, B=T -> P1=T + pytest.param("https://example.com", True, id="no_whitespace_valid"), # A=F, B=F -> P1=F + ], +) +def test_logic_coverage_whitespace_and_control_predicate(value, is_valid): + """CACC/CC/PC for the emptiness and whitespace/control-character guard.""" + result = url(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + # Predicate P2 (is_local_file): C and D + # C: scheme == "file" + # D: netloc in ("", "localhost") + pytest.param("file:///etc/hosts", True, id="file_empty_netloc"), # C=T, D=T -> P2=T + pytest.param("file://localhost/etc/hosts", True, id="file_localhost_netloc"), # C=T, D=T -> P2=T + pytest.param("file://example.com/etc/hosts", True, id="file_domain_netloc"), # C=T, D=F -> P2=F (netloc valid) + pytest.param("file://:8080/etc/hosts", False, id="file_missing_host_port"), # C=T, D=F -> P2=F (netloc fails) + pytest.param("http://localhost/path", False, id="http_localhost_without_simple"), # C=F, D=T -> P2=F + pytest.param("http:///path", False, id="http_empty_netloc"), # C=F, D=T -> P2=F + pytest.param("http://example.com/path", True, id="http_domain_netloc"), # C=F, D=F -> P2=F + ], +) +def test_logic_coverage_is_local_file_predicate(value, is_valid): + """CACC/CC/PC for is_local_file = (scheme == 'file' and netloc in ('', 'localhost')).""" + result = url(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + # Predicate P3: S and (L or N) and O + # S: validate_scheme(scheme) + # L: is_local_file + # N: _validate_netloc(...) + # O: _validate_optionals(...) + pytest.param("https://example.com/path?a=1#frag", True, id="all_parts_valid"), # S=T, L=F, N=T, O=T -> T + pytest.param("unknown://example.com/path?a=1#frag", False, id="invalid_scheme_fails"), # S=F -> F + pytest.param("file:///path?a=1#frag", True, id="file_bypasses_netloc"), # S=T, L=T, N=F, O=T -> T + pytest.param("http:///path?a=1#frag", False, id="http_empty_netloc_fails"), # S=T, L=F, N=F, O=T -> F + pytest.param("https://example.com/path?=", False, id="invalid_query_fails"), # S=T, L=F, N=T, O=F -> F + ], +) +def test_logic_coverage_main_return_predicate(value, is_valid): + """CACC/CC/PC for the top-level scheme, authority/file, and optionals predicate.""" + result = url(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "skip_ipv6_addr", "is_valid"), + [ + # Predicate P4 (_confirm_ipv6_skip): X or Y or Z + # X: skip_ipv6_addr + # Y: value.count(":") < 2 + # Z: not value.startswith("[") + pytest.param("http://[::1]", False, True, id="ipv6_enabled_valid"), # X=F, Y=F, Z=F -> P4=F + pytest.param("http://[::1]", True, False, id="ipv6_skipped_fails"), # X=T, Y=F, Z=F -> P4=T + pytest.param("http://[127.0.0.1]", False, False, id="non_ipv6_in_brackets_fails"), # X=F, Y=T, Z=F -> P4=T + pytest.param("http://::1", False, False, id="unbracketed_ipv6_fails"), # X=F, Y=F, Z=T -> P4=T + ], +) +def test_logic_coverage_confirm_ipv6_skip_predicate(value, skip_ipv6_addr, is_valid): + """CACC/CC/PC for _confirm_ipv6_skip(value, skip_ipv6_addr).""" + result = url(value, skip_ipv6_addr=skip_ipv6_addr) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "strict_query", "is_valid"), + [ + # Predicate P5 (_validate_optionals): + # query and parse_qs(..., separator="&") and parse_qs(..., separator=";") + pytest.param("https://example.com?a=1&b=2;c=3", True, True, id="amp_and_semicolon_valid"), + pytest.param("https://example.com?a=1&", True, False, id="trailing_amp_fails"), + pytest.param("https://example.com?a=1;", True, False, id="trailing_semicolon_fails"), + pytest.param("https://example.com?flag", True, False, id="no_equals_fails_strict"), + pytest.param("https://example.com?flag", False, True, id="no_equals_passes_non_strict"), + pytest.param("https://example.com?=", True, False, id="empty_key_equals_fails_strict"), + ], +) +def test_logic_coverage_query_separator_predicate(value, strict_query, is_valid): + """Verify both '&' and ';' strict query parsing checks in _validate_optionals.""" + result = url(value, strict_query=strict_query) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +# --------------------------------------------------------------------------- +# 4. Boundary, Branch, and Mutation-Killing Tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + pytest.param("file:///path", True, id="scheme_file"), + pytest.param("ftp://example.com", True, id="scheme_ftp"), + pytest.param("ftps://example.com", True, id="scheme_ftps"), + pytest.param("git://example.com", True, id="scheme_git"), + pytest.param("http://example.com", True, id="scheme_http"), + pytest.param("https://example.com", True, id="scheme_https"), + pytest.param("irc://example.com", True, id="scheme_irc"), + pytest.param("rtmp://example.com", True, id="scheme_rtmp"), + pytest.param("rtmps://example.com", True, id="scheme_rtmps"), + pytest.param("rtsp://example.com", True, id="scheme_rtsp"), + pytest.param("sftp://example.com", True, id="scheme_sftp"), + pytest.param("ssh://example.com", True, id="scheme_ssh"), + pytest.param("telnet://example.com", True, id="scheme_telnet"), + pytest.param("HTTPS://example.com", True, id="scheme_uppercase_https"), + pytest.param("mailto:user@example.com", False, id="scheme_mailto_invalid"), + pytest.param("javascript:alert(1)", False, id="scheme_javascript_invalid"), + ], +) +def test_url_schemes(value, is_valid): + """Cover every allowed scheme in _validate_scheme plus unsupported schemes.""" + result = url(value) + if is_valid: + assert result is True + else: + _assert_invalid(result) + + +@pytest.mark.parametrize( + ("value", "is_valid"), + [ + # Auth segment & netloc '@' handling + pytest.param("http://@example.com", True, id="empty_auth"), + pytest.param("http://admin@example.com", True, id="username_only"), + pytest.param("http://admin:hunter1@example.com", True, id="username_and_password"), + pytest.param("http://\u0100admin:pass@example.com", True, id="extended_latin_username"), + pytest.param("http://user:pass:extra@example.com", True, id="multi_colon_auth"), + pytest.param("http://user%20name:a:b@example.com", False, id="multi_colon_decoded_space_fails"), + pytest.param('http://"bad"@example.com', False, id="quoted_username_rejected"), + pytest.param("http://user@extra@example.com", False, id="double_at_netloc_rejected"), + pytest.param("http://user:pa/ss@example.com", False, id="password_slash_rejected"), + pytest.param("http://user:pa?ss@example.com", False, id="password_question_rejected"), + pytest.param("http://user:pa#ss@example.com", False, id="password_hash_rejected"), + pytest.param("http://user:pass@[::1]:8080", True, id="ipv6_with_auth_and_port"), + pytest.param("http://user:pass@[::1]", True, id="ipv6_with_auth_no_port"), + # urlsplit ValueError & port boundaries + pytest.param("http://[::1", False, id="unclosed_ipv6_bracket"), + pytest.param("http://example.com]", False, id="unmatched_closing_bracket"), + pytest.param("http://example.com:65536", False, id="port_out_of_range"), + pytest.param("http://example.com:abc", False, id="non_numeric_port"), + # Path & fragment regex branches + pytest.param("https://example.com/a/b-c_d.e~f!$&'()*+,;=:@%20", True, id="path_allowed_symbols"), + pytest.param("https://example.com/\U0001f600", True, id="path_emoji"), + pytest.param("https://example.com/\U0001f300", True, id="path_pictograph"), + pytest.param("https://example.com/caf\u00e9", True, id="path_unicode_latin"), + pytest.param('http://example.com/">user@example.com', False, id="path_docstring_xss_invalid"), + pytest.param("https://example.com/