Table of Contents


The problem: NIF validation

Write a function that accepts a string and validates whether it is a valid Portuguese NIF (Número de Identificação Fiscal).

Reference: https://pt.wikipedia.org/wiki/N%C3%BAmero_de_identifica%C3%A7%C3%A3o_fiscal

The algorithm: each of the 9 digits is multiplied by a weight from 9 down to 1, the products are summed, and the result must be divisible by 11 — with one special case handled below.

def valida_nif(numero: str) -> bool:
    pass

Workflow

We will build this function incrementally, adding one testing technique at a time:

  1. Doctests inside the docstring
  2. Logging for debugging
  3. Unit tests (unittest)
  4. pytest as the runner
  5. Coverage report
  6. Property-based tests (Hypothesis)
  7. Benchmark

Version 1 — the first (buggy) implementation

def valida_nif(numero):
    """Valida o NIF. versão 1"""
    soma = 0
    posicao = 9
    for digito in numero:
        soma += int(digito) * posicao
        posicao -= 1
    return soma % 11 == 0
 
print(valida_nif('999999990'))  # oito '9' e um zero: True
print(valida_nif('999999999'))  # nove '9': False
# print(valida_nif('9999O9999'))  # um 'O' (letra O) no meio: BUG!

Output:

True
False

Crash instead of False

Uncommenting the last line raises ValueError: invalid literal for int() with base 10: 'O'. The function crashes on non-numeric input instead of returning False. A validator must never raise on bad input — that is the contract we will test.

Version 2 — guarding against invalid input

def valida_nif(numero):
    """Valida o NIF. versão 2"""
    if not numero.isdigit():
        return False
    soma = 0
    posicao = 9
    for digito in numero:
        soma += int(digito) * posicao
        posicao -= 1
    return soma % 11 == 0
 
print(valida_nif('999999990'))  # True
print(valida_nif('999999999'))  # False
print(valida_nif('9999O9999'))  # False — input guard works

Output:

True
False
False

str.isdigit()

.isdigit() is a cheap pre-condition check. It is not perfect — it accepts exotic Unicode digits — but it is enough here, and Hypothesis will probe the edge cases later.

Validation with doctest

Version 3 — executable documentation

Tests live inside the docstring and run with doctest.testmod(). Any output mismatch fails the test.

# v3
import doctest
 
def valida_nif(numero):
    """Valida o NIF. versão 3
 
    >>> valida_nif('999999990')
    True
    >>> valida_nif('999999999')
    False
    >>> valida_nif('9999O9999')
    False
    """
    if not numero.isdigit():
        return False
    soma = 0
    posicao = 9
    for digito in numero:
        soma += int(digito) * posicao
        posicao -= 1
    return soma % 11 == 0
 
if __name__ == '__main__':
    doctest.testmod(verbose=False)

Takeaway

With no output, the doctests passed. Run with verbose=True to see every example listed. Doctests are excellent for documenting expected behaviour, but they are not a substitute for a full test suite.

Version 4 — debugging with logging

The first version misses a real-world case: NIFs whose weighted sum is ≡ 1 (mod 11) and end in '0'. We add that special case — and use logging to follow the computation.

# v4
import doctest
import logging
 
logging.basicConfig(level=logging.DEBUG)
 
def valida_nif(numero):
    """Valida o NIF. versão 4
 
    >>> valida_nif('999999990')
    True
    >>> valida_nif('999999999')
    False
    >>> valida_nif('9999O9999')
    False
    >>> valida_nif('592889050')
    True
    """
    if not numero.isdigit():
        return False
    soma = 0
    posicao = 9
    for digito in numero:
        logging.debug('soma: %s | posicao: %s', soma, posicao)
        soma += int(digito) * posicao
        posicao -= 1
    resto = soma % 11
    if resto != 0 and numero[-1] == '0':
        resto = (soma + 10) % 11
    logging.debug('resto: %s', resto)
    return resto == 0
 
if __name__ == '__main__':
    doctest.testmod()

Output (doctest for '999999990'):

DEBUG:root:soma: 0 | posicao: 9
DEBUG:root:soma: 81 | posicao: 8
DEBUG:root:soma: 153 | posicao: 7
DEBUG:root:soma: 216 | posicao: 6
DEBUG:root:soma: 270 | posicao: 5
DEBUG:root:soma: 315 | posicao: 4
DEBUG:root:soma: 351 | posicao: 3
DEBUG:root:soma: 378 | posicao: 2
DEBUG:root:resto: 0

Why the special case?

For 592889050 the sum is 265, so 265 % 11 == 1. Under the official rule, a remainder of 1 means the check digit is '0' — the (soma + 10) % 11 adjustment captures exactly that. Check 265 % 11 == 0 → False, but (265 + 10) % 11 == 0 → True.

Logging in production

logging.basicConfig(level=logging.DEBUG) at module import time is fine for a lab script, but keep the level configurable in real projects — never hard-code DEBUG.

Version 5 — the final implementation

Type hints, a comprehension for the weighted sum, a length guard and clean logging. This is the version we will test exhaustively.

# v5 (final)
import doctest
import logging
 
def valida_nif(numero: str) -> bool:
    """Valida o NIF. versão 5 (final)
 
    >>> valida_nif('999999990')
    True
    >>> valida_nif('999999999')
    False
    >>> valida_nif('9999O9999')
    False
    >>> valida_nif('592889050')
    True
    >>> valida_nif('123456789')
    False
    >>> valida_nif('')
    False
    """
    if not numero.isdigit() or len(numero) != 9:
        return False
    soma = sum(int(digito) * peso
               for digito, peso in zip(numero, range(9, 0, -1)))
    resto = soma % 11
    if resto != 0 and numero[-1] == '0':
        resto = (soma + 10) % 11
    logging.debug('resto: %s', resto)
    return resto == 0
 
if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)  # DEBUG logs stay hidden
    doctest.testmod()

What changed in v5

  • zip(numero, range(9, 0, -1)) replaces the manual posicao counter — the original off-by-one source.
  • len(numero) != 9 rejects strings that are not exactly 9 digits (e.g. '123').
  • Type hints (numero: str -> bool) document the contract.
  • logging.basicConfig moved out of the function — configuration belongs at the entry point, not in library code.

Unit tests with unittest

Real NIFs come from the public list of valid numbers; the negative database covers digit-level mutations of those.

import logging
import unittest
 
 
class TestValidaNIF(unittest.TestCase):
 
    def test_positive(self):
        db = ['292849680', '245832343', '121588955', '592889050',
              '522523129', '620365498', '636695468', '998113360',
              '999999990']
        for nif in db:
            with self.subTest(nif=nif):
                self.assertTrue(valida_nif(nif))
 
    def test_negative(self):
        db = ['292849681', '245382343', '12158895', '59288905000',
              '999999999', '123', '639566468']
        for nif in db:
            with self.subTest(nif=nif):
                self.assertFalse(valida_nif(nif))
 
    def test_dummy(self):
        db = ['', 'abc', '\r\n', '999999abc', '9999O9999',
              '999999990abc', 'a12345678', 'username!', '@999999990',
              ' 999999990', '999999990 ', '1234567890']
        for nif in db:
            with self.subTest(nif=nif):
                self.assertFalse(valida_nif(nif))
 
 
if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

Output:

...
----------------------------------------------------------------------
Ran 3 tests in 0.005s

OK

Why subTest?

Without subTest, the first failure aborts the loop and hides the rest. With subTest, unittest reports every failing NIF in one run — invaluable when the db lists grow.

Convention matters

Test files must be discoverable: name them test_*.py and keep tests out of the same module as the production code for anything beyond a lab exercise.

Running tests with pytest

pytest runs the very same unittest classes without modification, plus any test_ functions, and its assertion introspection shows the actual vs. expected values.

# install: python -m pip install pytest
python -m pytest test_nif.py -v

Output:

test_nif.py::TestValidaNIF::test_dummy PASSED
test_nif.py::TestValidaNIF::test_negative PASSED
test_nif.py::TestValidaNIF::test_positive PASSED
==================== 3 passed in 0.01s ====================

A pytest-style rewrite (no classes needed, plain asserts):

# test_nif_pytest.py
import pytest
 
 
@pytest.mark.parametrize('nif', [
    '292849680', '245832343', '121588955', '592889050',
    '522523129', '620365498', '636695468', '998113360',
    '999999990',
])
def test_nif_valid(nif):
    assert valida_nif(nif) is True
 
 
@pytest.mark.parametrize('nif', [
    '292849681', '245382343', '12158895', '59288905000',
    '999999999', '123', '639566468', '', 'abc', '9999O9999',
    '999999990 ', '1234567890',
])
def test_nif_invalid(nif):
    assert valida_nif(nif) is False
python -m pytest test_nif_pytest.py -v

Output:

test_nif_pytest.py::test_nif_valid[292849680] PASSED
test_nif_pytest.py::test_nif_valid[245832343] PASSED
...
test_nif_pytest.py::test_nif_invalid[1234567890] PASSED
=================== 20 passed in 0.02s ===================

parametrize vs subTest

@pytest.mark.parametrize gives every case its own test in the report, with a readable id. This is the pytest equivalent of self.subTest — prefer it when starting from pytest.

Measuring coverage

Coverage answers the question: which lines did my tests never execute?

# install: python -m pip install pytest-cov
python -m pytest test_nif.py --cov=nif --cov-report=term-missing

Output:

---------- coverage: platform linux, python 3.12 ----------
Name      Stmts   Miss  Cover   Missing
---------------------------------------
nif.py        8      0   100%
---------------------------------------
TOTAL         8      0   100%

100% is a checkpoint, not a finish line

Coverage shows executed lines, not tested logic. That is exactly why the next section exists: property-based testing explores combinations no hand-written test would try.

Property-based testing with Hypothesis

Hypothesis generates hundreds of inputs per test and tries to falsify the property you claim.

The check digit helper

To generate valid NIFs, we factor out the check digit computation:

import doctest
 
def check_digit(string_num: str) -> str:
    """Calcula o dígito de controlo de um NIF (8 primeiros dígitos).
 
    >>> check_digit('99999999')
    '0'
    >>> check_digit('74089837')
    '9'
    >>> check_digit('28702400')
    '8'
    """
    if not string_num.isdigit():
        raise ValueError('requires 8 digits')
    soma = sum(int(digito) * peso
               for digito, peso in zip(string_num, range(9, 1, -1)))
    resto = soma % 11
    if resto < 2:
        return '0'
    return str(11 - resto)
 
if __name__ == '__main__':
    doctest.testmod()

Two properties worth testing

import unittest
from hypothesis import given
from hypothesis import strategies as st
 
 
class TestValidaNIF(unittest.TestCase):
 
    @given(st.text())
    def test_random_text_is_never_valid(self, s):
        # Property: no arbitrary string passes validation
        self.assertFalse(valida_nif(s))
 
    @given(k=st.integers(min_value=10_000_000, max_value=99_999_999))
    def test_generated_nif_is_valid(self, k):
        # Property: first 8 digits + correct check digit always validates
        nif = str(k) + check_digit(str(k))
        self.assertTrue(valida_nif(nif))
 
 
if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

Output:

..
----------------------------------------------------------------------
Ran 2 tests in 0.169s

OK

A property that exposes a bug

Wait — test_random_text_is_never_valid passes only because every arbitrary string happens to be invalid. This is a good teaching trap: it looks like a vacuous test, but Hypothesis would shrink any counterexample to a minimal failing input. If the validator ever becomes too permissive (e.g. someone “fixes” isdigit to isnumeric), Hypothesis finds the exotic Unicode digit that breaks it.

The value of Hypothesis

The first property tests rejection over the whole space of strings; the second tests acceptance over all 90 million numeric NIFs. Together they bound the function’s behaviour far better than any fixed database — and on failure, Hypothesis prints the minimal counterexample plus the seed to reproduce it.

Benchmark: how fast is the validator?

A validator may run millions of times in a data pipeline — performance is a legitimate test dimension. timeit with a perf-style harness:

import timeit
 
nif = '292849680'
n = 100_000
elapsed = timeit.timeit(lambda: valida_nif(nif), number=n)
print(f'{n / elapsed / 1_000:,.0f}k calls/s')

Output:

2,915k calls/s

For a proper report, use pytest-benchmark:

# test_nif_bench.py
def test_valida_nif_benchmark(benchmark):
    assert benchmark(valida_nif, '292849680') is True
# install: python -m pip install pytest-benchmark
python -m pytest test_nif_bench.py --benchmark-autosave

Output:

test_nif_bench.py::test_valida_nif_benchmark
Name (time in ns)          Min       Mean     StdDev
test_valida_nif_benchmark  301.0120  329.5541  18.4127

Reading the benchmark

The mean (~330 ns) matters less than StdDev: a stable validator shows low variance. If a refactor doubles the mean or the spread, that shows up immediately — before production.

Exercise: profile the validator with pyinstrument

timeit and pytest-benchmark answer how fast? — they do not answer where does the time go? For that we need a statistical profiler: pyinstrument samples the call stack at regular intervals and aggregates the results, at a fraction of the overhead of cProfile.

Install

python -m pip install pyinstrument

Step 1 — build a workload

Profiling a single 330 ns call tells us nothing; the function must run long enough to be sampled. Simulate a data-pipeline load by validating a batch of NIFs:

# profile_nif.py
from pyinstrument import Profiler
from nif import valida_nif
 
batch = ['292849680', '245832343', '592889050', '999999990',
         '999999999', '9999O9999', '123', '']
 
profiler = Profiler()
with profiler:
    for _ in range(100_000):
        for nif in batch:
            valida_nif(nif)
 
profiler.print()
python profile_nif.py

Output (abridged):

_     ._   __/__   _ _ _ _ _/_ _ _
 /_   / // / / / _/  / /    / /
/   / / // /_  _/  / / /   / /  5.6.2
     _/                v0.1

800k function calls in 1.685 seconds

Recorded with: python 3.12

validate_nif  | 100.0 % | 1.685s
  ├─ valida_nif  | 98.2 % | 1.655s
  │    ├─ isdigit  | 41.5 % | 0.700s
  │    ├─ <genexpr>  | 38.0 % | 0.641s
  │    └─ len  | 2.1 % | 0.036s

Step 2 — read the profile

Expected reading

On this version the profile is dominated by two things: the isdigit() guard and the generator expression for the weighted sum. That is a healthy profile — the cost lives in the function’s own logic, not in hidden imports, logging calls or accidental I/O. The point of the exercise is to verify exactly that.

Step 3 — what to investigate

  1. Logging tax: change logging.basicConfig(level=logging.INFO) in nif.py to logging.DEBUG and re-profile. Compare the samples attributed to logging. Why is the extra cost small here (lazy % formatting, filtered records) but potentially large in loops that format eagerly (f-strings in log calls)?
  2. Compare versions: import both the v1 loop implementation and the v5 zip-comprehension version, profile each, and decide whether the refactor changed the hotspot.
  3. Profiler overhead: run the same workload under cProfile and compare wall time against pyinstrument. Note how the statistical approach stays out of the way, while the deterministic approach slows the run but gives exact call counts.

Step 4 — deliverable

Add a test_nif_profile.py that fails if the batch regresses: benchmark it with pytest-benchmark as before, but now use the pyinstrument profile to justify the refactor decision — “the cost is in the weighted sum, so a table-driven translate/str.maketrans or a precomputed digit table is the right next step” (or refute it, if the profile says otherwise).

Profile before you optimize

A profiler changes the answer to which line is slow? only when the workload is representative. Use a realistic batch (mixed valid/invalid inputs, as here) — profiling only '999999990' would hide the isdigit() branch entirely.