Skip to content

Commit 5b63465

Browse files
committed
retaking support for unmanaged models, see pytest-dev#310
working code from timb07@176ac9f see pytest-dev#270
1 parent 9996d43 commit 5b63465

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

pytest_django/plugin.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,10 @@ def pytest_load_initial_conftests(early_config, parser, args):
184184
'the `urls` attribute of Django `TestCase` objects. *modstr* is '
185185
'a string specifying the module of a URL config, e.g. '
186186
'"my_app.test_urls".')
187+
early_config.addinivalue_line(
188+
'markers',
189+
'django_use_model(model=Unmanaged): force model creation, where Unmanaged is your unmanaged model.'
190+
'Model(s) are deleted at the end of scope')
187191

188192
options = parser.parse_known_args(args)
189193

@@ -600,6 +604,47 @@ def _django_clear_site_cache():
600604
from django.contrib.sites.models import Site
601605
Site.objects.clear_cache()
602606

607+
@pytest.fixture(autouse=True)
608+
def _django_use_model(request):
609+
"""Implement ``django_use_model`` marker.
610+
611+
Marker creates unmanaged models that normally aren't created.
612+
Destroys it at the end of marked scope.
613+
614+
Note that you still need to use ``django_db`` marker before this one.
615+
The test unit should be decorated:
616+
617+
@pytest.mark.django_db
618+
@pytest.mark.django_use_model(model=ModelClass)
619+
620+
:model: ModelClass, one or many
621+
"""
622+
marker = request.keywords.get('django_use_model', None)
623+
if not marker:
624+
return
625+
from django.db import connection
626+
627+
model = marker.kwargs['model']
628+
629+
if isinstance(model, (list, tuple)):
630+
models = model
631+
else:
632+
models = (model,)
633+
634+
with connection.schema_editor() as schema:
635+
schema.deferred_sql = []
636+
for model_class in models:
637+
if not hasattr(model, '_meta'):
638+
raise ValueError('"model" must be a valid model class')
639+
schema.create_model(model_class)
640+
641+
def drop():
642+
with connection.schema_editor() as schema:
643+
for model_class in models:
644+
schema.delete_model(model_class)
645+
646+
request.addfinalizer(drop)
647+
603648
# ############### Helper Functions ################
604649

605650

0 commit comments

Comments
 (0)