In [11]:
import warnings
warnings.filterwarnings('ignore')

mixer

Gerador de objetos

Problema

  • Escrita de testes geralmente demanda instanciar e popular vários objetos e suas dependências até que possam ser persistidos no banco de dados;

Motivação

  • Facilitar a escrita de testes;
    • Que dependem de registros no banco de dados ou;
    • Instâncias em memória;
  • Foco nas propriedades relevantes para o seu teste.
  • Sem fixtures;
  • Sem factories;

Setup

pip install mixer

fake-factory

fake-factory é o motor do Mixer e possui providers para gerar dados aleatórios

In [2]:
from faker import Factory

faker = Factory.create()
for _ in range(5):
    print(faker.name())
Imelda Lang
Sable Bogisich
Terrell Lind II
Ms. Helena Wolf
Redmond Stiedemann
In [3]:
from faker import Factory

faker = Factory.create('pt_BR')
print(faker.name())
Bianca Costela
In [4]:
print(faker.address())
Núcleo Castro, 388
Conjunto Jatoba
63875355 Dias / AC
In [5]:
print(faker.phone_number())
81 6126-4767

Instanciar objetos

from mixer.main import Mixer

class SomeScheme:
    score = int
    name = str

mixer = Mixer()
instance = mixer.blend(SomeScheme)
print instance.name  # Some like: 'Mike Douglass'

mixer = Mixer(fake=False)
instance = mixer.blend(SomeScheme)
print instance.name  # Some like: 'AKJfdjh3'
In [6]:
# Dica: Usar models do Django em um IPython Notebook
import os
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'conf.settings'
django.setup()

courses/models.py

class Student(models.Model):
    name = models.CharField(max_length=30)
    def __str__(self): return self.name


class Course(models.Model):
    name = models.CharField(max_length=30)
    def __str__(self): return self.name


class Score(models.Model):
    points = models.IntegerField(max_length=4)
    course = models.ForeignKey('Course')
    student = models.ForeignKey('Student')

    def __str__(self):
        return "{s} has {p} points.".format(s=self.student, p=self.points)
In [17]:
# Obter um objeto
from mixer.backend.django import mixer

score = mixer.blend('courses.Score')
In [18]:
print "points: ", score.points
print "course: ", score.course
print "student: ", score.student
points:  3706
course:  Mr. Guss Blick PhD
student:  Macedo
In [23]:
# Iniciar variáveis relevantes ao teste
score = mixer.blend('courses.Score', score=11, student__name='Macedo')
print "points: ", score.points
print "course: ", score.course
print "student: ", score.student
points:  9295
course:  Anabelle Hudson
student:  Macedo
In [31]:
# Suporta generators
seq_name = mixer.sequence('Macedo {0}')
seq_points = (p for p in [30, 13, 55])

for counter in range(3):
    print mixer.blend('courses.Score', points=seq_points, student__name=seq_name)
Macedo 0 has 30
Macedo 1 has 13
Macedo 2 has 55
In [32]:
# Ciclos para facilitar a geração de vários objetos
students = mixer.cycle(5).blend('courses.Student')
print students
[<Student: Mr. Dennie Reichel III>, <Student: Teagan Hartmann>, <Student: Janis Ondricka>, <Student: Myrtle Wolff>, <Student: Carmen O'Connell>]

É isso!

  • Fernando Macedo
  • fgmacedo@gmail.com
  • Trabalho na labCorp (estamos contratando!)
  • @fgmacedo
  • github.com/fgmacedo