Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Session-scoped temporary directories in pytest#
I habitually use the tmpdir fixture in pytest to get a temporary directory that will be cleaned up after each test, but that doesn’t work with scope="session" - which can be used to ensure an expensive fixture is run only once per test session and the generated content is used for multiple tests.
To get a temporary directory that works with scope="session", use the tmp_path_factory built-in pytest fixture like this:
1import pytest2
3
4@pytest.fixture(scope="session")5def template_dir(tmp_path_factory):6 template_dir = tmp_path_factory.mktemp("page-templates")7 pages_dir = template_dir / "pages"8 pages_dir.mkdir()9 (pages_dir / "about.html").write_text("ABOUT!", "utf-8")10 (pages_dir / "request.html").write_text("request", "utf-8")11 return template_dir12
13
14def test_about(template_dir):15 assert "ABOUT!" == (template_dir / "pages" / "about.html").read_text()16
17
18def test_request(template_dir):19 assert "request" == (template_dir / "pages" / "request.html").read_text()Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.