Skip to content

Sentinel object for excluding items in DictFactory #1140

@chriswyatt

Description

@chriswyatt

The problem

Testing missing items in dictionaries can be very tedious. I use an abstraction that removes items with a 'MISSING' sentinel object. I think this would be a great feature to integrate into Factory Boy, and I imagine it wouldn't be too hard to do.

Proposed solution

This is my current solution:

import factory
from unittest.mock import sentinel


MISSING = sentinel.MISSING


class MyDictFactory(factory.DictFactory):

    @classmethod
    def _adjust_kwargs(cls, **kwargs):
        keys = [k for k, v in kwargs.items() if v is MISSING]

        for key in keys:
            del kwargs[key]

        return kwargs


def _bypass_missing(func):

    def bypass_func(value):
        return func(value) if value is not MISSING else value

    return bypass_func


class _MyTransformer(factory.Transformer):

    def __init__(self, default, *, transform):
        super().__init__(default, transform=_bypass_missing(transform))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions