@@ -184,6 +184,10 @@ def pytest_load_initial_conftests(early_config, parser, args):
184
184
'the `urls` attribute of Django `TestCase` objects. *modstr* is '
185
185
'a string specifying the module of a URL config, e.g. '
186
186
'"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' )
187
191
188
192
options = parser .parse_known_args (args )
189
193
@@ -600,6 +604,47 @@ def _django_clear_site_cache():
600
604
from django .contrib .sites .models import Site
601
605
Site .objects .clear_cache ()
602
606
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
+
603
648
# ############### Helper Functions ################
604
649
605
650
0 commit comments