DEV Community

TravelHistoryTool
TravelHistoryTool

Posted on

Testing rolling date windows with Schengen 90/180 examples

Published by TravelHistoryTool.

Rolling windows become tricky when records describe intervals rather than individual events. Summing interval lengths can double-count overlapping records; subtracting endpoints can lose a day. A useful test fixture should expose both errors without requiring a large dataset.

Schengen stay dates provide a concrete exercise. This tutorial models the basic 90/180 count for visa-free short stays where that rule applies. The European Commission's short-stay calculator guidance describes checking the reference period for each day of a stay. Article 6 of the Schengen Borders Code counts entry and exit as days of stay.

The examples below are three separate, fictional histories in 2027, with no additional stays. The code is an independent teaching reference, not TravelHistoryTool's production implementation, a benchmark, or a legal eligibility checker.

Define the contract before the loop

Represent a stay as a closed interval [entry, exit] of Python date objects. On a check date t, the reference window is [t - 179 days, t]: both endpoints belong to its 180 dates. Subtracting 180 would accidentally include 181 dates.

For every stay, intersect its interval with that window. Collect the resulting dates into a set, then count the set. This is interval deduplication at the calendar-date level: two records describing the same day must contribute one day, even when their endpoints differ.

Use dates rather than elapsed hours. This exercise assumes entry and exit calendar dates are already established; parsing documents, resolving conflicting records, and assigning dates to timestamps are separate concerns. Reject reversed intervals rather than silently turning them into empty stays.

A small reference implementation

This uses only Python's standard library. Copy both Python blocks, in order, into one file and run it with python3; keep assertions enabled, without -O.

from datetime import date, timedelta

DAY = timedelta(days=1)
d = date.fromisoformat


def covered_dates(stays, on):
    left = on - 179 * DAY
    covered = set()
    for entry, exit in stays:
        if exit < entry:
            raise ValueError("exit precedes entry")
        start, stop = max(entry, left), min(exit, on)
        if start <= stop:
            covered.update(
                start + offset * DAY
                for offset in range((stop - start).days + 1)
            )
    return covered
Enter fullscreen mode Exit fullscreen mode

Clipping happens before expansion, so dates outside the reference window never enter the set. Keeping the dates, rather than returning only an integer, also makes failed tests inspectable. This deliberately straightforward implementation is a reference against which another implementation could be tested; it makes no performance claim.

Turn the three histories into assertions

The first history is 12–16 April: four nights, five dates. The second combines 10–19 February, 5–24 March, and 1 May–29 June: 10 + 20 + 60 = 90. Extending the last interval through 30 June produces 91, because none of those earlier dates has rolled out yet.

The third history is 1–10 January plus 20 June–1 July. Across three check dates, the window starts on 1, 2, and 3 January. Its January contribution falls from ten to eight while its current-stay contribution rises from ten to twelve. The total stays at twenty.

# 1. Inclusive endpoints, including a same-day stay.
april = [(d("2027-04-12"), d("2027-04-16"))]
assert len(covered_dates(april, d("2027-04-16"))) == 5
assert len(covered_dates([(d("2027-04-12"),) * 2],
                         d("2027-04-12"))) == 1
print("April: 5 days")

# 2. Accumulation, duplicate records, and overlapping intervals.
feb = (d("2027-02-10"), d("2027-02-19"))
march = (d("2027-03-05"), d("2027-03-24"))
history = [feb, march, (d("2027-05-01"), d("2027-06-29"))]
check = d("2027-06-29")
base = covered_dates(history, check)
assert len(base) == 90
assert covered_dates(history + [feb], check) == base
assert covered_dates(history + [(d("2027-02-15"), feb[1])], check) == base
extended = history[:2] + [(d("2027-05-01"), d("2027-06-30"))]
assert len(covered_dates(extended, d("2027-06-30"))) == 91
print("Accumulated: 90 days; extended: 91 days")

# 3. Partial roll-off: test components, not just the total.
january = [(d("2027-01-01"), d("2027-01-10"))]
current = [(d("2027-06-20"), d("2027-07-01"))]
for iso, left, old, new in [
    ("2027-06-29", "2027-01-01", 10, 10),
    ("2027-06-30", "2027-01-02", 9, 11),
    ("2027-07-01", "2027-01-03", 8, 12),
]:
    on = d(iso)
    assert on - 179 * DAY == d(left)
    assert len(covered_dates(january, on)) == old
    assert len(covered_dates(current, on)) == new
    assert len(covered_dates(january + current, on)) == 20
    assert covered_dates([(d(left), d(left))], on) == {d(left)}
    assert covered_dates([(d(left) - DAY, d(left) - DAY)], on) == set()
    print(f"{iso}: {old} + {new} = 20; window starts {left}")

assert covered_dates([], check) == set()
assert covered_dates([(d("2027-07-01"), d("2027-07-02"))], check) == set()
try:
    covered_dates([(d("2027-04-16"), d("2027-04-12"))], check)
except ValueError:
    pass
else:
    raise AssertionError("reversed interval accepted")
print("All assertions passed.")
Enter fullscreen mode Exit fullscreen mode

What these tests protect

Testing the January and current-stay contributions separately matters: a correct total could conceal two offsetting errors. The extra boundary assertions distinguish “on the left edge” from “one day too old.” The overlapping-record assertion catches an implementation that merely removes identical interval tuples before summing lengths.

For a larger test suite, add invariants alongside these fixed examples. Reordering records must leave the covered set unchanged. Splitting one valid stay into adjacent intervals must preserve that set. Adding an interval already contained in the union must not change the answer. These properties exercise combinations that a few handpicked totals may miss, without pretending that the reference implementation is a complete specification for every travel situation.

Keep data validation separate from deduplication. A set can prevent repeated dates from inflating a count, but it cannot tell whether a claimed entry or exit actually happened. In an application, retain the source records so ambiguous dates can be reviewed rather than silently “fixed.” Likewise, choose the relevant calendar dates before calling this function; changing a timestamp's timezone inside the counting loop would mix two responsibilities and make a boundary failure harder to diagnose.

A check-date count is not a verdict on an entire itinerary. To examine a planned stay, evaluate every proposed day with the relevant history, not just arrival. The threshold is only one part of applicable entry and stay conditions. This is general information, not legal advice or a guarantee of permission to travel.

Optional related tool

TravelHistoryTool also publishes a Schengen calculator. It is separate from the reference code above; no product is needed to run or adapt these tests.

Top comments (0)