def test_invalid_template_variable(django_testdir):
    django_testdir.create_app_file("""
        from django.conf.urls import url
        from pytest_django_test.compat import patterns

        from tpkg.app import views

        urlpatterns = patterns(
            '',
            url(r'invalid_template/', views.invalid_template),
        )
        """, 'urls.py')
    django_testdir.create_app_file("""
        from django.shortcuts import render


        def invalid_template(request):
            return render(request, 'invalid_template.html', {})
        """, 'views.py')
    django_testdir.create_app_file(
        "<div>{{ invalid_var }}</div>",
        'templates/invalid_template_base.html'
    )
    django_testdir.create_app_file(
        "{% extends 'invalid_template_base.html' %}",
        'templates/invalid_template.html'
    )
    django_testdir.create_test_module('''
        import pytest

        def test_for_invalid_template(client):
            client.get('/invalid_template/')

        @pytest.mark.ignore_template_errors
        def test_ignore(client):
            client.get('/invalid_template/')
        ''')
    result = django_testdir.runpytest_subprocess('-s', '--fail-on-template-vars')

    if get_django_version() >= (1, 9):
        origin = "'*/tpkg/app/templates/invalid_template_base.html'"
    else:
        origin = "'invalid_template.html'"
    result.stdout.fnmatch_lines_random([
        "tpkg/test_the_test.py F.",
        "E * Failed: Undefined template variable 'invalid_var' in {}".format(origin)
    ])
            '*Operations to perform:*',
            "*Apply all migrations:*",
            "*PASSED*Destroying test database for alias 'default' ('*')...*"])

    def test_more_verbose_with_vv_and_reusedb(self, testdir):
        """More verbose output with '-v -v', and --create-db."""
        result = testdir.runpytest_subprocess('-s', '-v', '-v', '--create-db')
        result.stdout.fnmatch_lines([
            "tpkg/test_the_test.py:*Creating test database for alias*",
            "*PASSED*"])
        assert ("*Destroying test database for alias 'default' ('*')...*"
                not in result.stdout.str())


@pytest.mark.skipif(
    get_django_version() < (1, 8),
    reason='Django 1.7 requires settings.SITE_ID to be set, so this test is invalid'
)
@pytest.mark.django_db
@pytest.mark.parametrize('site_name', ['site1', 'site2'])
def test_clear_site_cache(site_name, rf, monkeypatch):
    request = rf.get('/')
    monkeypatch.setattr(request, 'get_host', lambda: 'foo.com')
    Site.objects.create(domain='foo.com', name=site_name)
    assert Site.objects.get_current(request=request).name == site_name


@pytest.mark.django_db
@pytest.mark.parametrize('site_name', ['site1', 'site2'])
def test_clear_site_cache_check_site_cache_size(site_name, settings):
    assert len(site_models.SITE_CACHE) == 0
Example #3
0
 def __init__(self):
     self._django_version = get_django_version()
                db_name = conn_default.creation._get_test_db_name()
                assert 'file:memorydb' in db_name

                assert conn_db2.vendor == 'sqlite'
                db_name = conn_db2.creation._get_test_db_name()
                assert 'test_custom_db_name_gw' in db_name
        """)

        result = django_testdir.runpytest_subprocess("--tb=short", "-vv",
                                                     "-n1")
        assert result.ret == 0
        result.stdout.fnmatch_lines(["*PASSED*test_a*"])


@pytest.mark.skipif(
    get_django_version() >= (1, 9),
    reason=
    ("Django 1.9 requires migration and has no concept of initial data fixtures"
     ),
)
def test_initial_data(django_testdir_initial):
    """Test that initial data gets loaded."""
    django_testdir_initial.create_test_module("""
        import pytest

        from .app.models import Item

        @pytest.mark.django_db
        def test_inner():
            assert [x.name for x in Item.objects.all()] \
                == ["mark_initial_data"]
class TestLiveServer:
    def test_url(self, live_server):
        assert live_server.url == force_text(live_server)

    def test_transactions(self, live_server):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert not connection.in_atomic_block

    def test_db_changes_visibility(self, live_server):
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 0'
        Item.objects.create(name='foo')
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    def test_fixture_db(self, db, live_server):
        Item.objects.create(name='foo')
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    def test_fixture_transactional_db(self, transactional_db, live_server):
        Item.objects.create(name='foo')
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    @pytest.fixture
    def item(self):
        # This has not requested database access explicitly, but the
        # live_server fixture auto-uses the transactional_db fixture.
        Item.objects.create(name='foo')

    def test_item(self, item, live_server):
        pass

    @pytest.fixture
    def item_db(self, db):
        return Item.objects.create(name='foo')

    def test_item_db(self, item_db, live_server):
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    @pytest.fixture
    def item_transactional_db(self, transactional_db):
        return Item.objects.create(name='foo')

    def test_item_transactional_db(self, item_transactional_db, live_server):
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    @pytest.mark.django_project(extra_settings="""
        INSTALLED_APPS = [
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.staticfiles',
            'tpkg.app',
        ]

        STATIC_URL = '/static/'
        """)
    def test_serve_static_with_staticfiles_app(self, django_testdir, settings):
        """
        LiveServer always serves statics with ``django.contrib.staticfiles``
        handler.
        """
        django_testdir.create_test_module("""
            import pytest
            from django.utils.encoding import force_text

            try:
                from urllib2 import urlopen, HTTPError
            except ImportError:
                from urllib.request import urlopen, HTTPError

            class TestLiveServer:
                def test_a(self, live_server, settings):
                    assert ('django.contrib.staticfiles'
                            in settings.INSTALLED_APPS)
                    response_data = urlopen(
                        live_server + '/static/a_file.txt').read()
                    assert force_text(response_data) == 'bla\\n'
            """)
        result = django_testdir.runpytest_subprocess('--tb=short', '-v')
        result.stdout.fnmatch_lines(['*test_a*PASSED*'])
        assert result.ret == 0

    def test_serve_static_dj17_without_staticfiles_app(self, live_server,
                                                       settings):
        """
        Because ``django.contrib.staticfiles`` is not installed
        LiveServer can not serve statics with django >= 1.7 .
        """
        with pytest.raises(HTTPError):
            urlopen(live_server + '/static/a_file.txt').read()

    @pytest.mark.skipif(get_django_version() < (1, 11),
                        reason='Django >= 1.11 required')
    def test_specified_port_range_error_message_django_111(self, django_testdir):
        django_testdir.create_test_module("""
        def test_with_live_server(live_server):
            pass
        """)

        result = django_testdir.runpytest_subprocess('--liveserver=localhost:1234-2345')
        result.stdout.fnmatch_lines([
            '*Specifying multiple live server ports is not supported in Django 1.11. This '
            'will be an error in a future pytest-django release.*'
        ])

    @pytest.mark.skipif(get_django_version() < (1, 11, 2),
                        reason='Django >= 1.11.2 required')
    def test_specified_port_django_111(self, django_testdir):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.bind(('', 0))
            __, port = sock.getsockname()
        finally:
            sock.close()

        django_testdir.create_test_module("""
        def test_with_live_server(live_server):
            assert live_server.port == %d
        """ % port)

        django_testdir.runpytest_subprocess('--liveserver=localhost:%s' % port)
class TestLiveServer:
    def test_settings_before(self):
        from django.conf import settings

        assert ("%s.%s" %
                (settings.__class__.__module__,
                 settings.__class__.__name__) == "django.conf.Settings")
        TestLiveServer._test_settings_before_run = True

    def test_url(self, live_server):
        assert live_server.url == force_text(live_server)

    def test_change_settings(self, live_server, settings):
        assert live_server.url == force_text(live_server)

    def test_settings_restored(self):
        """Ensure that settings are restored after test_settings_before."""
        import django
        from django.conf import settings

        assert TestLiveServer._test_settings_before_run is True
        assert ("%s.%s" %
                (settings.__class__.__module__,
                 settings.__class__.__name__) == "django.conf.Settings")
        if django.VERSION >= (1, 11):
            assert settings.ALLOWED_HOSTS == ["testserver"]
        else:
            assert settings.ALLOWED_HOSTS == ["*"]

    def test_transactions(self, live_server):
        if not connections_support_transactions():
            pytest.skip("transactions required for this test")

        assert not connection.in_atomic_block

    def test_db_changes_visibility(self, live_server):
        response_data = urlopen(live_server + "/item_count/").read()
        assert force_text(response_data) == "Item count: 0"
        Item.objects.create(name="foo")
        response_data = urlopen(live_server + "/item_count/").read()
        assert force_text(response_data) == "Item count: 1"

    def test_fixture_db(self, db, live_server):
        Item.objects.create(name="foo")
        response_data = urlopen(live_server + "/item_count/").read()
        assert force_text(response_data) == "Item count: 1"

    def test_fixture_transactional_db(self, transactional_db, live_server):
        Item.objects.create(name="foo")
        response_data = urlopen(live_server + "/item_count/").read()
        assert force_text(response_data) == "Item count: 1"

    @pytest.fixture
    def item(self):
        # This has not requested database access explicitly, but the
        # live_server fixture auto-uses the transactional_db fixture.
        Item.objects.create(name="foo")

    def test_item(self, item, live_server):
        pass

    @pytest.fixture
    def item_db(self, db):
        return Item.objects.create(name="foo")

    def test_item_db(self, item_db, live_server):
        response_data = urlopen(live_server + "/item_count/").read()
        assert force_text(response_data) == "Item count: 1"

    @pytest.fixture
    def item_transactional_db(self, transactional_db):
        return Item.objects.create(name="foo")

    def test_item_transactional_db(self, item_transactional_db, live_server):
        response_data = urlopen(live_server + "/item_count/").read()
        assert force_text(response_data) == "Item count: 1"

    @pytest.mark.django_project(extra_settings="""
        INSTALLED_APPS = [
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.staticfiles',
            'tpkg.app',
        ]

        STATIC_URL = '/static/'
        """)
    def test_serve_static_with_staticfiles_app(self, django_testdir, settings):
        """
        LiveServer always serves statics with ``django.contrib.staticfiles``
        handler.
        """
        django_testdir.create_test_module("""
            import pytest
            from django.utils.encoding import force_text

            try:
                from urllib2 import urlopen, HTTPError
            except ImportError:
                from urllib.request import urlopen, HTTPError

            class TestLiveServer:
                def test_a(self, live_server, settings):
                    assert ('django.contrib.staticfiles'
                            in settings.INSTALLED_APPS)
                    response_data = urlopen(
                        live_server + '/static/a_file.txt').read()
                    assert force_text(response_data) == 'bla\\n'
            """)
        result = django_testdir.runpytest_subprocess("--tb=short", "-v")
        result.stdout.fnmatch_lines(["*test_a*PASSED*"])
        assert result.ret == 0

    def test_serve_static_dj17_without_staticfiles_app(self, live_server,
                                                       settings):
        """
        Because ``django.contrib.staticfiles`` is not installed
        LiveServer can not serve statics with django >= 1.7 .
        """
        with pytest.raises(HTTPError):
            urlopen(live_server + "/static/a_file.txt").read()

    @pytest.mark.skipif(get_django_version() < (1, 11),
                        reason="Django >= 1.11 required")
    def test_specified_port_range_error_message_django_111(
            self, django_testdir):
        django_testdir.create_test_module("""
        def test_with_live_server(live_server):
            pass
        """)

        result = django_testdir.runpytest_subprocess(
            "--liveserver=localhost:1234-2345")
        result.stdout.fnmatch_lines([
            "*Specifying multiple live server ports is not supported in Django 1.11. This "
            "will be an error in a future pytest-django release.*"
        ])

    @pytest.mark.skipif(get_django_version() < (1, 11, 2),
                        reason="Django >= 1.11.2 required")
    def test_specified_port_django_111(self, django_testdir):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.bind(("", 0))
            __, port = sock.getsockname()
        finally:
            sock.close()

        django_testdir.create_test_module("""
        def test_with_live_server(live_server):
            assert live_server.port == %d
        """ % port)

        django_testdir.runpytest_subprocess("--liveserver=localhost:%s" % port)
            @pytest.mark.django_db
            def test_a():
                (conn, ) = connections.all()

                assert conn.vendor == 'sqlite'
                db_name = conn.creation._get_test_db_name()
                assert 'file:memorydb' in db_name or db_name == ':memory:'
        ''')

        result = django_testdir.runpytest_subprocess('--tb=short', '-vv',
                                                     '-n1')
        assert result.ret == 0
        result.stdout.fnmatch_lines(['*PASSED*test_a*'])


@pytest.mark.skipif(get_django_version() >= (1, 9),
                    reason=('Django 1.9 requires migration and has no concept '
                            'of initial data fixtures'))
def test_initial_data(django_testdir_initial):
    """Test that initial data gets loaded."""
    django_testdir_initial.create_test_module('''
        import pytest

        from .app.models import Item

        @pytest.mark.django_db
        def test_inner():
            assert [x.name for x in Item.objects.all()] \
                == ["mark_initial_data"]
    ''')
Example #8
0
def nonverbose_config(config) -> Generator[None, None, None]:
    """Ensure that pytest's config.option.verbose is <= 0."""
    if config.option.verbose <= 0:
        yield
    else:
        saved = config.option.verbose
        config.option.verbose = 0
        yield
        config.option.verbose = saved


def test_client(client) -> None:
    assert isinstance(client, Client)


@pytest.mark.skipif(get_django_version() < (3, 1),
                    reason="Django >= 3.1 required")
def test_async_client(async_client) -> None:
    from django.test.client import AsyncClient

    assert isinstance(async_client, AsyncClient)


@pytest.mark.django_db
def test_admin_client(admin_client: Client) -> None:
    assert isinstance(admin_client, Client)
    resp = admin_client.get("/admin-required/")
    assert force_str(resp.content) == "You are an admin"


def test_admin_client_no_db_marker(admin_client: Client) -> None:
Example #9
0
        with pytest.raises(HTTPError):
            urlopen(live_server + '/static/a_file.txt').read()


@pytest.mark.django_project(extra_settings="""
    AUTH_USER_MODEL = 'app.MyCustomUser'
    INSTALLED_APPS = [
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'tpkg.app',
    ]
    ROOT_URLCONF = 'tpkg.app.urls'
    """)
@pytest.mark.skipif(get_django_version() < (1, 5),
                    reason="Django >= 1.5 required")
def test_custom_user_model(django_testdir):
    django_testdir.create_app_file(
        """
        from django.contrib.auth.models import AbstractUser
        from django.db import models

        class MyCustomUser(AbstractUser):
            identifier = models.CharField(unique=True, max_length=100)

            USERNAME_FIELD = 'identifier'
        """, 'models.py')
    django_testdir.create_app_file(
        """
        from django.conf.urls import url
Example #10
0
 def __init__(self):
     self._django_version = get_django_version()
class TestDatabaseFixtures:
    """Tests for the different database fixtures."""
    @pytest.fixture(
        params=["db", "transactional_db", "django_db_reset_sequences"])
    def all_dbs(self, request) -> None:
        if request.param == "django_db_reset_sequences":
            return request.getfixturevalue("django_db_reset_sequences")
        elif request.param == "transactional_db":
            return request.getfixturevalue("transactional_db")
        elif request.param == "db":
            return request.getfixturevalue("db")

    def test_access(self, all_dbs: None) -> None:
        Item.objects.create(name="spam")

    def test_clean_db(self, all_dbs: None) -> None:
        # Relies on the order: test_access created an object
        assert Item.objects.count() == 0

    def test_transactions_disabled(self, db: None) -> None:
        if not connection.features.supports_transactions:
            pytest.skip("transactions required for this test")

        assert connection.in_atomic_block

    def test_transactions_enabled(self, transactional_db: None) -> None:
        if not connection.features.supports_transactions:
            pytest.skip("transactions required for this test")

        assert not connection.in_atomic_block

    def test_transactions_enabled_via_reset_seq(
        self,
        django_db_reset_sequences: None,
    ) -> None:
        if not connection.features.supports_transactions:
            pytest.skip("transactions required for this test")

        assert not connection.in_atomic_block

    def test_django_db_reset_sequences_fixture(
        self,
        db: None,
        django_testdir,
        non_zero_sequences_counter: None,
    ) -> None:

        if not db_supports_reset_sequences():
            pytest.skip("transactions and reset_sequences must be supported "
                        "by the database to run this test")

        # The test runs on a database that already contains objects, so its
        # id counter is > 1. We check for the ids of newly created objects.
        django_testdir.create_test_module("""
            import pytest
            from .app.models import Item

            def test_django_db_reset_sequences_requested(
                    django_db_reset_sequences):
                item = Item.objects.create(name='new_item')
                assert item.id == 1
        """)

        result = django_testdir.runpytest_subprocess("-v", "--reuse-db")
        result.stdout.fnmatch_lines(
            ["*test_django_db_reset_sequences_requested PASSED*"])

    @pytest.fixture
    def mydb(self, all_dbs: None) -> None:
        # This fixture must be able to access the database
        Item.objects.create(name="spam")

    def test_mydb(self, mydb: None) -> None:
        if not connection.features.supports_transactions:
            pytest.skip("transactions required for this test")

        # Check the fixture had access to the db
        item = Item.objects.get(name="spam")
        assert item

    def test_fixture_clean(self, all_dbs: None) -> None:
        # Relies on the order: test_mydb created an object
        # See https://github.com/pytest-dev/pytest-django/issues/17
        assert Item.objects.count() == 0

    @pytest.fixture
    def fin(self, request, all_dbs: None) -> None:
        # This finalizer must be able to access the database
        request.addfinalizer(lambda: Item.objects.create(name="spam"))

    def test_fin(self, fin: None) -> None:
        # Check finalizer has db access (teardown will fail if not)
        pass

    @pytest.mark.skipif(get_django_version() < (3, 2),
                        reason="Django >= 3.2 required")
    def test_durable_transactions(self, all_dbs: None) -> None:
        with transaction.atomic(durable=True):
            item = Item.objects.create(name="foo")
        assert Item.objects.get() == item
Example #12
0
class TestLiveServer:
    pytestmark = [
        pytest.mark.skipif(get_django_version() < (1, 4),
                           reason="Django > 1.3 required"),
        pytest.mark.urls('tests.urls_liveserver'),
    ]

    def test_url(self, live_server):
        assert live_server.url == force_text(live_server)

    def test_transactions(self, live_server):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert not noop_transactions()

    def test_db_changes_visibility(self, live_server):
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 0'
        Item.objects.create(name='foo')
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    def test_fixture_db(self, db, live_server):
        Item.objects.create(name='foo')
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    def test_fixture_transactional_db(self, transactional_db, live_server):
        Item.objects.create(name='foo')
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    @pytest.fixture
    def item(self):
        # This has not requested database access so should fail.
        # Unfortunately the _live_server_helper autouse fixture makes this
        # test work.
        with pytest.raises(pytest.fail.Exception):
            Item.objects.create(name='foo')

    @pytest.mark.xfail
    def test_item(self, item, live_server):
        # test should fail/pass in setup
        pass

    @pytest.fixture
    def item_db(self, db):
        return Item.objects.create(name='foo')

    def test_item_db(self, item_db, live_server):
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    @pytest.fixture
    def item_transactional_db(self, transactional_db):
        return Item.objects.create(name='foo')

    def test_item_transactional_db(self, item_transactional_db, live_server):
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'
Example #13
0

@pytest.mark.django_project(
    extra_settings="""
    AUTH_USER_MODEL = 'app.MyCustomUser'
    INSTALLED_APPS = [
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'tpkg.app',
    ]
    ROOT_URLCONF = 'tpkg.app.urls'
    """
)
@pytest.mark.skipif(get_django_version() < (1, 5), reason="Django >= 1.5 required")
def test_custom_user_model(django_testdir):
    django_testdir.create_app_file(
        """
        from django.contrib.auth.models import AbstractUser
        from django.db import models

        class MyCustomUser(AbstractUser):
            identifier = models.CharField(unique=True, max_length=100)

            USERNAME_FIELD = 'identifier'
        """,
        "models.py",
    )
    django_testdir.create_app_file(
        """
Example #14
0
            '*Operations to perform:*',
            "*Apply all migrations:*",
            "*PASSED*Destroying test database for alias 'default' ('*')...*"])

    def test_more_verbose_with_vv_and_reusedb(self, testdir):
        """More verbose output with '-v -v', and --create-db."""
        result = testdir.runpytest_subprocess('-s', '-v', '-v', '--create-db')
        result.stdout.fnmatch_lines([
            "tpkg/test_the_test.py:*Creating test database for alias*",
            "*PASSED*"])
        assert ("*Destroying test database for alias 'default' ('*')...*"
                not in result.stdout.str())


@pytest.mark.skipif(
    get_django_version() < (1, 8),
    reason='Django 1.7 requires settings.SITE_ID to be set, so this test is invalid'
)
@pytest.mark.django_db
@pytest.mark.parametrize('site_name', ['site1', 'site2'])
def test_clear_site_cache(site_name, rf, monkeypatch):
    request = rf.get('/')
    monkeypatch.setattr(request, 'get_host', lambda: 'foo.com')
    Site.objects.create(domain='foo.com', name=site_name)
    assert Site.objects.get_current(request=request).name == site_name


@pytest.mark.django_db
@pytest.mark.parametrize('site_name', ['site1', 'site2'])
def test_clear_site_cache_check_site_cache_size(site_name, settings):
    assert len(site_models.SITE_CACHE) == 0
        with pytest.raises(HTTPError):
            urlopen(live_server + '/static/a_file.txt').read()


@pytest.mark.django_project(extra_settings="""
    AUTH_USER_MODEL = 'app.MyCustomUser'
    INSTALLED_APPS = [
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'tpkg.app',
    ]
    ROOT_URLCONF = 'tpkg.app.urls'
    """)
@pytest.mark.skipif(get_django_version() < (1, 5),
                    reason="Django >= 1.5 required")
def test_custom_user_model(django_testdir):
    django_testdir.create_app_file("""
        from django.contrib.auth.models import AbstractUser
        from django.db import models

        class MyCustomUser(AbstractUser):
            identifier = models.CharField(unique=True, max_length=100)

            USERNAME_FIELD = 'identifier'
        """, 'models.py')
    django_testdir.create_app_file("""
        try:
            from django.conf.urls import patterns  # Django >1.4
        except ImportError:
Example #16
0
class TestLiveServer:
    def test_url(self, live_server):
        assert live_server.url == force_text(live_server)

    def test_transactions(self, live_server):
        if not connections_support_transactions():
            pytest.skip('transactions required for this test')

        assert not noop_transactions()

    def test_db_changes_visibility(self, live_server):
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 0'
        Item.objects.create(name='foo')
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    def test_fixture_db(self, db, live_server):
        Item.objects.create(name='foo')
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    def test_fixture_transactional_db(self, transactional_db, live_server):
        Item.objects.create(name='foo')
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    @pytest.fixture
    def item(self):
        # This has not requested database access explicitly, but the
        # live_server fixture auto-uses the transactional_db fixture.
        Item.objects.create(name='foo')

    def test_item(self, item, live_server):
        pass

    @pytest.fixture
    def item_db(self, db):
        return Item.objects.create(name='foo')

    def test_item_db(self, item_db, live_server):
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    @pytest.fixture
    def item_transactional_db(self, transactional_db):
        return Item.objects.create(name='foo')

    def test_item_transactional_db(self, item_transactional_db, live_server):
        response_data = urlopen(live_server + '/item_count/').read()
        assert force_text(response_data) == 'Item count: 1'

    @pytest.mark.skipif(get_django_version() >= (1, 7),
                        reason="Django < 1.7 required")
    def test_serve_static(self, live_server, settings):
        """
        Test that the LiveServer serves static files by default.
        """
        response_data = urlopen(live_server + '/static/a_file.txt').read()
        assert force_text(response_data) == 'bla\n'

    @pytest.mark.django_project(extra_settings="""
        INSTALLED_APPS = [
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.staticfiles',
            'tpkg.app',
        ]

        STATIC_URL = '/static/'
        """)
    def test_serve_static_with_staticfiles_app(self, django_testdir, settings):
        """
        LiveServer always serves statics with ``django.contrib.staticfiles``
        handler.
        """
        django_testdir.create_test_module("""
            import pytest
            try:
                from django.utils.encoding import force_text
            except ImportError:
                from django.utils.encoding import force_unicode as force_text

            try:
                from urllib2 import urlopen, HTTPError
            except ImportError:
                from urllib.request import urlopen, HTTPError

            class TestLiveServer:
                def test_a(self, live_server, settings):
                    assert ('django.contrib.staticfiles'
                            in settings.INSTALLED_APPS)
                    response_data = urlopen(
                        live_server + '/static/a_file.txt').read()
                    assert force_text(response_data) == 'bla\\n'
            """)
        result = django_testdir.runpytest_subprocess('--tb=short', '-v')
        result.stdout.fnmatch_lines(['*test_a*PASSED*'])
        assert result.ret == 0

    @pytest.mark.skipif(get_django_version() < (1, 7),
                        reason="Django >= 1.7 required")
    def test_serve_static_dj17_without_staticfiles_app(self, live_server,
                                                       settings):
        """
        Because ``django.contrib.staticfiles`` is not installed
        LiveServer can not serve statics with django >= 1.7 .
        """
        with pytest.raises(HTTPError):
            urlopen(live_server + '/static/a_file.txt').read()
        from .app.models import Item

        @pytest.mark.django_db
        def test_inner_south():
            assert [x.name for x in Item.objects.all()] \
                == ["mark_initial_data"]
    ''')

    result = django_testdir_initial.runpytest('--tb=short', '-v')
    result.stdout.fnmatch_lines(['*test_inner_south*PASSED*'])


# NOTE: South tries to monkey-patch management._commands, which has been
#       replaced by lru_cache and would cause an AttributeError.
@pytest.mark.skipif(get_django_version() >= (1, 7),
                    reason='South fails with Django 1.7.')
@pytest.mark.skipif(sys.version_info[:2] == (3, 4),
                    reason='South fails on Python 3.4.')
class TestSouth:
    """Test interaction with initial_data and South."""

    @pytest.mark.extra_settings("""
        INSTALLED_APPS += [ 'south', ]
        SOUTH_TESTS_MIGRATE = True
        SOUTH_MIGRATION_MODULES = {
            'app': 'app.south_migrations',
        }
        """)
    def test_initial_data_south(self, django_testdir_initial, settings):
        django_testdir_initial.create_test_module('''
Example #18
0
def nonverbose_config(config):
    """Ensure that pytest's config.option.verbose is <= 0."""
    if config.option.verbose <= 0:
        yield
    else:
        saved = config.option.verbose
        config.option.verbose = 0
        yield
        config.option.verbose = saved


def test_client(client):
    assert isinstance(client, Client)


@pytest.mark.skipif(get_django_version() < (3, 1), reason="Django >= 3.1 required")
def test_async_client(async_client):
    from django.test.client import AsyncClient

    assert isinstance(async_client, AsyncClient)


@pytest.mark.django_db
def test_admin_client(admin_client):
    assert isinstance(admin_client, Client)
    resp = admin_client.get("/admin-required/")
    assert force_str(resp.content) == "You are an admin"


def test_admin_client_no_db_marker(admin_client):
    assert isinstance(admin_client, Client)