Created
October 3, 2012 19:37
-
-
Save epicserve/3829302 to your computer and use it in GitHub Desktop.
Example Factory-boy (https://github.com/dnerdy/factory_boy) factory that uses a file field.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.template.defaultfilters import slugify | |
from django.contrib.sites.models import Site | |
from django.core.files import File | |
from taggit.models import Tag | |
from .models import Photo | |
import factory | |
import os | |
TEST_MEDIA_PATH = os.path.join(os.path.dirname(__file__), 'tests', 'test_media') | |
TEST_PHOTO_PATH = os.path.join(TEST_MEDIA_PATH, 'test_photo.png') | |
class PhotoFactory(factory.Factory): | |
FACTORY_FOR = Photo | |
title = factory.Sequence(lambda n: 'Test Photo {0}'.format(n)) | |
slug = factory.LazyAttribute(lambda a: slugify(a.title)) | |
status = 'P' | |
photo = factory.LazyAttribute(lambda a: File(open(TEST_PHOTO_PATH))) | |
@factory.post_generation(extract_prefix='tags') | |
def add_default_tags(self, create, extracted, **kwargs): | |
# allow something like ArticleFactory(tags=Tag.objects.all()) | |
if extracted and type(extracted) == type(Tag.objects.all()): | |
self.tags = extracted | |
self.save() | |
else: | |
self.tags.add("lorem", "ipsum", "dolor") | |
@factory.post_generation(extract_prefix='sites') | |
def add_default_site(self, create, extracted, **kwargs): | |
# allow something like ArticleFactory(sites=Site.objects.all()) | |
if extracted and type(extracted) == type(Site.objects.all()): | |
self.sites = extracted | |
self.save() | |
else: | |
self.sites.add(Site.objects.get_current()) | |
self.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you - the FileField and post_generation are exactly what I was looking to add to my factories.