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)
Plugin for generating HTML reports for pytest results

pytest-html pytest-html is a plugin for pytest that generates a HTML report for test results. Resources Documentation Release Notes Issue Tracker Code

pytest-dev 548 Dec 28, 2022
Enabling easy statistical significance testing for deep neural networks.

deep-significance: Easy and Better Significance Testing for Deep Neural Networks Contents ⁉️ Why 📥 Installation 🔖 Examples Intermezzo: Almost Stocha

Dennis Ulmer 270 Dec 20, 2022
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 03, 2023
Active Directory Penetration Testing methods with simulations

AD penetration Testing Project By Ruben Enkaoua - GL4Di4T0R Based on the TCM PEH course (Heath Adams) Index 1 - Setting Up the Lab Intallation of a Wi

GL4DI4T0R 3 Aug 12, 2021
A feature flipper for Django

README Django Waffle is (yet another) feature flipper for Django. You can define the conditions for which a flag should be active, and use it in a num

952 Jan 06, 2023
Selects tests affected by changed files. Continous test runner when used with pytest-watch.

This is a pytest plug-in which automatically selects and re-executes only tests affected by recent changes. How is this possible in dynamic language l

Tibor Arpas 614 Dec 30, 2022
자동 건강상태 자가진단 메크로 서버전용

Auto-Self-Diagnosis-for-server 자동 자가진단 메크로 서버전용 이 프로그램은 SaidBySolo님의 auto-self-diagnosis를 참고하여 제작하였습니다. 개인 사용 목적으로 제작하였기 때문에 추후 업데이트는 진행하지 않습니다. 의존성 G

JJooni 3 Dec 04, 2021
A automated browsing experience.

browser-automation This app is an automated browsing technique where one has to enter the required information, it's just like searching for Animals o

Ojas Barawal 3 Aug 04, 2021
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
masscan + nmap 快速端口存活检测和服务识别

masnmap masscan + nmap 快速端口存活检测和服务识别。 思路很简单,将masscan在端口探测的高速和nmap服务探测的准确性结合起来,达到一种相对比较理想的效果。 先使用masscan以较高速率对ip存活端口进行探测,再以多进程的方式,使用nmap对开放的端口进行服务探测。 安

starnightcyber 75 Dec 19, 2022
A Demo of Feishu automation testing framework

FeishuAutoTestDemo This is a automation testing framework which use Feishu as an example. Execute runner.py to run. Technology Web UI Test pytest + se

2 Aug 19, 2022
Headless chrome/chromium automation library (unofficial port of puppeteer)

Pyppeteer Pyppeteer has moved to pyppeteer/pyppeteer Unofficial Python port of puppeteer JavaScript (headless) chrome/chromium browser automation libr

miyakogi 3.5k Dec 30, 2022
Automatic SQL injection and database takeover tool

sqlmap sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of

sqlmapproject 25.7k Jan 04, 2023
Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.

Prism is a set of packages for API mocking and contract testing with OpenAPI v2 (formerly known as Swagger) and OpenAPI v3.x. Mock Servers: Life-like

Stoplight 3.3k Jan 05, 2023
HTTP traffic mocking and testing made easy in Python

pook Versatile, expressive and hackable utility library for HTTP traffic mocking and expectations made easy in Python. Heavily inspired by gock. To ge

Tom 305 Dec 23, 2022
🏃💨 For when you need to fill out feedback in the last minute.

BMSCE Auto Feedback For when you need to fill out feedback in the last minute. 🏃 💨 Setup Clone the repository Run pip install selenium Set the RATIN

Shaan Subbaiah 10 May 23, 2022
Python scripts for a generic performance testing infrastructure using Locust.

TODOs Reference to published paper or online version of it loadtest_plotter.py: Cleanup and reading data from files ARS_simulation.py: Cleanup, docume

Juri Tomak 3 Dec 15, 2022
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 Dec 30, 2022
hyppo is an open-source software package for multivariate hypothesis testing.

hyppo (HYPothesis Testing in PythOn, pronounced "Hippo") is an open-source software package for multivariate hypothesis testing.

neurodata 137 Dec 18, 2022
A friendly wrapper for modern SQLAlchemy and Alembic

A friendly wrapper for modern SQLAlchemy (v1.4 or later) and Alembic. Documentation: https://jpsca.github.io/sqla-wrapper/ Includes: A SQLAlchemy wrap

Juan-Pablo Scaletti 129 Nov 28, 2022