question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to avoid Faker('domain_name') having the same domain twice in a row ?

See original GitHub issue

I use factory.Faker(“domain_name”) in my factory, is there any way to stop it coming up with the same domain twice ?

I got a unique key error after calling my factory twice:

class SiteFactory(factory.DjangoModelFactory):
    class Meta:
        model = Site

    name = factory.Faker('word')
    domain = factory.Faker('domain_name')
        self.slovak_site = SiteFactory(id=5)
        self.czech_site = SiteFactory(id=6)

Got this unique key error one test run: DETAIL: Key (domain)=(smith.info) already exists.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
francoisfreitagcommented, Aug 29, 2019

Do you mean something like MyFactory.create_batch(2, domain=["example.org", "example.com"])? If so, then no, that is not possible.

What I meant by using factory.Sequence was:

class MyFactory(factory.DjangoModelFactory):
    class Meta:
        model = AModel

    domain = factory.Sequence(lambda n: f"www{n}.example.org")

That yields unique values for domain as long as the sequence is not reset. That does not make domain names as realistic as Faker’s, but they should be good enough for tests and are sure to be unique.


An overkill way to generate unique domain from Faker().domain_name():

from faker import Faker


def generate_domain_name(n):
    """
    Returns a Faker generated domain with the sequence number
    appended to the first part of the domain.

    With n=6, jim.org becomes jim6.com.
    """
    base_domain = Faker().domain_name()
    parts = base_domain.split(".")
    first_part = parts[0]
    parts = [f"{first_part}{n}", *parts[1:]]
    return ".".join(parts)


class MyFactory(factory.DjangoModelFactory):
    class Meta:
        model = AModel

    domain = factory.Sequence(generate_domain_name)
0reactions
stuaxocommented, Sep 26, 2019

In the end I made a SiteFactory that handles this, posted below

It does feel like both faker and factoryboy would benefit from being able to handle uniqueness, especially when it comes to fields that are declared unique.

# some code ommited
class SiteFactory(factory.DjangoModelFactory):
    class Meta:
        model = Site

    name = factory.Faker('word')
    domain = factory.Faker('domain_name')

    _used_domains = set()

    @classmethod
    def _get_unique_domain(cls):
        domain = cls.domain.generate()
        for i in range(8):
            if domain not in cls._used_domains:
                break
            domain = cls.domain.generate()
        return domain

    @receiver(post_delete, sender=Site)
    def _remove_domain_from_cache(sender, instance, created, **kwargs):
        SiteFactory._used_domains.discard(instance.domain)

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        if "domain" not in kwargs:
            kwargs["domain"] = cls._get_unique_domain()
        cls._used_domains.add(kwargs["domain"])

        return super()._create(model_class, *args, **kwargs)
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to avoid Faker('domain_name') having the same domain twice ...
I use factory.Faker("domain_name") in my factory, is there any way to stop it coming up with the same domain twice ? I got...
Read more >
Faker generates same word 2 times in a row #655 - GitHub
We use faker in our project and generally are happy with it. But from time to time one of our tests fails because...
Read more >
using Twice the same FK in the same table with laravel
Found. A problem in one of my var names.
Read more >
What happens when a domain name is linked to two different ...
That depends. As mentioned, it's fairly common for a domain to be connected to multiple IP addresses. Do the two IPs serve the...
Read more >
Bought the same domain name twice - Web Hosting Talk
1. It is not the case buying the domain 2 times, it is the case when the domain wasn't registered first time. 2....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found