Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

test.diff

import test.diff

test does not re-export this module, so it is reached only by importing it directly.

Structural equality, and the rendering of what two unequal values disagree about.

equal() is what to_equal() is built on, and it is worth knowing exactly how it differs from ==:

==equal()
list, dict, bytescompares contentscompares contents
instancecompares identitycompares class, then every field
NaNnever equal to anythingequal to NaN
-0 and 0equalequal
int and bigintnever equalnever equal
cyclic valueshangscompares, treating a repeated pair as equal

The one that surprises people is instances: Point(1, 2) == Point(1, 2) is false, because two separately constructed objects are two objects. equal() is the one to reach for when what you care about is the contents.

render() turns a failed comparison into lines to print. It picks the shape that shows the most: a line diff for multi-line strings, a character marker for single-line ones, a keyed structural diff for dictionaries and instances, a positional one for lists, and a plain two-line expected/received block for anything else.

Constants

MAX_DIFF_DEPTH

test.diff.MAX_DIFF_DEPTH = 6

MAX_DIFF_LINES

test.diff.MAX_DIFF_LINES = 30

Functions

equal()

test.diff.equal(left, right) -> bool

Whether left and right are structurally equal.

Parameters

  • left (any)
  • right (any)

Returns bool

subset()

test.diff.subset(expected: dict, value) -> bool

Whether every key in subset is present in value with a structurally equal value, ignoring any key value has that subset does not mention.

Nested dictionaries recurse, so { user: { id: 1 } } matches { user: { id: 1, name: 'Ada' } }. Lists do not: a list in subset must equal the list in value outright, since “some of these elements, in no particular place” is a different question and has its own matcher.

Instances are matched by property, so a dictionary of expectations can be checked against a real object.

Parameters

  • subset (dict)
  • value (any)

Returns bool

render()

test.diff.render(expected, received)

The lines to print underneath a failure message, showing what the two values disagree about.

Every line is already coloured and carries no indent of its own; the reporter decides how far in the whole block sits.

import test.diff

for line in diff.render([1, 2, 3], [1, 9, 3]) {
  echo line
}

Parameters

  • expected (any)
  • received (any)

Returns — list: the lines, or an empty list when the two are equal.