emtest 0.0.9__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- _auto_run_with_pytest/__init__.py +32 -0
- emtest/__init__.py +20 -0
- emtest/log_recording.py +154 -0
- emtest/log_utils.py +29 -0
- emtest/pytest_utils.py +176 -0
- emtest/testing_utils.py +159 -0
- emtest-0.0.9.dist-info/METADATA +108 -0
- emtest-0.0.9.dist-info/RECORD +12 -0
- emtest-0.0.9.dist-info/WHEEL +5 -0
- emtest-0.0.9.dist-info/licenses/LICENSE +18 -0
- emtest-0.0.9.dist-info/licenses/LICENSE-CC0 +121 -0
- emtest-0.0.9.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Rerun the orignially executed python script in pytest instead of python."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from emtest import run_pytest
|
|
7
|
+
|
|
8
|
+
# Configuration for standalone execution
|
|
9
|
+
|
|
10
|
+
path_parts = sys.argv[0].split(os.sep)
|
|
11
|
+
if not (
|
|
12
|
+
path_parts[-1] == "pytest"
|
|
13
|
+
or (
|
|
14
|
+
len(path_parts) > 1
|
|
15
|
+
and path_parts[-2] == "pytest"
|
|
16
|
+
and path_parts[-1] == "__main__.py"
|
|
17
|
+
)
|
|
18
|
+
):
|
|
19
|
+
test_file = os.path.abspath(sys.argv[0])
|
|
20
|
+
pytest_args = sys.argv[1:]
|
|
21
|
+
# print("RERUNNING IN PYTEST:", test_file)
|
|
22
|
+
|
|
23
|
+
# Use emtest's custom test runner with specific settings:
|
|
24
|
+
run_pytest(
|
|
25
|
+
test_path=test_file, # Run tests in this file
|
|
26
|
+
pytest_args=pytest_args,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
sys.exit(-1)
|
|
30
|
+
else:
|
|
31
|
+
# print("ALREADY RUNNING IN PYTEST")
|
|
32
|
+
pass
|
emtest/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from .pytest_utils import (
|
|
2
|
+
run_pytest,
|
|
3
|
+
configure_pytest_reporter,
|
|
4
|
+
env_vars,
|
|
5
|
+
get_pytest_report_dirs,
|
|
6
|
+
get_pytest_report_files,
|
|
7
|
+
)
|
|
8
|
+
from .testing_utils import (
|
|
9
|
+
add_path_to_python,
|
|
10
|
+
assert_is_loaded_from_source,
|
|
11
|
+
polite_wait,
|
|
12
|
+
await_thread_cleanup,
|
|
13
|
+
get_thread_names,
|
|
14
|
+
set_env_var,
|
|
15
|
+
are_we_in_docker,
|
|
16
|
+
make_dir,
|
|
17
|
+
delete_path,
|
|
18
|
+
ensure_dirs_exist,
|
|
19
|
+
ensure_dir_exists,
|
|
20
|
+
)
|
emtest/log_recording.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""In-memory log recording utilities for Python's logging framework.
|
|
2
|
+
|
|
3
|
+
This module provides a `RecordingHandler` and helper methods to
|
|
4
|
+
dynamically attach and detach in-memory log recorders to standard
|
|
5
|
+
`logging.Logger` instances. It allows recording log output programmatically
|
|
6
|
+
for testing, debugging, or analysis without relying on files or streams.
|
|
7
|
+
|
|
8
|
+
Example:
|
|
9
|
+
>>> import logging
|
|
10
|
+
>>> import emtest.log_recording
|
|
11
|
+
>>> logger = logging.getLogger("demo")
|
|
12
|
+
>>> logger.setLevel(logging.INFO)
|
|
13
|
+
>>> logger.start_recording() # Start recording logs
|
|
14
|
+
>>> logger.info("Hello world")
|
|
15
|
+
>>> logs = logger.get_recording()
|
|
16
|
+
>>> print(logs)
|
|
17
|
+
['2025-10-18 10:00:00,000 [INFO] Hello world']
|
|
18
|
+
>>> logger.stop_recording() # Stop and remove recorder
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import logging
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RecordingHandler(logging.Handler):
|
|
25
|
+
"""A logging handler that buffers formatted log records in memory.
|
|
26
|
+
|
|
27
|
+
This handler captures each emitted log record, formats it,
|
|
28
|
+
and stores the resulting string in an internal list.
|
|
29
|
+
It is useful for unit tests or scenarios where log output
|
|
30
|
+
needs to be inspected programmatically.
|
|
31
|
+
|
|
32
|
+
Attributes:
|
|
33
|
+
formatter (logging.Formatter): The formatter used to format log messages.
|
|
34
|
+
_records (list[str]): Internal buffer of recorded log messages.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, formatter: logging.Formatter):
|
|
38
|
+
"""Initialize the handler with a specific formatter.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
formatter (logging.Formatter): Formatter to apply to each log record.
|
|
42
|
+
"""
|
|
43
|
+
super().__init__()
|
|
44
|
+
self.formatter = formatter
|
|
45
|
+
self._records: list[str] = []
|
|
46
|
+
|
|
47
|
+
def emit(self, record: logging.LogRecord):
|
|
48
|
+
"""Store a formatted log record in the internal buffer.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
record (logging.LogRecord): The log record to handle.
|
|
52
|
+
"""
|
|
53
|
+
self._records.append(self.format(record))
|
|
54
|
+
|
|
55
|
+
def get_records(self) -> list[str]:
|
|
56
|
+
"""Retrieve the recorded log messages.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
list[str]: A copy of the list of formatted log messages.
|
|
60
|
+
"""
|
|
61
|
+
return list(self._records)
|
|
62
|
+
|
|
63
|
+
def clear(self):
|
|
64
|
+
"""Clear all recorded log messages from the buffer."""
|
|
65
|
+
self._records.clear()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def start_recording(self: logging.Logger, name: str | None = None):
|
|
69
|
+
"""Start recording logs to a named recorder.
|
|
70
|
+
|
|
71
|
+
This function dynamically attaches a `RecordingHandler` to the logger.
|
|
72
|
+
If a recorder with the given name already exists, it does nothing.
|
|
73
|
+
|
|
74
|
+
The recorder uses the formatter from the first existing handler
|
|
75
|
+
if available, or falls back to a default formatter.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
self (logging.Logger): The logger instance.
|
|
79
|
+
name (str | None): Optional name of the recorder. Defaults to `"__default__"`.
|
|
80
|
+
|
|
81
|
+
Example:
|
|
82
|
+
>>> logger.start_recording("test")
|
|
83
|
+
>>> logger.info("Message")
|
|
84
|
+
"""
|
|
85
|
+
if name is None:
|
|
86
|
+
name = "__default__"
|
|
87
|
+
|
|
88
|
+
# Ensure the logger has a dict of recording handlers attached
|
|
89
|
+
if not hasattr(self, "_recording_handlers"):
|
|
90
|
+
self._recording_handlers = {}
|
|
91
|
+
if name in self._recording_handlers:
|
|
92
|
+
return # already recording under this name
|
|
93
|
+
|
|
94
|
+
# Use same formatter as first handler, or fallback
|
|
95
|
+
if self.handlers:
|
|
96
|
+
formatter = self.handlers[0].formatter
|
|
97
|
+
else:
|
|
98
|
+
formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
|
|
99
|
+
|
|
100
|
+
handler = RecordingHandler(formatter)
|
|
101
|
+
self.addHandler(handler)
|
|
102
|
+
self._recording_handlers.update({name: handler})
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def stop_recording(self: logging.Logger, name: str | None = None):
|
|
106
|
+
"""Stop and remove a named recorder from the logger.
|
|
107
|
+
|
|
108
|
+
If no recorder exists for the given name, the function does nothing.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
self (logging.Logger): The logger instance.
|
|
112
|
+
name (str | None): Optional name of the recorder to stop.
|
|
113
|
+
Defaults to `"__default__"`.
|
|
114
|
+
|
|
115
|
+
Example:
|
|
116
|
+
>>> logger.stop_recording("test")
|
|
117
|
+
"""
|
|
118
|
+
if name is None:
|
|
119
|
+
name = "__default__"
|
|
120
|
+
|
|
121
|
+
handler = self._recording_handlers.get(name, None)
|
|
122
|
+
if handler:
|
|
123
|
+
self.removeHandler(handler)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def get_recording(self: logging.Logger, name: str | None = None) -> list[str]:
|
|
127
|
+
"""Retrieve the recorded log messages for a named recorder.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
self (logging.Logger): The logger instance.
|
|
131
|
+
name (str | None): Optional name of the recorder. Defaults to `"__default__"`.
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
list[str]: A list of formatted log messages recorded so far.
|
|
135
|
+
Returns an empty list if no handler is found for the name.
|
|
136
|
+
|
|
137
|
+
Raises:
|
|
138
|
+
KeyError: If the recorder with the specified name does not exist.
|
|
139
|
+
|
|
140
|
+
Example:
|
|
141
|
+
>>> messages = logger.get_recording("test")
|
|
142
|
+
>>> print(messages)
|
|
143
|
+
"""
|
|
144
|
+
if name is None:
|
|
145
|
+
name = "__default__"
|
|
146
|
+
|
|
147
|
+
handler = self._recording_handlers[name]
|
|
148
|
+
return handler.get_records() if handler else []
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# Monkey-patch Logger with recording methods
|
|
152
|
+
logging.Logger.start_recording = start_recording
|
|
153
|
+
logging.Logger.stop_recording = stop_recording
|
|
154
|
+
logging.Logger.get_recording = get_recording
|
emtest/log_utils.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import appdirs
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def get_app_log_dir(app_name: str, app_family: str = ""):
|
|
6
|
+
"""Get the directory to store this app's logs in.
|
|
7
|
+
|
|
8
|
+
If an environment variable APP_NAME_LOG_DIR is set, returns that.
|
|
9
|
+
If APP_FAMILY_LOG_DIR is set in env, returns APP_FAMILY_LOG_DIR/APP_NAME.
|
|
10
|
+
Otherwise, returns the standard user log dir (e.g. ~/.local/log/APP_NAME.).
|
|
11
|
+
"""
|
|
12
|
+
# check environment variables
|
|
13
|
+
env_app_log_dir = os.environ.get(f"{app_name.upper()}_LOG_DIR", None)
|
|
14
|
+
env_family_log_dir = os.environ.get(f"{app_family.upper()}_LOG_DIR", None)
|
|
15
|
+
|
|
16
|
+
# decide which log dir to use
|
|
17
|
+
log_dir = ""
|
|
18
|
+
if env_app_log_dir:
|
|
19
|
+
log_dir = env_app_log_dir
|
|
20
|
+
elif env_family_log_dir and app_family:
|
|
21
|
+
log_dir = os.path.join(env_family_log_dir, app_name)
|
|
22
|
+
else:
|
|
23
|
+
log_dir = os.path.join(appdirs.user_log_dir(), app_name)
|
|
24
|
+
|
|
25
|
+
# ensure log dir exists
|
|
26
|
+
if not os.path.exists(log_dir):
|
|
27
|
+
os.makedirs(log_dir)
|
|
28
|
+
|
|
29
|
+
return log_dir
|
emtest/pytest_utils.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
import pytest
|
|
3
|
+
from .testing_utils import set_env_var
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from typing import Any, Optional
|
|
7
|
+
from _pytest.terminal import TerminalReporter
|
|
8
|
+
from _pytest.config import Config
|
|
9
|
+
from _pytest.reports import TestReport
|
|
10
|
+
from termcolor import colored
|
|
11
|
+
|
|
12
|
+
from environs import Env
|
|
13
|
+
|
|
14
|
+
env_vars = Env()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MinimalReporter(TerminalReporter):
|
|
18
|
+
"""Custom pytest reporter that provides clean, minimal output with colored symbols.
|
|
19
|
+
|
|
20
|
+
This reporter suppresses most default pytest output and displays only:
|
|
21
|
+
- ✓ for passed tests (green)
|
|
22
|
+
- ✗ for failed tests (red)
|
|
23
|
+
- - for skipped tests (yellow)
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, config: Config, print_errors: bool = True) -> None:
|
|
27
|
+
super().__init__(config)
|
|
28
|
+
self._tw.hasmarkup = True # enables colored output safely
|
|
29
|
+
self.print_errors = print_errors
|
|
30
|
+
self.current_test_file = ""
|
|
31
|
+
|
|
32
|
+
def report_collect(self, final: bool = False) -> None:
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
def pytest_collection(self) -> None:
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
def pytest_sessionstart(self, session: Any) -> None:
|
|
39
|
+
"""Override session start to suppress 'collected x items' message."""
|
|
40
|
+
# print("pytest_sessionstart")
|
|
41
|
+
pass # suppress "collected x items"
|
|
42
|
+
|
|
43
|
+
def pytest_runtest_logstart(self, nodeid: str, location: Any) -> None:
|
|
44
|
+
"""Override test start logging to suppress it."""
|
|
45
|
+
# print("pytest_runtest_logstart")
|
|
46
|
+
current_test_file = os.path.basename(location[0]).strip(".py")
|
|
47
|
+
if current_test_file != self.current_test_file:
|
|
48
|
+
self.current_test_file = current_test_file
|
|
49
|
+
print(f"\n{self.current_test_file}")
|
|
50
|
+
pass # suppress test start lines
|
|
51
|
+
|
|
52
|
+
def pytest_runtest_logreport(self, report: TestReport) -> None:
|
|
53
|
+
"""Display minimal test results with colored symbols."""
|
|
54
|
+
if report.when != "call":
|
|
55
|
+
return
|
|
56
|
+
|
|
57
|
+
test_name = report.nodeid.split("::")[-1]
|
|
58
|
+
if report.passed:
|
|
59
|
+
self.write("✓", green=True)
|
|
60
|
+
# symbol = colored("✓", "green")
|
|
61
|
+
elif report.failed:
|
|
62
|
+
self.write("✗", red=True)
|
|
63
|
+
# symbol = colored("✗", "red")
|
|
64
|
+
elif report.skipped:
|
|
65
|
+
self.write("-", yellow=True)
|
|
66
|
+
# symbol = colored("-", "yellow")
|
|
67
|
+
# self.write(f"{symbol} {test_name}")
|
|
68
|
+
|
|
69
|
+
self.write(f" {test_name}\n")
|
|
70
|
+
|
|
71
|
+
if self.print_errors and report.failed:
|
|
72
|
+
print(colored(report.longreprtext, "red"))
|
|
73
|
+
|
|
74
|
+
def summary_stats(self) -> None:
|
|
75
|
+
"""Override result counts to suppress them."""
|
|
76
|
+
pass # suppress result counts
|
|
77
|
+
|
|
78
|
+
def pytest_terminal_summary(
|
|
79
|
+
self, terminalreporter: Any, exitstatus: int, config: Config
|
|
80
|
+
) -> None:
|
|
81
|
+
"""Override final summary output to suppress it."""
|
|
82
|
+
pass # suppress final summary output
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# Environment Variable and CLI option to deactivate MinimalReporter
|
|
86
|
+
PYTEST_STANDARD_OUTPUT_ENV = "DEFAULT_TERMINAL_REPORTER"
|
|
87
|
+
PYTEST_STANDARD_OUTPUT_OPT = "--default-terminal-reporter"
|
|
88
|
+
if PYTEST_STANDARD_OUTPUT_OPT in sys.argv:
|
|
89
|
+
set_env_var(PYTEST_STANDARD_OUTPUT_ENV, "1", True)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def configure_pytest_reporter(config: Config, print_errors=True) -> None:
|
|
93
|
+
"""Configure the minimal reporter if terminalreporter plugin is disabled.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
config: Pytest configuration object
|
|
97
|
+
"""
|
|
98
|
+
if env_vars.bool(PYTEST_STANDARD_OUTPUT_ENV, default=False):
|
|
99
|
+
return
|
|
100
|
+
minimal_reporter = MinimalReporter(config, print_errors=print_errors)
|
|
101
|
+
# if terminalreporter plugin is disabled
|
|
102
|
+
if "no:terminalreporter" in config.option.plugins:
|
|
103
|
+
pluginmanager = config.pluginmanager
|
|
104
|
+
pluginmanager.register(minimal_reporter, "minimal-reporter")
|
|
105
|
+
|
|
106
|
+
if config.pluginmanager.has_plugin("terminalreporter"):
|
|
107
|
+
reporter = config.pluginmanager.get_plugin("terminalreporter")
|
|
108
|
+
config.pluginmanager.unregister(reporter, "terminalreporter")
|
|
109
|
+
config.pluginmanager.register(minimal_reporter, "terminalreporter")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def run_pytest(
|
|
113
|
+
test_path: str,
|
|
114
|
+
breakpoints: bool = False,
|
|
115
|
+
enable_print: bool = False,
|
|
116
|
+
pytest_args: list[str] | None = None,
|
|
117
|
+
) -> None:
|
|
118
|
+
"""Run pytest with customizable options for output control and debugging.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
test_path: Path to the test file or directory to run
|
|
122
|
+
breakpoints: If True, enables pytest debugger (--pdb) on failures
|
|
123
|
+
deactivate_pytest_output: If True, uses minimal reporter instead of default output
|
|
124
|
+
enable_print: If True, enables print statements in tests (-s flag)
|
|
125
|
+
"""
|
|
126
|
+
if pytest_args:
|
|
127
|
+
args = pytest_args
|
|
128
|
+
if PYTEST_STANDARD_OUTPUT_OPT in args:
|
|
129
|
+
args.remove(PYTEST_STANDARD_OUTPUT_OPT)
|
|
130
|
+
else:
|
|
131
|
+
args = []
|
|
132
|
+
if enable_print:
|
|
133
|
+
args.append("-s") # -s disables output capturing
|
|
134
|
+
if breakpoints:
|
|
135
|
+
args.append("--pdb")
|
|
136
|
+
os.system(f"{sys.executable} -m pytest {test_path} {' '.join(args)}")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def get_pytest_report_files(config: pytest.Config) -> set[Path]:
|
|
140
|
+
"""
|
|
141
|
+
Collect all pytest report output files.
|
|
142
|
+
"""
|
|
143
|
+
paths: set[Path] = set()
|
|
144
|
+
|
|
145
|
+
# JUnit XML
|
|
146
|
+
junitxml = config.getoption("--junitxml", default=None)
|
|
147
|
+
if junitxml:
|
|
148
|
+
paths.add(Path(junitxml).resolve())
|
|
149
|
+
|
|
150
|
+
# pytest-html
|
|
151
|
+
htmlpath = getattr(config.option, "htmlpath", None)
|
|
152
|
+
if htmlpath:
|
|
153
|
+
paths.add(Path(htmlpath).resolve())
|
|
154
|
+
|
|
155
|
+
# pytest-json-report
|
|
156
|
+
json_report_file = getattr(config.option, "json_report_file", None)
|
|
157
|
+
if json_report_file:
|
|
158
|
+
paths.add(Path(json_report_file).resolve())
|
|
159
|
+
return paths
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def get_pytest_report_dirs(
|
|
163
|
+
config: pytest.Config, fallback_to_cwd: bool = False
|
|
164
|
+
) -> set[Path]:
|
|
165
|
+
"""
|
|
166
|
+
Collect all pytest report output directories, deduplicated.
|
|
167
|
+
"""
|
|
168
|
+
dirs: set[Path] = set(
|
|
169
|
+
[report_path.parent for report_path in get_pytest_report_files(config)]
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
# Fallback if no reports were configured
|
|
173
|
+
if fallback_to_cwd and not dirs:
|
|
174
|
+
dirs.add(Path.cwd())
|
|
175
|
+
|
|
176
|
+
return dirs
|
emtest/testing_utils.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
import shutil
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from time import sleep
|
|
7
|
+
from typing import List
|
|
8
|
+
from tqdm import TMonitor, tqdm
|
|
9
|
+
|
|
10
|
+
from types import ModuleType
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def are_we_in_docker() -> bool:
|
|
14
|
+
"""Check if this code is running in a docker container."""
|
|
15
|
+
return os.path.exists("/.dockerenv")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def add_path_to_python(src_path: str) -> None:
|
|
19
|
+
"""Add a directory to the Python path for importing modules.
|
|
20
|
+
|
|
21
|
+
Removes the path if it already exists, then inserts it at the beginning
|
|
22
|
+
of sys.path to ensure it takes priority over installed packages.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
src_path: Directory path to add to Python path
|
|
26
|
+
|
|
27
|
+
Raises:
|
|
28
|
+
FileNotFoundError: If the path doesn't exist
|
|
29
|
+
NotADirectoryError: If the path is not a directory
|
|
30
|
+
"""
|
|
31
|
+
src_path = os.path.abspath(src_path)
|
|
32
|
+
if not os.path.exists(src_path):
|
|
33
|
+
raise FileNotFoundError(f"The path doesn't exist: {src_path}")
|
|
34
|
+
if not os.path.isdir(src_path):
|
|
35
|
+
raise NotADirectoryError(f"The path doesn't exist: {src_path}")
|
|
36
|
+
|
|
37
|
+
if src_path in sys.path:
|
|
38
|
+
sys.path.remove(src_path)
|
|
39
|
+
sys.path.insert(0, src_path)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def assert_is_loaded_from_source(
|
|
43
|
+
source_dir: str, module: ModuleType, print_confirmation=False
|
|
44
|
+
) -> None:
|
|
45
|
+
"""Assert a module is loaded from source code, not an installation.
|
|
46
|
+
|
|
47
|
+
Asserts that the loaded module's source code is located within the given
|
|
48
|
+
directory, regardless of whether it's file is located in that folder or is
|
|
49
|
+
nested in subfolders.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
source_dir: a directory in which the module's source should be
|
|
53
|
+
module: the module to check
|
|
54
|
+
"""
|
|
55
|
+
module_path = os.path.abspath(module.__file__)
|
|
56
|
+
source_path = os.path.abspath(source_dir)
|
|
57
|
+
assert source_path in module_path, (
|
|
58
|
+
f"The module `{module.__name__}` has been loaded from an installion, "
|
|
59
|
+
"not this source code!\n"
|
|
60
|
+
f"Desired source dir: {source_path}\n"
|
|
61
|
+
f"Loaded module path: {module_path}\n"
|
|
62
|
+
)
|
|
63
|
+
if print_confirmation:
|
|
64
|
+
print(f"Using module {module.__name__} from {module_path}")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def polite_wait(n_sec: int) -> None:
|
|
68
|
+
"""Wait for the given duration, displaying a progress bar.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
n_sec: Number of seconds to wait
|
|
72
|
+
"""
|
|
73
|
+
# print(f"{n_sec}s patience...")
|
|
74
|
+
for i in tqdm(range(n_sec), leave=False):
|
|
75
|
+
time.sleep(1)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def await_thread_cleanup(
|
|
79
|
+
timeout: int = 5, print_remaining_threads: bool = True
|
|
80
|
+
) -> bool:
|
|
81
|
+
"""Wait for all threads to exit, with a timeout and progress bar.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
timeout: Maximum seconds to wait for thread cleanup
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
True if only the main thread remains, False if other threads persist
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def get_threads() -> List[threading.Thread]:
|
|
91
|
+
"""Get all active threads except tqdm monitor threads."""
|
|
92
|
+
return [x for x in threading.enumerate() if not isinstance(x, TMonitor)]
|
|
93
|
+
|
|
94
|
+
for i in tqdm(range(timeout), leave=False):
|
|
95
|
+
if len(get_threads()) == 1:
|
|
96
|
+
break
|
|
97
|
+
sleep(1)
|
|
98
|
+
if print_remaining_threads and len(get_threads()) > 1:
|
|
99
|
+
print("Remaining threads:")
|
|
100
|
+
for tn in get_thread_names():
|
|
101
|
+
print(f"- {tn}")
|
|
102
|
+
|
|
103
|
+
return len(get_threads()) == 1
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def get_thread_names():
|
|
107
|
+
"""Get a list of the names of all active threads."""
|
|
108
|
+
return [thread.name for thread in threading.enumerate()]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def set_env_var(name: str, value: str | bool | int, override: bool = True):
|
|
112
|
+
"""
|
|
113
|
+
Set an environment variable with optional overriding behavior.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
name (str): The name of the environment variable to set.
|
|
117
|
+
value (str): The value to assign to the environment variable.
|
|
118
|
+
override (bool, optional): Whether to overwrite the variable if it is already set.
|
|
119
|
+
Defaults to False.
|
|
120
|
+
|
|
121
|
+
Behavior:
|
|
122
|
+
- If 'override' is True, the environment variable will always be set to 'value'.
|
|
123
|
+
- If 'override' is False, the variable will only be set if it is not already defined.
|
|
124
|
+
"""
|
|
125
|
+
if isinstance(value, bool):
|
|
126
|
+
value = int(value)
|
|
127
|
+
if isinstance(value, int):
|
|
128
|
+
value = str(value)
|
|
129
|
+
if override or name not in os.environ:
|
|
130
|
+
os.environ[name] = value
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def make_dir(dir_path: str, clear_existing: bool = False) -> str:
|
|
134
|
+
"""Create a directory, handling the case where it already exists."""
|
|
135
|
+
if clear_existing and os.path.exists(dir_path):
|
|
136
|
+
shutil.rmtree(dir_path)
|
|
137
|
+
if not os.path.isdir(dir_path):
|
|
138
|
+
os.makedirs(dir_path)
|
|
139
|
+
return dir_path
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def delete_path(path: bool) -> bool:
|
|
143
|
+
"""Delete the specified file or folder."""
|
|
144
|
+
if os.path.isdir(path):
|
|
145
|
+
shutil.rmtree(path)
|
|
146
|
+
elif os.path.exists(path):
|
|
147
|
+
os.remove(path)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def ensure_dirs_exist(*dirs):
|
|
151
|
+
"""Ensure that all directories in the list exist."""
|
|
152
|
+
for dir in dirs:
|
|
153
|
+
os.makedirs(dir, exist_ok=True)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def ensure_dir_exists(dir_path):
|
|
157
|
+
if not os.path.exists(dir_path):
|
|
158
|
+
os.makedirs(dir_path)
|
|
159
|
+
return dir_path
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: emtest
|
|
3
|
+
Version: 0.0.9
|
|
4
|
+
Summary: Testing utilities which I find useful.
|
|
5
|
+
Author-email: Emendir <dev@emendir.tech>
|
|
6
|
+
License-Expression: MIT-0 OR CC0-1.0
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Requires-Python: >=3.6
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
License-File: LICENSE-CC0
|
|
13
|
+
Requires-Dist: appdirs
|
|
14
|
+
Requires-Dist: environs
|
|
15
|
+
Requires-Dist: pytest
|
|
16
|
+
Requires-Dist: termcolor
|
|
17
|
+
Requires-Dist: tqdm
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# emtest - Python Testing Utilities
|
|
21
|
+
|
|
22
|
+
A Python package providing testing utilities.
|
|
23
|
+
|
|
24
|
+
## Features
|
|
25
|
+
|
|
26
|
+
### 🎨 Clean Test Output for Pytest
|
|
27
|
+
- **MinimalReporter**: Custom pytest reporter with clean, colored output using simple symbols (✓/✗/-)
|
|
28
|
+
- **Configurable Output**: Toggle between minimal and standard pytest output modes
|
|
29
|
+
|
|
30
|
+
### 🔧 Development Utilities
|
|
31
|
+
- **Source Path Management**: Dynamically add directories to Python path for testing source code
|
|
32
|
+
- **Module Source Validation**: Ensure modules are loaded from source directories (not installed packages)
|
|
33
|
+
- **Thread Cleanup Monitoring**: Wait for and verify proper thread cleanup in tests
|
|
34
|
+
|
|
35
|
+
### ⚡ Enhanced Test Execution
|
|
36
|
+
- **Dual Execution Pattern**: Run tests both as pytest tests and standalone Python scripts
|
|
37
|
+
- **Breakpoint Integration**: Easy debugging with pytest's `--pdb` integration
|
|
38
|
+
- **Progress Indicators**: Visual progress bars for waiting operations
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
pip install emtest
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
See the [Usage docs](docs/Usage/PytestUtils.md) for explanations and a complete working example showing:
|
|
49
|
+
- Basic test setup with `conftest.py`
|
|
50
|
+
- Showing and hiding logs
|
|
51
|
+
- Dual execution pattern implementation
|
|
52
|
+
- Source loading validation
|
|
53
|
+
- Thread cleanup testing
|
|
54
|
+
- Options like minising output, python-debugger breakpoints and more
|
|
55
|
+
|
|
56
|
+
## Documentation
|
|
57
|
+
|
|
58
|
+
- [Full Documentation](docs/README.md):
|
|
59
|
+
- [API-Reference](docs/API-Reference/README.html)
|
|
60
|
+
- Usage:
|
|
61
|
+
- [PytestUtils](docs/Usage/PytestUtils.md)
|
|
62
|
+
- [LogRecording](docs/Usage/LogRecording.md)
|
|
63
|
+
|
|
64
|
+
## Roadmap
|
|
65
|
+
|
|
66
|
+
## Contributing
|
|
67
|
+
|
|
68
|
+
### Get Involved
|
|
69
|
+
|
|
70
|
+
- GitHub Discussions: if you want to share ideas
|
|
71
|
+
- GitHub Issues: if you find bugs, other issues, or would like to submit feature requests
|
|
72
|
+
- GitHub Merge Requests: if you think you know what you're doing, you're very welcome!
|
|
73
|
+
|
|
74
|
+
### Donate
|
|
75
|
+
|
|
76
|
+
To support me in my work on this and other projects, you can make donations with the following currencies:
|
|
77
|
+
|
|
78
|
+
- **Bitcoin:** `BC1Q45QEE6YTNGRC5TSZ42ZL3MWV8798ZEF70H2DG0`
|
|
79
|
+
- **Ethereum:** `0xA32C3bBC2106C986317f202B3aa8eBc3063323D4`
|
|
80
|
+
- [Credit Card, Debit Card, Bank Transfer, Apple Pay, Google Pay, Revolut Pay)](https://checkout.revolut.com/pay/4e4d24de-26cf-4e7d-9e84-ede89ec67f32)
|
|
81
|
+
|
|
82
|
+
Donations help me:
|
|
83
|
+
- dedicate more time to developing and maintaining open-source projects
|
|
84
|
+
- cover costs for IT resources
|
|
85
|
+
|
|
86
|
+
## About the Developer
|
|
87
|
+
|
|
88
|
+
This project is developed by a human one-man team, publishing under the name _Emendir_.
|
|
89
|
+
I build open technologies trying to improve our world;
|
|
90
|
+
learning, working and sharing under the principle:
|
|
91
|
+
|
|
92
|
+
> _Freely I have received, freely I give._
|
|
93
|
+
|
|
94
|
+
Feel welcome to join in with code contributions, discussions, ideas and more!
|
|
95
|
+
|
|
96
|
+
## Open-Source in the Public Domain
|
|
97
|
+
|
|
98
|
+
I dedicate this project to the public domain.
|
|
99
|
+
It is open source and free to use, share, modify, and build upon without restrictions or conditions.
|
|
100
|
+
|
|
101
|
+
I make no patent or trademark claims over this project.
|
|
102
|
+
|
|
103
|
+
Formally, you may use this project under either the:
|
|
104
|
+
- [MIT No Attribution (MIT-0)](https://choosealicense.com/licenses/mit-0/) or
|
|
105
|
+
- [Creative Commons Zero (CC0)](https://choosealicense.com/licenses/cc0-1.0/)
|
|
106
|
+
licence at your choice.
|
|
107
|
+
|
|
108
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
_auto_run_with_pytest/__init__.py,sha256=P2Tgn9TbVJvNiyOygCrBso4uAd7Og9suuHmKE0-CEtU,753
|
|
2
|
+
emtest/__init__.py,sha256=TnZFKkEnSSI1yBhtT1NvllRXLCCv0RK63kIQNaKLpmw,418
|
|
3
|
+
emtest/log_recording.py,sha256=vNBRHmjTbYPv2JNj8QPbWzLKabDHZI7G5JDXOG79FnI,5062
|
|
4
|
+
emtest/log_utils.py,sha256=HlsHxLYbg1k0BT2AjdykvOGNVpj7fPWlUeWGsR4LYAE,967
|
|
5
|
+
emtest/pytest_utils.py,sha256=UUcNAgKJoNwGWe0x2hSHX70tekKi1wO2K4j1LZKWPek,5943
|
|
6
|
+
emtest/testing_utils.py,sha256=Cv1IWrTL7pKvUccL2bRKvCZlUM2pX9EWdVkiwUxOIrQ,4951
|
|
7
|
+
emtest-0.0.9.dist-info/licenses/LICENSE,sha256=i720OgyQLs68DSskm7ZLzaGKMnfskBIIHOuPWfwT2q4,907
|
|
8
|
+
emtest-0.0.9.dist-info/licenses/LICENSE-CC0,sha256=kXBMw0w0VVXQAbLjqMKmis4OngrPaK4HY9ScH6MdtxM,7038
|
|
9
|
+
emtest-0.0.9.dist-info/METADATA,sha256=u8IMqdTrajS0W0JwHYdxrwIlXeb0YBiWf7g8fQrsBbI,3663
|
|
10
|
+
emtest-0.0.9.dist-info/WHEEL,sha256=qELbo2s1Yzl39ZmrAibXA2jjPLUYfnVhUNTlyF1rq0Y,92
|
|
11
|
+
emtest-0.0.9.dist-info/top_level.txt,sha256=sfToBhqMjk35PDheZ42yiMGYNYatT3V5Mwhb79fp5dE,29
|
|
12
|
+
emtest-0.0.9.dist-info/RECORD,,
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
MIT No Attribution
|
|
2
|
+
|
|
3
|
+
Copyright [year] [fullname]
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so.
|
|
11
|
+
|
|
12
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
13
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
14
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
15
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
16
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
17
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
18
|
+
SOFTWARE.
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
Creative Commons Legal Code
|
|
2
|
+
|
|
3
|
+
CC0 1.0 Universal
|
|
4
|
+
|
|
5
|
+
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
|
6
|
+
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
|
7
|
+
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
|
8
|
+
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
|
9
|
+
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
|
10
|
+
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
|
11
|
+
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
|
12
|
+
HEREUNDER.
|
|
13
|
+
|
|
14
|
+
Statement of Purpose
|
|
15
|
+
|
|
16
|
+
The laws of most jurisdictions throughout the world automatically confer
|
|
17
|
+
exclusive Copyright and Related Rights (defined below) upon the creator
|
|
18
|
+
and subsequent owner(s) (each and all, an "owner") of an original work of
|
|
19
|
+
authorship and/or a database (each, a "Work").
|
|
20
|
+
|
|
21
|
+
Certain owners wish to permanently relinquish those rights to a Work for
|
|
22
|
+
the purpose of contributing to a commons of creative, cultural and
|
|
23
|
+
scientific works ("Commons") that the public can reliably and without fear
|
|
24
|
+
of later claims of infringement build upon, modify, incorporate in other
|
|
25
|
+
works, reuse and redistribute as freely as possible in any form whatsoever
|
|
26
|
+
and for any purposes, including without limitation commercial purposes.
|
|
27
|
+
These owners may contribute to the Commons to promote the ideal of a free
|
|
28
|
+
culture and the further production of creative, cultural and scientific
|
|
29
|
+
works, or to gain reputation or greater distribution for their Work in
|
|
30
|
+
part through the use and efforts of others.
|
|
31
|
+
|
|
32
|
+
For these and/or other purposes and motivations, and without any
|
|
33
|
+
expectation of additional consideration or compensation, the person
|
|
34
|
+
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
|
35
|
+
is an owner of Copyright and Related Rights in the Work, voluntarily
|
|
36
|
+
elects to apply CC0 to the Work and publicly distribute the Work under its
|
|
37
|
+
terms, with knowledge of his or her Copyright and Related Rights in the
|
|
38
|
+
Work and the meaning and intended legal effect of CC0 on those rights.
|
|
39
|
+
|
|
40
|
+
1. Copyright and Related Rights. A Work made available under CC0 may be
|
|
41
|
+
protected by copyright and related or neighboring rights ("Copyright and
|
|
42
|
+
Related Rights"). Copyright and Related Rights include, but are not
|
|
43
|
+
limited to, the following:
|
|
44
|
+
|
|
45
|
+
i. the right to reproduce, adapt, distribute, perform, display,
|
|
46
|
+
communicate, and translate a Work;
|
|
47
|
+
ii. moral rights retained by the original author(s) and/or performer(s);
|
|
48
|
+
iii. publicity and privacy rights pertaining to a person's image or
|
|
49
|
+
likeness depicted in a Work;
|
|
50
|
+
iv. rights protecting against unfair competition in regards to a Work,
|
|
51
|
+
subject to the limitations in paragraph 4(a), below;
|
|
52
|
+
v. rights protecting the extraction, dissemination, use and reuse of data
|
|
53
|
+
in a Work;
|
|
54
|
+
vi. database rights (such as those arising under Directive 96/9/EC of the
|
|
55
|
+
European Parliament and of the Council of 11 March 1996 on the legal
|
|
56
|
+
protection of databases, and under any national implementation
|
|
57
|
+
thereof, including any amended or successor version of such
|
|
58
|
+
directive); and
|
|
59
|
+
vii. other similar, equivalent or corresponding rights throughout the
|
|
60
|
+
world based on applicable law or treaty, and any national
|
|
61
|
+
implementations thereof.
|
|
62
|
+
|
|
63
|
+
2. Waiver. To the greatest extent permitted by, but not in contravention
|
|
64
|
+
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
|
65
|
+
irrevocably and unconditionally waives, abandons, and surrenders all of
|
|
66
|
+
Affirmer's Copyright and Related Rights and associated claims and causes
|
|
67
|
+
of action, whether now known or unknown (including existing as well as
|
|
68
|
+
future claims and causes of action), in the Work (i) in all territories
|
|
69
|
+
worldwide, (ii) for the maximum duration provided by applicable law or
|
|
70
|
+
treaty (including future time extensions), (iii) in any current or future
|
|
71
|
+
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
|
72
|
+
including without limitation commercial, advertising or promotional
|
|
73
|
+
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
|
74
|
+
member of the public at large and to the detriment of Affirmer's heirs and
|
|
75
|
+
successors, fully intending that such Waiver shall not be subject to
|
|
76
|
+
revocation, rescission, cancellation, termination, or any other legal or
|
|
77
|
+
equitable action to disrupt the quiet enjoyment of the Work by the public
|
|
78
|
+
as contemplated by Affirmer's express Statement of Purpose.
|
|
79
|
+
|
|
80
|
+
3. Public License Fallback. Should any part of the Waiver for any reason
|
|
81
|
+
be judged legally invalid or ineffective under applicable law, then the
|
|
82
|
+
Waiver shall be preserved to the maximum extent permitted taking into
|
|
83
|
+
account Affirmer's express Statement of Purpose. In addition, to the
|
|
84
|
+
extent the Waiver is so judged Affirmer hereby grants to each affected
|
|
85
|
+
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
|
86
|
+
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
|
87
|
+
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
|
88
|
+
maximum duration provided by applicable law or treaty (including future
|
|
89
|
+
time extensions), (iii) in any current or future medium and for any number
|
|
90
|
+
of copies, and (iv) for any purpose whatsoever, including without
|
|
91
|
+
limitation commercial, advertising or promotional purposes (the
|
|
92
|
+
"License"). The License shall be deemed effective as of the date CC0 was
|
|
93
|
+
applied by Affirmer to the Work. Should any part of the License for any
|
|
94
|
+
reason be judged legally invalid or ineffective under applicable law, such
|
|
95
|
+
partial invalidity or ineffectiveness shall not invalidate the remainder
|
|
96
|
+
of the License, and in such case Affirmer hereby affirms that he or she
|
|
97
|
+
will not (i) exercise any of his or her remaining Copyright and Related
|
|
98
|
+
Rights in the Work or (ii) assert any associated claims and causes of
|
|
99
|
+
action with respect to the Work, in either case contrary to Affirmer's
|
|
100
|
+
express Statement of Purpose.
|
|
101
|
+
|
|
102
|
+
4. Limitations and Disclaimers.
|
|
103
|
+
|
|
104
|
+
a. No trademark rights held by Affirmer are waived, abandoned,
|
|
105
|
+
surrendered, licensed or otherwise affected by this document.
|
|
106
|
+
b. Affirmer offers the Work as-is and makes no representations or
|
|
107
|
+
warranties of any kind concerning the Work, express, implied,
|
|
108
|
+
statutory or otherwise, including without limitation warranties of
|
|
109
|
+
title, merchantability, fitness for a particular purpose, non
|
|
110
|
+
infringement, or the absence of latent or other defects, accuracy, or
|
|
111
|
+
the present or absence of errors, whether or not discoverable, all to
|
|
112
|
+
the greatest extent permissible under applicable law.
|
|
113
|
+
c. Affirmer disclaims responsibility for clearing rights of other persons
|
|
114
|
+
that may apply to the Work or any use thereof, including without
|
|
115
|
+
limitation any person's Copyright and Related Rights in the Work.
|
|
116
|
+
Further, Affirmer disclaims responsibility for obtaining any necessary
|
|
117
|
+
consents, permissions or other rights required for any use of the
|
|
118
|
+
Work.
|
|
119
|
+
d. Affirmer understands and acknowledges that Creative Commons is not a
|
|
120
|
+
party to this document and has no duty or obligation with respect to
|
|
121
|
+
this CC0 or use of the Work.
|