Debian Codegraph @

tests/helper.py

raw
1 # SPDX-FileCopyrightText: © 2023 Christian BUHTZ <[email protected]>
2 #
3 # SPDX-License-Identifier: GPL-3.0-only
4 #
5 # This file is part of the program "Hyperorg" which is released under GNU
6 # General Public License v3 (GPLv3).
7 # See folder LICENSES or go to <https://www.gnu.org/licenses/#GPL>.
8 """Helper functions and data for unit tests.
9
10 Some functions helping with repetitive task while running unittests.
11 """
12 import random
13 import string
14 import re
15
16
17 def rand_string(max_length: int = 25, min_length: int = 1):
18 """Create a string with random uppercase characters and digits. Default
19 length is 25.
20
21 Args:
22 max_length (int): Max length of the string (default: 25).
23 min_length (int): Min string length (default: 1)
24
25 Returns:
26 (string): The created random string.
27 """
28 return ''.join(random.choice(string.ascii_uppercase + string.digits) for _
29 in range(random.randint(min_length, max_length)))
30
31
32 class MockWriter:
33 """Collect all written data.
34
35 https://stackoverflow.com/a/70868549/4865723
36 """
37
38 def __init__(self):
39 self.contents = ''
40
41 def write(self, data):
42 """Add data to the content."""
43 self.contents += data
44
45 def pop_contents(self) -> str:
46 """Return content and remove it from the object."""
47 to_pop = self.contents
48 self.contents = ''
49 return to_pop
50
51
52 def unify_html(html, join_string: str = ' ') -> str:
53 """Createas a unified and comparable HTML string.
54
55 Args:
56 html (str): The HTML string to unify.
57
58 Returns:
59 (str): The unified string
60
61 Beside other modifications mainly newlines and indentions are removed.
62 """
63 unified_html = f'{join_string}'.join(
64 [line.strip() for line in html.split('\n')])
65
66 # remove trailing whitespace
67 unified_html = unified_html.strip()
68
69 unified_html = unified_html.replace(' &nbsp;', '&nbsp;')
70 unified_html = unified_html.replace('&nbsp; ', '&nbsp;')
71
72 # fix line breaks and (multiple) blanks between tags
73 # e.g. "</body> </html>"
74 unified_html = re.sub(r'>\s+<', '><', unified_html)
75
76 return unified_html
77
78
79 def extract_html_hyperorg_content(html, tags='section'):
80 """Extract html part that is related to the 'body' of the content
81 instance.
82
83 By default it is everything between the ``section``-tag.
84 """
85 if isinstance(tags, tuple):
86 tag_open, tag_close = tags
87 else:
88 tag_open = tags
89 tag_close = tags
90
91 # The "single line" mode modifier '(?s)' does take care that this
92 # regex work on multilines two.
93 # Credits: https://stackoverflow.com/a/21766670/4865723
94 # Credits. https://stackoverflow.com/a/75097992/4865723
95 pattern = fr'(?s)<{tag_open}(?: [^>]+)?>(.+?)</{tag_close}>'
96
97 return re.findall(
98 # r'<div id="hyperorg-content">(.+?)<hr /><\/div>',
99 pattern,
100 html,
101 re.M | re.DOTALL)[0].strip()