pytest-factoryboy icon indicating copy to clipboard operation
pytest-factoryboy copied to clipboard

SubFactory uses wrong fixture name when factory class registered with different model_name

Open ryancausey opened this issue 5 years ago • 2 comments

It appears that when processing SubFactory attributes on the parent factory and generating deps for the SubFactory fixture, the introspected names do not take into account whether a given factory was registered earlier with a different model_name.

This gist demonstrates a failing test where the generated SubFactory fixture is expecting to find a b_model__name fixture when the one available is actually named b_model_with_some_other_name__name. https://gist.github.com/ryancausey/904ad5b77349769d32c72d413dd79a59

I think the root cause of all the issues I'm experiencing can be boiled down to this. This generally shows up when a second factory class is created from a parent subclass. Using the documentation's AuthorFactory as an example:

class BobAuthorFactory(AuthorFactory):
    name = "Bob"

register(BobAuthorFactory, "author_bob")

If we create a second BookFactory subclass that uses BobAuthorFactory as the SubFactory:

class BobBookFactory(BookFactory):
    author = factory.SubFactory(BobAuthorFactory)

register(BobBookFactory, "book_bob")

Then any use of book_bob will actually end up using the original author fixture and end up with an author whose name is "Charles Dickens" based on the docs at the time of this writing.

It doesn't appear that there's an easy fix for register to be able to look up what model_name a given factory class was registered with so I don't have a good answer on how to fix this right now.

ryancausey avatar May 12 '20 23:05 ryancausey

I had a similar issue with SubFactory registering automatically. I used a new Factory with a conflicting name DocumentFactory only as a SubFactory and later the old DocumentFactory is registered. This caused the old one to not be registered and the new one to take precedent, even though I never explicitly registered it. Which caused all references to the old factory to break, as they were now using the new one.

https://github.com/pytest-dev/pytest-factoryboy/blob/6ca239a5c062ed7c725ac0df377c3ccbe9afe8d4/pytest_factoryboy/fixture.py#L169 Maybe throwing a warning here would be nice, if there is a name conflict if they arent the same class.

Yelinz avatar Jun 15 '23 07:06 Yelinz