No longer maintained, please migrate to model_bakery

Overview

Model Mommy: Smart fixtures for better tests

Test Status Latest PyPI version

IMPORTANT: Model Mommy is no longer maintained and was replaced by Model Bakery. Please, consider migrating your project to use the new lib.

Model Mommy's creator and the maintainers decided to rename the project to not reinforce gender stereotypes for women in technology. You can read more about this subject here.

Maintainers

Creator

Comments
  • Better coordination of Foreign Key model use during generation

    Better coordination of Foreign Key model use during generation

    We have a multi-tenant app where all models are ultimately owned by a customer model, but some of the models are only indirectly owned by that customer model, some pseudocode:

    class Job(Model):  has foreignkey to Customer
    class Call(Model): has foreignkey to Job
      contains PositionTitle(Model): has foreignkey to Customer
    class Position(Model): has foreignkey to Call
    class Assignment(Model): has foreignkey to Position
    

    That isn't all the models in my code, but when I do

    mommy.make(Assignment) 
    

    mommy creates 32 Customer objects because of the generation. It would be nice if you could say something like

    with mommy.register({"customers.customer": mommy.make(Customer)}):
        assignment = mommy.make(Assignment)
    

    Admittedly the syntax needs some work, and you would probably need to do with nesting of the with clauses. Recipes might work for this case, but it seems like a HUGE amount of overhead for something simple like this.

    opened by mark0978 18
  • Feature/custom field value generation api #90

    Feature/custom field value generation api #90

    Started some code on a feature branch. Needs more work and discussion. Doing a pull_request for further discussion following #90.

    Not sure about the decorators. They don't really make sense, as we aren't really wrapping the fields.

    def gen_func():
        return "random_value"
    
    class CustomField(models.Fields):
        ... #some field code
    
    add_value_generator(gen_func, CustomField)
    

    Is the same LOC. But make more sense semantically, than

    def gen_func():
        return "random_value"
    
    @custom_field_gen("gen_func")
    class CustomField(models.Fields):
        ... #some field code
    

    I do still see a usecase for the context_manager as it is better at handling exception cases than a single_use parameter would.

    And what about a model_field param? When I did the model param, I thought, about a model using the same CustomField multiple times for different model_fields. But when implementing that, I felt like I was redoing stuff, that can already be done pretty well with recipes.

    opened by CharString 16
  • Enabling spatial support into model mommy

    Enabling spatial support into model mommy

    Hello @vandersonmota.

    This is a great project, but in my day to day work uses a lot of geospatial information, so I need model_mommy to generate spatial data as well.

    This a first draft that includes a point generator, using the already consolidated formulaes used by model_mommy.

    In here I've updated the association between a field type and generators and created the spatial generator.

    perhaps there are other ways to handle this, but let me know.

    opened by george-silva 14
  • New feature: objects creation using multiple attrs values

    New feature: objects creation using multiple attrs values

    I'll explain the idea given by @henriquebastos during our last lunch. Suppose that we have the following model:

    class Person(models.Model):
        name = models.CharField(max_length=60)
        age = models.PositiveIntegerField()
    

    Now, imagine some test situation that we need to create 4 objects with the same age but different, but not random, names. Today, the way we can achieve this with model mommy is as following:

    person1 = mommy.make(Person, age=20, name='bob')
    person2 = mommy.make(Person, age=20, name='alice')
    person3 = mommy.make(Person, age=20, name='john')
    person4 = mommy.make(Person, age=20, name='peter')
    

    There is a lot of code repetition on the previous snippet and maybe we can improve this. This issue is to start this discussion to explore possibilities of how we can implement something better. The first suggestion was using something like this:

    names = ['bob', 'alice', 'john', 'peter']
    persons = mommy.make(Person, age=20, name=names)
    

    So, we can instantiate an iterable object with the multiple values that we expect and pass it to the model attribute that we want to change. Although this is an easy approach, it could make the API more complex and confusing. I mean, on the previous code we have a model attribute receiving a list as a parameter, which is something king of odd if we think about model creation...

    Well, let the discussion begins =)

    opened by berinhard 14
  • Column user_id is not Unique

    Column user_id is not Unique

    I have the following models

    app1.models.py

    class UserProfile(Subject): """ UserProfile class """ # This field is required. user = models.OneToOneField(User) # Other fields here company = models.CharField(max_length=50, null=True, blank=True, verbose_name=("Company")) contact = models.CharField(max_length=50, null=True, blank=True, verbose_name=("Contact")) msg = models.TextField(null=True, blank=True, verbose_name=_("Message"))

    def __unicode__(self):
        return self.user.username
    

    class ParentImportJob(models.Model): """ Class to store importing jobs """

    STATUS_ACTIVE = u'A'
    STATUS_SUCCESS = u'S'
    STATUS_PARTIAL = u'P'
    STATUS_ERROR = u'E'
    
    STATUS_CHOICES = (
        (STATUS_ACTIVE, _(u'In Progress')),
        (STATUS_SUCCESS, _(u'Successfully Imported')),
        (STATUS_PARTIAL, _(u'Partially Imported')),
        (STATUS_ERROR, _(u'Aborted with error')),
    )
    
    status = models.CharField(max_length=1, choices=STATUS_CHOICES)
    user_profile = models.ForeignKey(UserProfile)
    errors = models.TextField(null=True, blank=True)
    start_date = models.DateTimeField(auto_now_add=True)
    end_date = models.DateTimeField(blank=True, null=True)
    instance_class = models.CharField(max_length=200)
    

    app2.models.py

    class ImportJob(ParentImportJob): """ Class to store jobs of files being imported Extends ParentImportJob ParentImportJob is not abstract! But I am interested in 2 separated tables """

    _imported_file = models.TextField(null=True,
                                      blank=True,
                                      db_column='imported_file')
    import_result = models.TextField(null=True, blank=True)
    
    def set_import_file(self, imported_file):
        """ Set method for import_file field """
        self._imported_file = base64.encodestring(imported_file)
    
    def get_import_file(self, imported_file):
        """ Set method for import_file field """
        return base64.decodestring(self._imported_file)
    
    imported_file = property(get_import_file, set_import_file)
    

    The following recipe:

    ob_mock = Recipe(ImportJob, import_file=ofile.read(), import_result=EXCEL_DICT)

    When I ran self.job = mommy.make_recipe('excel2db.job_mock') inside the testcase I get IntegrityError: column user_id is not unique

    I'm doing something wrong?

    opened by fernandoferreira-me 13
  • Override default recipe

    Override default recipe

    Is there a way to provide a recipe that replaces mommy's default recipe for a model? In other words, when I run mommy.make('myapp.MyModel'), I want it to use a custom recipe, without having to worry about mommy.make_recipe.

    opened by rouge8 12
  • Write a recipe where ommitted fields are still populated automatically?

    Write a recipe where ommitted fields are still populated automatically?

    I really only need to write a recipe to populate one field--not all of them. Is it possible to have the remaining fields auto-populate? If not, I'd be happy to add this functionality.

    opened by grjones 12
  • Recipe generators

    Recipe generators

    These changes add a little more magic to Recipe and allow us to eliminate the need for Sequence, and allow Recipe to accept iterators (and generators) as field values.

    Advantages:

    • no need for users to work with Sequence, they can use Python generators or iterators which are more familiar and more powerful.
    • the "seq" function still works the same as it always has, and is a simple 2 line generator.
    • all the original unit tests pass, and all new code is covered by new tests

    Disadvantages:

    • The Recipe _mapping function is more complicated.

    This is my first pull request ever. If there are any problem please be patient. I'm open to any feedback you may have.

    opened by DevJac 11
  • *** DoesNotExist: Post matching query does not exist. Lookup parameters were {'pk': 1}

    *** DoesNotExist: Post matching query does not exist. Lookup parameters were {'pk': 1}

    (Pdb) mommy.make(Post)
    *** DoesNotExist: Post matching query does not exist. Lookup parameters were {'pk': 1}
    (Pdb) Post.objects.all()
    []
    (Pdb) Article.objects.all()
    [<Article: /article/3apmB5cyN0yDsyzZwmBhqhf0mDlsIA-BlNrdcJVul0zpiLIM-Y/HY1y3VDgxuERG5-a0Sys8RbzJaQpOl2hlKA9eZuGbF_S09o6mW>]
    (Pdb)
    

    Model Post extend model Article (not abstract).

    mommy.make: Article created and not created Post

    opened by avelino 11
  • Version 1.2.1 and

    Version 1.2.1 and "ValueError: Cannot assign None: "Foo.bar" does not allow null values."

    I have been using version 1.2 for a while without a problem, but since I installed 1.2.1 I started to get a lot of ValueError as the one you see above. Basically, it looks like that when mommy creates a ManyToManyField for a model it's not able to relate it to the instance being created.

    An example will help me explain it: this worked with version 1.2 (simplified):

        tag1 = mommy.make_recipe('myapp.TagRecipe')
        tag2 = mommy.make_recipe('myapp.TagRecipe')
        tag3 = mommy.make_recipe('myapp.TagRecipe')
        params = {
            'tags': [tag1, tag2, tag3],
        }
        article = mommy.make_recipe("myapp.ArticleRecipe", **params)
    

    The recipes simply being:

    TagRecipe = Recipe(Tag, name = seq('tag'))
    ArticleRecipe = Recipe(Article, name = seq('article'))
    

    And the models:

    class Tag(models.Model):
         name = models.CharField(max_length=255, unique=True)
         [...]
    
    class Article(models.Model):
        name = models.CharField(max_length=255, unique=True)
        tags = models.ManyToManyField(Tag, related_name="articles", blank=True, null=True)
        [...]
    

    Since version 1.2.1 I'm getting:

    ValueError: Cannot assign None: "Article_tags.article" does not allow null values.
    

    If you need more information I'll be happy to provide it.

    opened by GermanoGuerrini 10
  • TaggableManager from django-taggit fails in model creation

    TaggableManager from django-taggit fails in model creation

    This is related to #89, but it looks like recent versions of taggit's TaggableManager now subclasses Field and provides has_default() == False.

    ../../.virtualenvs/dashboard/lib/python2.7/site-packages/model_mommy/mommy.py:75: in make
    >           return mommy.make(**attrs)
    ../../.virtualenvs/dashboard/lib/python2.7/site-packages/model_mommy/mommy.py:241: in make
    >       return self._make(commit=True, **attrs)
    ../../.virtualenvs/dashboard/lib/python2.7/site-packages/model_mommy/mommy.py:277: in _make
    >                   model_attrs[field.name] = self.generate_value(field)
    ../../.virtualenvs/dashboard/lib/python2.7/site-packages/model_mommy/mommy.py:351: in generate_value
    >       return generator(**generator_attrs)
    ../../.virtualenvs/dashboard/lib/python2.7/site-packages/model_mommy/mommy.py:75: in make
    >           return mommy.make(**attrs)
    ../../.virtualenvs/dashboard/lib/python2.7/site-packages/model_mommy/mommy.py:241: in make
    >       return self._make(commit=True, **attrs)
    ../../.virtualenvs/dashboard/lib/python2.7/site-packages/model_mommy/mommy.py:277: in _make
    >                   model_attrs[field.name] = self.generate_value(field)
    ../../.virtualenvs/dashboard/lib/python2.7/site-packages/model_mommy/mommy.py:342: in generate_value
    >           raise TypeError('%s is not supported by mommy.' % field.__class__)
    E           TypeError: <class 'taggit.managers.TaggableManager'> is not supported by mommy.
    

    I can't provide a generator function for a custom field either, because the tags cannot be set from the model constructor.

    I don't see an easy way to identify this kind of fake field. :/

    opened by rouge8 10
Releases(1.5.1)
Waitress - A WSGI server for Python 2 and 3

Waitress Waitress is a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in t

Pylons Project 1.2k Dec 30, 2022
Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

The Mixer is a helper to generate instances of Django or SQLAlchemy models. It's useful for testing and fixture replacement. Fast and convenient test-

Kirill Klenov 871 Dec 25, 2022
A mocking library for requests

httmock A mocking library for requests for Python 2.7 and 3.4+. Installation pip install httmock Or, if you are a Gentoo user: emerge dev-python/httm

Patryk Zawadzki 452 Dec 28, 2022
The lightning-fast ASGI server. 🦄

The lightning-fast ASGI server. Documentation: https://www.uvicorn.org Community: https://discuss.encode.io/c/uvicorn Requirements: Python 3.6+ (For P

Encode 6k Jan 03, 2023
A modern API testing tool for web applications built with Open API and GraphQL specifications.

Schemathesis Schemathesis is a modern API testing tool for web applications built with Open API and GraphQL specifications. It reads the application s

Schemathesis.io 1.6k Jan 04, 2023
splinter - python test framework for web applications

splinter - python tool for testing web applications splinter is an open source tool for testing web applications using Python. It lets you automate br

Cobra Team 2.6k Dec 27, 2022
Python HTTP Server

Python HTTP Server Preview Languange and Code Editor: How to run? Download the zip first. Open the http.py and wait 1-2 seconds. You will see __pycach

SonLyte 16 Oct 21, 2021
A drop-in replacement for Django's runserver.

About A drop in replacement for Django's built-in runserver command. Features include: An extendable interface for handling things such as real-time l

David Cramer 1.3k Dec 15, 2022
AWS Lambda & API Gateway support for ASGI

Mangum Mangum is an adapter for using ASGI applications with AWS Lambda & API Gateway. It is intended to provide an easy-to-use, configurable wrapper

Jordan Eremieff 1.2k Jan 06, 2023
Green is a clean, colorful, fast python test runner.

Green -- A clean, colorful, fast python test runner. Features Clean - Low redundancy in output. Result statistics for each test is vertically aligned.

Nathan Stocks 756 Dec 22, 2022
Sixpack is a language-agnostic a/b-testing framework

Sixpack Sixpack is a framework to enable A/B testing across multiple programming languages. It does this by exposing a simple API for client libraries

1.7k Dec 24, 2022
Meinheld is a high performance asynchronous WSGI Web Server (based on picoev)

What's this This is a high performance python wsgi web server. And Meinheld is a WSGI compliant web server. (PEP333 and PEP3333 supported) You can als

Yutaka Matsubara 1.4k Jan 01, 2023
No longer maintained, please migrate to model_bakery

Model Mommy: Smart fixtures for better tests IMPORTANT: Model Mommy is no longer maintained and was replaced by Model Bakery. Please, consider migrati

Bernardo Fontes 917 Oct 04, 2022
The successor to nose, based on unittest2

Welcome to nose2 nose2 is the successor to nose. It's unittest with plugins. nose2 is a new project and does not support all of the features of nose.

738 Jan 09, 2023
Scalable user load testing tool written in Python

Locust Locust is an easy to use, scriptable and scalable performance testing tool. You define the behaviour of your users in regular Python code, inst

Locust.io 20.4k Jan 08, 2023
A cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.

PyAutoGUI PyAutoGUI is a cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard. pip inst

Al Sweigart 7.6k Jan 01, 2023
Coroutine-based concurrency library for Python

gevent Read the documentation online at http://www.gevent.org. Post issues on the bug tracker, discuss and ask open ended questions on the mailing lis

gevent 5.9k Dec 28, 2022
gunicorn 'Green Unicorn' is a WSGI HTTP Server for UNIX, fast clients and sleepy applications.

Gunicorn Gunicorn 'Green Unicorn' is a Python WSGI HTTP Server for UNIX. It's a pre-fork worker model ported from Ruby's Unicorn project. The Gunicorn

Benoit Chesneau 8.7k Jan 01, 2023
A test fixtures replacement for Python

factory_boy factory_boy is a fixtures replacement based on thoughtbot's factory_bot. As a fixtures replacement tool, it aims to replace static, hard t

FactoryBoy project 3k Jan 05, 2023
create custom test databases that are populated with fake data

About Generate fake but valid data filled databases for test purposes using most popular patterns(AFAIK). Current support is sqlite, mysql, postgresql

Emir Ozer 2.2k Jan 06, 2023