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)
This repository contnains sample problems with test cases using Cormen-Lib

Cormen Lib Sample Problems Description This repository contnains sample problems with test cases using Cormen-Lib. These problems were made for the pu

Cormen Lib 3 Jun 30, 2022
Test utility for validating OpenAPI documentation

DRF OpenAPI Tester This is a test utility to validate DRF Test Responses against OpenAPI 2 and 3 schema. It has built-in support for: OpenAPI 2/3 yaml

snok 103 Dec 21, 2022
Selenium Manager

SeleniumManager I'm fed up with always having to struggle unnecessarily when I have to use Selenium on a new machine, so I made this little python mod

Victor Vague 1 Dec 24, 2021
hCaptcha solver and bypasser for Python Selenium. Simple website to try to solve hCaptcha.

hCaptcha solver for Python Selenium. Many thanks to engageub for his hCaptcha solver userscript. This script is solely intended for the use of educati

Maxime Dréan 59 Dec 25, 2022
Selenium Page Object Model with Python

Page-object-model (POM) is a pattern that you can apply it to develop efficient automation framework.

Mohammad Ifran Uddin 1 Nov 29, 2021
Tools for test driven data-wrangling and data validation.

datatest: Test driven data-wrangling and data validation Datatest helps to speed up and formalize data-wrangling and data validation tasks. It impleme

269 Dec 16, 2022
This is a simple software for fetching new changes to remote repositories automatically.

Git Autofetch Git Autofetch is a simple software for fetching new changes from a repo to local repositories after a set time interval. This program is

Shreyas Ashtamkar 10 Jul 21, 2022
pytest plugin for testing mypy types, stubs, and plugins

pytest plugin for testing mypy types, stubs, and plugins Installation This package is available on PyPI pip install pytest-mypy-plugins and conda-forg

TypedDjango 74 Dec 31, 2022
:game_die: Pytest plugin to randomly order tests and control random.seed

pytest-randomly Pytest plugin to randomly order tests and control random.seed. Features All of these features are on by default but can be disabled wi

pytest-dev 471 Dec 30, 2022
To automate the generation and validation tests of COSE/CBOR Codes and it's base45/2D Code representations

To automate the generation and validation tests of COSE/CBOR Codes and it's base45/2D Code representations, a lot of data has to be collected to ensure the variance of the tests. This respository was

160 Jul 25, 2022
Ward is a modern test framework for Python with a focus on productivity and readability.

Ward is a modern test framework for Python with a focus on productivity and readability.

Darren Burns 1k Dec 31, 2022
A pytest plugin, that enables you to test your code that relies on a running PostgreSQL Database

This is a pytest plugin, that enables you to test your code that relies on a running PostgreSQL Database. It allows you to specify fixtures for PostgreSQL process and client.

Clearcode 252 Dec 21, 2022
Pynguin, The PYthoN General UnIt Test geNerator is a test-generation tool for Python

Pynguin, the PYthoN General UnIt test geNerator, is a tool that allows developers to generate unit tests automatically.

Chair of Software Engineering II, Uni Passau 997 Jan 06, 2023
An AWS Pentesting tool that lets you use one-liner commands to backdoor an AWS account's resources with a rogue AWS account - or share the resources with the entire internet 😈

An AWS Pentesting tool that lets you use one-liner commands to backdoor an AWS account's resources with a rogue AWS account - or share the resources with the entire internet 😈

Brandon Galbraith 276 Mar 03, 2021
Python drivers for YeeNet firmware

yeenet-router-driver-python Python drivers for YeeNet firmware This repo is under heavy development. Many or all of these scripts are not likely to wo

Jason Paximadas 1 Dec 26, 2021
A pytest plugin to skip `@pytest.mark.slow` tests by default.

pytest-skip-slow A pytest plugin to skip @pytest.mark.slow tests by default. Include the slow tests with --slow. Installation $ pip install pytest-ski

Brian Okken 19 Jan 04, 2023
pytest plugin for a better developer experience when working with the PyTorch test suite

pytest-pytorch What is it? pytest-pytorch is a lightweight pytest-plugin that enhances the developer experience when working with the PyTorch test sui

Quansight 39 Nov 18, 2022
A framework-agnostic library for testing ASGI web applications

async-asgi-testclient Async ASGI TestClient is a library for testing web applications that implements ASGI specification (version 2 and 3). The motiva

122 Nov 22, 2022
Cloint India Pvt. Ltd's (ClointFusion) Pythonic RPA (Automation) Platform

Welcome to , Made in India with ❤️ Description Cloint India Pvt. Ltd - Python functions for Robotic Process Automation shortly RPA. What is ClointFusi

Cloint India Pvt. Ltd 31 Apr 12, 2022