Coder Social home page Coder Social logo

pytest-django's Introduction

PyPI Version Supported Python versions Build Status Supported Django versions Coverage

Welcome to pytest-django!

pytest-django allows you to test your Django project/applications with the pytest testing tool.

Install pytest-django

pip install pytest-django

Why would I use this instead of Django's manage.py test command?

Running your test suite with pytest-django allows you to tap into the features that are already present in pytest. Here are some advantages:

  • Manage test dependencies with pytest fixtures.
  • Less boilerplate tests: no need to import unittest, create a subclass with methods. Write tests as regular functions.
  • Database re-use: no need to re-create the test database for every test run.
  • Run tests in multiple processes for increased speed (with the pytest-xdist plugin).
  • Make use of other pytest plugins.
  • Works with both worlds: Existing unittest-style TestCase's still work without any modifications.

See the pytest documentation for more information on pytest itself.

pytest-django's People

Contributors

adamantike avatar adamchainz avatar akx avatar bfirsh avatar bh avatar birdsarah avatar bittner avatar bluetech avatar blueyed avatar code0x58 avatar dcramer avatar dstufft avatar flub avatar hramezani avatar jjmurre avatar julen avatar magopian avatar meshy avatar michael-k avatar minusf avatar mjkaye avatar pelme avatar peterlauri avatar rafales avatar renanivo avatar schmir avatar steenzout avatar tony avatar uncomplex avatar voidus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytest-django's Issues

Pytest cannot find settings

The current working directory is not in the sys.path so it cannot find my settings file... now I'm wondering what would be the "clean" way to fix this.

I have no problem running other parts of py.test but the pytest_django module cannot find my settings.

My file structure is roughly like this:

project_directory/settings.py
project_directory/app_1/
project_directory/app_2/
project_directory/manage.py

Obviously manage.py has no problems importing the settings.

Py.test is being called like this:
py.test --ds settings

The exception:

_pytest.config.UsageError: Could not import settings 'settings' (Is it on sys.path? Is there an import error in the settings file?): No module named settings

What is the proper way to fix this? I know I can set the PYTHONPATH variable in my environment but that just seems hacky. Why won't pytest_django import from the current directory as you would expect?

Models/apps get imported twice: Conflicting 'model' models in application 'app': <class 'project.project.app.models.Model'> and <class 'app.models.Model'>.

I am not sure, if this is a bug in Django 1.7 (alpha, master), or a problem with pytest_django.

I am using django-configurations.

When calling py.test as follows, I get an exception (see title):

DJANGO_SETTINGS_MODULE=config.settings DJANGO_CONFIGURATION=Tests PYTHONPATH=. py.test --debug -s --ipdb tmm/movies/tests.py

It appears that setup() is called twice, and first the app/model is project.project.app.model, and the second time app.model.

I see two issues here: setup() being called twice, and the different naming of the same app/model.

This gets triggered/caused by from .models import Model in the test file.
(When I comment this line, another error pops up: " AttributeError: 'db.backends.dummy.base.DatabaseWrapper' object has no attribute 'Database' "
https://code.djangoproject.com/ticket/22279#ticket)

> …/django-master/django/apps/registry.py(201)register_model()
    200                 "Conflicting '%s' models in application '%s': %s and %s." %
--> 201                 (model_name, app_label, app_models[model_name], model))
    202         app_models[model_name] = model

ipdb> w
  /home/user/.virtualenvs/tmm/bin/py.test(9)<module>()
      6 
      7 if __name__ == '__main__':
      8     sys.exit(
----> 9         load_entry_point('pytest==2.5.3.dev1', 'console_scripts', 'py.test')()
     10     )

  …/pytest/_pytest/config.py(20)main()
     18     """
     19     config = _prepareconfig(args, plugins)
---> 20     return config.hook.pytest_cmdline_main(config=config)
     21 
     22 class cmdline:  # compatibility namespace

  …/pytest/_pytest/core.py(377)__call__()
    375     def __call__(self, **kwargs):
    376         methods = self.hookrelay._pm.listattr(self.name)
--> 377         return self._docall(methods, kwargs)
    378 
    379     def pcall(self, plugins, **kwargs):

  …/pytest/_pytest/core.py(388)_docall()
    386         mc = MultiCall(methods, kwargs, firstresult=self.firstresult)
    387         try:
--> 388             res = mc.execute()
    389             if res:
    390                 self.trace("finish", self.name, "-->", res)

  …/pytest/_pytest/core.py(289)execute()
    287             method = self.methods.pop()
    288             kwargs = self.getkwargs(method)
--> 289             res = method(**kwargs)
    290             if res is not None:
    291                 self.results.append(res)

  …/pytest/_pytest/main.py(112)pytest_cmdline_main()
    110 
    111 def pytest_cmdline_main(config):
--> 112     return wrap_session(config, _main)
    113 
    114 def _main(config, session):

  …/pytest/_pytest/main.py(81)wrap_session()
     79             config.hook.pytest_sessionstart(session=session)
     80             initstate = 2
---> 81             doit(config, session)
     82         except pytest.UsageError:
     83             args = sys.exc_info()[1].args

  …/pytest/_pytest/main.py(118)_main()
    116     running tests and reporting. """
    117     config.hook.pytest_collection(session=session)
--> 118     config.hook.pytest_runtestloop(session=session)
    119 
    120 def pytest_collection(session):

  …/pytest/_pytest/core.py(377)__call__()
    375     def __call__(self, **kwargs):
    376         methods = self.hookrelay._pm.listattr(self.name)
--> 377         return self._docall(methods, kwargs)
    378 
    379     def pcall(self, plugins, **kwargs):

  …/pytest/_pytest/core.py(388)_docall()
    386         mc = MultiCall(methods, kwargs, firstresult=self.firstresult)
    387         try:
--> 388             res = mc.execute()
    389             if res:
    390                 self.trace("finish", self.name, "-->", res)

  …/pytest/_pytest/core.py(289)execute()
    287             method = self.methods.pop()
    288             kwargs = self.getkwargs(method)
--> 289             res = method(**kwargs)
    290             if res is not None:
    291                 self.results.append(res)

  …/pytest/_pytest/main.py(138)pytest_runtestloop()
    136     for i, item in enumerate(session.items):
    137         nextitem = getnextitem(i)
--> 138         item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
    139         if session.shouldstop:
    140             raise session.Interrupted(session.shouldstop)

  …/pytest/_pytest/core.py(377)__call__()
    375     def __call__(self, **kwargs):
    376         methods = self.hookrelay._pm.listattr(self.name)
--> 377         return self._docall(methods, kwargs)
    378 
    379     def pcall(self, plugins, **kwargs):

  …/pytest/_pytest/core.py(388)_docall()
    386         mc = MultiCall(methods, kwargs, firstresult=self.firstresult)
    387         try:
--> 388             res = mc.execute()
    389             if res:
    390                 self.trace("finish", self.name, "-->", res)

  …/pytest/_pytest/core.py(289)execute()
    287             method = self.methods.pop()
    288             kwargs = self.getkwargs(method)
--> 289             res = method(**kwargs)
    290             if res is not None:
    291                 self.results.append(res)

  …/pytest/_pytest/runner.py(64)pytest_runtest_protocol()
     62         nodeid=item.nodeid, location=item.location,
     63     )
---> 64     runtestprotocol(item, nextitem=nextitem)
     65     return True
     66 

  …/pytest/_pytest/runner.py(71)runtestprotocol()
     69     if hasrequest and not item._request:
     70         item._initrequest()
---> 71     rep = call_and_report(item, "setup", log)
     72     reports = [rep]
     73     if rep.passed:

  …/pytest/_pytest/runner.py(110)call_and_report()
    108     call = call_runtest_hook(item, when, **kwds)
    109     hook = item.ihook
--> 110     report = hook.pytest_runtest_makereport(item=item, call=call)
    111     if log:
    112         hook.pytest_runtest_logreport(report=report)

  …/pytest/_pytest/runner.py(126)call_runtest_hook()
    124     hookname = "pytest_runtest_" + when
    125     ihook = getattr(item.ihook, hookname)
--> 126     return CallInfo(lambda: ihook(item=item, **kwds), when=when)
    127 
    128 class CallInfo:

  …/pytest/_pytest/runner.py(145)__init__()
    143                 self.excinfo = py.code.ExceptionInfo()
    144         finally:
--> 145             self.stop = time()
    146 
    147     def __repr__(self):

  …/pytest/_pytest/runner.py(126)<lambda>()
    124     hookname = "pytest_runtest_" + when
    125     ihook = getattr(item.ihook, hookname)
--> 126     return CallInfo(lambda: ihook(item=item, **kwds), when=when)
    127 
    128 class CallInfo:

  …/pytest/_pytest/main.py(162)call_matching_hooks()
    160         def call_matching_hooks(**kwargs):
    161             plugins = self.config._getmatchingplugins(self.fspath)
--> 162             return hookmethod.pcall(plugins, **kwargs)
    163         return call_matching_hooks
    164 

  …/pytest/_pytest/core.py(381)pcall()
    379     def pcall(self, plugins, **kwargs):
    380         methods = self.hookrelay._pm.listattr(self.name, plugins=plugins)
--> 381         return self._docall(methods, kwargs)
    382 
    383     def _docall(self, methods, kwargs):

  …/pytest/_pytest/core.py(392)_docall()
    390                 self.trace("finish", self.name, "-->", res)
    391         finally:
--> 392             self.trace.root.indent -= 1
    393         return res
    394 

  …/pytest/_pytest/core.py(289)execute()
    287             method = self.methods.pop()
    288             kwargs = self.getkwargs(method)
--> 289             res = method(**kwargs)
    290             if res is not None:
    291                 self.results.append(res)

  …/pytest/_pytest/runner.py(85)pytest_runtest_setup()
     83 
     84 def pytest_runtest_setup(item):
---> 85     item.session._setupstate.prepare(item)
     86 
     87 def pytest_runtest_call(item):

  …/pytest/_pytest/runner.py(387)prepare()
    385             except Exception:
    386                 col._prepare_exc = sys.exc_info()
--> 387                 raise
    388 
    389 def collect_one_node(collector):

  …/pytest/_pytest/unittest.py(74)setup()
     72             self._testcase.setup_method(self._obj)
     73         if hasattr(self, "_request"):
---> 74             self._request._fillfixtures()
     75 
     76     def teardown(self):

  …/pytest/_pytest/python.py(1265)_fillfixtures()
   1263         for argname in fixturenames:
   1264             if argname not in item.funcargs:
-> 1265                 item.funcargs[argname] = self.getfuncargvalue(argname)
   1266 
   1267     def cached_setup(self, setup, teardown=None, scope="module", extrakey=None):

  …/pytest/_pytest/python.py(1313)getfuncargvalue()
   1311         function body.
   1312         """
-> 1313         return self._get_active_fixturedef(argname).cached_result[0]
   1314 
   1315     def _get_active_fixturedef(self, argname):

  …/pytest/_pytest/python.py(1327)_get_active_fixturedef()
   1325                     return PseudoFixtureDef
   1326                 raise
-> 1327             result = self._getfuncargvalue(fixturedef)
   1328             self._funcargs[argname] = result
   1329             self._fixturedefs[argname] = fixturedef

  …/pytest/_pytest/python.py(1383)_getfuncargvalue()
   1381             # if fixture function failed it might have registered finalizers
   1382             self.session._setupstate.addfinalizer(fixturedef.finish,
-> 1383                                                   subrequest.node)
   1384         return val
   1385 

  …/pytest/_pytest/python.py(1827)execute()
   1825                     fixturefunc = fixturefunc.__get__(request.instance)
   1826             result = call_fixture_func(fixturefunc, request, kwargs,
-> 1827                                        self.yieldctx)
   1828         self.cached_result = (result, my_cache_key)
   1829         return result

  …/pytest/_pytest/python.py(1755)call_fixture_func()
   1753                     "Instead write and return an inner function/generator "
   1754                     "and let the consumer call and iterate over it.")
-> 1755         res = fixturefunc(**kwargs)
   1756     return res
   1757 

  …/virtualenv/lib/python2.7/site-packages/pytest_django/plugin.py(129)_django_runner()
    127         # Django >= 1.7: Call django.setup() to initialize Django
    128         setup = getattr(django, 'setup', lambda: None)
--> 129         setup()
    130 
    131         from django.test.simple import DjangoTestSuiteRunner

  …/django-master/django/__init__.py(21)setup()
     17     from django.conf import settings
     18     from django.utils.log import configure_logging
     19 
     20     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
---> 21     apps.populate(settings.INSTALLED_APPS)

  …/django-master/django/apps/registry.py(112)populate()
    110 
    111             for app_config in self.get_app_configs():
--> 112                 app_config.ready()
    113 
    114     def check_ready(self):

  …/django-master/django/apps/config.py(190)import_models()
    188         if module_has_submodule(self.module, MODELS_MODULE_NAME):
    189             models_module_name = '%s.%s' % (self.name, MODELS_MODULE_NAME)
--> 190             self.models_module = import_module(models_module_name)
    191 
    192     def ready(self):

  /usr/lib/python2.7/importlib/__init__.py(37)import_module()
     34                 break
     35             level += 1
     36         name = _resolve_name(name[level:], package, level)
---> 37     __import__(name)
     38     return sys.modules[name]

  …/tmm/movies/models.py(54)<module>()
     52 
     53 
---> 54 class Person(models.Model):
     55     name = models.CharField(max_length=255)
     56 

  …/django-master/django/db/models/base.py(299)__new__()
    297 
    298         new_class._prepare()
--> 299         new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
    300         return new_class
    301 

> …/django-master/django/apps/registry.py(201)register_model()
    199             raise RuntimeError(
    200                 "Conflicting '%s' models in application '%s': %s and %s." %
--> 201                 (model_name, app_label, app_models[model_name], model))
    202         app_models[model_name] = model
    203         self.clear_cache()

  …/pytest/_pytest/runner.py(139)__init__()
    137         try:
    138             try:
--> 139                 self.result = func()
    140             except KeyboardInterrupt:
    141                 raise

  …/pytest/_pytest/runner.py(126)<lambda>()
    124     hookname = "pytest_runtest_" + when
    125     ihook = getattr(item.ihook, hookname)
--> 126     return CallInfo(lambda: ihook(item=item, **kwds), when=when)
    127 
    128 class CallInfo:

  …/pytest/_pytest/main.py(162)call_matching_hooks()
    160         def call_matching_hooks(**kwargs):
    161             plugins = self.config._getmatchingplugins(self.fspath)
--> 162             return hookmethod.pcall(plugins, **kwargs)
    163         return call_matching_hooks
    164 

  …/pytest/_pytest/core.py(381)pcall()
    379     def pcall(self, plugins, **kwargs):
    380         methods = self.hookrelay._pm.listattr(self.name, plugins=plugins)
--> 381         return self._docall(methods, kwargs)
    382 
    383     def _docall(self, methods, kwargs):

  …/pytest/_pytest/core.py(388)_docall()
    386         mc = MultiCall(methods, kwargs, firstresult=self.firstresult)
    387         try:
--> 388             res = mc.execute()
    389             if res:
    390                 self.trace("finish", self.name, "-->", res)

  …/pytest/_pytest/core.py(289)execute()
    287             method = self.methods.pop()
    288             kwargs = self.getkwargs(method)
--> 289             res = method(**kwargs)
    290             if res is not None:
    291                 self.results.append(res)

  …/pytest/_pytest/runner.py(85)pytest_runtest_setup()
     83 
     84 def pytest_runtest_setup(item):
---> 85     item.session._setupstate.prepare(item)
     86 
     87 def pytest_runtest_call(item):

  …/pytest/_pytest/runner.py(384)prepare()
    382             self.stack.append(col)
    383             try:
--> 384                 col.setup()
    385             except Exception:
    386                 col._prepare_exc = sys.exc_info()

  …/pytest/_pytest/unittest.py(74)setup()
     72             self._testcase.setup_method(self._obj)
     73         if hasattr(self, "_request"):
---> 74             self._request._fillfixtures()
     75 
     76     def teardown(self):

  …/pytest/_pytest/python.py(1265)_fillfixtures()
   1263         for argname in fixturenames:
   1264             if argname not in item.funcargs:
-> 1265                 item.funcargs[argname] = self.getfuncargvalue(argname)
   1266 
   1267     def cached_setup(self, setup, teardown=None, scope="module", extrakey=None):

  …/pytest/_pytest/python.py(1313)getfuncargvalue()
   1311         function body.
   1312         """
-> 1313         return self._get_active_fixturedef(argname).cached_result[0]
   1314 
   1315     def _get_active_fixturedef(self, argname):

  …/pytest/_pytest/python.py(1327)_get_active_fixturedef()
   1325                     return PseudoFixtureDef
   1326                 raise
-> 1327             result = self._getfuncargvalue(fixturedef)
   1328             self._funcargs[argname] = result
   1329             self._fixturedefs[argname] = fixturedef

  …/pytest/_pytest/python.py(1379)_getfuncargvalue()
   1377         try:
   1378             # call the fixture function
-> 1379             val = fixturedef.execute(request=subrequest)
   1380         finally:
   1381             # if fixture function failed it might have registered finalizers

  …/pytest/_pytest/python.py(1827)execute()
   1825                     fixturefunc = fixturefunc.__get__(request.instance)
   1826             result = call_fixture_func(fixturefunc, request, kwargs,
-> 1827                                        self.yieldctx)
   1828         self.cached_result = (result, my_cache_key)
   1829         return result

  …/pytest/_pytest/python.py(1755)call_fixture_func()
   1753                     "Instead write and return an inner function/generator "
   1754                     "and let the consumer call and iterate over it.")
-> 1755         res = fixturefunc(**kwargs)
   1756     return res
   1757 

  …/virtualenv/lib/python2.7/site-packages/pytest_django/plugin.py(129)_django_runner()
    127         # Django >= 1.7: Call django.setup() to initialize Django
    128         setup = getattr(django, 'setup', lambda: None)
--> 129         setup()
    130 
    131         from django.test.simple import DjangoTestSuiteRunner

  …/django-master/django/__init__.py(21)setup()
     17     from django.conf import settings
     18     from django.utils.log import configure_logging
     19 
     20     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
---> 21     apps.populate(settings.INSTALLED_APPS)

  …/django-master/django/apps/registry.py(106)populate()
    104             for app_config in self.app_configs.values():
    105                 all_models = self.all_models[app_config.label]
--> 106                 app_config.import_models(all_models)
    107 
    108             self.clear_cache()

  …/django-master/django/apps/config.py(190)import_models()
    188         if module_has_submodule(self.module, MODELS_MODULE_NAME):
    189             models_module_name = '%s.%s' % (self.name, MODELS_MODULE_NAME)
--> 190             self.models_module = import_module(models_module_name)
    191 
    192     def ready(self):

  /usr/lib/python2.7/importlib/__init__.py(37)import_module()
     34                 break
     35             level += 1
     36         name = _resolve_name(name[level:], package, level)
---> 37     __import__(name)
     38     return sys.modules[name]

  …/tmm/movies/models.py(54)<module>()
     52 
     53 
---> 54 class Person(models.Model):
     55     name = models.CharField(max_length=255)
     56 

  …/django-master/django/db/models/base.py(299)__new__()
    297 
    298         new_class._prepare()
--> 299         new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
    300         return new_class
    301 

> …/django-master/django/apps/registry.py(201)register_model()
    199             raise RuntimeError(
    200                 "Conflicting '%s' models in application '%s': %s and %s." %
--> 201                 (model_name, app_label, app_models[model_name], model))
    202         app_models[model_name] = model
    203         self.clear_cache()


> RuntimeError: Conflicting 'person' models in application 'movies': <class 'tmm.tmm.movies.models.Person'> and <class 'movies.models.Person'>.

Add the current working directory to `sys.path` by default

As @rafales already commented, the only way to get pytest_django to work is to somehow modify the sys.path so the path with the settings file can be imported.

Since there is no way the project can work without having the settings file (or parent path depending on your setup) somewhere in sys.path, why isn't it the default setting? There should of course be a flag to disable modifying the sys.path but there is simply no way for it to work without any modification so why not save everyone the trouble and fix it by default :)

Setttings cannot be found on the sys path?

Hi all,
I do have the issue, that the settings module, which I defined, cannot be found on the sys path. Although, when I try to import the settings module manually, it just works fine. I have already asked for help and described the problem in more detail at: http://stackoverflow.com/questions/15199700/django-py-test-does-not-find-settings-module. But no help/resolution so far. I am not sure, if this is a bug or just a usage issue. But any help would be highly appreciated (otherwise I will not be able to use pytest in my Django projects).
Thanks
schacki

db modifications in a funcarg are not torn down

Since funcargs (apparently) run before pytest_runtest_setup, the Django run-a-test-within-a-transaction-and-roll-it-back-afterwards code does not encompass the code in the funcarg. Thus any model instances created in a funcarg are not rolled back after the test.

This may be actually ok, but is surprising when you first hit it and should probably be noted prominently somewhere. Or perhaps db access from a funcarg should be disabled by default?

Inability to work with django_pytds backend

In short, django_pytds have following code

    import sys

    if sys.version_info >= (2,7):
        # Django Ticket #17671 - Allow using a cursor as a ContextManager
        # in Python 2.7
        from django.db.backends.util import CursorWrapper
        if not hasattr(CursorWrapper, '__enter__'):
            enter = lambda self: self
            exit = lambda self, type, value, traceback: self.cursor.__exit__(type, value, traceback)

>           CursorWrapper.__enter__ = enter
E           AttributeError: 'instancemethod' object has no attribute '__enter__'

As you can see, django_pytds module expects to have a class named CursorWrapper

And when it have instancemethod instead it fails

You can say, off course, that this problem related to django_pytds module
But I think that task to emulate behavior of CursorWrapper is on pytest_django
And I think it is simple to implement CursorWrapper as a class

Thanks

Plugin stops testing non-django projects

Hi

When the plugin is installed testing a non-django project without having DJANGO_SETTINGS_MODULE results in an error. The reason (AFAIK) is that pytest_django.plugin, which is registered as the pytest11 entrypoint via "from .plugin import *" in pytest_django.init, does a direct "from django.conf import settings".

I'm not immediately sure how the plugin can detect it is testing a django application in order to decide to activate itself or not. But I think it would be beneficial to not have pytest-django break normal test runs by default.

Regards,
Floris

database creation not happening for LiveServerTestCase?

Am in Holger's py.test tutorial at the PyCon. Thought I'd try to get py.test working on a small test repo, and it looks like django.test.TestCase tests are working fine, including those that need the test database, but classes from django.test.LiveServerTestCase seem not to be seeing the test database...

Maybe I'm just confused?

here's the test repo: https://github.com/hjwp/book-example/tree/chapter_07

you'll need a virtualenv built with python3, django 1.7 beta, and selenium:

mkvirtualenv pytest-py3-superlists --python=python3
pip install selenium pytest pytest-django https://www.djangoproject.com/download/1.7b1/tarball/

and then

py.test lists/tests.py  # normal django tests, work fine
py.test functional_tests.py  # liveserver tests, fail seemingly because no db

Support cleanup between tests with multiple databases

pytest-django doesn't clean up between tests when using Django with multiple databases. The problem is related to this StackOverflow question: http://stackoverflow.com/questions/10121485/django-testcase-not-using-transactions-on-secondary-database

The db fixture uses Django's TestCase under the covers.

Here is the code from the original db fixture:

case = TestCase(methodName='__init__')
case._pre_setup()
request.addfinalizer(case._post_teardown)
request.addfinalizer(_django_cursor_wrapper.disable)

Here is how I patched it as a work-around in my code:

case = TestCase(methodName='__init__')
case.multi_db = True
case._pre_setup()
request.addfinalizer(case._post_teardown)
request.addfinalizer(_django_cursor_wrapper.disable)

Obviously that multi_db flag exists and defaults to False for a reason. I'm not sure the right way to incorporate multi_db support into pytest_django, and I'm not sure the right way to test such a change.

If you have a suggestion I can work on a pull request.

Multiple DJANGO_SETTINGS_MODULEs

I'm trying to get django-admin2 to work with pytest, but I ran into a few problems.

One of them is that we have two example apps that need to be tested, but they both have different settings.py files.

Is it possible to use different DJANGO_SETTINGS_MODULE values for different subdirectories? I tried adding a pytest.ini file to each of the apps, but that only works if pytest is invoked with the app directory as target directly.

ReverseUrl's failing first time through.

I am trying to use pytest-django with https://github.com/rcos/Observatory/tree/dev but for some reason the reverse urls are failing in the first test case they are called from.

Test cases are in Observatory/observatory/tests
The test runner script is in Observatory/dev
To actually run the tests, follow the readme instructions then do make unittest from the root directory.

I'm not sure whats going on here, does anyone have any ideas?

Python 3 support

With Django 1.5 around the corner, we should support Python 3 too!

setup examples

i've tried to find examples on how to use new fixture mark w/ pytest_django.
something like:

import pytest
from django.contrib.sites.models import Site
from django.contrib.auth.models import User

@pytest.fixture(scope="session", autouse=True)
@pytest.mark.django_db
def project_setup(*args, **kwargs):
    user = User.objects.create(username="session user #1")
    assert User.objects.count(), 1
    site, created = Site.objects.get_or_create(id=1)
    site.domain = "testserver"
    site.save()

to do some db modifications after test db is ready.
this fails w/ error "Failed: Database access not allowed, use the "django_db" mark to enable"

could somebody provide an example on howto setup additional stuff after test db is ready?

Fails to detect django settings are configured without env

It is possible to configure django using a django.conf.settings.configure() call, if this is done then pytest-django does not detect that it should be enabled. One way of reproducing this is:

django.conf.settings.configure(...)
pytest.main()

In which case pytest-django will not enable itself and the tests will fail.

bug in _get_test_db_name

You have code now:
if self.connection.settings_dict['TEST_NAME']:
original = self.connection.settings_dict['TEST_NAME']
original = 'test_' + self.connection.settings_dict['NAME']

but correct is:
if self.connection.settings_dict['TEST_NAME']:
original = self.connection.settings_dict['TEST_NAME']
else:
original = 'test_' + self.connection.settings_dict['NAME']

"Database access not allowed" error, although "django_db"/"live_server" is used

I am using pytest_django for a Selenium test (via the live_server fixture), and see the following error (delivered via Sentry).

The test works fine (login, clicking), but when I submit the form for a new model, it gets triggered.

The test has all the marks it needs (live_server should include transactional_db already):

pytestmark = pytest.mark.transactional_db

@pytest.mark.django_db
def test_submitter_login(browser, live_server, submitter, load_fixture_data):

I can work around this by commenting the manager.disable() line in _django_cursor_wrapper.

It does not happen always.

Also, there is no output from stderr being captured by py.test, which I get when manually throwing an exception.

Stacktrace:

File "django/core/handlers/base.py", line 113, in get_response
  response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "django/views/decorators/cache.py", line 52, in _wrapped_view_func
  response = view_func(request, *args, **kwargs)
File "django/contrib/admin/sites.py", line 334, in login
  if request.method == 'GET' and self.has_permission(request):
File "django/contrib/admin/sites.py", line 150, in has_permission
  return request.user.is_active and request.user.is_staff
File "django/utils/functional.py", line 224, in inner
  self._setup()
File "django/utils/functional.py", line 357, in _setup
  self._wrapped = self._setupfunc()
File "django/contrib/auth/middleware.py", line 18, in <lambda>
  request.user = SimpleLazyObject(lambda: get_user(request))
File "django/contrib/auth/middleware.py", line 10, in get_user
  request._cached_user = auth.get_user(request)
File "django/contrib/auth/__init__.py", line 144, in get_user
  user_id = request.session[SESSION_KEY]
File "django/contrib/sessions/backends/base.py", line 49, in __getitem__
  return self._session[key]
File "django/contrib/sessions/backends/base.py", line 175, in _get_session
  self._session_cache = self.load()
File "django/contrib/sessions/backends/db.py", line 21, in load
  expire_date__gt=timezone.now()
File "django/db/models/manager.py", line 92, in manager_method
  return getattr(self.get_queryset(), name)(*args, **kwargs)
File "django/db/models/query.py", line 346, in get
  num = len(clone)
File "django/db/models/query.py", line 122, in __len__
  self._fetch_all()
File "django/db/models/query.py", line 963, in _fetch_all
  self._result_cache = list(self.iterator())
File "django/db/models/query.py", line 265, in iterator
  for row in compiler.results_iter():
File "django/db/models/sql/compiler.py", line 694, in results_iter
  for rows in self.execute_sql(MULTI):
File "django/db/models/sql/compiler.py", line 778, in execute_sql
  cursor = self.connection.cursor()
File "django/db/backends/__init__.py", line 159, in cursor
  cursor = utils.CursorWrapper(self._cursor(), self)
File "pytest_django/plugin.py", line 238, in _blocking_wrapper
  pytest.fail('Database access not allowed, '
File "_pytest/runner.py", line 459, in fail
  raise Failed(msg=msg, pytrace=pytrace)

platform linux2 -- Python 2.7.5 -- py-1.4.20 -- pytest-2.5.3.dev1
plugins: django, ipdb

Easy fixture loading

I noticed that the helper function for loading fixtures was removed. Possibly it wasn't worth keeping around the way it was, but I was wondering if there was scope for something more useful.

The simplest thing would be a function that takes a list of fixtures and loads them. What would be even better would be to be able to use a fixtures variable within a class and have it automatically loaded as with Django's TestCases.

It does seem like a bit of a step backwards from the functionality of Django's built in testing to have to do this:

    def setup_class(self):
        fixtures = ['base.json', 'things.json']

        for fixture in fixtures:
            call_command('loaddata', fixture)

..even if it is just a few lines of code.

What do you think?

settings changed after initialization

example:

from django.conf import settings
print "debug: ", settings.DEBUG

def test_create_something():
    print 'settings: ', settings.DEBUG
    assert True == False

DEBUG is still True on line 2 but it's False on line 5 in test_create_something.

can't figure out why settings.DEBUG changed

Docs should mention standard database/settings rollback behavior

It would be nice if the documentation mentioned the way database rollbacks are handled for each test case as is mentioned in the plugin.py docstring:

Similar to Django's TestCase, a transaction is started and rolled back for each
test. Additionally, the settings are copied before each test and restored at
the end of the test, so it is safe to modify settings within tests.

pytest.mark.django_db doesn't play nice with setup_module()

Here is my test code:

import pytest
pytestmark = pytest.mark.django_db

from handy.db import do_sql, fetch_val

def setup_module(fetch_val):
    print 1
    do_sql('''
        create table test (
            id int primary key,
            tag int not null
        );

        insert into test values (1, 10), (2, 20);
    ''')
    print 2

def test_fetch_val():
    print 3
    assert fetch_val('select min(id) from test') == 1

And I get DatabaseError: relation "test" does not exist from test_fetch_val(). I also get

1
2
Creating test database for alias 'default'...
3

captured output. Looks like setup_module() is called before database is created.

Too agressive exception handling on settings module testing

Hi,

I had a problem where the only message I got was: ERROR: No module named core. It was impossible to trace down where it came from and no hint at all that it was from the pytest-django plugin. I think it would be nice if the error string in raise pytest.UsageError() started with something like "pytest-django failed to load the Django settings: " and then the error message. But maybe it is time to revisit the pytest.UsageError abuse and see if there's a better solution.

Most basic use case fails with "could not import myproj.settings"

I must have missed something.

I've installed py.test and pytest-django with pip

$ django-admin.py startproject myproj
$ cd myproj
$ python manage.py startapp myapp
$ DJANGO_SETTINGS_MODULE=myproj.settings py.test
ERROR: Could not import settings 'myproj.settings' (Is it on sys.path?): No module named myproj.settings

Have tried this both with my system python/pytest and with some installed freshly in a virtualenv.

pytest_sessionfinish hides database teardown errors

If there is an error in database teardown, the test run seems to just silently die, due to the output capturing in pytest_sessionfinish.

This may be more fully fixed by #9 - the short-term fix would be wrap the output-captured code in a try/finally, and write the captured stuff to stderr in the finally clause.

conftest.py presence changes sys.path and settings import

running py.test with DJANGO_SETTINGS_MODULE=myproject.settings py.test fails if there is no conftest.py file in root folder with ERROR: Could not import settings 'myproject.settings' (Is it on sys.path?): No module named myproject.settings

Consider a models funcarg

This is a split off from issue #9: consider creating a funcarg which has all the models available. See e.g. this snippet to load all models in use: http://djangosnippets.org/snippets/549/ The idea is that you then could use this in the test to manipulate the database. e.g.:

def test_foo(models):
    do_test_call()
    assert models.MyModel.get(...).attr = 'foo'

`INTERNALERROR> RuntimeError: Settings already configured` when using pytest_configure()

I'm confused about why my pytest_configure() function in conftest.py is throwing this error:

> py.test ./tests/application/test_templatetags.py
INTERNALERROR> Traceback (most recent call last):
INTERNALERROR>   File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/_pytest/main.py", line 77, in wrap_session
INTERNALERROR>     config.do_configure()
INTERNALERROR>   File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/_pytest/config.py", line 608, in do_configure
INTERNALERROR>     self.hook.pytest_configure(config=self)
INTERNALERROR>   File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/_pytest/core.py", line 368, in __call__
INTERNALERROR>     return self._docall(methods, kwargs)
INTERNALERROR>   File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/_pytest/core.py", line 379, in _docall
INTERNALERROR>     res = mc.execute()
INTERNALERROR>   File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/_pytest/core.py", line 297, in execute
INTERNALERROR>     res = method(**kwargs)
INTERNALERROR>   File "/Users/chaz/dev/projects/startupinst/tests/conftest.py", line 11, in pytest_configure
INTERNALERROR>     "NAME": ":memory:",
INTERNALERROR>   File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/django/conf/__init__.py", line 93, in configure
INTERNALERROR>     raise RuntimeError('Settings already configured.')
INTERNALERROR> RuntimeError: Settings already configured.

According to your docs, this seems really straightforward, so I'm not sure why this would happen.

I know that Django doesn't allow configure() to happen twice; my assumption is that defining it in pytest_configure() would cause the first and only configuration process.

The simple contents of my conftest.py:

import pytest
from django.conf import settings

def pytest_configure():
    settings.configure(
        EMAIL_BACKEND='django.core.mail.backends.console.EmailBackend',
        DATABASES={
            "default": {
                "ENGINE": "django.db.backends.sqlite3",
                "NAME": ":memory:",
            },
        }
    )

Do you see anything here that I'm doing wrong? Did I miss something from the docs?

Move db setup to item setup, require item mark for db access

Currently the Django database setup happens at pytest session setup, but errors there (e.g. incorrect model) result in py.test internal errors. This issue discusses moving the db setup to item setup with session-wide caching. It also proposes to remove the --no-db option and instead require each tests which uses the database to be marked as such.

Original report:

If you break the model you get an ugly INTERNALERROR. The quick and dirty fix for this is to wrap the setup_databases() call in pytest_sessionstart():

import pytest
...
try:
    old_db_config = runner.setup_databases()
except SystemExit:   # django is harsh
    raise pytest.UsageError('Django DB setup failed')

I'm not sure if there's a better way to resolve this, it does feel a bit odd to use UsageError but it gives a nice result:

~$ py.test app_reef/views_test.py
============================= test session starts ==============================
platform linux2 -- Python 2.7.3 -- pytest-2.2.1
Creating test database for alias 'default'...
Error: One or more models did not validate:
app_reef.eventattr: 'event' has a relation with model Events, which has either not been installed or is abstract.

ERROR: Django DB setup failed
~$

Checkout this django/pytest integration code

Carl Meyer, one of the Django core developers, told me he did integration of pytest/django. He claims his conftest plugin does all that the django test runner does. I am not familiar with Django code much so i just put the link here for Andreas or others to checkout and possible copy some lines.

https://gist.github.com/2936937

repeatedly prepending `test_` to database name, failure

Hi,

Can you please help me track down the problem I've started having when I run py.test on my project.

Some of the tests run successfully but at some point it goes wrong and I start getting errors creating the test database. In my postgres shell I see this:

ERROR:  database "test_myproject" already exists
STATEMENT:  CREATE DATABASE "test_myproject"
ERROR:  database "test_test_myproject" already exists
STATEMENT:  CREATE DATABASE "test_test_myproject"
ERROR:  database "test_test_test_myproject" already exists
STATEMENT:  CREATE DATABASE "test_test_test_myproject"
ERROR:  database "test_test_test_test_myproject" already exists
STATEMENT:  CREATE DATABASE "test_test_test_test_myproject"
ERROR:  database "test_test_test_test_test_myproject" already exists
STATEMENT:  CREATE DATABASE "test_test_test_test_test_myproject"
ERROR:  database "test_test_test_test_test_test_myproject" already exists
STATEMENT:  CREATE DATABASE "test_test_test_test_test_test_myproject"
ERROR:  database "test_test_test_test_test_test_test_myproject" already exists
STATEMENT:  CREATE DATABASE "test_test_test_test_test_test_test_myproject"
ERROR:  database "test_test_test_test_test_test_test_test_myproject" already exists
STATEMENT:  CREATE DATABASE "test_test_test_test_test_test_test_test_myproject"
ERROR:  database "test_test_test_test_test_test_test_test_test_myproject" already exists
STATEMENT:  CREATE DATABASE "test_test_test_test_test_test_test_test_test_myproject"
ERROR:  database "test_test_test_test_test_test_test_test_test_test_myproject" already exists

The tests were previously working fine, something must have changed but I don't know what. I have tests marked with @pytest.mark.django_db.

Any ideas?

Classifiers in setup.py

Could you add those classifiers to setup.py?

Programming Language :: Python :: 2.5
Programming Language :: Python :: 2.6
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3.2
Programming Language :: Python :: 3.3

It will tell pypi that this package supports python 3.

feature request, modifying sequences

Typos such as mistakenly writing user.pk instead of e.g. user.profile.pk are sometimes not caught in tests (e.g. assert may pass as both have pk==1). I wrote a small snippet to make such mistakes more easily blow up in tests. Perhaps a modification of it could be considered for an optional feature?

def setup_modified_seq(connection):
    # detect cases where we are using the wrong pk (either in test or in code, e.g. user.pk vs user.profile.pk)
    if connection.vendor == 'postgresql':
        print('is postgres vnedor:', connection.vendor)
        def get_seqs(cursor):
            cursor.execute("SELECT c.relname FROM pg_class c WHERE c.relkind = 'S'")
            for seq_row in cursor.fetchall():
                seq = seq_row[0]
                yield seq
        cursor = connection.cursor()
        for count, seq in enumerate(get_seqs(cursor)):
            cursor.execute("ALTER SEQUENCE {} RESTART WITH %s;".format(seq), [(count+1)*1000])

and in hook def pytest_configure(config): adding:

    from django.db import connections
    for connection in connections.all():
        from pytest_django.db_reuse import _monkeypatch
        create_test_db = connection.creation.create_test_db
        def create_test_db_with_modified_sequences(self, *args, **kwargs):
            create_test_db(*args, **kwargs)
            setup_modified_seq(connection)
        _monkeypatch(connection.creation, 'create_test_db', create_test_db_with_modified_sequences)

Inconsistent behaviour of db mark

When I was upgrading my project tests to use pytest_django plugin I've ran into this issue:

Currently @pytest.mark.django_db has (at least) 3 different behaviours

  • When using simple function based test you forget to add marker, you get:
    Failed: Database access not allowed, use the "django_db" mark to enable
  • When using tests as methods on unitest2.TestCase subclass you forget to add db marker, you get:
    ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value.
  • When using test as methods on django.test.TestCase subclass, the marker is completely ignored (You're always allowed yo use DB inside)

Probably this should be documented as a feature ;) or fixed to behave concisely for all cases.

Doesn't work out of the box

The out of the box experience with this package is very frustrating. I think I have spent the last hour trying to get this to work to no avail. This package doesn't work out of the box.

I installed pytest-django, then running py.test, I get lots of weird errors.

export PYTHONPATH=`pwd`
export DJANGO_SETTINGS_MODULE=myproject.settings

py.test

ImportError: Could not import settings 'myproject.settings' (Is it on sys.path?): No module named settings

Tried setup.py trick to install into virtualenv. No luck.

Let's try to run at least tests in a single app.

tree mobile_notifications/tests
mobile_notifications/tests
├── __init__.py
└── tests.py

0 directories, 2 files

py.test mobile_notifications/tests
========================================================= test session starts ==========================================================
platform darwin -- Python 2.7.3 -- py-1.4.20 -- pytest-2.5.2
collected 0 items 

===========================================================  in 0.00 seconds ===========================================================

It didn't collect any items.

Any ideas?

Easy fixture loading

Re-opening this bug. Sometimes you need to test your fixtures, would be very interesting to being able to load them on acceptance tests.

All tests fail with TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

self = <django.db.models.fields.related.ForeignKey: company>

    def get_default(self):
        "Here we check if the default value is an object and return the to_field if so."
        field_default = super(ForeignKey, self).get_default()
>       if isinstance(field_default, self.rel.to):
E       TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

../../../scv14/lib/python2.7/site-packages/django/db/models/fields/related.py:1038: TypeError

Basically any model touching test fails with the same error. Looks like it is a bug in Django, but wanted to know whether there is a workaround for this.

I have put

from django.db.models.loading import get_models
get_models()

to force loading of models in the test file, but the error persists.

django 1.3 ImportError

Hi,

Django 1.3 is listed as supported, however pytest_django.utils tries to import SimpleTestCase which is new in 1.4:

File "/home/flub/.local/lib/python2.7/site-packages/pytest_django/utils.py", line 3, in <module>
    from django.test.testcases import SimpleTestCase, TransactionTestCase, TestCase
ImportError: cannot import name SimpleTestCase

pytest.mark.django_db(transaction=True) doesn't allow database access to fixtures used in a test

I have the following test that fails only when transaction=True. If I remove transaction=True, the test succeeds. It seems to me that the fixture should be able to use the database in this case. (I've included the traceback at the end)

import pytest

@pytest.fixture
def user(db):
    """
    Create a test user.
    """
    from django.contrib.auth.models import User
    user = User.objects.create_user('test', '[email protected]', 'test')
    return user

@pytest.mark.django_db(transaction=True)
def test_transaction_true_db_fixture(user):
    assert True

It also works (and I think it rolls back the transaction) if I write the test like this:

@pytest.mark.django_db
def test_transaction_true_db_fixture(user, transactional_db):
    assert True

Traceback:

============================= test session starts ==============================
platform darwin -- Python 2.7.4 -- pytest-2.3.4
plugins: django
collected 1 items

test_transactions.py .E

==================================== ERRORS ====================================
____________ ERROR at teardown of test_transaction_true_db_fixture _____________

    def flushdb():
        """Flush the database and close database connections"""
        # Django does this by default *before* each test
        # instead of after.
        from django.db import connections
        from django.core.management import call_command

        for db in connections:
            call_command('flush', verbosity=0,
>                        interactive=False, database=db)

../../.virtualenvs/578475623c447d29/lib/python2.7/site-packages/pytest_django/fixtures.py:107: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

name = 'flush', args = ()
options = {'database': 'default', 'interactive': False, 'verbosity': 0}
app_name = 'django.core'
klass = <django.core.management.commands.flush.Command object at 0x106d48510>
defaults = {'database': 'default', 'interactive': False, 'load_initial_data': True, 'pythonpath': None, ...}
opt = <Option at 0x106dabd88: --no-initial-data>

    def call_command(name, *args, **options):
        """
        Calls the given command, with the given options and args/kwargs.

        This is the primary API you should use for calling specific commands.

        Some examples:
            call_command('syncdb')
            call_command('shell', plain=True)
            call_command('sqlall', 'myapp')
        """
        # Load the command object.
        try:
            app_name = get_commands()[name]
        except KeyError:
            raise CommandError("Unknown command: %r" % name)

        if isinstance(app_name, BaseCommand):
            # If the command is already loaded, use it directly.
            klass = app_name
        else:
            klass = load_command_class(app_name, name)

        # Grab out a list of defaults from the options. optparse does this for us
        # when the script runs from the command line, but since call_command can
        # be called programatically, we need to simulate the loading and handling
        # of defaults (see #10080 for details).
        defaults = {}
        for opt in klass.option_list:
            if opt.default is NO_DEFAULT:
                defaults[opt.dest] = None
            else:
                defaults[opt.dest] = opt.default
        defaults.update(options)

>       return klass.execute(*args, **defaults)

../../.virtualenvs/578475623c447d29/lib/python2.7/site-packages/django/core/management/__init__.py:161: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <django.core.management.commands.flush.Command object at 0x106d48510>
args = ()
options = {'database': 'default', 'interactive': False, 'load_initial_data': True, 'pythonpath': None, ...}
saved_lang = 'en-us'
translation = <module 'django.utils.translation' from '/Users/rouge8/.virtualenvs/578475623c447d29/lib/python2.7/site-packages/django/utils/translation/__init__.pyc'>

    def execute(self, *args, **options):
        """
            Try to execute this command, performing model validation if
            needed (as controlled by the attribute
            ``self.requires_model_validation``, except if force-skipped).
            """

        # Switch to English, because django-admin.py creates database content
        # like permissions, and those shouldn't contain any translations.
        # But only do this if we can assume we have a working settings file,
        # because django.utils.translation requires settings.
        saved_lang = None
        self.stdout = OutputWrapper(options.get('stdout', sys.stdout))
        self.stderr = OutputWrapper(options.get('stderr', sys.stderr), self.style.ERROR)

        if self.can_import_settings:
            from django.utils import translation
            saved_lang = translation.get_language()
            translation.activate('en-us')

        try:
            if self.requires_model_validation and not options.get('skip_validation'):
                self.validate()
>           output = self.handle(*args, **options)

../../.virtualenvs/578475623c447d29/lib/python2.7/site-packages/django/core/management/base.py:255: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <django.core.management.commands.flush.Command object at 0x106d48510>
args = ()
options = {'database': 'default', 'interactive': False, 'load_initial_data': True, 'pythonpath': None, ...}

    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")
>       return self.handle_noargs(**options)

../../.virtualenvs/578475623c447d29/lib/python2.7/site-packages/django/core/management/base.py:385: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <django.core.management.commands.flush.Command object at 0x106d48510>
options = {'database': 'default', 'interactive': False, 'load_initial_data': True, 'pythonpath': None, ...}
db = 'default'
connection = <django.db.backends.sqlite3.base.DatabaseWrapper object at 0x1069a2210>
verbosity = 0, interactive = False, reset_sequences = True
app_name = 'django.contrib.staticfiles'

    def handle_noargs(self, **options):
        db = options.get('database')
        connection = connections[db]
        verbosity = int(options.get('verbosity'))
        interactive = options.get('interactive')
        # 'reset_sequences' is a stealth option
        reset_sequences = options.get('reset_sequences', True)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                import_module('.management', app_name)
            except ImportError:
                pass

>       sql_list = sql_flush(self.style, connection, only_django=True, reset_sequences=reset_sequences)

../../.virtualenvs/578475623c447d29/lib/python2.7/site-packages/django/core/management/commands/flush.py:46: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

style = <[TypeError("<lambda>() takes exactly 1 argument (0 given)") raised in repr()] dummy object at 0x106d496c8>
connection = <django.db.backends.sqlite3.base.DatabaseWrapper object at 0x1069a2210>
only_django = True, reset_sequences = True

    def sql_flush(style, connection, only_django=False, reset_sequences=True):
        """
        Returns a list of the SQL statements used to flush the database.

        If only_django is True, then only table names that have associated Django
        models and are in INSTALLED_APPS will be included.
        """
        if only_django:
>           tables = connection.introspection.django_table_names(only_existing=True)

../../.virtualenvs/578475623c447d29/lib/python2.7/site-packages/django/core/management/sql.py:113: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <django.db.backends.sqlite3.introspection.DatabaseIntrospection object at 0x1069a2ed0>
only_existing = True

    def django_table_names(self, only_existing=False):
        """
            Returns a list of all table names that have associated Django models and
            are in INSTALLED_APPS.

            If only_existing is True, the resulting list will only include the tables
            that actually exist in the database.
            """
        from django.db import models, router
        tables = set()
        for app in models.get_apps():
            for model in models.get_models(app):
                if not model._meta.managed:
                    continue
                if not router.allow_syncdb(self.connection.alias, model):
                    continue
                tables.add(model._meta.db_table)
                tables.update([f.m2m_db_table() for f in model._meta.local_many_to_many])
        tables = list(tables)
        if only_existing:
>           existing_tables = self.table_names()

../../.virtualenvs/578475623c447d29/lib/python2.7/site-packages/django/db/backends/__init__.py:995: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <django.db.backends.sqlite3.introspection.DatabaseIntrospection object at 0x1069a2ed0>
cursor = None

    def table_names(self, cursor=None):
        """
            Returns a list of names of all tables that exist in the database.
            The returned table list is sorted by Python's default sorting. We
            do NOT use database's ORDER BY here to avoid subtle differences
            in sorting order between databases.
            """
        if cursor is None:
>           cursor = self.connection.cursor()

../../.virtualenvs/578475623c447d29/lib/python2.7/site-packages/django/db/backends/__init__.py:965: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <django.db.backends.sqlite3.base.DatabaseWrapper object at 0x1069a2210>

    def cursor(self):
        self.validate_thread_sharing()
        if (self.use_debug_cursor or
            (self.use_debug_cursor is None and settings.DEBUG)):
            cursor = self.make_debug_cursor(self._cursor())
        else:
>           cursor = util.CursorWrapper(self._cursor(), self)
E           Failed: Database access not allowed, use the "django_db" mark to enable

../../.virtualenvs/578475623c447d29/lib/python2.7/site-packages/django/db/backends/__init__.py:326: Failed
------------------------------- Captured stdout --------------------------------
Creating test database for alias 'default'...
=========================== short test summary info ============================
ERROR test_transactions.py::test_transaction_true_db_fixture
====================== 1 passed, 1 error in 0.37 seconds =======================
Destroying test database for alias 'default'...

alternative database setup shemes

at work we have a large set of fixtures, an option to copy a database from a template would be helpful

it can be file copies in sqlite and db template in postgresql

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.