Tuesday, March 26, 2019

Reinout van Rees: Quiet down 'faker' in pytests

Faker is a nice library for creating sample data for tests. No more company called "example company" and no more email address "something@example.org". No, you get readable random proper email addresses and company names and so. Handy in combination with factory_boy, which provides integration. Here's an example:

from myproject import models
import factory


class PersonF(factory.DjangoModelFactory):
    class Meta:
        model = models.Person

    email = factory.Faker("email")
    name = factory.Faker("name")
    password = factory.Faker("password")


class TeamF(factory.DjangoModelFactory):
    class Meta:
        model = models.Team

    name = factory.Faker("company")

Problem I'm having is that, when running the tests with pytest, pytest helpfully reports all the logging when something goes wrong. Only, tests related to factory_boy/faker fill the log with locale-related messages:

factory.py 97  DEBUG Looking for locale `en_US` in provider `faker.providers.address`.
factory.py 111 DEBUG Provider `faker.providers.address` has been localized to `en_US`.
factory.py 97  DEBUG Looking for locale `en_US` in provider `faker.providers.automotive`.
factory.py 111 DEBUG Provider `faker.providers.automotive` has been localized to `en_US`.
factory.py 97  DEBUG Looking for locale `en_US` in provider `faker.providers.bank`.

Which makes it harder to spot the actual error.

There's been a recent helpful change to faker, reducing those log messages from INFO to DEBUG. So fixing these extraneous messages was as simple as including these lines at the top of my factories.py:

import logging
logger = logging.getLogger('faker')
logger.setLevel(logging.INFO)  # Quiet faker locale messages down in tests.


from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...