Python factory.Faker() Examples

The following are 30 code examples of factory.Faker(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module factory , or try the search function .
Example #1
Source File: test_profile_model.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_age(self):
        profile = ProfileFactory.build(birth_date=None)
        self.assertRaises(TypeError, lambda: profile.age)
        profile = ProfileFactory.build(birth_date=Faker('date_this_year', before_today=True, after_today=False))
        self.assertEqual(profile.age, 0)
        profile = ProfileFactory.build(birth_date=Faker('date_this_year', before_today=False, after_today=True))
        self.assertEqual(profile.age, 0)
        profile = ProfileFactory.build(birth_date=Faker('date_between', start_date='-725d', end_date='-365d'))
        self.assertEqual(profile.age, 1)
        profile = ProfileFactory.build(birth_date=Faker('date_between', start_date='+365d', end_date='+725d'))
        self.assertEqual(profile.age, -1)
        profile = ProfileFactory.build(birth_date=Faker('date_between', start_date='-6935d', end_date='-6575d'))
        self.assertEqual(profile.age, 18)

        profile = ProfileFactory.build(birth_date=None, death_date=Faker('date_this_year'))
        self.assertRaises(TypeError, lambda: profile.age)
        profile = ProfileFactory.build(
            birth_date=Faker('date_between', start_date='-2000d', end_date='-1825d'),
            death_date=Faker('date_between', start_date='-360d', end_date='-185d'))
        self.assertEqual(profile.age, 4)
        profile = ProfileFactory.build(
            birth_date=Faker('date_between', start_date='-2000d', end_date='-1825d'),
            death_date=Faker('date_between', start_date='+370d', end_date='+545d'))
        self.assertEqual(profile.age, 6) 
Example #2
Source File: factories.py    From richie with MIT License 6 votes vote down vote up
def fill_excerpt(self, create, extracted, **kwargs):
        """
        Add a plain text plugin for excerpt with a short random text
        """
        if create and extracted:
            placeholder = self.extended_object.placeholders.get(slot="program_excerpt")

            for language in self.extended_object.get_languages():
                text = factory.Faker(
                    "text",
                    max_nb_chars=random.randint(50, 100),  # nosec
                    locale=language,
                ).generate({})
                add_plugin(
                    language=language,
                    placeholder=placeholder,
                    plugin_type="PlainTextPlugin",
                    body=text,
                ) 
Example #3
Source File: factories.py    From richie with MIT License 6 votes vote down vote up
def fill_excerpt(self, create, extracted, **kwargs):
        """
        Add a plain text plugin for excerpt with a short random text
        """
        if create and extracted:
            placeholder = self.extended_object.placeholders.get(slot="excerpt")

            for language in self.extended_object.get_languages():
                text = factory.Faker(
                    "text",
                    max_nb_chars=random.randint(50, 100),  # nosec
                    locale=language,
                ).generate({})
                add_plugin(
                    language=language,
                    placeholder=placeholder,
                    plugin_type="PlainTextPlugin",
                    body=text,
                ) 
Example #4
Source File: factories.py    From richie with MIT License 6 votes vote down vote up
def extended_object(self):
        """
        Automatically create a related page with the title (or random title if None) in all the
        requested languages
        """
        title = getattr(self, "page_title", None)
        languages = getattr(self, "page_languages", None)
        if not title:
            # Create realistic titles in each language with faker
            languages = languages or [settings.LANGUAGE_CODE]
            title = {
                language: factory.Faker("catch_phrase", locale=language).generate({})
                for language in languages
            }

        return create_i18n_page(
            title,
            in_navigation=getattr(self, "page_in_navigation", False),
            languages=languages,
            parent=getattr(self, "page_parent", None),
            reverse_id=getattr(self, "page_reverse_id", None),
            template=getattr(self, "page_template", None),
        ) 
Example #5
Source File: slack.py    From busy-beaver with MIT License 6 votes vote down vote up
def SlackInstallation(session):
    class _SlackInstallationFactory(factory.alchemy.SQLAlchemyModelFactory):
        class Meta:
            model = slack_installation_model
            sqlalchemy_session_persistence = "commit"
            sqlalchemy_session = session

        access_token = factory.Faker("uuid4")
        authorizing_user_id = "abc"

        bot_access_token = factory.Faker("uuid4")
        bot_user_id = "def"

        scope = "identity chat:message:write"
        workspace_id = "SC234sdfsde"
        workspace_name = "ChiPy"

        state = "active"

    return _SlackInstallationFactory 
Example #6
Source File: blocks.py    From hypha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_form_answer(cls, params=dict()):
        try:
            address = json.loads(params)
        except TypeError:
            if not params:
                params = {}
            return {
                'country': 'GB',
                'thoroughfare': factory.Faker('street_name').generate(params),
                'premise': factory.Faker('building_number').generate(params),
                'locality': {
                    'localityname': factory.Faker('city').generate(params),
                    'administrativearea': factory.Faker('city').generate(params),
                    'postal_code': 'SW1 4AQ',
                }
            }

        address['locality'] = {
            'localityname': address.pop('localityname'),
            'administrativearea': address.pop('administrativearea'),
            'postalcode': address.pop('postalcode'),
        }
        return address 
Example #7
Source File: __init__.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def __init__(self, signed=True, from_file=None, addon_id=None, overwrite_data=None):
        super().__init__(signed=signed)

        if not addon_id:
            addon_id = f"{factory.Faker('md5').generate({})}@normandy.mozilla.org"

        if from_file:
            with open(from_file, "rb") as f:
                self.add_file("install.rdf", f.read())
        else:
            data = {
                "id": addon_id,
                "version": "0.1",
                "name": "Signed Bootstrap Mozilla Extension Example",
                "description": "Example of a bootstrapped addon",
            }

            if overwrite_data:
                data.update(overwrite_data)

            self.generate_install_rdf(data) 
Example #8
Source File: __init__.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def __init__(self, signed=True, from_file=None, gecko_id=None, overwrite_data=None):
        super().__init__(signed=signed)

        if not gecko_id:
            gecko_id = f"{factory.Faker('md5').generate({})}@normandy.mozilla.org"

        if from_file:
            self._manifest = json.load(from_file)
        else:
            self._manifest = {
                "manifest_version": 2,
                "name": "normandy test addon",
                "version": "0.1",
                "description": "This is an add-on for us in Normandy's tests",
                "applications": {"gecko": {"id": gecko_id}},
            }

        if overwrite_data:
            self._manifest.update(overwrite_data)

        self.save_manifest() 
Example #9
Source File: test_registration.py    From conf_site with MIT License 6 votes vote down vote up
def test_user_registration(self):
        """Ensure that user registration works properly."""
        EMAIL = Faker("email").generate()
        PASSWORD = fuzzy.FuzzyText(length=16)
        test_user_data = {
            "password1": PASSWORD,
            "password2": PASSWORD,
            "email": EMAIL,
            "email2": EMAIL,
        }

        # Verify that POSTing user data to the registration view
        # succeeds / returns the right HTTP status code.
        response = self.client.post(
            reverse("account_signup"), test_user_data)
        # Successful form submission will cause the HTTP status code
        # to be "302 Found", not "200 OK".
        self.assertEqual(response.status_code, 302)

        # Verify that a User has been successfully created.
        user_model = get_user_model()
        user_model.objects.get(email=EMAIL) 
Example #10
Source File: factories.py    From caluma with GNU General Public License v3.0 6 votes vote down vote up
def value(self):
        if (
            self.question.type == models.Question.TYPE_MULTIPLE_CHOICE
            or self.question.type == models.Question.TYPE_DYNAMIC_MULTIPLE_CHOICE
        ):
            return [Faker("name").generate({}), Faker("name").generate({})]
        elif self.question.type == models.Question.TYPE_FLOAT:
            return Faker("pyfloat").generate({})
        elif self.question.type == models.Question.TYPE_INTEGER:
            return Faker("pyint").generate({})
        elif self.question.type not in [
            models.Question.TYPE_TABLE,
            models.Question.TYPE_FILE,
            models.Question.TYPE_DATE,
        ]:
            return Faker("name").generate({})

        return None 
Example #11
Source File: factories.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
        password = Faker(
            "password",
            length=42,
            special_chars=True,
            digits=True,
            upper_case=True,
            lower_case=True,
        ).generate(
            extra_kwargs={}
        )
        self.set_password(password) 
Example #12
Source File: factories.py    From Ghostwriter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
        password = Faker(
            "password",
            length=42,
            special_chars=True,
            digits=True,
            upper_case=True,
            lower_case=True,
        ).generate(extra_kwargs={})
        self.set_password(password) 
Example #13
Source File: event_details.py    From busy-beaver with MIT License 5 votes vote down vote up
def EventDetails(session):
    class _EventDetailsFactory(factory.Factory):
        class Meta:
            model = model

        id = factory.Faker("uuid4")
        name = "ChiPy"
        url = "http://meetup.com/_ChiPy_/event/blah"
        start_epoch = int((datetime.now() + timedelta(days=1)).timestamp())
        end_epoch = start_epoch + 60 * 60 * 2
        venue = "Numerator"

    return _EventDetailsFactory 
Example #14
Source File: event.py    From busy-beaver with MIT License 5 votes vote down vote up
def Event(session):
    class _EventFactory(factory.alchemy.SQLAlchemyModelFactory):
        class Meta:
            model = model
            sqlalchemy_session_persistence = "commit"
            sqlalchemy_session = session

        remote_id = factory.Faker("uuid4")
        name = "ChiPy"
        url = "http://meetup.com/_ChiPy_/event/blah"
        start_epoch = int((datetime.now() + timedelta(days=1)).timestamp())
        end_epoch = start_epoch + 60 * 60 * 2
        venue = "Numerator"

    return _EventFactory 
Example #15
Source File: github_summary_user.py    From busy-beaver with MIT License 5 votes vote down vote up
def GitHubSummaryUser(session):
    class _GitHubSummaryUserFactory(factory.alchemy.SQLAlchemyModelFactory):
        class Meta:
            model = github_summary_user_model
            sqlalchemy_session_persistence = "commit"
            sqlalchemy_session = session

        slack_id = "slack_user"
        github_id = "13242345435"
        github_username = "github_user"
        github_state = ""
        github_access_token = factory.Faker("uuid4")
        configuration = factory.SubFactory(GitHubSummaryConfiguration(session))

    return _GitHubSummaryUserFactory 
Example #16
Source File: factories.py    From open with MIT License 5 votes vote down vote up
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
        password = Faker(
            "password",
            length=42,
            special_chars=True,
            digits=True,
            upper_case=True,
            lower_case=True,
        ).generate(extra_kwargs={})
        self.set_password(password) 
Example #17
Source File: conftest.py    From micromasters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _update_discussion_user(discussion_user, allow_email_optin=False):
    """Helper function to create a DiscussionUser and update its username"""
    if discussion_user.username is None:
        discussion_user.username = Faker('user_name').generate({})
    discussion_user.last_sync = discussion_user.user.profile.updated_on
    discussion_user.save() 
Example #18
Source File: factories.py    From django-quick-start with MIT License 5 votes vote down vote up
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
        password = Faker(
            "password",
            length=42,
            special_chars=True,
            digits=True,
            upper_case=True,
            lower_case=True,
        ).generate(
            extra_kwargs={}
        )
        self.set_password(password) 
Example #19
Source File: factories.py    From viettel-shake with MIT License 5 votes vote down vote up
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
        password = Faker(
            "password",
            length=42,
            special_chars=True,
            digits=True,
            upper_case=True,
            lower_case=True,
        ).generate(extra_kwargs={})
        self.set_password(password) 
Example #20
Source File: factories.py    From MetaCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fake_name(prefix=None):
    """Generate a fake name with a certain prefix. You can push the name_prefix
       from outside of the factory if you have a preference when you instantiate
       the class."""
    return factory.LazyAttribute(
        lambda a: (getattr(a, "name_prefix", None) or prefix or "")
        + factory.Faker("word").generate({})
    ) 
Example #21
Source File: factories.py    From scrooge with MIT License 5 votes vote down vote up
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
        password = Faker(
            "password",
            length=42,
            special_chars=True,
            digits=True,
            upper_case=True,
            lower_case=True,
        ).generate(extra_kwargs={})
        self.set_password(password) 
Example #22
Source File: blocks.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_answer(cls, params):
        if not params:
            params = {}
        return json.dumps({
            'country': 'GB',
            'thoroughfare': factory.Faker('street_name').generate(params),
            'premise': factory.Faker('building_number').generate(params),
            'localityname': factory.Faker('city').generate(params),
            'administrativearea': factory.Faker('city').generate(params),
            'postalcode': 'SW1 4AQ',
        }) 
Example #23
Source File: blocks.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_answer(cls, params=dict()):
        return json.dumps([factory.Faker('paragraph').generate(params), random.randint(1, 5)]) 
Example #24
Source File: blocks.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_form_answer(cls, params=dict()):
        defaults = {
            'description': factory.Faker('paragraph').generate({}),
            'score': random.randint(1, 5),
        }
        defaults.update(params)
        return defaults 
Example #25
Source File: factories.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def state_province(self):
        if self.country in COUNTRIES_WITH_MANDATORY_REGION or random() > 0.85:
            return Faker('state').generate({})
        else:
            return "" 
Example #26
Source File: factories.py    From readux with MIT License 5 votes vote down vote up
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
        password = Faker(
            "password",
            length=42,
            special_chars=True,
            digits=True,
            upper_case=True,
            lower_case=True,
        ).generate(
            extra_kwargs={}
        )
        self.set_password(password) 
Example #27
Source File: factories.py    From bud with MIT License 5 votes vote down vote up
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
        password = (
            extracted
            if extracted
            else Faker(
                "password",
                length=42,
                special_chars=True,
                digits=True,
                upper_case=True,
                lower_case=True,
            ).generate(extra_kwargs={})
        )
        self.set_password(password) 
Example #28
Source File: factories.py    From django_cookiecutter_docker with MIT License 5 votes vote down vote up
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
        password = Faker(
            "password",
            length=42,
            special_chars=True,
            digits=True,
            upper_case=True,
            lower_case=True,
        ).generate(extra_kwargs={})
        self.set_password(password) 
Example #29
Source File: test_blog_models.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_has_more_flag(self):
        # A normal blog post with introduction and content.
        PostFactory()
        # A blog post without an introduction.
        PostFactory(content=Faker('text').generate({}))

        qs = Post.objects.get_queryset().order_by('id')
        self.assertEqual(len(qs), 2)
        for i, flag in enumerate((True, False)):
            with self.subTest(has_more=flag):
                self.assertEqual(qs[i].has_more, flag) 
Example #30
Source File: test_whereabouts_model.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_str(self):
        loc = WhereaboutsFactory.build(name="Córdoba", state="", country=Country('AR'))
        self.assertEquals(str(loc), "Location of Córdoba (Argentina)")
        loc = WhereaboutsFactory.build(name="Córdoba", state="Córdoba", country=Country('AR'))
        self.assertEquals(str(loc), "Location of Córdoba (Córdoba, Argentina)")
        loc = WhereaboutsFactory.build(
            name=Faker('city', locale='el_GR'), state="", country=Country('GR'))
        self.assertEquals(str(loc), "Location of {} ({})".format(loc.name, loc.country.name))
        loc = WhereaboutsFactory.build(
            name=Faker('city', locale='el_GR'), state=Faker('region', locale='el_GR'), country=Country('GR'))
        self.assertEquals(str(loc), "Location of {} ({}, {})".format(loc.name, loc.state, loc.country.name))