File: asserts.py

package info (click to toggle)
alire 1.2.1-2.1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 13,124 kB
  • sloc: ada: 77,497; python: 6,605; sh: 477; ansic: 347; makefile: 258; javascript: 87; xml: 40
file content (59 lines) | stat: -rw-r--r-- 1,765 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
This module provides several helpers to perform user-friendly assertions in
testcases based on Python scripts.
"""

import re
import difflib

from drivers.alr import run_alr

def indent(text, prefix='  '):
    """
    Return `text` indented using `prefix`.
    """
    return '\n'.join(prefix + repr(line) for line in text.splitlines())


def pretty_diff(expected, actual):
    diff = difflib.unified_diff(expected.splitlines(),
                                actual.splitlines(),
                                fromfile='expected',
                                tofile='actual')

    return "\n".join(diff)


def assert_eq(expected, actual, label=None):
    if expected != actual:
        if isinstance(actual, str) and isinstance(expected, str):
            diff = '\nDiff:\n' + pretty_diff(expected, actual)
        else:
            diff = ''

        text = ['Unexpected {}:'.format(label or 'output'),
                'Expecting:',
                indent(str(expected)),
                'But got:',
                indent(str(actual))]
        assert False, '\n'.join(text) + diff


def assert_match(expected_re, actual, label=None, flags=re.S):
    if not re.match(expected_re, actual, flags=flags):
        text = ['Unexpected {}'.format(label or 'output'),
                'Expecting a match on:',
                indent(expected_re),
                'But got:',
                indent(actual)]
        assert False, '\n'.join(text)


def match_solution(regex, escape=False, whole=False):
    "Check whether a regex matches the current solution"
    p = run_alr("with", "--solve")
    wrap = "" if whole else ".*"
    assert_match(wrap +
                 (regex if not escape else re.escape(regex)) +
                 wrap,
                 p.out)