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)
Let your Python tests travel through time

FreezeGun: Let your Python tests travel through time FreezeGun is a library that allows your Python tests to travel through time by mocking the dateti

Steve Pulec 3.5k Jan 09, 2023
Generic automation framework for acceptance testing and RPA

Robot Framework Introduction Installation Example Usage Documentation Support and contact Contributing License Introduction Robot Framework is a gener

Robot Framework 7.7k Dec 31, 2022
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
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
Mimesis is a high-performance fake data generator for Python, which provides data for a variety of purposes in a variety of languages.

Mimesis - Fake Data Generator Description Mimesis is a high-performance fake data generator for Python, which provides data for a variety of purposes

Isaak Uchakaev 3.8k Jan 01, 2023
An HTTP server to easily download and upload files.

httpsweet An HTTP server to easily download and upload files. It was created with flexibility in mind, allowing be used in many different situations,

Eloy 17 Dec 23, 2022
Radically simplified static file serving for Python web apps

WhiteNoise Radically simplified static file serving for Python web apps With a couple of lines of config WhiteNoise allows your web app to serve its o

Dave Evans 2.1k Jan 08, 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
HTTP client mocking tool for Python - inspired by Fakeweb for Ruby

HTTPretty 1.0.5 HTTP Client mocking tool for Python created by Gabriel Falcão . It provides a full fake TCP socket module. Inspired by FakeWeb Github

Gabriel Falcão 2k Jan 06, 2023
PyQaver is a PHP like WebServer for Python.

PyQaver is a PHP like WebServer for Python.

Dev Bash 7 Apr 25, 2022
Automatically mock your HTTP interactions to simplify and speed up testing

VCR.py 📼 This is a Python version of Ruby's VCR library. Source code https://github.com/kevin1024/vcrpy Documentation https://vcrpy.readthedocs.io/ R

Kevin McCarthy 2.3k Jan 01, 2023
a socket mock framework - for all kinds of socket animals, web-clients included

mocket /mɔˈkɛt/ A socket mock framework for all kinds of socket animals, web-clients included - with gevent/asyncio/SSL support ...and then MicroPytho

Giorgio Salluzzo 249 Dec 14, 2022
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
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
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
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
A utility for mocking out the Python Requests library.

Responses A utility library for mocking out the requests Python library. Note Responses requires Python 2.7 or newer, and requests = 2.0 Installing p

Sentry 3.8k Jan 02, 2023
Official mirror of https://gitlab.com/pgjones/hypercorn https://pgjones.gitlab.io/hypercorn/

Hypercorn Hypercorn is an ASGI web server based on the sans-io hyper, h11, h2, and wsproto libraries and inspired by Gunicorn. Hypercorn supports HTTP

Phil Jones 432 Jan 08, 2023
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
Robyn is an async Python backend server with a runtime written in Rust, btw.

Robyn is an async Python backend server with a runtime written in Rust, btw. Python server running on top of of Rust Async RunTime. Installation

Sanskar Jethi 1.8k Dec 30, 2022