[TIP] pytest + Django: Where to put the test settings.py?

Carl Meyer carl at oddbird.net
Mon Mar 24 15:52:42 PDT 2014


Hi Tin,

On 03/23/2014 04:44 PM, Tin Tvrtković wrote:
> this little project of mine (https://github.com/Tinche/bower-cache) uses
> Django, together with pytest for testing. I use the first layout from
> http://pytest.org/latest/goodpractises.html; a separate top-level
> directory for tests, and I'd like to keep my test data and the actual
> app code separate.
> 
> I do, however, need a valid Django settings.py in order to run the
> tests. My first instinct was to put it into the tests directory and
> refer to it as tests.settings in my pytest.ini, but this doesn't work
> unless I make the tests directory a proper Python package (with
> __init__.py) which pytest explicitly suggests to avoid. The other option
> would be to put it somewhere into the app itself, but then this means
> I'm mixing test and normal code, which is something I'm trying to avoid
> in the first place.
> 
> I was wondering if there was a generally-accepted way of solving this
> problem. Any advice from the community would be appreciated. :)

I'm afraid there isn't a generally-accepted solution here (at least not
as far as I know).

Personally in my deployable web projects I usually want my tests to be
in a real Python module hierarchy (so I can have top-level test
utilities imported by various tests, as well as having test settings
that can be referenced by DJANGO_SETTINGS_MODULE), so I generally ignore
the recommendation in the py.test documentation and include __init__.py
files in my test directories.

I haven't had any problems with doing so; the rationale given in the
py.test documentation doesn't generally apply to these projects, as I
don't "install" them (in the setup.py sense), and I always want the
tests to run against the code sitting next to them in the repo, never
against some other version of the code "installed" somewhere else.

I realize this isn't a general answer that satisfies all scenarios --
but since I haven't found such a solution, this is the tradeoff I've
chosen. Hope it helps,

Carl



More information about the testing-in-python mailing list