Kaydet (Commit) 7c404a4b authored tarafından Fred Drake's avatar Fred Drake

add __file__ to the globals available for tests loaded via DocFileSuite;

this is useful for locating supporting data files, just as it is in Python
modules
üst e57d7b17
...@@ -1107,6 +1107,10 @@ instances from text files and modules with doctests: ...@@ -1107,6 +1107,10 @@ instances from text files and modules with doctests:
defaults to a normal parser (i.e., \code{\class{DocTestParser}()}). defaults to a normal parser (i.e., \code{\class{DocTestParser}()}).
\versionadded{2.4} \versionadded{2.4}
Starting in Python 2.5, the global \code{__file__} was added to the
globals provided to doctests loaded from a text file using
\function{DocFileSuite()}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{DocTestSuite}{\optional{module}\optional{, \begin{funcdesc}{DocTestSuite}{\optional{module}\optional{,
......
...@@ -2328,6 +2328,8 @@ def DocFileTest(path, module_relative=True, package=None, ...@@ -2328,6 +2328,8 @@ def DocFileTest(path, module_relative=True, package=None,
globs=None, parser=DocTestParser(), **options): globs=None, parser=DocTestParser(), **options):
if globs is None: if globs is None:
globs = {} globs = {}
else:
globs = globs.copy()
if package and not module_relative: if package and not module_relative:
raise ValueError("Package may only be specified for module-" raise ValueError("Package may only be specified for module-"
...@@ -2337,6 +2339,8 @@ def DocFileTest(path, module_relative=True, package=None, ...@@ -2337,6 +2339,8 @@ def DocFileTest(path, module_relative=True, package=None,
if module_relative: if module_relative:
package = _normalize_module(package) package = _normalize_module(package)
path = _module_relative_path(package, path) path = _module_relative_path(package, path)
if "__file__" not in globs:
globs["__file__"] = path
# Find the file and read it. # Find the file and read it.
name = os.path.basename(path) name = os.path.basename(path)
......
...@@ -2010,6 +2010,14 @@ def test_DocFileSuite(): ...@@ -2010,6 +2010,14 @@ def test_DocFileSuite():
modified the test globals. The test globals are modified the test globals. The test globals are
automatically cleared for us after a test. automatically cleared for us after a test.
Tests in a file run using `DocFileSuite` can also access the
`__file__` global, which is set to the name of the file
containing the tests:
>>> suite = doctest.DocFileSuite('test_doctest3.txt')
>>> suite.run(unittest.TestResult())
<unittest.TestResult run=1 errors=0 failures=0>
""" """
def test_trailing_space_in_test(): def test_trailing_space_in_test():
......
Here we check that `__file__` is provided:
>>> type(__file__)
<type 'str'>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment