Multi db and unmanged models - Test case are failing

微笑、不失礼 提交于 2019-12-08 08:15:28

I can show you how I am solving this issue;

So I've created a signal, which more or less looks like this:

def create_test_models(**kwargs):
    if "test" in sys.argv:
        Organization = apps.get_model("organizations.Organization")
        ...  # other models here too
        # as we do not manage it - we need to create it manually;
        with connection.schema_editor() as schema_editor:
            sid = transaction.savepoint()
            try:
                schema_editor.create_model(Organization)
                ... # different models here if needed
                transaction.savepoint_commit(sid)
            except ProgrammingError:  # tables already exists;
                transaction.savepoint_rollback(sid)

This signal is connected in the config as pre_migrate signal:

class OrganizationsConfig(AppConfig):
    name = "engine.organizations"

    def ready(self):
        # run after each migration; so each deploy, but this method can handle the
        # incremental updates.
        pre_migrate.connect(create_test_models, sender=self)

It is maybe not super solution - but it is working and you have models created during tests and you can play with them or create test data etc.

Hope that this will help you to move forward.

I found a good solution working in current django 2.2. Works perfectly with pytest-django, but will probably work even without pytest.

To make it work, you need to:

  1. split your project into two django apps. One will contain only the unmanaged models and the other will contain the rest. Don't specify managed = False in any of these two apps

  2. in settings.py in DATABASES you will have two databases, one is default and one is your external DB

  3. In the same folder where you have settings, create routers.py and implement a router that will route based on app label to given DB (cca 45 lines including checks that you will never ever write to these external DBs). Then add this router to settings.py's ROUTERS list.

When running tests with pytest, it really creates all tables for apps that don't have migrations folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!