Opened 9 years ago

Closed 8 years ago

#26570 closed Bug (needsinfo)

Test runner imports models package with Python 3.5+

Reported by: Torsten Bronger Owned by: nobody
Component: Testing framework Version: 1.9
Severity: Normal Keywords:
Cc: bronger@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Since Python 3.5, unittest's runner searches for tests also in all __init__.py modules. The release notes say:

Found packages are now checked for load_tests regardless of
whether their path matches pattern, because it is impossible for
a package name to match the default pattern.

If you organise your models in a package rather than a single models.py (the __init__.py file contains commands like from submodule import * to collect all model classes in the package), this leads to an error in a bogus test saying that the app is not ready yet. This happens because the model classes are executed, and this occurs too early (it should not occur at all).

A workaround is to say

manage.py test myapp/tests

instead of

manage.py test myapp

if your tests live in tests/ and only there.

Change History (9)

comment:1 by Torsten Bronger, 9 years ago

Summary: Test runner imports module package with Python 3.5+Test runner imports models package with Python 3.5+

comment:2 by Claude Paroz, 9 years ago

#26576 was a duplicate with some other symptoms described.

comment:3 by Tim Graham, 9 years ago

I can't reproduce with the tutorial and a models structure that looks like this:

polls/models
    __init__.py: from .models import *
    models.py (copied from `polls/models.py`)

Did I do something incorrectly or am I missing some detail to reproduce this?

comment:4 by Torsten Bronger, 9 years ago

Isn't __init__.py loaded at all, or does it simply not throw an exception?

comment:5 by Tim Graham, 9 years ago

I'm not sure what you're asking.

comment:6 by Tim Graham, 9 years ago

Resolution: needsinfo
Status: newclosed

comment:7 by Torsten Bronger, 8 years ago

Resolution: needsinfo
Status: closednew

http://stackoverflow.com/a/37098808/188108 is due to the same problem. I had an __init__.py in the project's root directory when I ran my tests. So maybe this is the reason why Tim could not reproduce it.

I need this __init__.py because the project is mounted in sub-directories of other projects. However, I admit that it may be an exotic use case.

comment:8 by Tim Graham, 8 years ago

Are you able to suggest a solution or propose a patch?

comment:9 by Tim Graham, 8 years ago

Resolution: needsinfo
Status: newclosed

I don't know enough to determine if this is something we should/can fix in Django. I think someone with the use case will have to provide a patch.

Note: See TracTickets for help on using tickets.
Back to Top