Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix random generation of ContentType values when there is no database access #290

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Added

### Changed
- Fixed random generation of ContentType values when there is no database access [#290](https://github.com/model-bakers/model_bakery/pull/290)

### Removed

Expand Down
6 changes: 5 additions & 1 deletion model_bakery/random_gen.py
Expand Up @@ -206,7 +206,11 @@ def gen_content_type():

try:
return ContentType.objects.get_for_model(choice(apps.get_models()))
except AssertionError:
except (AssertionError, RuntimeError):
# AssertionError is raised by Django's test framework when db access is not available:
# https://github.com/django/django/blob/stable/4.0.x/django/test/testcases.py#L150
# RuntimeError is raised by pytest-django when db access is not available:
# https://github.com/pytest-dev/pytest-django/blob/v4.5.2/pytest_django/plugin.py#L709
warnings.warn("Database access disabled, returning ContentType raw instance")
return ContentType()

Expand Down
10 changes: 8 additions & 2 deletions tests/test_baker.py
Expand Up @@ -5,6 +5,7 @@

import pytest
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models import Manager
from django.db.models.signals import m2m_changed
from django.test import TestCase, override_settings
Expand Down Expand Up @@ -592,13 +593,18 @@ class TestHandlingContentTypeField:
def test_create_model_with_contenttype_field(self):
dummy = baker.make(models.DummyGenericForeignKeyModel)
assert isinstance(dummy, models.DummyGenericForeignKeyModel)
assert isinstance(dummy.content_type, ContentType)


@pytest.mark.django_db
class TestHandlingContentTypeFieldNoQueries:
def test_create_model_with_contenttype_field(self):
dummy = baker.prepare(models.DummyGenericForeignKeyModel)
with pytest.warns(
UserWarning,
match="Database access disabled, returning ContentType raw instance",
):
dummy = baker.prepare(models.DummyGenericForeignKeyModel)
assert isinstance(dummy, models.DummyGenericForeignKeyModel)
assert isinstance(dummy.content_type, ContentType)


@pytest.mark.django_db
Expand Down