Skip to content
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

Closed
rbtcollins opened this issue Dec 11, 2012 · 37 comments
Closed

load_tests not invoked in package/__init__.py #60866

rbtcollins opened this issue Dec 11, 2012 · 37 comments
Assignees
Labels
stdlib Python modules in the Lib dir type-feature A feature request or enhancement

Comments

@rbtcollins
Copy link
Member

BPO 16662
Nosy @warsaw, @vstinner, @rbtcollins, @bitdancer, @voidspace, @cjerdonek, @zware, @ElOpio, @asottile
PRs
  • bpo-30813: Fix unittest when hunting refleaks #2502
  • [3.6] bpo-30813: Fix unittest when hunting refleaks (#2502) #2505
  • [3.5] bpo-30813: Fix unittest when hunting refleaks (#2502) #2506
  • Files
  • 16662.diff
  • 16662_with_doc.diff: Barry's patch + doc changes
  • 16662_passing_tests.diff: patch
  • 16662_passing_tests_full.diff: updated patch.
  • fix-windows-tests.diff
  • 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:

    assignee = 'https://github.com/warsaw'
    closed_at = <Date 2014-10-17.19:42:38.292>
    created_at = <Date 2012-12-11.09:14:51.800>
    labels = ['type-feature', 'library']
    title = 'load_tests not invoked in package/__init__.py'
    updated_at = <Date 2017-06-30.11:12:22.901>
    user = 'https://github.com/rbtcollins'

    bugs.python.org fields:

    activity = <Date 2017-06-30.11:12:22.901>
    actor = 'vstinner'
    assignee = 'barry'
    closed = True
    closed_date = <Date 2014-10-17.19:42:38.292>
    closer = 'rbcollins'
    components = ['Library (Lib)']
    creation = <Date 2012-12-11.09:14:51.800>
    creator = 'rbcollins'
    dependencies = []
    files = ['31102', '31575', '36482', '36491', '36714']
    hgrepos = ['269']
    issue_num = 16662
    keywords = ['patch']
    message_count = 37.0
    messages = ['177327', '177340', '177346', '177350', '191024', '194019', '194022', '194032', '196853', '197203', '200271', '200272', '200274', '225940', '225943', '226008', '226585', '226589', '226590', '226596', '226600', '226601', '226604', '226611', '226613', '226747', '226802', '227331', '227496', '227497', '227865', '229594', '264204', '264253', '297373', '297383', '297387']
    nosy_count = 11.0
    nosy_names = ['barry', 'vstinner', 'rbcollins', 'vila', 'r.david.murray', 'michael.foord', 'chris.jerdonek', 'python-dev', 'zach.ware', 'elopio', 'Anthony Sottile']
    pr_nums = ['2502', '2505', '2506']
    priority = 'normal'
    resolution = 'fixed'
    stage = 'resolved'
    status = 'closed'
    superseder = None
    type = 'enhancement'
    url = 'https://bugs.python.org/issue16662'
    versions = ['Python 3.5']

    @rbtcollins
    Copy link
    Member Author

    In loader.py:
    if fnmatch(path, pattern):
    # only check load_tests if the package directory itself matches the filter
    name = self._get_name_from_path(full_path)
    package = self._get_module_from_name(name)
    load_tests = getattr(package, 'load_tests', None)
    tests = self.loadTestsFromModule(package, use_load_tests=False)

    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).

    @bitdancer
    Copy link
    Member

    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.

    @cjerdonek
    Copy link
    Member

    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:

    If a test package name (directory with '__init__.py') matches the
    pattern then the package will be checked for a 'load_tests' function. If
    this exists then it will be called with loader, tests, pattern.
    

    @rbtcollins
    Copy link
    Member Author

    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.

    @voidspace voidspace self-assigned this Jun 12, 2013
    @voidspace
    Copy link
    Contributor

    I agree that load_tests *should* be used in packages and that not doing this from the start was a mistake.

    @warsaw
    Copy link
    Member

    warsaw commented Jul 31, 2013

    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.

    @warsaw
    Copy link
    Member

    warsaw commented Jul 31, 2013

    Seems like this patch does the trick for my very limited testing.

    @voidspace
    Copy link
    Contributor

    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.

    @zware
    Copy link
    Member

    zware commented Sep 3, 2013

    I took a stab at the doc changes, attached here and including Barry's patch.

    @zware zware added stdlib Python modules in the Lib dir type-feature A feature request or enhancement labels Sep 3, 2013
    @voidspace
    Copy link
    Contributor

    I get a couple of test failures with this patch applied:

    ======================================================================
    ERROR: test_find_tests (unittest.test.test_discovery.TestDiscovery)
    ----------------------------------------------------------------------

    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'

    ======================================================================
    FAIL: test_find_tests_with_package (unittest.test.test_discovery.TestDiscovery)
    ----------------------------------------------------------------------

    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:
    a_directory module tests
    load_tests

    First list contains 1 additional elements.
    First extra element 2:
    test_directory2 module tests

    • ['a_directory module tests', 'load_tests', 'test_directory2 module tests']
      ? ----------------------------

    + ['load_tests', 'test_directory2 module tests']

    ----------------------------------------------------------------------

    @warsaw
    Copy link
    Member

    warsaw commented Oct 18, 2013

    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?

    @warsaw
    Copy link
    Member

    warsaw commented Oct 18, 2013

    On the second failure, the expected output just needs to be updated. Is that the right thing to do?

    @voidspace
    Copy link
    Contributor

    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.

    @rbtcollins
    Copy link
    Member Author

    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.

    @rbtcollins
    Copy link
    Member Author

    @rbtcollins
    Copy link
    Member Author

    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.

    @warsaw warsaw assigned warsaw and unassigned voidspace Sep 8, 2014
    @warsaw
    Copy link
    Member

    warsaw commented Sep 8, 2014

    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.

    @warsaw
    Copy link
    Member

    warsaw commented Sep 8, 2014

    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 arg will be keyword-only. *args and **kws will be parsed for use_load_tests usage and a deprecation warning will be issued if found, but the argument will be ignored. load_tests() will always be called if it's found.

    @warsaw
    Copy link
    Member

    warsaw commented Sep 8, 2014

    pattern will have to be documented and accepted as official API

    @python-dev
    Copy link
    Mannequin

    python-dev mannequin commented Sep 8, 2014

    New changeset d0ff527c53da by Barry Warsaw in branch 'default':

    @warsaw warsaw closed this as completed Sep 8, 2014
    @rbtcollins
    Copy link
    Member Author

    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):

    @rbtcollins
    Copy link
    Member Author

    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?

    @voidspace
    Copy link
    Contributor

    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!

    @rbtcollins
    Copy link
    Member Author

    @michael - ah I think I inverted the sense of the old parameter. It was defaulting True. So - no need to document anything extra:)

    @python-dev
    Copy link
    Mannequin

    python-dev mannequin commented Sep 8, 2014

    New changeset 92b292d68104 by Barry Warsaw in branch 'default':
    A few tweaks for bpo-16662 based on feedback from Robert Collins.
    http://hg.python.org/cpython/rev/92b292d68104

    @vstinner
    Copy link
    Member

    The changeset d0ff527c53da5b925b61a8a70afc686ca6e05960 related to this issue introduced a regression in test_unittest. The test now fails on Windows. Example:

    http://buildbot.python.org/all/builders/AMD64%20Windows7%20SP1%203.x/builds/5065/steps/test/logs/stdio

    ======================================================================
    ERROR: test_discover_with_init_module_that_raises_SkipTest_on_import (unittest.test.test_discovery.TestDiscovery)
    ----------------------------------------------------------------------

    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'

    @vstinner vstinner reopened this Sep 11, 2014
    @warsaw
    Copy link
    Member

    warsaw commented Sep 11, 2014

    On Sep 11, 2014, at 07:23 AM, STINNER Victor wrote:

    The changeset d0ff527c53da5b925b61a8a70afc686ca6e05960 related to this issue
    introduced a regression in test_unittest. The test now fails on
    Windows.

    Darn. I don't have Windows handy to work out a fix. I'll try to get a VM
    running but wouldn't mind if someone beats me to it. :)

    @rbtcollins
    Copy link
    Member Author

    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.

    @rbtcollins
    Copy link
    Member Author

    Fix up the tests patch - tested on windows 7.

    @rbtcollins
    Copy link
    Member Author

    bah, wrong extension to trigger review code :)

    @python-dev
    Copy link
    Mannequin

    python-dev mannequin commented Sep 30, 2014

    New changeset 090dc85f4226 by Benjamin Peterson in branch 'default':
    fix windows tests (bpo-16662)
    https://hg.python.org/cpython/rev/090dc85f4226

    @rbtcollins
    Copy link
    Member Author

    Closing as the fix to the test suite is applied.

    @asottile
    Copy link
    Mannequin

    asottile mannequin commented Apr 26, 2016

    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
    echo 'import pytest' > tests/init.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

    ======================================================================
    ERROR: tests (unittest.loader._FailedTest)
    ----------------------------------------------------------------------

    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)

    @vstinner
    Copy link
    Member

    ImportError: No module named 'pytest'

    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.

    @vstinner
    Copy link
    Member

    New changeset e4f9a2d by Victor Stinner in branch 'master':
    bpo-30813: Fix unittest when hunting refleaks (bpo-2502)
    e4f9a2d

    @vstinner
    Copy link
    Member

    New changeset 714afcc by Victor Stinner in branch '3.5':
    bpo-30813: Fix unittest when hunting refleaks (bpo-2502) (bpo-2506)
    714afcc

    @vstinner
    Copy link
    Member

    New changeset 22d4e8f by Victor Stinner in branch '3.6':
    bpo-30813: Fix unittest when hunting refleaks (bpo-2502) (bpo-2505)
    22d4e8f

    @ezio-melotti ezio-melotti transferred this issue from another repository Apr 10, 2022
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    stdlib Python modules in the Lib dir type-feature A feature request or enhancement
    Projects
    None yet
    Development

    No branches or pull requests

    7 participants