How to create table during Django tests with managed = False

前端 未结 9 1928
执笔经年
执笔经年 2020-12-24 12:25

I have a model with managed = False.

class SampleModel(models.Model):
    apple = models.CharField(max_length=30)
    orange = models.CharField(max_length=3         


        
9条回答
  •  臣服心动
    2020-12-24 12:49

    Using pytest and pytest-django

    To make this work (has been tested with django 3.0.2, pytest 5.3.5 and pytest-django 3.8.0):

    1. Run your pytest with the additional argument --no-migrations.
    2. Put the following code in your conftest.py. This has an unfortunate amount of copypasta, but I could not figure out how to first make my models unmanaged and then call the original django_db_setup. The issue of not being able to call pytest fixtures directly is discussed here: https://github.com/pytest-dev/pytest/issues/3950

    conftest.py

    # example file
    import pytest
    from pytest_django.fixtures import _disable_native_migrations
    
    
    @pytest.fixture(scope="session")
    def django_db_setup(
            request,
            django_test_environment,
            django_db_blocker,
            django_db_use_migrations,
            django_db_keepdb,
            django_db_createdb,
            django_db_modify_db_settings,
    ):
        # make unmanaged models managed
        from django.apps import apps
        unmanaged_models = []
        for app in apps.get_app_configs():
            unmanaged_models = [m for m in app.get_models()
                                if not m._meta.managed]
        for m in unmanaged_models:
            m._meta.managed = True
    
        # copypasta fixture code
    
        """Top level fixture to ensure test databases are available"""
        from pytest_django.compat import setup_databases, teardown_databases
    
        setup_databases_args = {}
    
        if not django_db_use_migrations:
            _disable_native_migrations()
    
        if django_db_keepdb and not django_db_createdb:
            setup_databases_args["keepdb"] = True
    
        with django_db_blocker.unblock():
            db_cfg = setup_databases(
                verbosity=request.config.option.verbose,
                interactive=False,
                **setup_databases_args
            )
    
        def teardown_database():
            with django_db_blocker.unblock():
                try:
                    teardown_databases(db_cfg, verbosity=request.config.option.verbose)
                except Exception as exc:
                    request.node.warn(
                        pytest.PytestWarning(
                            "Error when trying to teardown test databases: %r" % exc
                        )
                    )
    
        if not django_db_keepdb:
            request.addfinalizer(teardown_database)
    

提交回复
热议问题