Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RedirectFactory #82

Open
kbayliss opened this issue Jan 5, 2024 · 0 comments · May be fixed by #83
Open

Add RedirectFactory #82

kbayliss opened this issue Jan 5, 2024 · 0 comments · May be fixed by #83

Comments

@kbayliss
Copy link

kbayliss commented Jan 5, 2024

Wagtail provides a Redirect model so it would be useful to add a reusable RedirectFactory.

Example:

class RedirectFactory(factory.django.DjangoModelFactory):
    old_path = factory.Faker("slug")
    site = factory.SubFactory(wagtail_factories.SiteFactory)
    redirect_page = factory.SubFactory(wagtail_factories.PageFactory)
    redirect_link = factory.Faker("url")
    is_permanent = factory.Faker("boolean")

    class Meta:
        model = Redirect

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        """
        Override _create() to ensure that Redirect.clean() is run in order to
        normalise `old_path`.
        @see https://github.com/wagtail/wagtail/blob/main/wagtail/contrib/redirects/models.py#L191
        @see https://github.com/jamescooke/factory_djoy/blob/2744fa062f58f5eb13c68938faf844a0812a3ff6/factory_djoy/factories.py#L21
        """
        obj = model_class(*args, **kwargs)
        try:
            obj.clean()
        except ValidationError as ve:
            message = (
                f"Error building {model_class} with {cls.__name__}.\nBad values:\n"
            )
            for field in ve.error_dict.keys():
                if field == "__all__":
                    message += "  __all__: obj.clean() failed\n"
                else:
                    message += f'  {field}: "{getattr(obj, field)}"\n'
            raise RuntimeError(message) from ve
        obj.save()
        return obj

Needs tests adding :).

@JakubMastalerz JakubMastalerz linked a pull request Jan 5, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant