From 8f5dc3fc702cf6d688d2fb5275df1e3577c714e1 Mon Sep 17 00:00:00 2001 From: Kevin Carrogan Date: Fri, 6 Dec 2024 12:50:57 +0000 Subject: [PATCH] Add function to rebuild factories from frozen migration models --- test_helpers/factories.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 test_helpers/factories.py diff --git a/test_helpers/factories.py b/test_helpers/factories.py new file mode 100644 index 000000000..c0181053f --- /dev/null +++ b/test_helpers/factories.py @@ -0,0 +1,32 @@ +import factory + + +def get_model_for_factory(factory_class, apps): + model_meta = factory_class._meta.model._meta + + return apps.get_model(model_meta.app_label, model_meta.object_name) + + +def fullname(cls): + return f"{cls.__module__}.{cls.__name__}" + + +def generate_factory(apps, factory_class, **defaults): + for field_name, field_value in factory_class._meta.declarations.items(): + if field_name in defaults: + continue + if not isinstance(field_value, factory.declarations.SubFactory): + continue + generated_factory = generate_factory( + apps, + field_value.get_factory(), + **field_value.defaults, + ) + defaults[field_name] = factory.declarations.SubFactory(generated_factory) + + updated_factory = factory.make_factory( + get_model_for_factory(factory_class, apps), + **defaults, + FACTORY_CLASS=factory_class, + ) + return updated_factory