-
Notifications
You must be signed in to change notification settings - Fork 49
/
conftest.py
203 lines (162 loc) · 6.04 KB
/
conftest.py
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# note about virtual events: sometimes running any_widget.update()
# before generating a virtual event is needed for the virtual event to
# actually do something, if you have weird problems with tests try
# adding any_widget.update() calls
# see also update(3tcl)
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import time
import tkinter
from concurrent.futures import Future
from pathlib import Path
import pytest
import porcupine
from porcupine import dirs, get_main_window, get_tab_manager, plugins, tabs
from porcupine.__main__ import main
from porcupine.plugins import git_status
from porcupine.plugins.directory_tree import get_directory_tree
# https://docs.pytest.org/en/latest/example/simple.html#dynamically-adding-command-line-options
#
# use 'pytest --test-pastebins' to run tests that send stuff to pastebins, it's
# disabled by default because pastebins might block you for using them
# repeatedly too fast
def pytest_addoption(parser):
parser.addoption(
"--test-pastebins",
action="store_true",
default=False,
help="run tests that invoke online pastebins",
)
def pytest_collection_modifyitems(config, items):
if config.getoption("--test-pastebins"):
# --test-pastebins given in cli: do not skip pastebin tests
return
skip_pastebins = pytest.mark.skip(reason="need --test-pastebins to run")
for item in items:
if "pastebin_test" in item.keywords:
item.add_marker(skip_pastebins)
@pytest.fixture(scope="session")
def monkeypatch_dirs():
# avoid errors from user's custom plugins
user_plugindir = plugins.__path__.pop(0)
assert user_plugindir == str(dirs.config_dir / "plugins")
font_cache = dirs.cache_dir / "font_cache.json"
with tempfile.TemporaryDirectory() as d:
dirs.cache_dir = Path(d) / "cache"
dirs.config_dir = Path(d) / "config"
dirs.log_dir = Path(d) / "logs"
# Copy font cache to speed up tests
if font_cache.exists():
dirs.cache_dir.mkdir()
shutil.copy(font_cache, dirs.cache_dir)
yield
@pytest.fixture(scope="session", autouse=True)
def porcusession(monkeypatch_dirs):
# these errors should not occur while porcupine is running
with pytest.raises(RuntimeError):
get_main_window()
with pytest.raises(RuntimeError):
get_tab_manager()
# monkeypatch fixture doesn't work for this for whatever reason
# porcupine calls mainloop(), but we want it to return immediately for tests
old_args = sys.argv[1:]
old_mainloop = tkinter.Tk.mainloop
try:
# --verbose here doesn't work for whatever reason
# I tried to make it work, but then pytest caplog fixture didn't work
sys.argv[1:] = ["--shuffle-plugins"]
tkinter.Tk.mainloop = lambda self: None
main()
finally:
sys.argv[1:] = old_args
tkinter.Tk.mainloop = old_mainloop
yield
# avoid "Do you want to save" dialogs
for tab in list(porcupine.get_tab_manager().tabs()):
porcupine.get_tab_manager().close_tab(tab)
porcupine.quit()
@pytest.fixture
def tabmanager(porcusession):
assert not get_tab_manager().tabs(), "something hasn't cleaned up its tabs"
yield get_tab_manager()
for tab in get_tab_manager().tabs():
get_tab_manager().close_tab(tab)
@pytest.fixture
def filetab(porcusession, tabmanager):
tab = tabs.FileTab(tabmanager)
tabmanager.add_tab(tab)
return tab
# makes git status tags immediately available in directory tree
@pytest.fixture(scope="session", autouse=True)
def fake_git_pool():
class FakeThreadPool:
def submit(self, func):
fut = Future()
fut.set_result(func())
return fut
# monkeypatch fixture doesn't work with scope="session"
git_status.git_pool = FakeThreadPool()
yield
@pytest.fixture(autouse=True)
def fail_test_if_a_tkinter_callback_errors(mocker):
mock = mocker.patch("tkinter.Tk.report_callback_exception")
yield
if mock.call_count != 0:
exc_type, exc_value, exc_tb = mock.call_args.args
raise ValueError("error in tkinter callback while running test") from exc_value
# TODO: consider longer name
@pytest.fixture
def tree():
tree = get_directory_tree()
for child in tree.get_children(""):
tree.delete(child)
return tree
@pytest.fixture(scope="function", autouse=True)
def check_nothing_logged(request):
if "caplog" in request.fixturenames:
# Test uses caplog fixture, expects to get logging errors
yield
else:
# Fail test if it logs an error
def emit(record: logging.LogRecord):
raise RuntimeError(f"test logged error: {record}")
handler = logging.Handler()
handler.setLevel(logging.ERROR)
handler.emit = emit
logging.getLogger().addHandler(handler)
yield
logging.getLogger().removeHandler(handler)
@pytest.fixture
def run_porcupine():
def actually_run_porcupine(args, expected_exit_status):
run_result = subprocess.run(
[sys.executable, "-m", "porcupine"] + args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding="utf-8",
)
assert run_result.returncode == expected_exit_status
return run_result.stdout
return actually_run_porcupine
@pytest.fixture
def wait_until():
if os.environ.get("GITHUB_ACTIONS") == "true":
# Avoid random timeouting errors
default_timeout = 20
else:
# Short timeout is good for local development, so that you quickly notice something is wrong
default_timeout = 4
def actually_wait_until(condition, *, timeout=default_timeout):
end = time.monotonic() + timeout
while time.monotonic() < end:
get_main_window().update()
boolean = condition()
assert isinstance(boolean, bool) # https://github.com/Akuli/porcupine/issues/1095
if boolean:
return
raise RuntimeError("timed out waiting")
return actually_wait_until