コード例 #1
0
ファイル: test_internet.py プロジェクト: ohbarye/faker
class TestNlNl(unittest.TestCase):

    def setUp(self):
        self.factory = Faker('nl_NL')
        self.provider = self.factory.provider('faker.providers.internet')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'fabiënné'
    )
    def test_ascii_safe_email(self):
        email = self.factory.ascii_safe_email()
        validate_email(email, check_deliverability=False)
        self.assertEqual(email.split('@')[0], 'fabienne')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'fabiënné'
    )
    def test_ascii_free_email(self):
        email = self.factory.ascii_free_email()
        validate_email(email, check_deliverability=False)
        self.assertEqual(email.split('@')[0], 'fabienne')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'fabiënné'
    )
    def test_ascii_company_email(self):
        email = self.factory.ascii_company_email()
        validate_email(email, check_deliverability=False)
        self.assertEqual(email.split('@')[0], 'fabienne')
コード例 #2
0
ファイル: generate_json.py プロジェクト: mrbitsdcf/quickjson
def mount_json(object_base):
    fake = Faker()
    obj = {}
    for key, value in object_base.items():
        if isinstance(value, dict):
            obj[key] = mount_json(value)
            continue
        if isinstance(value, list):
            if value[0] in dir(fake):
                try:
                    if value[0] == 'list_email':
                        obj[key] = [fake.email() for n in range(value[1])]
                        continue

                    func = getattr(fake, value[0])
                    obj[key] = func(value[1])
                except IndexError:
                    func = getattr(fake, value[0])
                    obj[key] = func()
                continue

            obj = {}
            break

    return obj
コード例 #3
0
ファイル: test_factory.py プロジェクト: bessl/faker-1
    def test_instance_seed_chain(self):
        factory = Faker()

        names = ['Real Name0', 'Real Name1', 'Real Name2', 'Real Name0', 'Real Name2']
        anonymized = [factory.seed_instance(name).name() for name in names]
        self.assertEqual(anonymized[0], anonymized[3])
        self.assertEqual(anonymized[2], anonymized[4])
コード例 #4
0
ファイル: cerise_datas.py プロジェクト: rodo/django-perf
    def handle(self, *args, **options):
        """
        Make
        """
        f = Faker()
        nbvalues = options['nbvalues']

        nba = 0
        datas = []
        for aux in range(nbvalues):

            dat = {'firstname': f.first_name(),
                   'lastname': f.last_name()[:30]}
            
            datas.append(Cerise(name=f.last_name()[:30],
                                data=dat,
                                indice=2,
                                objtxt=json.dumps(dat)))

            datas.append(Cerise(name=f.last_name()[:30],
                                indice=3,                                
                                data={'delta': 3}))
            nba += 1
            if nba > 9:
                Cerise.objects.bulk_create(datas)
                datas = []
                nba = 0
コード例 #5
0
ファイル: mongo.py プロジェクト: cl0ne/kpi-educational-tasks
def main():
    fake = Faker()
    db = MongoClient().kpi  # use default settings
    c = db.students
    c.drop()

    for _ in range(10):
        log = [
            _gen_subject(fake, s)
            for s in ['math', 'geography', 'biology', 'physics']
        ]
        s = {
            'name': fake.name(),
            'log': log
        }
        c.insert_one(s)

    print('Best marks:')
    print('\n'.join(str(m) for m in _best_avg_marks(c)))

    print('Subjects with low marks:')
    print('\n'.join(m['_id'] for m in _subjects_with_low_marks(c)))

    print('Daily average marks:')
    print('\n'.join(str(m) for m in _daily_avg_marks(c)))
コード例 #6
0
    def test_0010_send_mails(self, mock_smtp):
        """
        Tests send_mails functionality.
        """
        EmailQueue = POOL.get('email.queue')

        with Transaction().start(DB_NAME, USER, CONTEXT) as transaction:
            # Put some emails in queue
            f = Faker()
            for item in xrange(10):
                EmailQueue.queue_mail(f.email(), f.email(), f.text())

            transaction.cursor.commit()

            self.assertEqual(EmailQueue.search([], count=True), 10)
            self.assertEqual(
                EmailQueue.search([('state', '=', 'outbox')], count=True), 10
            )

        with Transaction().start(DB_NAME, USER, CONTEXT) as transaction:
            # Run cron method to send mails
            EmailQueue.send_all()

        with Transaction().start(DB_NAME, USER, CONTEXT) as transaction:
            self.assertEqual(
                EmailQueue.search([('state', '=', 'sent')], count=True), 10
            )
コード例 #7
0
ファイル: test_factory.py プロジェクト: bessl/faker-1
 def test_prefix_suffix_always_string(self):
     # Locales known to contain `*_male` and `*_female`.
     for locale in ("bg_BG", "dk_DK", "en", "ru_RU", "tr_TR"):
         f = Faker(locale=locale)
         for x in range(20):  # Probabilistic testing.
             self.assertIsInstance(f.prefix(), string_types)
             self.assertIsInstance(f.suffix(), string_types)
def create_posts():
    oauth_session, legacy_token = get_legacy_app_token()
    backend_token = get_backend_app_token()

    backend_token.viewkeys()

    legacy_token.viewkeys()

    fake = Faker()

    [attr for attr in dir(fake) if not attr.startswith('_')]

    post_data = [{
        'content': "Hello, content {}.".format(SPACE.join((SPACE.join(fake.words()) for _ in range(10)))),
        'title': fake.catch_phrase(),
        'excerpt': "Hello, excerpt {}.".format(SPACE.join(fake.words())),
        'status': "publish",
        'comment_status': "closed",
        'x-tags': fake.words(),
        'format': "status",
    } for _ in range(5)]

    for post_datum in post_data:
        response = oauth_session.post(posts_url, data=post_datum, **verify_ssl_certificate)
        try:
            pprint(response.json())
        except ValueError:
            pprint(response.content)
コード例 #9
0
ファイル: manga_datas.py プロジェクト: rodo/django-perf
    def handle(self, *args, **options):
        """
        Make
        """
        f = Faker()
        nbvalues = options['nbvalues']

        childs = options  ['childs']
        catid = randrange(10)
        name = f.name()

        root = Category.objects.create(name=name,
                                       catid=catid)

        moot = Genre.objects.create(name=name,
                                    catid=catid)

        for aux in range(nbvalues):
            parent = root
            marent = moot
            for child in range(childs):
                catid = randrange(10)
                name = f.name()

                parent = Category.objects.create(name=name,
                                                 catid=catid,
                                                 parent=parent)

                marent = Genre.objects.create(name=name,
                                              catid=catid,
                                              parent=marent)

        print Category.objects.all().count()
        print Genre.objects.all().count()
コード例 #10
0
ファイル: test_internet.py プロジェクト: joke2k/faker
class TestPtBR(unittest.TestCase):

    def setUp(self):
        self.factory = Faker('pt_BR')
        self.provider = self.factory.provider('faker.providers.internet')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'VitóriaMagalhães',
    )
    def test_ascii_safe_email(self):
        email = self.factory.ascii_safe_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'vitoriamagalhaes'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'JoãoSimões',
    )
    def test_ascii_free_email(self):
        email = self.factory.ascii_free_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'joaosimoes'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'AndréCauã',
    )
    def test_ascii_company_email(self):
        email = self.factory.ascii_company_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'andrecaua'
コード例 #11
0
ファイル: test_internet.py プロジェクト: joke2k/faker
class TestInternetProviderUrl(unittest.TestCase):
    """ Test internet url generation """

    def setUp(self):
        self.factory = Faker()

    @staticmethod
    def is_correct_scheme(url, schemes):
        return any(url.startswith('{}://'.format(scheme)) for scheme in schemes)

    def test_url_default_schemes(self):
        for _ in range(100):
            url = self.factory.url()
            assert self.is_correct_scheme(url, ['http', 'https'])

    def test_url_custom_schemes(self):
        schemes_sets = [
            ['usb'],
            ['ftp', 'file'],
            ['usb', 'telnet', 'http'],
        ]
        for _, schemes in zip(range(100), cycle(schemes_sets)):
            url = self.factory.url(schemes=schemes)
            assert self.is_correct_scheme(url, schemes)

    def test_url_empty_schemes_list_generate_schemeless_urls(self):
        for _ in range(100):
            url = self.factory.url(schemes=[])
            assert not url.startswith('http')
            assert url.startswith('://')
コード例 #12
0
ファイル: test_internet.py プロジェクト: joke2k/faker
class TestInternetProvider(unittest.TestCase):
    """ Tests internet """

    def setUp(self):
        self.factory = Faker()

    def test_email(self):
        email = self.factory.email(domain='example.com')
        assert email.split('@')[1] == 'example.com'

    @mock.patch(
        'faker.providers.internet.Provider.image_placeholder_services',
        {'https://dummyimage.com/{width}x{height}'},
    )
    def test_image_url(self):
        my_width = 500
        my_height = 1024
        url = self.factory.image_url(my_width, my_height)
        assert 'https://dummyimage.com/{}x{}'.format(my_width, my_height) == url
        url = self.factory.image_url()
        assert 'https://dummyimage.com/' in url

    def test_hostname(self):
        hostname_1_level = self.factory.hostname(levels=1)
        hostname_parts = hostname_1_level.split(".")
        assert hostname_1_level
        self.assertIsInstance(hostname_1_level, six.string_types)
        assert len(hostname_parts) == 3

        hostname_0_level = self.factory.hostname(levels=0)
        assert hostname_0_level
        self.assertIsInstance(hostname_0_level, six.string_types)
コード例 #13
0
ファイル: test_internet.py プロジェクト: joke2k/faker
class TestArAa(unittest.TestCase):

    def setUp(self):
        self.factory = Faker('ar_AA')
        self.provider = self.factory.provider('faker.providers.internet')

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'اصيل',
    )
    def test_ascii_safe_email(self):
        email = self.factory.ascii_safe_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'asyl'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'اصيل',
    )
    def test_ascii_free_email(self):
        email = self.factory.ascii_free_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'asyl'

    @mock.patch(
        'faker.providers.internet.Provider.user_name',
        lambda x: 'اصيل',
    )
    def test_ascii_company_email(self):
        email = self.factory.ascii_company_email()
        validate_email(email, check_deliverability=False)
        assert email.split('@')[0] == 'asyl'
コード例 #14
0
    def handle(self, *args, **options):
        app_dir = os.path.dirname(__file__)
        with open(os.path.join(app_dir, 'data.json')) as f:
            raw_data = json.load(f)
            for c in raw_data:
                self._populate_collection(c, raw_data[c])

        fake = Faker()
        with open(os.path.join(app_dir, 'words.json')) as f:
            word_list = json.load(f)
            counts = [
                _mongo_db.priorities.count(),
                _mongo_db.statuses.count(),
                _mongo_db.users.count(),
            ]
            for _ in range(50000):
                Issue.insert_one({
                    'title': _get_random_string(word_list, 6),
                    'description': _get_random_string(word_list, 12, True, True),
                    'create_time': fake.date_time_this_decade(),
                    'priority': IssuePriority.find(random.randrange(counts[0]), 1)[0],
                    'status': IssueStatus.find(random.randrange(counts[1]), 1)[0],
                    'created_by': User.get(random.randrange(counts[2]), 1)[0],
                    'assigned_to': User.get(random.randrange(counts[2]), 1)[0] if random.randint(0, 2) else None
                })
コード例 #15
0
ファイル: test_internet.py プロジェクト: joke2k/faker
class TestZhCN(unittest.TestCase):

    def setUp(self):
        self.factory = Faker(locale='zh_CN')

    def test_email(self):
        email = self.factory.email()
        validate_email(email, check_deliverability=False)

    def test_domain_word(self):
        domain_word = self.factory.domain_word()
        assert len(domain_word) > 1

    @mock.patch(
        'faker.providers.internet.Provider.tld',
        lambda x: 'cn',
    )
    def test_domain_name(self):
        domain_name_1_level = self.factory.domain_name(levels=1)
        domain_parts = domain_name_1_level.split(".")
        assert len(domain_parts) == 2
        assert domain_parts[-1] == 'cn'
        domain_name_2_level = self.factory.domain_name(levels=2)
        domain_parts = domain_name_2_level.split(".")
        assert len(domain_parts) == 3
        assert domain_parts[-1] == 'cn'
        assert domain_parts[1] in ['ac', 'com', 'edu', 'gov', 'mil',
                                   'net', 'org', 'ah', 'bj', 'cq',
                                   'fj', 'gd', 'gs', 'gz', 'gx', 'ha',
                                   'hb', 'he', 'hi', 'hk', 'hl', 'hn',
                                   'jl', 'js', 'jx', 'ln', 'mo', 'nm',
                                   'nx', 'qh', 'sc', 'sd', 'sh', 'sn',
                                   'sx', 'tj', 'xj', 'xz', 'yn', 'zj']
コード例 #16
0
ファイル: pod.py プロジェクト: kcaylor/old_api
 def generate_fake(count=100):
     from random import choice, randint
     from faker import Faker
     from .user import User
     import phonenumbers
     nusers = User.objects().count()
     fake = Faker()
     # fake.seed(3123)
     fake_pods = []
     for i in range(count):
         if nusers > 0:
             user = User.objects()[randint(0, nusers - 1)]
         else:
             user = User.generate_fake(1)[0]
         pod = Pod(
             name=fake.first_name() + '-' + fake.last_name() + '-' +
             str(fake.random_int(min=1000)),
             owner=user,
             pod_id=fake.random_int(min=20),
             qr='https://s3.amazonaws.com/pulsepodqrsvgs/default.svg',
             imei=str(randint(100000000000000, 999999999999999)),
             radio='gsm',
             mode=choice(['normal', 'teenager', 'asleep', 'inactive']),
             number=phonenumbers.format_number(
                 phonenumbers.parse(
                     '1' + ''.join([str(randint(0, 9)) for x in range(7)]),
                     'US'),
                 phonenumbers.PhoneNumberFormat.E164),
         )
         try:
             pod.save()
             fake_pods.append(pod)
         except:
             "Pod save failed"
     return fake_pods
コード例 #17
0
ファイル: createmetafile.py プロジェクト: Nicolas570/chris_db
    def handle(self, *args, **options):

        fake = Faker()

        d_meta = {}
        l_history = []

        for i in range(0, 5):

            now = str(fake.date_time())

            d_meta[now] = {}

            d_meta[now]['username']     = fake.name()
            d_meta[now]['realname']     = fake.name()
            d_meta[now]['uid']          = fake.random_int(min=0, max=9999)
            d_meta[now]['email']        = fake.email()
            d_meta[now]['groupname']    = fake.name()
            d_meta[now]['gid']          = fake.random_int(min=0, max=9999)
            d_meta[now]['groupproject']      = fake.name()
            d_meta[now]['review']       = {}
            d_meta[now]['review']['comment'] = fake.text()
            d_meta[now]['review']['rating'] = fake.random_int(min=0, max=10)

            l_history.append(d_meta[now])

        with open('meta.json', 'w') as f:
            json.dump(d_meta, f)
コード例 #18
0
def main(dataFile):
	faker = Faker()

	with open(dataFile, 'r') as fileHandle:
		for entry in csv.reader(fileHandle):
			# Skip header row
			if entry[0] == "pregnant":
				continue

			# Create a patient entry
			patient = patientService.create(Patient(faker.name()))

			# Create a session entry
			session = sessionService.create(Session(patient.id))

			# Load the questions
			questions = questionService.getAll()

			# Create the answers
			answers = []
			for i, rawAnswer in enumerate(entry):
				answer = Answer(questions[i].id, session.id, rawAnswer)
				answerService.create(answer)
				answers.append(answer)

			# Save the eligibility
			sessionService.updateEligibility(session, isEligible(answers))
コード例 #19
0
ファイル: __main__.py プロジェクト: PeteRichardson/faker
def main(provider_or_field=None, *args):
    from faker import Faker, documentor
    fake = Faker()

    doc = documentor.Documentor(fake)

    if provider_or_field:
        try:

            print fake.format(provider_or_field, *args)
            return
        except AttributeError:
            providers = [p for p in fake.providers if documentor.Documentor.getProviderName(p) == provider_or_field]
            if not providers:
                return 'No faker found for "%s"' % provider_or_field
            from faker.providers import BaseProvider
            doc.already_generated = [fake for fake in dir(BaseProvider)]
            formatters = [(providers[0],doc.getProviderFormatters(providers[0]))]
    else:
        formatters = doc.getFormatters(with_args='first', with_defaults=True)


    for provider, fakers in formatters:

        print
        print "### %s" % documentor.Documentor.getProviderName(provider)
        print

        for signature, example in fakers.items():

            print u"{fake:<{margin}}# {example}".format(fake=signature, example=example, margin=max(30,doc.max_name_len+1))
コード例 #20
0
ファイル: utils.py プロジェクト: bfirsh/Website
    def run(self):
        faker = Faker()
        for i in range(1500):
            user = User('*****@*****.**' % i, faker.name())
            db.session.add(user)
            db.session.commit()

        for user in User.query.all():
            try:
                # Choose a random number and type of tickets for this user
                full_count = random.choice([1] * 3 + [2, 3])
                full_type = TicketType.query.filter_by(fixed_id=random.choice([0, 1, 2, 3] * 30 + [9, 10] * 3 + [4])).one()
                full_tickets = [Ticket(user.id, type=full_type) for _ in range(full_count)]

                kids_count = random.choice([0] * 10 + [1, 2])
                kids_type = TicketType.query.filter_by(fixed_id=random.choice([5, 11, 6])).one()
                kids_tickets = [Ticket(user.id, type=kids_type) for _ in range(kids_count)]

                vehicle_count = random.choice([0] * 2 + [1])
                vehicle_type = TicketType.query.filter_by(fixed_id=random.choice([7] * 5 + [8])).one()
                vehicle_tickets = [Ticket(user.id, type=vehicle_type) for _ in range(vehicle_count)]

                for t in full_tickets + kids_tickets + vehicle_tickets:
                    t.paid = random.choice([True] * 4 + [False])
                    t.refunded = random.choice([False] * 20 + [True])

                db.session.commit()

            except TicketLimitException:
                db.session.rollback()
コード例 #21
0
ファイル: test_address.py プロジェクト: joke2k/faker
class TestEnAU(unittest.TestCase):
    """ Tests addresses in the en_AU locale """

    def setUp(self):
        self.factory = Faker('en_AU')

    def test_postcode(self):
        for _ in range(100):
            postcode = self.factory.postcode()
            assert re.match(r"\d{4}", postcode)

    def test_state(self):
        state = self.factory.state()
        assert isinstance(state, string_types)
        assert state in EnAuProvider.states

    def test_city_prefix(self):
        city_prefix = self.factory.city_prefix()
        assert isinstance(city_prefix, string_types)
        assert city_prefix in EnAuProvider.city_prefixes

    def test_state_abbr(self):
        state_abbr = self.factory.state_abbr()
        assert isinstance(state_abbr, string_types)
        assert state_abbr in EnAuProvider.states_abbr
        assert state_abbr.isupper()
コード例 #22
0
ファイル: test_factory.py プロジェクト: joke2k/faker
    def test_words_ext_word_list_unique(self):
        fake = Faker()

        my_word_list = [
            'danish',
            'cheesecake',
            'sugar',
            'Lollipop',
            'wafer',
            'Gummies',
            'Jelly',
            'pie',
        ]

        num_words = 5
        words = fake.words(5, ext_word_list=my_word_list, unique=True)
        assert isinstance(words, list)
        assert len(words) == num_words

        checked_words = []
        for word in words:
            assert isinstance(word, six.string_types)
            assert word in my_word_list
            # Check that word is unique
            assert word not in checked_words
            checked_words.append(word)
コード例 #23
0
def load_raters():
    from faker import Faker
    import random

    fake = Faker()
    raters = []
    with open('ratingsdb/data/users.dat') as f:
        reader = csv.DictReader([line.replace('::', '\t') for line in f],
                                fieldnames=['UserID', 'Gender', 'Age',
                                            'Occupation', 'Zip-code'],
                                delimiter='\t')
        for line in reader:
            User.objects.create_user(username=fake.user_name() +
                                     str(random.randint(100, 999)),
                                     email=fake.email(),
                                     password='******',
                                     pk=int(line['UserID']))
            rater = {
                'fields': {
                    'gender': line['Gender'],
                    'age': line['Age'],
                    'occupation': line['Occupation'],
                    'zipcode': line['Zip-code']
                },
                'model': 'ratingsdb.Rater',
                'pk': int(line['UserID'])
            }
            raters.append(rater)

    with open('ratingsdb/fixtures/raters.json', 'w') as f:
        f.write(json.dumps(raters))
コード例 #24
0
def fake_broadcast():
    """
    Broadcast fake events (useful for testing).

    :return: None
    """
    fake = Faker()

    while True:
        random_types = ('tweet', 'retweet', 'favorite')
        random_tweet = fake.text(max_nb_chars=140)

        data = {
            'created_at': str(datetime.datetime.now(pytz.utc)),
            'type': random.choice(random_types),
            'tweet': random_tweet,
            'user': fake.user_name()
        }

        faye_protocol = {
            'channel': '/cats',
            'data': data,
            'ext': {
                'pushToken': BROADCAST_PUSH_TOKEN
            }
        }

        broadcast_message.delay(BROADCAST_INTERNAL_URL, faye_protocol)
        logging.info(data)
        sleep(1)

    return None
コード例 #25
0
    def handle(self, *args, **options):

        # make up a fake HUID
        fake_huid = 'fake{}'.format(random.randint(1000, 9999))
        enc_id = util.get_encrypted_huid(fake_huid)

        current_time = time.time()
        current_date = datetime.datetime.utcfromtimestamp(current_time).strftime('%Y-%m-%dT%H:%M:%S')
        # for this test token, make the expiration one day in the future
        expiration_date = datetime.datetime.utcfromtimestamp(current_time + 86400).strftime('%Y-%m-%dT%H:%M:%S')

        fake = Faker()
        first_name = fake.first_name()
        last_name = fake.last_name()
        email = '{}.{}@fake.harvard.edu'.format(first_name.lower(), last_name.lower())

        # UserType is either employee or student
        user_type = random.choice(['student', 'employee'])

        # Division
        div_name, div_id = random.choice(list(util.DIVISION_MAPPING.items()))

        key_value_pairs = u"id={}&timestamp={}&expiration={}&firstname={}&lastname={}&email={}&UserType={}&Division={}".format(
            enc_id, current_date, expiration_date, first_name, last_name, email, user_type, div_id
        )

        login_url = util.get_qualtrics_url(key_value_pairs)

        print('{}: {}\n{} {}, {}, {}, {}\n{}\n{}'.format(fake_huid, enc_id,
            first_name, last_name, email, user_type, div_name, key_value_pairs, login_url))
コード例 #26
0
ファイル: user.py プロジェクト: hack4impact/maps4all
    def generate_fake(count=100, **kwargs):
        """Generate a number of fake users for testing."""
        from sqlalchemy.exc import IntegrityError
        from random import seed, choice
        from faker import Faker

        fake = Faker()
        roles = Role.query.all()

        seed()
        for i in range(count):
            u = User(
                first_name=fake.first_name(),
                last_name=fake.last_name(),
                email=fake.email(),
                password=fake.password(),
                confirmed=True,
                role=choice(roles),
                **kwargs
            )
            db.session.add(u)
            try:
                db.session.commit()
            except IntegrityError:
                db.session.rollback()
コード例 #27
0
ファイル: test_mgnt_cmds.py プロジェクト: ruqaiya/shuup
def test_extract_products_shortdescription():
    activate("en")
    out = StringIO()

    html_description1 = "<b>a HTML description</b>"
    product1 = create_product("p1", description=html_description1)

    html_description2 = '<p class="what">another HTML description</p>'
    product2 = create_product("p2", description=html_description2)

    faker = Faker()
    long_description = faker.sentence(nb_words=150, variable_nb_words=True)
    product3 = create_product("p3", description=long_description)

    for lang, _ in settings.LANGUAGES:
        product2.set_current_language(lang)
        product2.description = html_description2
        product2.save()

    call_command("shuup_extract_products_shortdescription", stdout=out)

    product1 = Product.objects.get(pk=product1.pk)
    product2 = Product.objects.get(pk=product2.pk)
    product3 = Product.objects.get(pk=product3.pk)

    assert product1.short_description == do_striptags(html_description1)

    for lang, _ in settings.LANGUAGES:
        product2.set_current_language(lang)
        assert product2.short_description == do_striptags(html_description2)

    assert product3.short_description == long_description[:150]

    assert "Done." in out.getvalue()
コード例 #28
0
ファイル: views.py プロジェクト: TylerKotkin/urly-bird
def add_worm(request):
    if request.method == 'POST':
        form = WormForm(request.POST)
        if form.is_valid():
            worm = form.save(commit=False)
            if request.user.is_authenticated():
                worm.user = request.user
            fake = Faker()
            while True:
                slink = fake.password(length=7, special_chars=False)
                if len(Worm.objects.filter(slink=slink)) == 0:
                    worm.slink = slink
                    break
                continue
            worm.timestamp = make_aware(datetime.now())
            worm.save()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'You successfully got that worm!')
        else:
            messages.add_message(request,
                                 messages.ERROR,
                                 'Form data invalid, all fields required')
    else:
        messages.add_message(request,
                             messages.ERROR,
                             'Stop trying to hack this site!')
    return redirect(request.GET['next'])
コード例 #29
0
def collectionQuery1():
    fake = Faker()
    totalRuns = config.executions
    connection = pymysql.connect(**config.dbConfig)
    cursor = connection.cursor()
    timer = Timer()
    meanTime = 0
    limit = 20
    percentConfig = totalRuns / 100
    tags = []
    config.getTags(tags)
    print("=================================== Collection Query 1 ===================================")
    print("SELECT text_id AS id, p_text AS text FROM wp_tags AS t LEFT JOIN post2tag ON t.id = tag_id LEFT JOIN tag_query1 ON text_id = post_id LEFT JOIN text ON text_id = text.id WHERE t.name = 'tagName' AND p_site = 'site' AND p_country = 1 AND p_published < 'timestamp' ORDER BY p_published DESC LIMIT 20")
    for run in range(totalRuns):
        tagName = tags[randint(0, config.totalTags - 1)]
        published = fake.date_time_between(start_date = "-6y", end_date = "now")
        country = config.countries[randint(0, 3)]
        site = config.siteConfig[randint(0, 19)]
        query = "SELECT text_id AS id, p_text AS text FROM wp_tags AS t LEFT JOIN post2tag ON t.id = tag_id LEFT JOIN tag_query1 ON text_id = post_id LEFT JOIN text ON text_id = text.id WHERE t.name = '{}' AND p_site = '{}' AND p_{} = 1 AND p_published < '{}' ORDER BY p_published DESC LIMIT {}".format(tagName, site, country, published, limit)
        timer.restart()
        cursor.execute(query)
        meanTime += timer.get_seconds()
        percent = (run / totalRuns) * 100
        if (run % percentConfig) == 0:
            print("Completed: {:.0f} %                ".format(percent), end = '\r')
    print("Completed 100 %")
    print("Mean query execution time : {:.10f} seconds".format(meanTime / totalRuns))
    connection.close()
    print("")
    print("Example Query")
    print(query)
    print("")
    return meanTime / totalRuns
コード例 #30
0
def load_ratings():
    fake = Faker()
    ratings = []

    with open('data/ratings.dat') as f:
        reader = csv.DictReader([line.replace('::', '\t') for line in f],
                                fieldnames='UserID::MovieID::Rating::Timestamp'.split('::'),
                                delimiter='\t')
        count = 1
        for row in reader:
            print(count)
            rating = {
            'fields':{
                'rater':int(row['UserID']),
                'movie':row['MovieID'],
                'stars': row['Rating'],
                'text' : fake.text(max_nb_chars=100)
                },

            'model':'database.Rating',
            'pk': count }
            ratings.append(rating)
            count += 1

    with open('ratings.json', 'w') as f:
        f.write(json.dumps(ratings))
コード例 #31
0
 def test_weighting_disabled_single_choice(self, mock_choices_fn,
                                           mock_choice_fn):
     fake = Faker(use_weighting=False)
     fake.first_name()
     mock_choice_fn.assert_called()
     mock_choices_fn.assert_not_called()
コード例 #32
0
ファイル: test_validators.py プロジェクト: akyogi/commcare-hq
from corehq.apps.user_importer.exceptions import UserUploadError
from corehq.apps.user_importer.validation import (
    DuplicateValidator,
    EmailValidator,
    ExistingUserValidator,
    GroupValidator,
    UsernameLengthValidator,
    NewUserPasswordValidator,
    RoleValidator,
    UsernameTypeValidator,
    RequiredFieldsValidator,
    UsernameValidator,
    BooleanColumnValidator)

factory = Faker()
factory.seed(1571040848)

IsActiveValidator = BooleanColumnValidator('domain', 'is_active')
IsAccountConfirmedValidator = BooleanColumnValidator('domain', 'is_account_confirmed')

# tuple(specs, validator class, errors dict(row_index: message)
TEST_CASES = [
    (
        [
            {'username': '******'},
            {'username': factory.user_name()},
            {'username': ''},
            {},
        ],
        UsernameValidator('domain'),
コード例 #33
0
ファイル: models.py プロジェクト: wkddnjset/BlockChain_Django
    sender = models.CharField(max_length=200)
    receiver = models.CharField(max_length=200)
    amount = models.IntegerField(default=0)
    time_stamp = models.DateTimeField(auto_now_add=True)
    added_to_block = models.BooleanField(default=False)

    def __str__(self):
        return "'%s' transfered '%d' coins to '%s'" % (
            self.sender,
            self.amount,
            self.receiver,
        )


from faker import Faker
rand = Faker()


class Block(models.Model):
    time_stamp = models.DateTimeField(auto_now_add=False)
    index = models.IntegerField(auto_created=True, blank=True)
    data = models.TextField(blank=True, max_length=255)
    hash = models.CharField(max_length=255, blank=True)
    previous_hash = models.CharField(max_length=255)
    chain = models.ForeignKey(to='Chain', on_delete=models.CASCADE)
    nonce = models.CharField(max_length=255, default=0, blank=True)

    def __str__(self):
        return "Block " + str(self.index) + " on " + self.chain.name

    def __repr__(self):
コード例 #34
0
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings')

import django
django.setup()

import random
from first_app.models import AccessRecord,Webpage,Topic,User
from faker import Faker

fakegen = Faker()
topics = ['Search','Social','News','Games']

def add_topic():
    t = Topic.objects.get_or_create(top_name=random.choice(topics))[0]
    t.save()
    return t

def populate(N=5):

    for entry in range(N):

        top = add_topic()

        fake_url = fakegen.url()
        fake_date = fakegen.date()
        #fake_name = fakegen.company()
        fake_name = fakegen.name().split()
        fake_first_name = fake_name[0]
        fake_last_name = fake_name[1]
        fake_email = fakegen.email()
コード例 #35
0
import json
import asyncio
import websockets
import random
import time
import socket
from random import randrange

from faker import Faker

faker = Faker()

CATTLE_IO_SERVER_HOST = '192.168.1.245'
CATTLE_IO_SERVER_PORT = 9003


class Device:
    def __init__(self, uid):

        self.uid = uid
        self.ip = faker.ipv4()
        self.battery = 100.00
        self.signal = 100.00
        self.temperature = 34.00 - 0.025 * random.randrange(
            50, 100) + 0.025 * random.randrange(50, 100)
        self.humidity = 70.00 - 0.005 * random.randrange(
            1000, 2000) + 0.005 * random.randrange(1000, 2000)
        self.ax = 7.16000 + 0.005 * random.randrange(
            1000, 2000) - 0.005 * random.randrange(1000, 2000)
        self.ay = 0.16000 + 0.005 * random.randrange(
            1000, 2000) - 0.005 * random.randrange(1000, 2000)
コード例 #36
0
 def test_locale_as_list_invalid_value_type(self):
     locale = [1, 2]
     with pytest.raises(TypeError) as exc:
         Faker(locale)
     assert str(exc.value) == 'The locale "1" must be a string.'
コード例 #37
0
 def test_copy(self):
     fake = Faker("it_IT")
     fake2 = copy.deepcopy(fake)
     assert fake.locales == fake2.locales
     assert fake.locales is not fake2.locales
コード例 #38
0
 def test_locale_as_string(self):
     locale = 'en_US'
     fake = Faker(locale)
     assert len(fake.locales) == 1
     assert len(fake.factories) == 1
     assert fake.locales[0] == locale
コード例 #39
0
import django
import os
from faker import Faker
import random 

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bike_store.settings')
django.setup()
from rent.models import Rental, Customer, VehicleType



fakerental = Faker()


def pop_rental(n):
    for i in range(n):
        f_start_date = fakerental.date_between(start_date ='-100d', end_date ='-20d') 
        f_end_date = fakerental.date_between(start_date='-20d', end_date='now')
        customer = Customer.random.all()[0]
        vehicle = VehicleType.random.all()[0]

        print(f"{f_start_date}, {f_end_date}{customer}{vahicle}")



pop_rental(1)    
コード例 #40
0
 def test_multiple_locale_factory_selection_unsupported_method(self):
     fake = Faker(['en_US', 'en_PH'])
     with pytest.raises(AttributeError):
         fake.obviously_invalid_provider_method_a23f()
コード例 #41
0
 def setup_faker(self):
     self.fake = Faker('en_PH')
     Faker.seed(0)
コード例 #42
0
 def test_unspecified_locale(self):
     fake = Faker()
     assert len(fake.locales) == 1
     assert len(fake.factories) == 1
     assert fake.locales[0] == DEFAULT_LOCALE
コード例 #43
0
 def setUp(self):
     self.fake = Faker('pl_PL')
     Faker.seed(0)
コード例 #44
0
# **************** "iNNovationMerge DailyCodeHub" ****************
# Visit https://www.innovationmerge.com/
# Theme : Dummy Data Generation in Python

# Python program generate dummy address

from faker import Faker

fake = Faker("en_US")
for _ in range(10):
    print(fake.address())
""" 
# Output : 
    189 Carney Circles
    Frankfurt, CA 99389
    156 Kelli Fall
    East Jenniferport, CO 17673       
    897 Kennedy Lights Apt. 850       
    Thomasmouth, SD 93337
    90473 Thomas Glens
    Hollyfort, OK 80761
    745 Brady Prairie
    North Dominique, IL 42118
    USNV Fowler
    FPO AA 05390
    66782 Leslie Plains
    Banksville, WI 04771
    608 Kennedy Roads Apt. 597        
    Port Heather, OK 91578
    03193 Thompson Brook
    Carterbury, NV 95837
コード例 #45
0
 def setUp(self):
     self.fake = Faker('de_DE')
     Faker.seed(0)
コード例 #46
0
 def setUp(self):
     self.fake = Faker('pt_BR')
     Faker.seed(0)
     self.format = re.compile(r'[\w]{3}-[\d]{4}')
コード例 #47
0
 def setUp(self):
     self.fake = Faker('pt_PT')
     Faker.seed(0)
     self.pattern = re.compile(
         r'^\d{2}-\d{2}-[aA-zZ]{2}$|^\d{2}-[aA-zZ]{2}-\d{2}$|^[aA-zZ]{2}-\d{2}-\d{2}$'
     )
コード例 #48
0
 def setUp(self):
     self.fake = Faker('sv_SE')
     Faker.seed(0)
コード例 #49
0
 def setUp(self):
     self.fake = Faker('ru_RU')
     Faker.seed(0)
コード例 #50
0
 def setUp(self):
     self.fake = Faker('hu_HU')
     Faker.seed(0)
コード例 #51
0
 def setUp(self):
     self.factory = Faker('fi_FI')
コード例 #52
0
 def setUp(self):
     self.fake = Faker('fr_FR')
     Faker.seed(0)
     self.pattern = re.compile(
         r'^\d{3}-[A-Z]{3}-\d{2}$|^[A-Z]{2}-\d{3}-[A-Z]{2}')
コード例 #53
0
 def setUp(self):
     self.factory = Faker('pt_BR')
コード例 #54
0
 def setUp(self):
     self.factory = Faker('el_GR')
コード例 #55
0
 def setUp(self):
     self.factory = Faker('no_NO')
コード例 #56
0
 def setUp(self):
     self.factory = Faker('en_IE')
コード例 #57
0
 def setUp(self):
     self.factory = Faker('ja')
コード例 #58
0
 def setUp(self):
     self.factory = Faker('zh_CN')
コード例 #59
0
 def setUp(self):
     self.factory = Faker('de_DE')
コード例 #60
0
 def setUp(self):
     self.factory = Faker('ne_NP')