Skip to content

Set __file__ to the exported module path when testing notebooks#1597

Open
ncoop57 wants to merge 2 commits into
mainfrom
auto-file-in-tests
Open

Set __file__ to the exported module path when testing notebooks#1597
ncoop57 wants to merge 2 commits into
mainfrom
auto-file-in-tests

Conversation

@ncoop57

@ncoop57 ncoop57 commented Jul 2, 2026

Copy link
Copy Markdown

Summary

Sets __file__ in the notebook execution namespace when nbdev-test runs an exported notebook, pointing at the module the notebook exports to. Path-dependent code like Path(__file__).parent now behaves the same under test as it does in the exported module.

Depends on AnswerDotAI/fastcore#835 — that PR must be merged and a fastcore release cut before this one can land.

Changes

  • Inject __file__ before running cells: if a notebook declares a default_exp, test_nb sets __file__ in CaptureShell.user_ns to the exported module's path before run_all.
  • New fixture tests/file_var.ipynb: asserts __file__ resolves to nbdev/file_var.py and that an explicit assignment overrides the injected value; exercised from nbs/api/12_test.ipynb.

Motivation

Exported modules commonly locate resources relative to themselves via __file__, which doesn't exist in the test namespace, so such code can't be exercised by notebook tests without workarounds. The full suite passing is meaningful coverage here: every notebook in nbs/api declares a default_exp, so they all now run with __file__ set.

ncoop57 and others added 2 commits July 2, 2026 18:01
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…-file-in-tests

# Conflicts:
#	nbdev/test.py
#	nbs/api/12_test.ipynb
@ncoop57 ncoop57 marked this pull request as ready for review July 3, 2026 14:36
@ncoop57 ncoop57 requested a review from jph00 July 3, 2026 14:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant