File: testing.py

package info (click to toggle)
sphinx-toolbox 3.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,924 kB
  • sloc: python: 11,636; sh: 26; javascript: 25; makefile: 16
file content (959 lines) | stat: -rw-r--r-- 28,314 bytes parent folder | download | duplicates (2)
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
#!/usr/bin/env python3
#
#  testing.py
r"""
Functions for testing Sphinx extensions.

.. extras-require:: testing
	:pyproject:

.. seealso:: Sphinx's own ``testing`` library: https://github.com/sphinx-doc/sphinx/tree/3.x/sphinx/testing

.. latex:vspace:: 10px

.. _pytest-regressions: https://pypi.org/project/pytest-regressions/
"""
#
#  Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in all
#  copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
#  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
#  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
#  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
#  OR OTHER DEALINGS IN THE SOFTWARE.
#
#  Based on Sphinx
#  Copyright (c) 2007-2020 by the Sphinx team.
#  |  All rights reserved.
#  |
#  |  Redistribution and use in source and binary forms, with or without
#  |  modification, are permitted provided that the following conditions are
#  |  met:
#  |
#  |  * Redistributions of source code must retain the above copyright
#  |    notice, this list of conditions and the following disclaimer.
#  |
#  |  * Redistributions in binary form must reproduce the above copyright
#  |    notice, this list of conditions and the following disclaimer in the
#  |    documentation and/or other materials provided with the distribution.
#  |
#  |  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#  |  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#  |  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#  |  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#  |  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  |  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#  |  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#  |  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#  |  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#  |  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  |  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

# stdlib
import copy
import re
import sys
import tempfile
from functools import partial
from types import SimpleNamespace
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Set, Tuple, Type, Union, cast

# 3rd party
import pytest  # nodep
import sphinx.application
from bs4 import BeautifulSoup
from coincidence.regressions import (  # nodep
		AdvancedFileRegressionFixture,
		check_file_output,
		check_file_regression
		)
from docutils import __version_info__ as docutils_version
from docutils import nodes
from docutils.parsers.rst import Directive, roles
from docutils.transforms import Transform
from domdf_python_tools.doctools import prettify_docstrings
from domdf_python_tools.paths import PathPlus
from domdf_python_tools.stringlist import StringList
from domdf_python_tools.typing import PathLike
from jinja2 import Template  # nodep
from pygments.lexer import Lexer  # type: ignore[import-untyped]  # nodep
from pytest_regressions.common import check_text_files  # nodep
from pytest_regressions.file_regression import FileRegressionFixture  # nodep
from sphinx.builders import Builder
from sphinx.domains import Domain, Index
from sphinx.domains.python import PythonDomain
from sphinx.environment.collectors import EnvironmentCollector
from sphinx.events import EventListener
from sphinx.events import EventManager as BaseEventManager
from sphinx.ext.autodoc.directive import AutodocDirective
from sphinx.highlighting import lexer_classes
from sphinx.registry import SphinxComponentRegistry
from sphinx.roles import XRefRole
from sphinx.util import docutils
from sphinx.util.typing import RoleFunction, TitleGetter

# this package
from sphinx_toolbox.utils import Config, SphinxExtMetadata

# _ModuleWrapper unwrapping BS due to
# https://github.com/sphinx-doc/sphinx/commit/8866adeacfb045c97302cc9c7e3b60dec5ca38fd

try:
	# 3rd party
	from sphinx.deprecation import _ModuleWrapper  # type: ignore[attr-defined]
	if isinstance(docutils, _ModuleWrapper):
		docutils = docutils._module
except ImportError:
	# Unnecessary if unimportable
	pass

__all__ = (
		"Sphinx",
		"run_setup",
		"RunSetupOutput",
		"remove_html_footer",
		"check_html_regression",
		"remove_html_link_tags",
		"check_asset_copy",
		"HTMLRegressionFixture",
		"html_regression",
		"LaTeXRegressionFixture",
		"latex_regression",
		)


class FakeBuilder(Builder):
	pass


class EventManager(BaseEventManager):

	def connect(self, name: str, callback: Callable, priority: int) -> int:
		"""
		Connect a handler to specific event.
		"""

		listener_id = self.next_listener_id
		self.next_listener_id += 1
		self.listeners[name].append(EventListener(listener_id, callback, priority))
		return listener_id


class Sphinx:
	"""
	A class that pretends to be :class:`sphinx.application.Sphinx` but that is stripped
	back to allow the internals to be inspected. This can be used in tests to ensure the
	nodes, roles etc. being registered in an extension's ``setup()`` function are actually
	being registered.
	"""  # noqa: D400

	registry: SphinxComponentRegistry  #: Instance of :class:`sphinx.registry.SphinxComponentRegistry`
	config: Config  #: Instance of :class:`sphinx.config.Config`
	events: EventManager  #: Instance of :class:`sphinx.events.EventManager`
	html_themes: Dict[str, str]  #: Mapping of HTML theme names to filesystem paths.

	# builder: Builder  #: Instance of :class:`sphinx.builder.Builder`

	def __init__(self):  # , buildername: str = "html"
		self.registry = SphinxComponentRegistry()
		self.config = Config({}, {})
		self.events = EventManager(self)  # type: ignore[arg-type]
		self.html_themes: Dict[str, str] = {}
		# self.builder = self.registry.create_builder(self, buildername)

	def add_builder(self, builder: Type[Builder], override: bool = False) -> None:
		r"""
		Register a new builder.

		The registered values are stored in the ``app.registry.builders`` dictionary
		(:class:`typing.Dict`\[:class:`str`\, :class:`typing.Type`\[:class:`sphinx.builders.Builder`\]]).
		"""

		self.registry.add_builder(builder, override=override)

	def add_config_value(
			self,
			name: str,
			default: Any,
			rebuild: Union[bool, str],
			types: Any = (),
			) -> None:
		r"""
		Register a configuration value.

		The registered values are stored in the ``app.config.values`` dictionary
		(:class:`typing.Dict`\[:class:`str`\, :class:`typing.Tuple`]).
		"""

		if rebuild in {False, True}:
			rebuild = "env" if rebuild else ''

		self.config.add(name, default, rebuild, types)

	def add_event(self, name: str) -> None:
		r"""
		Register an event called ``name``.

		The registered values are stored in the ``app.events.events`` dictionary
		(:class:`typing.Dict`\[:class:`str`\, :class:`str`\]).
		"""

		self.events.add(name)

	def set_translator(
			self,
			name: str,
			translator_class: Type[nodes.NodeVisitor],
			override: bool = False,
			) -> None:
		r"""
		Register or override a Docutils translator class.

		The registered values are stored in the ``app.registry.translators`` dictionary.
		(:class:`typing.Dict`\[:class:`str`\, :class:`typing.Type`\[:class:`docutils.nodes.NodeVisitor`\]]).

		.. clearpage::
		"""

		self.registry.add_translator(name, translator_class, override=override)

	def add_node(
			self,
			node: Type[nodes.Element],
			override: bool = False,
			**kwargs: Tuple[Callable, Callable],
			) -> None:
		r"""
		Register a Docutils node class.

		The registered values are stored in the ``additional_nodes`` set returned by
		:func:`~sphinx_toolbox.testing.run_setup`
		(:class:`typing.Set`\[:class:`typing.Type`\[:class:`docutils.nodes.Node`\]]).
		"""

		if not override and docutils.is_node_registered(node):
			raise ValueError(
					f"node class {node.__name__!r} is already registered, its visitors will be overridden"
					)

		docutils.register_node(node)
		self.registry.add_translation_handlers(node, **kwargs)

	def add_enumerable_node(
			self,
			node: Type[nodes.Element],
			figtype: str,
			title_getter: Optional[TitleGetter] = None,
			override: bool = False,
			**kwargs: Tuple[Callable, Callable],
			) -> None:
		"""
		Register a Docutils node class as a numfig target.
		"""

		# Sphinx's signature is wrong WRT Optional
		self.registry.add_enumerable_node(
				node,
				figtype,
				title_getter,
				override=override,
				)
		self.add_node(node, override=override, **kwargs)

	def add_directive(self, name: str, cls: Type[Directive], override: bool = False) -> None:
		"""
		Register a Docutils directive.
		"""

		if not override and docutils.is_directive_registered(name):
			raise ValueError(f"directive {name!r} is already registered, it will be overridden")

		docutils.register_directive(name, cls)

	def add_role(self, name: str, role: Any, override: bool = False) -> None:
		r"""
		Register a Docutils role.

		The registered values are stored in the ``roles`` dictionary returned by
		:func:`~sphinx_toolbox.testing.run_setup`.
		(:class:`typing.Dict`\[:class:`str`\, :class:`typing.Callable`\]).
		"""

		if not override and docutils.is_role_registered(name):
			raise ValueError(f"role {name!r} is already registered, it will be overridden")

		docutils.register_role(name, role)

	def add_generic_role(self, name: str, nodeclass: Any, override: bool = False) -> None:
		"""
		Register a generic Docutils role.
		"""

		if not override and docutils.is_role_registered(name):
			raise ValueError(f"role {name!r} is already registered, it will be overridden")

		role = roles.GenericRole(name, nodeclass)

		docutils.register_role(name, role)

	def add_domain(
			self,
			domain: Type[Domain],
			override: bool = False,
			) -> None:
		"""
		Register a domain.
		"""

		self.registry.add_domain(domain, override=override)

	def add_directive_to_domain(
			self,
			domain: str,
			name: str,
			cls: Type[Directive],
			override: bool = False,
			) -> None:
		"""
		Register a Docutils directive in a domain.
		"""

		self.registry.add_directive_to_domain(domain, name, cls, override=override)

	def add_role_to_domain(
			self,
			domain: str,
			name: str,
			role: Union[RoleFunction, XRefRole],
			override: bool = False,
			) -> None:
		"""
		Register a Docutils role in a domain.
		"""

		self.registry.add_role_to_domain(domain, name, role, override=override)

	def add_index_to_domain(
			self,
			domain: str,
			index: Type[Index],
			override: bool = False,
			) -> None:
		"""
		Register a custom index for a domain.
		"""

		self.registry.add_index_to_domain(domain, index)

	def add_object_type(
			self,
			directivename: str,
			rolename: str,
			indextemplate: str = '',
			parse_node: Optional[Callable] = None,
			ref_nodeclass: Optional[Type[nodes.TextElement]] = None,
			objname: str = '',
			doc_field_types: List = [],
			override: bool = False,
			) -> None:
		"""
		Register a new object type.
		"""

		# Sphinx's signature is wrong WRT Optional
		self.registry.add_object_type(
				directivename,
				rolename,
				indextemplate,
				parse_node,
				ref_nodeclass,
				objname,
				doc_field_types,
				override=override,
				)

	def add_crossref_type(
			self,
			directivename: str,
			rolename: str,
			indextemplate: str = '',
			ref_nodeclass: Optional[Type[nodes.TextElement]] = None,
			objname: str = '',
			override: bool = False,
			) -> None:
		"""
		Register a new crossref object type.
		"""

		# Sphinx's signature is wrong WRT Optional
		self.registry.add_crossref_type(
				directivename,
				rolename,
				indextemplate,
				ref_nodeclass,
				objname,
				override=override,
				)

	def add_transform(self, transform: Type[Transform]) -> None:
		"""
		Register a Docutils transform to be applied after parsing.
		"""

		self.registry.add_transform(transform)

	def add_post_transform(self, transform: Type[Transform]) -> None:
		"""
		Register a Docutils transform to be applied before writing.
		"""

		self.registry.add_post_transform(transform)

	def add_js_file(self, filename: str, **kwargs: str) -> None:
		"""
		Register a JavaScript file to include in the HTML output.

		.. versionadded:: 2.8.0
		"""

		self.registry.add_js_file(filename, **kwargs)

	# 	if hasattr(self.builder, 'add_js_file'):
	# 		self.builder.add_js_file(filename, **kwargs)
	#

	def add_css_file(self, filename: str, **kwargs: str) -> None:
		"""
		Register a stylesheet to include in the HTML output.

		.. versionadded:: 2.7.0
		"""

		self.registry.add_css_files(filename, **kwargs)

	# 	if hasattr(self.builder, 'add_css_file'):
	# 		self.builder.add_css_file(filename, **kwargs)

	def add_latex_package(
			self,
			packagename: str,
			options: Optional[str] = None,
			after_hyperref: bool = False,
			) -> None:
		"""
		Register a package to include in the LaTeX source code.
		"""

		# Sphinx's signature is wrong WRT Optional
		self.registry.add_latex_package(packagename, cast(str, options), after_hyperref)

	def add_lexer(self, alias: str, lexer: Type[Lexer]) -> None:
		"""
		Register a new lexer for source code.
		"""

		if isinstance(lexer, Lexer):
			raise TypeError("app.add_lexer() API changed; Please give lexer class instead instance")
		else:
			lexer_classes[alias] = lexer

	def add_autodocumenter(self, cls: Any, override: bool = False) -> None:
		"""
		Register a new documenter class for the autodoc extension.
		"""

		self.registry.add_documenter(cls.objtype, cls)
		self.add_directive("auto" + cls.objtype, AutodocDirective, override=override)

	def add_autodoc_attrgetter(
			self,
			typ: Type,
			getter: Callable[[Any, str, Any], Any],
			) -> None:
		"""
		Register a new ``getattr``-like function for the autodoc extension.
		"""

		self.registry.add_autodoc_attrgetter(typ, getter)

	def add_source_suffix(self, suffix: str, filetype: str, override: bool = False) -> None:
		"""
		Register a suffix of source files.
		"""

		self.registry.add_source_suffix(suffix, filetype, override=override)

	def add_source_parser(self, *args: Any, **kwargs: Any) -> None:
		"""
		Register a parser class.
		"""

		self.registry.add_source_parser(*args, **kwargs)

	def add_env_collector(self, collector: Type[EnvironmentCollector]) -> None:
		"""
		No-op for now.

		.. TODO:: Make this do something
		"""

	# def add_env_collector(self, collector: Type[EnvironmentCollector]) -> None:
	# 	"""
	# 	Register an environment collector class.
	# 	"""
	#
	# 	collector().enable(self)

	def add_html_theme(self, name: str, theme_path: str) -> None:
		"""
		Register an HTML Theme.
		"""

		self.html_themes[name] = theme_path

	def add_html_math_renderer(
			self,
			name: str,
			inline_renderers: Optional[Tuple[Callable, Callable]] = None,
			block_renderers: Optional[Tuple[Callable, Callable]] = None,
			) -> None:
		"""
		Register a math renderer for HTML.
		"""

		self.registry.add_html_math_renderer(name, inline_renderers, block_renderers)

	def setup_extension(self, extname: str) -> None:
		"""
		Import and setup a Sphinx extension module.

		.. TODO:: implement this
		"""

		# self.registry.load_extension(self, extname)

	def require_sphinx(self, version: str) -> None:
		"""
		Check the Sphinx version if requested.

		No-op when testing
		"""

	# event interface
	def connect(self, event: str, callback: Callable, priority: int = 500) -> int:
		"""
		Register *callback* to be called when *event* is emitted.
		"""

		listener_id = self.events.connect(event, callback, priority)
		return listener_id


@prettify_docstrings
class RunSetupOutput(NamedTuple):
	"""
	:class:`~typing.NamedTuple` representing the output from :func:`~sphinx_toolbox.testing.run_setup`.
	"""

	setup_ret: Union[None, Dict[str, Any], "SphinxExtMetadata"]  #: The output from the ``setup()`` function.
	directives: Dict[str, Callable]  #: Mapping of directive names to directive functions.
	roles: Dict[str, Callable]  #: Mapping of role names to role functions.
	additional_nodes: Set[Type[Any]]  #: Set of custom docutils nodes registered in ``setup()``.
	app: Sphinx  #: Instance of :class:`sphinx_toolbox.testing.Sphinx`.


_sphinx_dict_setup = Callable[[sphinx.application.Sphinx], Optional[Dict[str, Any]]]
_sphinx_metadata_setup = Callable[[sphinx.application.Sphinx], Optional["SphinxExtMetadata"]]
_fake_dict_setup = Callable[[Sphinx], Optional[Dict[str, Any]]]
_fake_metadata_setup = Callable[[Sphinx], Optional["SphinxExtMetadata"]]
_setup_func_type = Union[_sphinx_dict_setup, _sphinx_metadata_setup, _fake_dict_setup, _fake_metadata_setup]


class GenericNodeVisitor(nodes.NodeVisitor):
	pass


def run_setup(setup_func: _setup_func_type) -> RunSetupOutput:  # , buildername: str = "html"
	"""
	Function for running an extension's ``setup()`` function for testing.

	:param setup_func: The ``setup()`` function under test.

	:returns: 5-element namedtuple
	"""

	app = Sphinx()  # buildername

	app.add_domain(PythonDomain)

	_additional_nodes = copy.copy(docutils.additional_nodes)
	orig_gnv = nodes.GenericNodeVisitor

	try:
		nodes.GenericNodeVisitor = GenericNodeVisitor  # type: ignore[misc,assignment]
		docutils.additional_nodes = set()

		with docutils.docutils_namespace():
			setup_ret = setup_func(app)  # type: ignore[arg-type]
			directives = copy.copy(docutils.directives._directives)  # type: ignore[attr-defined]
			roles = copy.copy(docutils.roles._roles)  # type: ignore[attr-defined]
			additional_nodes = copy.copy(docutils.additional_nodes)
	finally:
		docutils.additional_nodes = _additional_nodes
		nodes.GenericNodeVisitor = orig_gnv  # type: ignore[misc]

	return RunSetupOutput(setup_ret, directives, roles, additional_nodes, app)


def remove_html_footer(page: BeautifulSoup) -> BeautifulSoup:
	"""
	Remove the Sphinx footer from HTML pages.

	The footer contains the Sphinx and theme versions and therefore changes between versions.
	This can cause unwanted, false positive test failures.

	:param page: The page to remove the footer from.

	:return: The page without the footer.
	"""

	for div in page.select("div.footer"):
		div.extract()

	return page


def remove_html_link_tags(page: BeautifulSoup) -> BeautifulSoup:
	"""
	Remove link tags from HTML pages.

	These may vary between different versions of Sphinx and its extensions.
	This can cause unwanted, false positive test failures.

	:param page: The page to remove the link tags from.

	:return: The page without the link tags.
	"""

	for div in page.select("head link"):
		div.extract()

	return page


def check_html_regression(page: BeautifulSoup, file_regression: FileRegressionFixture) -> None:
	"""
	Check an HTML page generated by Sphinx for regressions, using `pytest-regressions`_.

	:param page: The page to test.
	:param file_regression: The file regression fixture.

	**Example usage**

	.. code-block:: python

		@pytest.mark.parametrize("page", ["index.html"], indirect=True)
		def test_page(page: BeautifulSoup, file_regression: FileRegressionFixture):
			check_html_regression(page, file_regression)
	"""  # noqa: RST306

	__tracebackhide__ = True

	page = remove_html_footer(page)
	page = remove_html_link_tags(page)

	for div in page.select("script"):
		if "_static/language_data.js" in str(div):
			div.extract()

	for div in page.select("div.sphinxsidebar"):
		div.extract()

	check_file_regression(
			StringList(page.prettify()),
			file_regression,
			extension=".html",
			)


class HTMLRegressionFixture(FileRegressionFixture):
	"""
	Subclass of :class:`pytest_regressions.file_regression.FileRegressionFixture` for checking HTML files.

	.. versionadded:: 2.0.0
	"""

	def check(  # type: ignore[override]
		self,
		page: BeautifulSoup,
		*,
		extension: str = ".html",
		jinja2: bool = False,
		jinja2_namespace: Optional[Dict[str, Any]] = None,
		**kwargs
		) -> None:
		r"""
		Check an HTML page generated by Sphinx for regressions, using `pytest-regressions`_.

		:param page: The page to test.
		:param jinja2: Whether to render the reference file as a jinja2 template.
		:param jinja2_namespace: If ``jinja2`` is :py:obj:`True`,
			a mapping of variable names to values to make available in the jinja2 template.
		:param \*\*kwargs: Additional keyword arguments passed to
			:meth:`pytest_regressions.file_regression.FileRegressionFixture.check`.

		.. versionchanged:: 2.14.0  Added the ``jinja2`` keyword argument.
		.. versionchanged:: 2.17.0  Added the ``jinja2_namespace`` keyword argument.

		.. latex:clearpage::

		When ``jinja2`` is :py:obj:`True`, the reference file will be rendered as a jinja2 template.
		The template is passed the following variables:

		* ``sphinx_version`` -- the Sphinx version number, as a tuple of integers.
		* ``python_version`` -- the Python version number, in the form returned by :data:`sys.version_info`.
		* ``docutils_version`` -- the docutils version number, as a tuple of integers (*New in version 2.16.0*).

		**Example usage**

		.. code-block:: python

			@pytest.mark.parametrize("page", ["index.html"], indirect=True)
			def test_page(page: BeautifulSoup, html_regression: HTMLRegressionFixture):
				html_regression.check(page, file_regression)
		"""  # noqa: RST306

		__tracebackhide__ = True

		page = remove_html_footer(page)
		page = remove_html_link_tags(page)

		for div in page.select("script"):
			if "_static/language_data.js" in str(div):
				div.extract()

		for div in page.select("div.sphinxsidebar"):
			div.extract()

		for div in page.select("div.related"):
			if div["aria-label"] == "Related":
				div.extract()

		if sphinx.version_info >= (4, 3):  # pragma: no cover
			for div in page.select("dt.sig em.property span.k"):
				div.replace_with_children()
			for div in page.select("span.w"):
				div.extract()
			for div in page.select("span.p"):
				if div.string == '=':
					sibling = div.next_sibling
					assert sibling is not None
					div.replace_with('')  # type: ignore[arg-type]
					sibling.replace_with(f"= {sibling.text}")  # type: ignore[arg-type]

		kwargs.pop("encoding", None)
		kwargs.pop("extension", None)

		if jinja2:

			def check_fn(obtained_filename: PathPlus, expected_filename: PathPlus):  # noqa: MAN002
				__tracebackhide__ = True

				expected_filename = PathPlus(expected_filename)
				template = Template(expected_filename.read_text())

				expected_filename.write_text(
						template.render(
								sphinx_version=sphinx.version_info,
								python_version=sys.version_info,
								docutils_version=docutils_version,
								**jinja2_namespace or {},
								)
						)

				return check_text_files(obtained_filename, expected_filename, encoding="UTF-8")

		else:
			check_fn = partial(check_text_files, encoding="UTF-8")

		super().check(
				str(StringList(page.prettify())),
				encoding="UTF-8",
				extension=extension,
				check_fn=check_fn,
				)


@pytest.fixture()
def html_regression(datadir, original_datadir, request) -> HTMLRegressionFixture:  # noqa: MAN001
	"""
	Returns an :class:`~.HTMLRegressionFixture` scoped to the test function.

	.. versionadded:: 2.0.0
	"""

	return HTMLRegressionFixture(datadir, original_datadir, request)


def check_asset_copy(
		func: Callable[[sphinx.application.Sphinx, Exception], Any],
		*asset_files: PathLike,
		file_regression: FileRegressionFixture,
		) -> None:
	r"""
	Helper to test functions which respond to Sphinx ``build-finished`` events and copy asset files.

	.. versionadded:: 2.0.0

	:param func: The function to test.
	:param \*asset_files: The paths of asset files copied by the function, relative to the Sphinx output directory.
	:param file_regression:
	"""

	__tracebackhide__ = True

	with tempfile.TemporaryDirectory() as tmpdir:
		tmp_pathplus = PathPlus(tmpdir)

		fake_app = SimpleNamespace()
		fake_app.builder = SimpleNamespace()
		fake_app.builder.format = "html"
		fake_app.outdir = fake_app.builder.outdir = tmp_pathplus

		func(fake_app, None)  # type: ignore[arg-type]

		for filename in asset_files:
			filename = tmp_pathplus / filename

			check_file_output(filename, file_regression, extension=f"_{filename.stem}{filename.suffix}")


_latex_date_re = re.compile(r"\\date{.*}")


class LaTeXRegressionFixture(AdvancedFileRegressionFixture):
	"""
	Subclass of :class:`coincidence.regressions.AdvancedFileRegressionFixture` for checking LaTeX files.

	.. versionadded:: 2.17.0
	"""

	def check(  # type: ignore[override]  # noqa: MAN002
		self,
		contents: Union[str, StringList],
		*,
		extension: str = ".html",
		jinja2: bool = False,
		jinja2_namespace: Optional[Dict[str, Any]] = None,
		**kwargs
		):
		r"""
		Check a LaTeX file generated by Sphinx for regressions,
		using `pytest-regressions <https://pypi.org/project/pytest-regressions/>`__

		:param contents:
		:param jinja2: Whether to render the reference file as a jinja2 template.
		:param jinja2_namespace: If ``jinja2`` is :py:obj:`True`,
			a mapping of variable names to values to make available in the jinja2 template.
		:param \*\*kwargs: Additional keyword arguments passed to
			:meth:`pytest_regressions.file_regression.FileRegressionFixture.check`.

		When ``jinja2`` is :py:obj:`True`, the reference file will be rendered as a jinja2 template.
		The template is passed the following variables:

		* ``sphinx_version`` -- the Sphinx version number, as a tuple of integers.
		* ``python_version`` -- the Python version number, in the form returned by :data:`sys.version_info`.
		* ``docutils_version`` -- the docutils version number, as a tuple of integers (*New in version 2.16.0*).

		.. note::

			Unlike standard HTML jinja2 templates,
			this class expects the use of ``<`` and ``>`` rather than ``{`` and ``}``.

			For example::

				<% if foo %>
				<# This should only happen on Tuesdays #>
				<< foo.upper() >>
				<% endif %>

		**Example usage**

		.. code-block:: python

			@pytest.mark.sphinx("latex")
			def test_latex_output(app: Sphinx, latex_regression: LaTeXRegressionFixture):
				app.build()
				output_file = app.outdir / "python.tex"
				latex_regression.check(output_file.read_text())

		"""  # noqa: D400

		__tracebackhide__ = True

		if jinja2:

			def check_fn(obtained_filename: PathPlus, expected_filename: PathLike):  # noqa: MAN002
				__tracebackhide__ = True

				expected_filename = PathPlus(expected_filename)

				template = Template(
						expected_filename.read_text(),
						block_start_string="<%",
						block_end_string="%>",
						variable_start_string="<<",
						variable_end_string=">>",
						comment_start_string="<#",
						comment_end_string="#>",
						)

				expected_filename.write_text(
						template.render(
								sphinx_version=sphinx.version_info,
								python_version=sys.version_info,
								docutils_version=docutils_version,
								**jinja2_namespace or {},
								)
						)

				return check_text_files(obtained_filename, expected_filename, encoding="UTF-8")

		else:
			check_fn = partial(check_text_files, encoding="UTF-8")

		new_contents = _latex_date_re.sub(
				r"\\date{Mar 11, 2021}",
				str(contents).replace("\\sphinxAtStartPar\n", ''),
				)
		new_contents = new_contents.replace("%% let collapsible ", "%% let collapsable ")  # changed in Sphinx 4.2

		return super().check(
				new_contents,
				extension=".tex",
				check_fn=check_fn,
				)


@pytest.fixture()
def latex_regression(datadir, original_datadir, request) -> LaTeXRegressionFixture:  # noqa: MAN001
	"""
	Returns a :class:`~.LaTeXRegressionFixture` scoped to the test function.

	.. versionadded:: 2.17.0
	"""

	return LaTeXRegressionFixture(datadir, original_datadir, request)