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,
):
    """This is an override of the original implementation in the https://github.com/pytest-dev/pytest-django plugin
    from file /pytest-django/fixtures.py.

    Because this "hides" the original implementation, it may get out-of-date as that plugin is upgraded. This override
    takes the implementation from pytest-django Release 3.5.1, and extends it in order to execute materialized views
    as part of database setup.

    If requirements.txt shows a different version than the one this is based on: compare, update, and test.
    More work could be put into trying to patch, replace, or wrap implementation of
    ``django.test.utils.setup_databases``, which is the actual method that needs to be wrapped and extended.
    """
    from pytest_django.compat import setup_databases, teardown_databases
    from pytest_django.fixtures import _disable_native_migrations

    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)
        # If migrations are skipped, assume matviews and views are not to be (re)created either
        # Other scenarios (such as reuse or keep DB) may still lead to creation of a non-existent DB, so they must be
        # (re)created under those conditions
        if not django_db_use_migrations:
            logger.warning(
                "Skipping generation of materialized views or other views in this test run because migrations are also "
                "being skipped. ")
        else:
            generate_matviews()
            ensure_transaction_etl_view_exists()

    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)
Beispiel #2
0
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,
):
    """
    Copied and pasted from here:
    https://github.com/pytest-dev/pytest-django/blob/d2973e21c34d843115acdbccdd7a16cb2714f4d3/pytest_django/fixtures.py#L84

    We override this fixture and give it a "function" scope as a hack to force
    the test database to be re-created per test case.  This causes the same
    database ids to be used for payment records in each test run.  Usage of the
    `reset_sequences` flag provided by pytest-django isn't always sufficient
    since it can depend on whether or not a particular database supports
    sequence resets.

    As an example of why sequence resets are necessary, tests in the
    `tests.integration.test_confirm_payments` module will fail if database ids
    are not reset per test function.  This is because the test wallet on the
    Goerli test net must hardcode payment ids into transactions and token
    transfers.  If payment ids don't deterministically begin at 1 per test
    case, payment ids in the Goerli test wallet won't correctly correspond to
    payment ids generated during test runs.
    """
    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)
Beispiel #3
0
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,
                    enable_migration_signals, pytestconfig):
    if django_db_createdb or enable_migration_signals:
        warnings.warn("Warning: pre/post migrate signals are enabled \n")
    else:
        warnings.warn("Warning: pre/post migrate signals have been disabled\n")
        import django.core.management.commands.migrate
        django.core.management.commands.migrate.emit_pre_migrate_signal = MagicMock(
        )
        django.core.management.commands.migrate.emit_post_migrate_signal = MagicMock(
        )

    # """Top level fixture to ensure test databases are available"""
    from django.test.utils import setup_databases, teardown_databases

    from pytest_django.fixtures import _disable_native_migrations
    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
    # this patch is logically wrong, but we do not use constance permissions
    # otherwise test fails with
    #
    # .venv/lib/python3.9/site-packages/django/db/backends/utils.py:84: in _execute
    #     return self.cursor.execute(sql, params)
    # E   django.db.utils.ProgrammingError: relation "django_content_type" does not exist
    # E   LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co...
    # E                                                                ^
    #
    signals.post_migrate.disconnect(dispatch_uid='constance.create_perm')
    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():
            teardown_databases(db_cfg, verbosity=request.config.option.verbose)

    if not django_db_keepdb:
        request.addfinalizer(_teardown_database)

    from test_utilities.factories import UserFactory

    from unicef_rest_framework.models import Service, UserAccessControl

    from etools_datamart.apps.etl.models import EtlTask
    from etools_datamart.apps.tracking.models import APIRequestLog

    with django_db_blocker.unblock():
        EtlTask.objects.inspect()
        Service.objects.load_services()
        UserAccessControl.objects.all().delete()
        APIRequestLog.objects.truncate()
        UserFactory(username='******', is_superuser=True)
        from django.contrib.sites.models import Site
        Site.objects.get_or_create(domain='example.com', name='example.com')
        assert Service.objects.exists()
        assert not APIRequestLog.objects.exists()