-
-
Notifications
You must be signed in to change notification settings - Fork 30.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
load_tests not invoked in package/__init__.py #60866
Comments
In loader.py: But pattern is test*.py by default, and packages will never match that. Its not at all clear why this is special cased at all, but if it is, we'll need a separate pattern. (Its not special cased in the bzrlib implementation that acted as the initial implementation). |
test_email is a package, and has a load_tests in its __init__.py that I had to add in order to make "python -m unittest test.test_email" work. So I'm not sure what bug you are reporting here. |
I think he's saying that a test package will never be discovered by default, because the default value of discover()'s pattern argument is test*.py: http://hg.python.org/cpython/file/bc322469a7a8/Lib/unittest/loader.py#l152 So I think he wants package directories with names of the form test* to match by default. The discover() docstring touches on this special case:
|
I have a package with tests in it. If the tests match test*.py, they are loaded, and load_tests within each one called. But load_tests on the package isn't called. If I change the pattern supplied by the user to match the package, then the tests within adjacent packages that don't have a load_tests hook but have files called test*.py will no longer match, but the package will match. My preference would be for the special case to just be removed, and load_tests called if it exists: its existence is enough of an opt-in. Failing that, having two distinct fn patterns, one for packages and one for filenames (note the difference: one operates in the python namespace, one the filesystem namespace), would suffice. |
I agree that load_tests *should* be used in packages and that not doing this from the start was a mistake. |
Hah, I just ran into this too. I was perplexed why my load_tests() function wasn't being called and ended up pdb'ing unittest's discover, and found exactly this problem. I'm not surprised lifeless beat me to it. (My use case was to piggyback on load_tests() to implement a package fixture, similar to what nose provides.) Note that in http://docs.python.org/3/library/unittest.html#load-tests-protocol the docs even give you a recipe for a "no-op" load_tests() which would have been perfect, except for this problem with pattern matching the directory. My preference would be to remove the pattern match on the path. I agree that the presence of a load_tests() is probably enough of an opt-in. The question is whether we could classify this change as a bug fix or new feature. I'd love to see this fixed in 3.3 so I'm hoping for the former. |
Seems like this patch does the trick for my very limited testing. |
I'm happy with the check being removed. The old behaviour was documented I believe - so there'd need to be documentation changes to go with it. As the old behaviour is so "un-useful" I don't think there are backward compatibility issues with changing it. |
I took a stab at the doc changes, attached here and including Barry's patch. |
I get a couple of test failures with this patch applied: ====================================================================== Traceback (most recent call last):
File "/compile/cpython/Lib/unittest/test/test_discovery.py", line 72, in test_find_tests
suite = list(loader._find_tests(top_level, 'test*.py'))
File "/compile/cpython/Lib/unittest/loader.py", line 298, in _find_tests
tests = self.loadTestsFromModule(package, use_load_tests=False)
TypeError: <lambda>() got an unexpected keyword argument 'use_load_tests' ====================================================================== Traceback (most recent call last):
File "/compile/cpython/Lib/unittest/test/test_discovery.py", line 137, in test_find_tests_with_package
['load_tests', 'test_directory2' + ' module tests'])
AssertionError: Lists differ: ['a_directory module tests', '... != ['load_tests', 'test_directory... First differing element 0: First list contains 1 additional elements.
+ ['load_tests', 'test_directory2 module tests'] ---------------------------------------------------------------------- |
The failure in test_discovery.py is odd. It's failing because loadTestsFromModule() is being passed a keyword arguemnt use_load_tests=False. On the surface, the failure makes sense because if you look in test_discover.py, it's defining a lambda for loader.loadTestsFromModule that takes only one argument, the module name. But the deeper question is why self.loadTestsFromModule() is being passed use_load_tests=False? loadTestsFromModule() is documented to take *only* the module name: http://docs.python.org/3/library/unittest.html#unittest.TestLoader.loadTestsFromModule But then if you look at loader.py, loadTestsFromModule does indeed take an undocumented use_load_tests keyword argument. So it seems like there's two problems here. use_load_tests is undocumented, and the lambda in test_discovery.py should take that keyword argument. Michael, can you weigh in on this? |
On the second failure, the expected output just needs to be updated. Is that the right thing to do? |
use_load_tests was deliberately undocumented. IIRC it only exists to allow us to load tests from a package module (init.py) without invoking load_tests - it maybe that it can just go away altogether now. I'll need to look at the code to confirm. |
I think we rather need a test that using a load_tests hook to recursively load and transform a subdir works. Hacking on that now. |
Ok, implementation I'm happy with is up in https://bitbucket.org/rbtcollins/cpython/commits/bbf2eb26dda8f3538893bf3dc33154089f37f99d |
The doc part of the patch was assuming this would be in 3.4 which it wasn't. Updated to 3.5. Also found a corner case - when packages were imported the _get_module_from_name method was not guarded for un-importable modules. This is strictly a separate issue, but since we'll now import considerably more modules, it seemed prudent to fix it at the same time. |
One thing I really do not like about Rob's last patch is that it exacerbates the documentation discrepancy for loadTestsFromModule(). As previously mentioned, use_load_tests arg was already not documented, and now the patch adds another undocumented pattern default arg. Undocumented "unofficial" APIs are really a fib - we treat them as official APIs for backward compatibility reasons anyway, so I think it behooves us to document them. In the same vein, the load_tests Protocol really should tell the truth about its third argument - i.e. it will not always be None. As Michael suggests in http://bugs.python.org/issue16662#msg200274 I think we should just remove use_load_tests. We'll still need to document the new pattern=None, unless there's a better way to handle that. |
So, I think what I'm going to do is change the sig of the method to: def loadTestsFromModule(self, module, *args, pattern=None, **kws): I.e. the new |
pattern will have to be documented and accepted as official API |
New changeset d0ff527c53da by Barry Warsaw in branch 'default':
|
Thanks for landing this barry, there's a couple quirks with your improvements - loadTestsFromModule(mod, foo, bar) will raise a TypeError but not warn about foo the way loadTestsFromModule(mod, foo) will. Secondly, the TypeError has an off-by-one error in its output: loadTestsFromModule(mod, foo, bar) will claim 2 arguments were passed. Three were. diff -r d0ff527c53da Lib/unittest/loader.py
--- a/Lib/unittest/loader.py Mon Sep 08 14:21:37 2014 -0400
+++ b/Lib/unittest/loader.py Tue Sep 09 07:32:05 2014 +1200
@@ -79,12 +79,12 @@
# use_load_tests argument. For backward compatibility, we still
# accept the argument (which can also be the first position) but we
# ignore it and issue a deprecation warning if it's present.
- if len(args) == 1 or 'use_load_tests' in kws:
+ if len(args) or 'use_load_tests' in kws:
warnings.warn('use_load_tests is deprecated and ignored',
DeprecationWarning)
kws.pop('use_load_tests', None)
if len(args) > 1:
- raise TypeError('loadTestsFromModule() takes 1 positional argument but {} were given'.format(len(args)))
+ raise TypeError('loadTestsFromModule() takes 1 positional argument but {} were given'.format(len(args) + 1))
if len(kws) != 0:
# Since the keyword arguments are unsorted (see PEP 468), just
# pick the alphabetically sorted first argument to complain about,
diff -r d0ff527c53da Lib/unittest/test/test_loader.py
--- a/Lib/unittest/test/test_loader.py Mon Sep 08 14:21:37 2014 -0400
+++ b/Lib/unittest/test/test_loader.py Tue Sep 09 07:32:05 2014 +1200
@@ -272,7 +272,7 @@
# however use_load_tests (which sorts first) is ignored.
self.assertEqual(
str(cm.exception),
- 'loadTestsFromModule() takes 1 positional argument but 2 were given')
+ 'loadTestsFromModule() takes 1 positional argument but 3 were given')
@warningregistry
def test_loadTestsFromModule__use_load_tests_other_bad_keyword(self): |
OH! One more thing I just spotted, which is that this change causes non-'discover' unittest test loading to invoke load_tests. IMO this is the Right Thing - its what I intended when I described the protocol a few years back, but we should document it, no? |
I agree, load_tests should be honoured even when not invoked through discovery. If that wasn't the case it was an unfortunate oversight on my part! |
@michael - ah I think I inverted the sense of the old parameter. It was defaulting True. So - no need to document anything extra:) |
New changeset 92b292d68104 by Barry Warsaw in branch 'default': |
The changeset d0ff527c53da5b925b61a8a70afc686ca6e05960 related to this issue introduced a regression in test_unittest. The test now fails on Windows. Example: ====================================================================== Traceback (most recent call last):
File "C:\buildbot.python.org\3.x.kloth-win64\build\lib\unittest\test\test_discovery.py", line 451, in test_discover_with_init_module_that_raises_SkipTest_on_import
suite = loader.discover('/foo')
File "C:\buildbot.python.org\3.x.kloth-win64\build\lib\unittest\loader.py", line 284, in discover
tests = list(self._find_tests(start_dir, pattern))
File "C:\buildbot.python.org\3.x.kloth-win64\build\lib\unittest\loader.py", line 319, in _find_tests
paths = sorted(os.listdir(start_dir))
File "C:\buildbot.python.org\3.x.kloth-win64\build\lib\unittest\test\test_discovery.py", line 388, in list_dir
return list(vfs[path])
KeyError: 'C:\\foo' |
On Sep 11, 2014, at 07:23 AM, STINNER Victor wrote:
Darn. I don't have Windows handy to work out a fix. I'll try to get a VM |
I've managed to get a windows setup working. Its my mini-vfs which needs to be Windows aware (because the abs path of /foo is C:\\foo). I'll work up a patch tomorrowish. |
Fix up the tests patch - tested on windows 7. |
bah, wrong extension to trigger review code :) |
New changeset 090dc85f4226 by Benjamin Peterson in branch 'default': |
Closing as the fix to the test suite is applied. |
I have a hunch that this fix here may be causing this: spotify/dh-virtualenv#148 Minimally: echo 'from setuptools import setup; setup(name="demo")' > setup.py $ python setup.py test
running test
running egg_info
writing dependency_links to demo.egg-info/dependency_links.txt
writing demo.egg-info/PKG-INFO
writing top-level names to demo.egg-info/top_level.txt
reading manifest file 'demo.egg-info/SOURCES.txt'
writing manifest file 'demo.egg-info/SOURCES.txt'
running build_ext Ran 0 tests in 0.000s OK $ python3.5 setup.py test
running test
running egg_info
writing demo.egg-info/PKG-INFO
writing dependency_links to demo.egg-info/dependency_links.txt
writing top-level names to demo.egg-info/top_level.txt
reading manifest file 'demo.egg-info/SOURCES.txt'
writing manifest file 'demo.egg-info/SOURCES.txt'
running build_ext
tests (unittest.loader._FailedTest) ... ERROR ====================================================================== ImportError: Failed to import test module: tests
Traceback (most recent call last):
File "/usr/lib/python3.5/unittest/loader.py", line 462, in _find_test_path
package = self._get_module_from_name(name)
File "/usr/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name
__import__(name)
File "/tmp/foo/tests/__init__.py", line 1, in <module>
import pytest
ImportError: No module named 'pytest' Ran 1 test in 0.000s FAILED (errors=1) |
It looks like you must install pytest dependency. If you consider that it's really a bug in Python, please open an issue: this issue is now closed. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: