summaryrefslogtreecommitdiff
path: root/creole/tests/utils/utils.py
blob: 005f6c404cc8b689b4968280ecf64d29e0bc6b3b (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# coding: utf-8


"""
    unitest generic utils
    ~~~~~~~~~~~~~~~~~~~~~

    Generic utils useable for a markup test.

    :copyleft: 2008-2011 by python-creole team, see AUTHORS for more details.
    :license: GNU GPL v3 or above, see LICENSE for more details.
"""


import difflib
import textwrap
import unittest

# error output format:
# =1 -> via repr()
# =2 -> raw
VERBOSE = 1
#VERBOSE = 2


def make_diff(block1, block2):
    d = difflib.Differ()

    block1 = block1.replace("\\n", "\\n\n").split("\n")
    block2 = block2.replace("\\n", "\\n\n").split("\n")

    diff = d.compare(block1, block2)

    result = ["%2s %s\n" % (line, i) for line, i in enumerate(diff)]
    return "".join(result)


class MarkupTest(unittest.TestCase):
    """
    Special error class: Try to display markup errors in a better way.
    """

    def _format_output(self, txt):
        txt = txt.split("\\n")
        if VERBOSE == 1:
            txt = "".join(['%s\\n\n' % i for i in txt])
        elif VERBOSE == 2:
            txt = "".join(['%s\n' % i for i in txt])
        return txt

    def assertEqual(self, first, second, msg=""):
        if first == second:
            return

        try:
            diff = make_diff(first, second)
        except AttributeError:
            raise self.failureException(f"{first!r} is not {second!r}")

        print("*" * 100)
        print("---[Output:]-----------------------------------------------------------------------------------------")
        print(first)
        print("---[not equal to:]-----------------------------------------------------------------------------------")
        print(second)
        print("---[diff:]-------------------------------------------------------------------------------------------")
        print(diff)
        print("*" * 100)

        assert first == second, f"{first!r} is not {second!r}"

    def _prepare_text(self, txt):
        """
        prepare the multiline, indentation text.
        """
        # Remove any common leading whitespace from every line
        txt = textwrap.dedent(txt)

        # Strip spaces and every line end and remove the last line ending:
        txt = "\n".join(line.rstrip(" ") for line in txt.splitlines())

        # strip *one* newline at the beginning...
        if txt.startswith("\n"):
            txt = txt[1:]

        return txt