FactoryBoy / factory_boy

A test fixtures replacement for Python
https://factoryboy.readthedocs.io/
MIT License
3.48k stars 392 forks source link

Allow inheritance of Params and Meta from abstract parent factories #909

Open Apreche opened 2 years ago

Apreche commented 2 years ago

The problem

There are cases in which an abstract factory will include Meta and Params. To remain DRY, it is desirable that any factory will inherit a combination of all the params and meta from all of its parent factories, with exceptions for some values like model and, of course, abstract.

Most notably, any child factory is going to want to include all the traits of its parent factories. Also, the child factory should have an exclude that is a combination of the excludes of all its parent factories excludes.

Proposed solution

If a factory inherits from one or more abstract factories, its Meta and Params classes should also inherit from the Meta and Params classes of its parent factories.

Extra notes

The only mention of this issue I could find online was this StackOverflow posting.

https://stackoverflow.com/questions/49178024/inherit-params-from-parent-factory-with-factory-boy

rbarrois commented 2 years ago

This is indeed a point where more documentation could be warranted.

For class Meta:

The list is here: https://github.com/FactoryBoy/factory_boy/blob/master/factory/base.py#L171-L178model, strategy, inline_args, rename, exclude are inherited; abstract isn't. For readability, I have opted to NOT combine the three collection fields (inline_args, rename, exclude) from the parents; instead, use the following pattern:

class FooFactory(Parent1Factory, Parent2Factory):
  class Meta:
    exclude = Parent1Factory._meta.exclude + Parent2Factory._meta.exclude + ["bar"]

For class Params:

Parameters (and declarations) are combined from all parent factories, based on the standard Python Method Resolution Order.

Next steps

I agree that this should be more clearly documented; as a user of the library, where would you look to find that information?