1# coding: utf-8
2"""A `pytest` plugin for importing notebooks as modules and using standard test discovered.
3
4The `AlternativeModule` is reusable. See `pidgin` for an example.
5"""
6
7from pathlib import Path
8
9import pytest
10
11from importnb import Notebook
12
13
14def get_file_patterns(cls, parent):
15 for pat in parent.config.getini("python_files"):
16 for e in cls.loader.extensions:
17 yield "*" + pat.rstrip(".py") + e
18
19
20class AlternativeModule(pytest.Module):
21 def _getobj(self):
22 return self.loader.load_file(str(self.path), False)
23
24 @classmethod
25 def pytest_collect_file(cls, parent, path):
26 if not parent.session.isinitpath(path):
27 for pat in get_file_patterns(cls, parent):
28 if path.fnmatch(pat):
29 break
30 else:
31 return
32
33 if hasattr(cls, "from_parent"):
34 return cls.from_parent(parent, path=Path(path))
35 return cls(path, parent)
36
37
38class NotebookModule(AlternativeModule):
39 loader = Notebook
40
41
42pytest_collect_file = NotebookModule.pytest_collect_file