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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
|
from __future__ import annotations
import contextlib
import datetime
import logging
import os
import shutil
import stat
import tempfile
from collections.abc import Sequence
from contextlib import ExitStack, contextmanager
from functools import cached_property
from typing import TYPE_CHECKING, Any, Union
from unittest import TestCase, mock
import pytz
from staticsite.cmd.build import Builder
from staticsite.file import File
from staticsite.settings import Settings
from staticsite.site import Site
from staticsite.utils import front_matter
if TYPE_CHECKING:
from staticsite.page import Page
MockFiles = dict[str, Union[str, bytes, dict]]
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
class MockSiteBase:
"""
Common code for different ways of setting up mock sites
"""
def __init__(
self, auto_load_site: bool = True, settings: dict[str, Any] | None = None
):
# Set to False if you only want to populate the workdir
self.auto_load_site = auto_load_site
self.stack = contextlib.ExitStack()
self.root: str | None = None
self.test_case: TestCase | None = None
self.settings = Settings()
self.settings.CACHE_REBUILDS = False
self.settings.THEME_PATHS = [os.path.join(project_root, "themes")]
self.settings.TIMEZONE = "Europe/Rome"
if settings is not None:
for k, v in settings.items():
setattr(self.settings, k, v)
# Timestamp used for mock files and site generation time
# date +%s --date="2019-06-01 12:30"
self.generation_time: int | None = 1559385000
# Mock stat to return this mtime for files scanned during site load
# date +%s --date="2019-06-01 12:30"
self.mock_file_mtime: int | None = 1559385000
self.root = self.stack.enter_context(tempfile.TemporaryDirectory())
self.builder: Builder | None = None
def populate_workdir(self):
raise NotImplementedError(
f"{self.__class__.__name__}.populate_workdir not implemented"
)
def create_site(self) -> Site:
return Site(
self.settings,
generation_time=(
datetime.datetime.fromtimestamp(self.generation_time, pytz.utc)
if self.generation_time
else None
),
)
@cached_property
def site(self) -> Site:
return self.create_site()
@cached_property
def build_root(self) -> str:
return self.stack.enter_context(tempfile.TemporaryDirectory())
def load_site(self, until=Site.LOAD_STEP_ALL):
if self.mock_file_mtime:
overrides = {"st_mtime": self.mock_file_mtime}
else:
overrides = None
with mock_file_stat(overrides):
self.site.load(until=until)
def build_site(self):
"""
Build the site in a temporary directory.
The build directory will be available as self.build_root.
The Builder object will be available as self.builder
"""
self.site.settings.OUTPUT = self.build_root
self.builder = Builder(self.site)
self.builder.write()
def page(self, *paths: tuple[str]) -> tuple[Page]:
"""
Ensure the site has the given page, by path, and return it
"""
res: list[Page] = []
for path in paths:
page = self.site.root.resolve_path(path)
if page is None:
self.test_case.fail(f"Page {path!r} not found in site")
res.append(page)
if len(res) == 1:
return res[0]
else:
return tuple(res)
def assertPagePaths(self, paths: Sequence[str]):
"""
Check that the list of pages in the site matches the given paths
"""
self.test_case.assertCountEqual(
[p.site_path for p in self.site.iter_pages(static=False)], paths
)
def _find_page_by_relpath(self, relpath: str) -> Page | None:
for page in self.site.iter_pages():
if page.src.relpath == relpath:
return page
return None
def assertBuilt(
self,
srcpath: str | None,
sitepath: str,
dstpath: str,
sample: str | bytes | None = None,
):
"""
Check that page at `srcpath` is in the site at `sitepath` and rendered in `dstpath`.
`srcpath` can be None for autogenerated pages.
Optionally check that the rendered content contains `sample`
"""
if not self.builder:
self.build_site()
page = self.page(sitepath)
if srcpath is not None:
if page is None:
found = self._find_page_by_relpath(srcpath)
if found is None:
self.test_case.fail(
"{sitepath!r} not found in site, and {srcpath} not found in website"
)
else:
self.test_case.fail(
"{sitepath!r} not found in site, and {srcpath} found at {found} instead"
)
elif page.src.relpath != srcpath:
found = self._find_page_by_relpath(srcpath)
if found is None:
self.test_case.fail(
f"{sitepath!r} found in site, but for {page.src.relpath} instead of {srcpath}."
f" {srcpath} not found in website"
)
else:
self.test_case.fail(
f"{sitepath!r} found in site, but for {page.src.relpath} instead of {srcpath}."
f" {srcpath} is instead at {found}"
)
rendered = self.builder.build_log.get(dstpath)
if rendered is None:
for path, pg in self.builder.build_log.items():
if pg == page:
self.test_case.fail(
f"{dstpath!r} not found in render log; {sitepath!r} was rendered as {path!r} instead"
)
break
else:
self.test_case.fail(f"{dstpath!r} not found in render log")
if rendered != page:
for path, pg in self.builder.build_log.items():
if pg == page:
self.test_case.fail(
f"{dstpath!r} rendered {rendered!r} instead of {page!r}."
" {sitepath!r} was rendered as {path!r} instead"
)
break
else:
self.test_case.fail(
f"{dstpath!r} rendered {rendered!r} instead of {page!r}"
)
if os.path.isdir(os.path.join(self.build_root, dstpath)):
self.test_case.fail(f"{dstpath!r} rendered as a directory")
if sample is not None:
if isinstance(sample, bytes):
args = {"mode": "rb"}
else:
args = {"mode": "rt", "encoding": "utf-8"}
with open(os.path.join(self.build_root, dstpath), **args) as fd:
if sample not in (body := fd.read()):
self.test_case.fail(
f"{dstpath!r} does not contain {sample!r}. Renrered contents: {body!r}"
)
def __enter__(self) -> MockSite:
self.populate_workdir()
if self.auto_load_site:
self.load_site()
return self
def __exit__(self, *args):
self.site = None
self.builder = None
self.build_root = None
self.stack.__exit__(*args)
class MockSite(MockSiteBase):
"""
Define a mock site for testing
"""
def __init__(self, files: MockFiles, **kw):
super().__init__(**kw)
self.files = files
# Default settings for testing
self.settings.SITE_NAME = "Test site"
self.settings.SITE_URL = "https://www.example.org"
self.settings.SITE_AUTHOR = "Test User"
def populate_workdir(self):
self.settings.PROJECT_ROOT = self.root
for relpath, content in self.files.items():
abspath = os.path.join(self.root, relpath)
os.makedirs(os.path.dirname(abspath), exist_ok=True)
if isinstance(content, str):
with open(abspath, "wt") as fd:
fd.write(content)
os.utime(fd.fileno(), (self.generation_time, self.generation_time))
elif isinstance(content, bytes):
with open(abspath, "wb") as fd:
fd.write(content)
os.utime(fd.fileno(), (self.generation_time, self.generation_time))
elif isinstance(content, dict):
with open(abspath, "wt") as fd:
fd.write(front_matter.write(content, style="json"))
os.utime(fd.fileno(), (self.generation_time, self.generation_time))
else:
raise TypeError("content should be a str or bytes")
class ExampleSite(MockSiteBase):
"""
Site taken from the example/ directory
"""
def __init__(self, name: str, **kw):
super().__init__(**kw)
self.name = name
# date +%s --date="2020-02-01 16:00 Z"
self.generation_time = 1580572800
def populate_workdir(self):
src = os.path.join(project_root, "example", self.name)
# dst = os.path.join(self.workdir, "site")
os.rmdir(self.root)
shutil.copytree(src, self.root)
settings_path = os.path.join(self.root, "settings.py")
if os.path.exists(settings_path):
self.settings.load(settings_path)
if self.settings.PROJECT_ROOT is None:
self.settings.PROJECT_ROOT = self.root
if self.settings.SITE_URL is None:
self.settings.SITE_URL = "http://localhost"
class MockSiteTestMixin:
"""
Test a site built from a mock description
"""
@contextmanager
def site(self, mocksite: MockSite | MockFiles, **kw):
if not isinstance(mocksite, MockSite):
mocksite = MockSite(mocksite, **kw)
mocksite.test_case = self
with mocksite:
yield mocksite
@contextmanager
def mock_file_stat(overrides: dict[int, Any] | None):
"""
Override File.stat contents.
Overrides is a dict like: `{"st_mtime": 12345}`
"""
if not overrides:
yield
return
real_stat = os.stat
real_file_from_dir_entry = File.from_dir_entry
# See https://www.peterbe.com/plog/mocking-os.stat-in-python
def mock_stat(*args, **kw):
res = list(real_stat(*args, **kw))
for k, v in overrides.items():
res[getattr(stat, k.upper())] = v
return os.stat_result(res)
def mock_file_from_dir_entry(dir, entry):
res = real_file_from_dir_entry(dir, entry)
st = list(res.stat)
for k, v in overrides.items():
st[getattr(stat, k.upper())] = v
res = File(res.relpath, res.abspath, os.stat_result(st))
return res
with mock.patch("staticsite.file.os.stat", new=mock_stat):
with mock.patch(
"staticsite.file.File.from_dir_entry", new=mock_file_from_dir_entry
):
yield
def datafile_abspath(relpath):
test_root = os.path.dirname(__file__)
return os.path.join(test_root, "data", relpath)
class TracebackHandler(logging.Handler):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.collected = []
def handle(self, record):
import traceback
if record.stack_info is None:
record.stack_info = traceback.print_stack()
self.collected.append(record)
@contextmanager
def assert_no_logs(level=logging.WARN):
handler = TracebackHandler(level=level)
try:
root_logger = logging.getLogger()
root_logger.addHandler(handler)
yield
finally:
root_logger.removeHandler(handler)
if handler.collected:
raise AssertionError(f"{len(handler.collected)} unexpected loggings")
class Args:
"""
Mock argparser namespace initialized with options from constructor
"""
def __init__(self, **kw):
self._args = kw
def __getattr__(self, k):
return self._args.get(k, None)
class SiteTestMixin:
"""
Test a real site found on disk
"""
site_name: str
site_settings: dict[str, Any] = {}
site_cls = ExampleSite
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.stack = ExitStack()
cls.mocksite = cls.stack.enter_context(
cls.site_cls(name=cls.site_name, settings=cls.site_settings)
)
cls.site = cls.mocksite.site
cls.mocksite.build_site()
cls.build_root = cls.mocksite.build_root
cls.build_log = cls.mocksite.builder.build_log
@classmethod
def tearDownClass(cls):
cls.mocksite.__exit__(None, None, None)
cls.stack.__exit__(None, None, None)
super().tearDownClass()
def setUp(self):
super().setUp()
self.mocksite.test_case = self
def tearDown(self):
self.mocksite.test_case = None
super().tearDown()
def page(self, *paths: tuple[str]) -> tuple[Page]:
"""
Ensure the site has the given page, by path, and return it
"""
return self.mocksite.page(*paths)
def assertPagePaths(self, paths: Sequence[str]):
"""
Check that the list of pages in the site matches the given paths
"""
return self.mocksite.assertPagePaths(paths)
def assertBuilt(
self,
srcpath: str,
sitepath: str,
dstpath: str,
sample: str | bytes | None = None,
):
"""
Check that page at `srcpath` is in the site at `sitepath` and rendered in `dstpath`.
Optionally check that the rendered content contains `sample`
"""
return self.mocksite.assertBuilt(srcpath, sitepath, dstpath, sample)
|