vendredi 26 avril 2019

Fake a locale field for model testing

I simply have a collection of languages in a model like this:

from django.conf.global_settings import LANGUAGES

class AvailableLanguage(models.Model):
    code = models.CharField(choices=LANGUAGES, unique=True)


In factories.py, I'd like to fake code field. I've tried to pick up a locale code ramdomly from LANGUAGES but it fails. Instead of creating one instance of AvailableLanguage, it loops over languages and quickly raises an issue because code is set to unique.

So I thought of creating a Provider as a singleton, and it fails for the same reason. It generates all the locale codes instead of providing only one !


class Provider(BaseProvider):

    lang_code = NotImplemented

    def __init__(self, generator):
        self.langs = LANGUAGES
        self.generator = generator

    def __getattribute__(self, attrib):
        if attrib == 'lang_code':
            self.lang_code = self.langs.pop()[0]
            return self.lang_code
        else:
            return super().__getattribute__(attrib)


fake.add_provider(Provider)


class AvailableLanguageFactory(DjangoModelFactory):

    code = Faker('lang_code')

    class Meta:
        model = AvailableLanguage

Aucun commentaire:

Enregistrer un commentaire