model-bakers/model_bakery

Using with Pytest raises naive datetime warning

WillowP opened this issue · 1 comments

Thanks for the great library!!!

When using with Pytest, if I do not supply a time for datetime fields, I get this warning:

 RuntimeWarning: DateTimeField MyModel.my_datetime_field received a naive datetime (2022-01-04 13:50:42.357321) while time zone support is active.

Expected behavior

I expect model_bakery to supply timezone-aware datetimes to datetime fields when time zone support is active.

Actual behavior

Model bakery supplied naive datetimes.

Reproduction Steps

How to reproduce this issue.

Make a model:

from django.db import models

class MyModel(models.Model):
    my_datetime_field = models.DateTimeField(
        null=True, blank=True,
    )

I've tried the above with default=None as well, with the same result. I was surprised that model bakery was even supplying a value for a nullable field.

Make a recipe:

from my_app import MyModel
from model_bakery.recipe import Recipe

my_recipe = Recipe(MyModel)

Use it in a test

from model_bakery import baker

def my_test():
  my_ instance = baker.make_recipe('tests.my_recipe')
  assert True

Run the test:

$ pytest

I think that's all that's required to get the warning.

If you do this with the recipe, you don't get the warning:

from my_app import MyModel
from model_bakery.recipe import Recipe
from django.utils import timezone

my_recipe = Recipe(MyModel, my_datetime_field=timezone.now())

Versions

Django==3.2.9
model-bakery==1.3.3
pytest==6.2.5
pytest-django==4.5.1
Python 3.9.6

@WillowP thanks for opening this PR, but I couldn't reproduce the error you are describing. I did exactly what you've suggestion on a project I have and got no warnings about naive datetime.

This is odd because we've already replaced any type of naive datetime manipulation since version 1.3.0 (see the Changelog here) and we have unit tests covering datetime creation on recipes as well and our test runner doesn't print any warning regards to that.

I'm closing this issue because we couldn't reproduce it. Keep on baking 🥮