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

Update pre-commit, add isort and fix imports #77

Merged
merged 8 commits into from
Jun 15, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions tests/generic/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class PaymentBill(models.Model):

class Person(models.Model):
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
# jards macalé is an amazing brazilian musician! =]
# Jards Macalé is an amazing brazilian musician! =]
enjoy_jards_macale = models.BooleanField(default=True)
like_metal_music = models.BooleanField(default=False)
name = models.CharField(max_length=30)
Expand Down Expand Up @@ -326,10 +326,11 @@ class Movie(models.Model):

class MovieManager(models.Manager):
def get_queryset(self):
"""Annotate queryset with an alias field 'name'.
"""
Annotate queryset with an alias field 'name'.

We want to test whether this annotation has been run after
calling baker.make().
calling `baker.make()`.
"""
return super(MovieManager, self).get_queryset().annotate(name=models.F("title"))

Expand Down
20 changes: 9 additions & 11 deletions tests/test_baker.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def test_multiple_inheritance_creation(self):
@pytest.mark.django_db
class TestsBakerRepeatedCreatesSimpleModel:
def test_make_should_create_objects_respecting_quantity_parameter(self):
people = baker.make(models.Person, _quantity=5)
baker.make(models.Person, _quantity=5)
assert models.Person.objects.count() == 5

people = baker.make(models.Person, _quantity=5, name="George Washington")
Expand Down Expand Up @@ -133,7 +133,7 @@ def test_prepare_raises_correct_exception_if_invalid_quantity(self):
baker.prepare(_model=models.Person, _quantity=0)

def test_accepts_generators_with_quantity(self):
people = baker.make(
baker.make(
models.Person,
name=itertools.cycle(["a", "b", "c"]),
id_document=itertools.cycle(["d1", "d2", "d3", "d4", "d5"]),
Expand All @@ -153,7 +153,7 @@ def test_accepts_generators_with_quantity(self):
assert "d5" == p5.id_document

def test_accepts_generators_with_quantity_for_unique_fields(self):
people = baker.make(
baker.make(
models.DummyUniqueIntegerFieldModel,
value=itertools.cycle([1, 2, 3]),
_quantity=3,
Expand All @@ -168,9 +168,7 @@ def test_generators_work_with_user_model(self):
from django.contrib.auth import get_user_model

User = get_user_model()
people = baker.make(
User, username=itertools.cycle(["a", "b", "c"]), _quantity=3
)
baker.make(User, username=itertools.cycle(["a", "b", "c"]), _quantity=3)
assert User.objects.count() == 3
u1, u2, u3 = User.objects.all()
assert "a" == u1.username
Expand All @@ -186,28 +184,28 @@ def test_default_behaviour_for_and_fk(self):
assert dog.pk is None
assert dog.owner.pk is None
with pytest.raises(ValueError):
dog.friends_with
assert dog.friends_with

def test_create_fk_instances(self):
dog = baker.prepare(models.Dog, _save_related=True)

assert dog.pk is None
assert dog.owner.pk
with pytest.raises(ValueError):
dog.friends_with
assert dog.friends_with

def test_create_fk_instances_with_quantity(self):
dog1, dog2 = baker.prepare(models.Dog, _save_related=True, _quantity=2)

assert dog1.pk is None
assert dog1.owner.pk
with pytest.raises(ValueError):
dog1.friends_with
assert dog1.friends_with

assert dog2.pk is None
assert dog2.owner.pk
with pytest.raises(ValueError):
dog2.friends_with
assert dog2.friends_with

def test_create_one_to_one(self):
lonely_person = baker.prepare(models.LonelyPerson, _save_related=True)
Expand Down Expand Up @@ -640,7 +638,7 @@ def test_annotation_within_manager_get_queryset_are_run_on_make(self):
"""
movie = baker.make(models.MovieWithAnnotation)
with pytest.raises(AttributeError):
movie.name
assert movie.name

movie = baker.make(
models.MovieWithAnnotation, title="Old Boy", _from_manager="objects",
Expand Down
26 changes: 15 additions & 11 deletions tests/test_filling_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@ class TestFillingFromChoice:
def test_if_gender_is_populated_from_choices(self, person):
from tests.generic.models import GENDER_CHOICES

person.gender in map(lambda x: x[0], GENDER_CHOICES)
assert person.gender in map(lambda x: x[0], GENDER_CHOICES)

def test_if_occupation_populated_from_choices(self, person):
from tests.generic.models import OCCUPATION_CHOICES

occupations = [item[0] for list in OCCUPATION_CHOICES for item in list[1]]
person.occupation in occupations
occupations = [item[0] for lst in OCCUPATION_CHOICES for item in lst[1]]
assert person.occupation in occupations


class TestStringFieldsFilling:
Expand Down Expand Up @@ -259,18 +259,20 @@ def test_filling_file_field(self):
def test_does_not_create_file_if_not_flagged(self):
dummy = baker.make(models.DummyFileFieldModel)
with pytest.raises(ValueError):
dummy.file_field.path # Django raises ValueError if file does not exist
assert (
amureki marked this conversation as resolved.
Show resolved Hide resolved
dummy.file_field.path
) # Django raises ValueError if file does not exist


@pytest.mark.django_db
class TestFillingCustomFields:
def test_raises_unsupported_field_for_custom_field(self, custom_cfg):
"""Should raise an exception if a generator is not provided for a custom field"""
"""Should raise an exception if a generator is not provided for a custom field."""
with pytest.raises(TypeError):
baker.make(models.CustomFieldWithoutGeneratorModel)

def test_uses_generator_defined_on_settings_for_custom_field(self, custom_cfg):
"""Should use the function defined in settings as a generator"""
"""Should use the function defined in settings as a generator."""
generator_dict = {
"tests.generic.fields.CustomFieldWithGenerator": generators.gen_value_string
}
Expand All @@ -281,7 +283,7 @@ def test_uses_generator_defined_on_settings_for_custom_field(self, custom_cfg):
def test_uses_generator_defined_as_string_on_settings_for_custom_field(
self, custom_cfg
):
"""Should import and use the function present in the import path defined in settings"""
"""Should import and use the function present in the import path defined in settings."""
# fmt: off
generator_dict = {
"tests.generic.fields.CustomFieldWithGenerator":
Expand All @@ -293,7 +295,7 @@ def test_uses_generator_defined_as_string_on_settings_for_custom_field(
assert "value" == obj.custom_value

def test_uses_generator_defined_on_settings_for_custom_foreignkey(self, custom_cfg):
"""Should use the function defined in the import path for a foreign key field"""
"""Should use the function defined in the import path for a foreign key field."""
generator_dict = {
"tests.generic.fields.CustomForeignKey": "model_bakery.random_gen.gen_related"
}
Expand All @@ -304,7 +306,7 @@ def test_uses_generator_defined_on_settings_for_custom_foreignkey(self, custom_c
assert "[email protected]" == obj.custom_fk.email

def test_uses_generator_defined_as_string_for_custom_field(self, custom_cfg):
"""Should import and use the generator function used in the add method"""
"""Should import and use the generator function used in the add method."""
baker.generators.add(
"tests.generic.fields.CustomFieldWithGenerator",
"tests.generic.generators.gen_value_string",
Expand All @@ -313,7 +315,7 @@ def test_uses_generator_defined_as_string_for_custom_field(self, custom_cfg):
assert "value" == obj.custom_value

def test_uses_generator_function_for_custom_foreignkey(self, custom_cfg):
"""Should use the generator function passed as a value for the add method"""
"""Should use the generator function passed as a value for the add method."""
baker.generators.add("tests.generic.fields.CustomForeignKey", gen_related)
obj = baker.make(
models.CustomForeignKeyWithGeneratorModel, custom_fk__email="[email protected]"
Expand Down Expand Up @@ -364,7 +366,9 @@ def test_filling_image_file_field(self):
def test_does_not_create_file_if_not_flagged(self):
dummy = baker.make(models.DummyImageFieldModel)
with pytest.raises(ValueError):
dummy.image_field.path # Django raises ValueError if file does not exist
assert (
amureki marked this conversation as resolved.
Show resolved Hide resolved
dummy.image_field.path
) # Django raises ValueError if file does not exist


@pytest.mark.skipif(
Expand Down
51 changes: 13 additions & 38 deletions tests/test_recipes.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"bio": "Someone in the crowd",
"birthday": now().date(),
"appointment": now(),
"blog": "http://joe.blogspot.com",
"blog": "https://joe.example.com",
"days_since_last_login": 4,
"birth_time": now(),
}
Expand All @@ -35,19 +35,14 @@
@pytest.mark.django_db
class TestDefiningRecipes:
def test_import_seq_from_baker(self):
"""
Import seq method directly from baker module
"""
"""Import seq method directly from baker module."""
try:
from model_bakery import seq # NoQA
except ImportError:
self.fail("{} raised".format(ImportError.__name__))

def test_flat_model_make_recipe_with_the_correct_attributes(self):
"""
A 'flat model' means a model without associations, like
foreign keys, many to many and one to one
"""
"""Test a 'flat model' - without associations, like FK, M2M and O2O."""
person = person_recipe.make()
assert person.name == recipe_attrs["name"]
assert person.nickname == recipe_attrs["nickname"]
Expand Down Expand Up @@ -81,8 +76,8 @@ def test_always_calls_when_creating(self):
choice_mock.return_value = "foo"
lst = ["foo", "bar", "spam", "eggs"]
r = Recipe(DummyBlankFieldsModel, blank_char_field=lambda: choice_mock(lst))
r.make().blank_char_field
r.make().blank_char_field
assert r.make().blank_char_field
assert r.make().blank_char_field
assert choice_mock.call_count == 2

def test_always_calls_with_quantity(self):
Expand All @@ -94,9 +89,7 @@ def test_always_calls_with_quantity(self):
assert choice_mock.call_count == 3

def test_make_recipes_with_args(self):
"""
Overriding some fields values at recipe execution
"""
"""Overriding some fields values at recipe execution."""
person = person_recipe.make(name="Guido", age=56)
assert person.name != recipe_attrs["name"]
assert person.name == "Guido"
Expand All @@ -113,9 +106,7 @@ def test_make_recipes_with_args(self):
assert person.id is not None

def test_prepare_recipes_with_args(self):
"""
Overriding some fields values at recipe execution
"""
"""Overriding some fields values at recipe execution."""
person = person_recipe.prepare(name="Guido", age=56)
assert person.name != recipe_attrs["name"]
assert person.name == "Guido"
Expand Down Expand Up @@ -169,9 +160,7 @@ def test_defining_recipes_str(self):

@pytest.mark.django_db
class TestExecutingRecipes:
"""
Tests for calling recipes defined in baker_recipes.py
"""
"""Tests for calling recipes defined in baker_recipes.py."""

def test_model_with_foreign_key(self):
dog = baker.make_recipe("tests.generic.dog")
Expand Down Expand Up @@ -348,10 +337,7 @@ def test_not_accept_other_type(self):
assert str(exception) == "Not a recipe"

def test_do_not_create_related_model(self):
"""
It should not attempt to create other object when
passing the object as argument
"""
"""It should not create another object when passing the object as argument."""
person = baker.make_recipe("tests.generic.person")
assert Person.objects.count() == 1
baker.make_recipe("tests.generic.dog", owner=person)
Expand All @@ -360,27 +346,18 @@ def test_do_not_create_related_model(self):
assert Person.objects.count() == 1

def test_do_query_lookup_for_recipes_make_method(self):
"""
It should not attempt to create other object when
using query lookup syntax
"""
"""It should not create another object when using query lookup syntax."""
dog = baker.make_recipe("tests.generic.dog", owner__name="James")
assert Person.objects.count() == 1
assert dog.owner.name == "James"

def test_do_query_lookup_for_recipes_prepare_method(self):
"""
It should not attempt to create other object when
using query lookup syntax
"""
"""It should not create another object when using query lookup syntax."""
dog = baker.prepare_recipe("tests.generic.dog", owner__name="James")
assert dog.owner.name == "James"

def test_do_query_lookup_empty_recipes(self):
"""
It should not attempt to create other object when
using query lookup syntax
"""
"""It should not create another object when using query lookup syntax."""
dog_recipe = Recipe(Dog)
dog = dog_recipe.make(owner__name="James")
assert Person.objects.count() == 1
Expand Down Expand Up @@ -446,9 +423,7 @@ def test_increment_for_numbers(self):
assert dummy.default_float_field == 4.23

def test_increment_for_numbers_2(self):
"""
This test is a repeated one but it is necessary to ensure Sequences atomicity
"""
"""Repeated test to ensure Sequences atomicity."""
dummy = baker.make_recipe("tests.generic.serial_numbers")
assert dummy.default_int_field == 11
assert dummy.default_decimal_field == Decimal("21.1")
Expand Down