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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
|
import importlib
import os
import shutil
import sys
import textwrap
from contextlib import contextmanager, suppress
from pathlib import Path
import pytest
from _pytest.monkeypatch import MonkeyPatch
import lektor_ng.project
from lektor_ng.builder import Builder
from lektor_ng.db import Database, Tree
from lektor_ng.environment import Environment
from lektor_ng.environment.expressions import Expression
from lektor_ng.project import Project
from lektor_ng.reporter import BufferReporter
from lektor_ng.utils import locate_executable
## shared test code
ROOT = Path(__file__).parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from aaasupport.loaders import finder, mfinder # noqa: F401
@pytest.fixture(scope="session")
def datadir():
return ROOT / "data"
@pytest.fixture(scope="function")
def demo_projects(finder, tmp_path): # noqa: F811
def _callme(name):
shutil.copytree(finder.lookup(name), tmp_path / name, dirs_exist_ok=True)
return tmp_path / name
try:
yield _callme
finally:
shutil.rmtree(tmp_path, ignore_errors=True)
# TO BE REVIEWED
@pytest.fixture(scope="session")
def top_path():
return Path(__file__).parent.parent
@pytest.fixture(scope="session")
def data_path():
"""Path to directory which contains test data.
Current this data lives in the ``tests`` directory.
"""
return Path(__file__).parent
@pytest.fixture(scope="session")
def example_path(top_path):
return top_path / "example"
@pytest.fixture(scope="session", autouse=True)
def temporary_lektor_cache(tmp_path_factory):
"""Get Lektor to use a temporary cache directory.
This prevents the tests from leaving scats behind in the
user’s real cache directory.
"""
cache_dir = tmp_path_factory.mktemp("lektor_cache")
# The stock monkeypatch fixture is function-scoped and so can not
# be used in a session-scoped fixture.
# Workaround from:
# https://github.com/pytest-dev/pytest/issues/363#issuecomment-406536200
def get_cache_dir():
return str(cache_dir)
mp = MonkeyPatch()
mp.setattr(lektor_ng.project, "get_cache_dir", get_cache_dir)
yield cache_dir
mp.undo()
@contextmanager
def restore_import_state():
"""Save `sys.path`, and `sys.modules` state on test
entry, restore after test completion.
Any test which constructs a `lektor_ng.environment.Environment` instance
or which runs any of the Lektor CLI commands should use this fixture
to ensure that alterations made to `sys.path` do not interfere with
other tests.
Lektor's private package cache is added to `sys.path` by
`lektor_ng.packages.load_packages`. This happens, for example,
whenever a Lektor `Environment` is constructed (unless
`load_plugins=False` is specified.) Since all tests are run
within an single invocation of the python interpreter, this can
cause problems when different tests are using different private
package caches.
"""
path = sys.path.copy()
meta_path = sys.meta_path.copy()
path_hooks = sys.path_hooks.copy()
modules = sys.modules.copy()
# Importlib_metadata, when it is imported, cripples the stdlib distribution finder
# by deleting its find_distributions method.
#
# https://github.com/python/importlib_metadata/blob/705a7571ec7c5abec4d4b008da3a58df7e5c94e7/importlib_metadata/_compat.py#L31
#
def clone_class(cls):
return type(cls)(cls.__name__, cls.__bases__, cls.__dict__.copy())
sys.meta_path[:] = [clone_class(findr) if isinstance(findr, type) else findr for findr in meta_path]
try:
yield
finally:
importlib.invalidate_caches()
# NB: Restore sys.modules, sys.path, et. all. in place. (Some modules may hold
# references to these — e.g. pickle appears to hold a reference to sys.modules.)
for module in set(sys.modules).difference(modules):
del sys.modules[module]
sys.modules.update(modules)
sys.path[:] = path
sys.meta_path[:] = meta_path
sys.path_hooks[:] = path_hooks
sys.path_importer_cache.clear()
_initial_path_key = object()
@pytest.hookimpl(tryfirst=True)
def pytest_runtest_setup(item):
item.stash[_initial_path_key] = sys.path.copy()
@pytest.hookimpl(trylast=True)
def pytest_runtest_teardown(item):
# Check that tests don't alter sys.path
initial_path = item.stash[_initial_path_key]
assert sys.path == initial_path
@pytest.fixture
def save_sys_path():
with restore_import_state():
yield
# Fix for spurious failures in pytest_runtest_teardown sanity-check:
#
# Import setuptools early to pre-mangle sys.path. This avoids mangling of sys.path
# during a test run, if setuptools is imported during the run.
#
# Details:
# - Setuptools>=71 adds its _vendor subdirectory to sys.path when imported.
# - When running under python < 3.12, setuptools can be imported during execution of
# import statements. (This appears to happen, somehow, through setuptools'
# _distutils_hack:DistUtilsMetafinder:find_spec.)
with suppress(ModuleNotFoundError):
__import__("setuptools")
@pytest.fixture(scope="session")
def project(data_path):
return Project.from_path(data_path / "demo-project")
@pytest.fixture(scope="function")
def scratch_project_data(tmp_path):
base = tmp_path / "scratch-proj"
def write_text(path, text):
filename = base / path
filename.parent.mkdir(parents=True, exist_ok=True)
filename.write_text(textwrap.dedent(text), "utf-8")
write_text(
"Scratch.lektorproject",
"""
[project]
name = Scratch
[alternatives.en]
primary = yes
[alternatives.de]
url_prefix = /de/
""",
)
write_text(
"content/contents.lr",
"""
_model: page
---
title: Index
---
body: *Hello World!*
""",
)
write_text(
"templates/page.html",
"""
<h1>{{ this.title }}</h1>
{{ this.body }}
""",
)
write_text(
"models/page.ini",
"""
[model]
label = {{ this.title }}
[fields.title]
type = string
[fields.body]
type = markdown
""",
)
return base
@pytest.fixture(scope="function")
def scratch_project(scratch_project_data):
return Project.from_path(scratch_project_data)
@pytest.fixture(scope="function")
def env(project, save_sys_path):
return Environment(project)
@pytest.fixture(scope="function")
def scratch_env(scratch_project, save_sys_path):
return Environment(scratch_project)
@pytest.fixture(scope="function")
def pad(env):
return Database(env).new_pad()
@pytest.fixture(scope="function")
def scratch_pad(scratch_env):
return Database(scratch_env).new_pad()
@pytest.fixture(scope="function")
def scratch_tree(scratch_pad):
return Tree(scratch_pad)
@pytest.fixture(scope="function")
def builder(tmp_path, pad):
output_path = tmp_path / "output"
output_path.mkdir()
return Builder(pad, str(output_path))
@pytest.fixture(scope="session")
def built_demo(tmp_path_factory, project):
output_path = tmp_path_factory.mktemp("demo-output")
with restore_import_state():
env = Environment(project)
builder = Builder(env.new_pad(), os.fspath(output_path))
builder.build_all()
return output_path
@pytest.fixture(scope="function")
def scratch_builder(tmp_path, scratch_pad):
output_path = tmp_path / "output"
output_path.mkdir()
return Builder(scratch_pad, str(output_path))
# Builder for child-sources-test-project, a project to test that child sources
# are built even if they're filtered out by a pagination query.
@pytest.fixture(scope="function")
def child_sources_test_project_builder(tmp_path, data_path, save_sys_path):
output_path = tmp_path / "output"
output_path.mkdir()
project = Project.from_path(data_path / "child-sources-test-project")
pad = project.make_env().new_pad()
return Builder(pad, str(output_path))
@pytest.fixture(scope="function")
def eval_expr(env):
def eval_expr(expr, **kwargs):
expr = Expression(env, expr)
return expr.evaluate(**kwargs)
return eval_expr
@pytest.fixture(scope="function")
def reporter(request, env):
reporter = BufferReporter(env)
reporter.push()
request.addfinalizer(reporter.pop)
return reporter
@pytest.fixture(scope="function")
def project_cli_runner(isolated_cli_runner, project, save_sys_path):
"""
Copy the project files into the isolated file system used by the
Click test runner.
"""
for entry in os.listdir(project.tree):
entry_path = os.path.join(project.tree, entry)
if os.path.isdir(entry_path):
shutil.copytree(entry_path, entry)
else:
shutil.copy2(entry_path, entry)
return isolated_cli_runner
@pytest.fixture
def no_utils(monkeypatch):
"""Monkeypatch $PATH to hide any installed external utilities
(e.g. git, ffmpeg)."""
monkeypatch.setitem(os.environ, "PATH", "/dev/null")
locate_executable.cache_clear()
try:
yield
finally:
locate_executable.cache_clear()
|