Ejemplo n.º 1
0
    def test_language_code(self):
        from faker.providers.misc import Provider

        for _ in range(99):
            language_code = Provider.language_code()
            self.assertTrue(isinstance(language_code, string_types))
            Factory.create(locale=language_code)
Ejemplo n.º 2
0
    def handle(self, *args, **options):
        fake = Factory.create()
        fakeru = Factory.create('ru_RU')

        number = int(options['number'])
        
        for i in range(0, number):
            profile = fake.simple_profile()

            u = User()
            u.username = profile['username']
            u.first_name = fakeru.first_name()
            u.last_name = fakeru.last_name()
            u.email = profile['mail']
            u.password = make_password('tp2015')
            u.is_active = True
            u.is_superuser = False
            u.save()

            up = Profile()
            up.user = u
            up.info = '%s [%s]' % (fakeru.company(), fakeru.catch_phrase())

            image_url = 'http://api.adorable.io/avatars/100/%s.png' % u.username
            content = urllib.urlretrieve(image_url)
            up.avatar.save('%s.png' % u.username, File(open(content[0])), save=True)
            up.save()

            self.stdout.write('[%d] added user %s' % (u.id, u.username))
Ejemplo n.º 3
0
    def generate_fake():
        from sqlalchemy.exc import IntegrityError
        from random import seed, randint
        from faker import Factory
        fake = Factory.create()
        inside_fake = Factory.create('zh_CN')

        start = datetime.now() - timedelta(days=1)
        seed()
        for i in range(50):
            name = fake.user_name()[:8]
            u = User(id=10 + i,
                     username=name,
                     role_id=3,
                     password=name,
                     email='{0}@gmail.com'.format(name),
                     sign_up_time=start + timedelta(minutes=randint(1, 10)),
                     city=inside_fake.city_name(),
                     email_confirmed=1,
                     avatar_extension='png',
                     github=name,
                     website='https://{0}.com'.format(name),
                     email_private=0)
            db.session.add(u)
            try:
                db.session.commit()
            except:
                db.session.rollback()
Ejemplo n.º 4
0
 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 = Factory.create(locale=locale)
         for x in range(20):  # Probabilistic testing.
             assert isinstance(f.prefix(), string_types)
             assert isinstance(f.suffix(), string_types)
Ejemplo n.º 5
0
def init(is_reset=True, is_dir_clean=True):
    if is_reset:
        call_command('reset_db', interactive=0)

    if is_dir_clean:
        for dir2clean in ['cache', 'infoimage', 'fact', 'news']:
            dir2clean = os.path.join(settings.BASE_DIR, 'media', dir2clean)
            if os.path.exists(dir2clean):
                shutil.rmtree(dir2clean)

    call_command('makemigrations')
    call_command('migrate')

    admin = G(User, username='******', is_active=True, is_staff=True,
              is_superuser=True)
    admin.set_password('hello')
    admin.save()

    fake = Factory.create()
    for i in xrange(20):
        G(fbask_models.Author,
          first_name=fake.first_name(),
          last_name=fake.last_name())
        G(fbask_models.Article,
          title=fake.company(),
          content=fake.address())
Ejemplo n.º 6
0
    def create_random_student(cls):
        """Fill database with random student"""

        fake = Factory.create('uk_UA')

        groups = ["ІН", "ПМ", "КІ", "КН", "АУТП"]

        random_grade = random.randint(1, 5)

        if random.choice([True, False]):
            Student.create(
                last_name=fake.last_name(),
                first_name=fake.first_name_male(),
                patronymic=fake.first_name_male() + "ович",
                group="{}-{}{}".format(
                    random.choice(groups),
                    random_grade,
                    random.randint(1, 3)
                ),
                grade=random_grade
            )

        else:
            Student.create(
                last_name=fake.last_name(),
                first_name=fake.first_name_female(),
                patronymic=fake.first_name_male() + "івна",
                group="{}-{}{}".format(
                    random.choice(groups),
                    random_grade,
                    random.randint(1, 3)
                ),
                grade=random_grade
            )
Ejemplo n.º 7
0
 def generate_users(self,user_count):
     fake = Factory.create()
     users = []
     for i in range(1,user_count):
         user = User(fake.email(),fake.name(),'welcome',True)
         users.append(user])
     return users
 def set_zip(self):
     fake = Factory.create()
     # Create data for zip code in address
     for i in range( 1, len( self.f_name ) ):
         zip_temp = fake.zipcode()
          
         self.zip.append( zip_temp.encode( 'ascii' ) )
 def set_phone2(self):
     fake=Factory.create()
     # Create data for phone2
     for i in range( 1, len( self.f_name ) ):
         phone2_temp = fake.phone_number()
          
         self.phone2.append( phone2_temp.encode( 'ascii' ) )
Ejemplo n.º 10
0
def make_shell_context():
    from modularodm import Q
    from framework.auth import User, Auth
    from framework.mongo import database
    from website.app import init_app
    from website.project.model import Node
    from website import models  # all models
    from website import settings
    import requests
    app = init_app()
    context = {
        'app': app,
        'db': database,
        'User': User,
        'Auth': Auth,
        'Node': Node,
        'Q': Q,
        'models': models,
        'run_tests': test,
        'rget': requests.get,
        'rpost': requests.post,
        'rdelete': requests.delete,
        'rput': requests.put,
        'settings': settings,
    }
    try:  # Add a fake factory for generating fake names, emails, etc.
        from faker import Factory
        fake = Factory.create()
        context['fake'] = fake
    except ImportError:
        pass
    return context
 def set_street(self):
     fake = Factory.create()
     # Create data for street name in address
     for i in range( 1, len( self.f_name ) ):
         street_temp = fake.street_address()
          
         self.street.append( street_temp.encode( 'ascii' ) )
Ejemplo n.º 12
0
def fake_xmi():
    faker = FFactory.create()
    for i in range(NUM_SAMPLES):
        PERSONS.append(
            TEMPLATE_PERSON.format(
                faker.first_name(),
                faker.last_name(),
                "MALE" if faker.boolean() is True else "FEMALE",
                faker.boolean(),
                faker.iso8601(),
                faker.street_name(),
                faker.building_number(),
                faker.postcode(),
                faker.city(),
                random.randint(0, NUM_COUNTRIES - 1)
            )
        )

    for i in range(NUM_COUNTRIES):
        COUNTRIES.append(
            TEMPLATE_COUNTRY.format(faker.country())
        )

    with open(OUTFILE, "w") as text_file:
        text_file.write(
            TEMPLATE.format(
                os.linesep.join(
                    [os.linesep.join(PERSONS), os.linesep.join(COUNTRIES)]
                )
            )
        )
Ejemplo n.º 13
0
 def generate_fake(count=50):
     from sqlalchemy.exc import IntegrityError
     from random import seed, randint
     from faker import Factory
     fake = Factory.create()
     seed()
     user_count = User.query.count()
     tag_count = Tag.query.count()
     category_count = Category.query.count()
     for i in range(count):
         u = User.query.offset(randint(0, user_count-1)).first()
         t = Tag.query.offset(randint(0, tag_count-1)).first()
         c = Category.query.offset(randint(0, category_count-1)).first()
         post = Post(title=fake.word(),
                     slug=fake.word(),
                     md_text=fake.paragraph(),
                     content=fake.paragraph(),
                     pub_date=fake.date_time(),
                     modify_date=fake.date_time(),
                     category_id=c.id,
                     author_id=u.id,
                     tags_name="python"
                     )
         db.session.add(post)
         try:
             db.session.commit()
         except IntegrityError:
             db.session.rollback()
Ejemplo n.º 14
0
def seed_from_fake():
    "This seeds a DB with fake text, using the faker"
    # create a fake factory
    fake = Factory.create()

    # print is as sanity check
    print(fake.text())

    # open or make text file
    text_file = open("Output.txt", "w")

    # 50 times
    for i in range(50):
        # make some fake text
        fake_text = fake.text() # this just gives stupid text 
        # # print fake text
        # print(fake_text[:49])
        # # print seperator
        # print("_____________")
        # make new post

        # split the text up to make a title and post 
        title = fake_text[:49]
        text = fake_text

        post = Post(title=fake_text, text=text)
        post.save()
Ejemplo n.º 15
0
def write_text_seed_file():
    "this creates a file with random fake text"
    fake = Factory.create()

    # print is as sanity check
    print(fake.text())

    # open or make text file
    text_file = open("Output.txt", "w")

    # 50 times
    for i in range(50):
        # make some fake text
        fake_text = fake.text()
        # # print fake text
        # print(fake_text[:49])
        # # print seperator
        # print("_____________")
        # make new post
        title = fake_text[:49]
        text = fake_text
        line = title + "\t" + text + "\n"
        text_file.write(line)

    text_file.close()
Ejemplo n.º 16
0
def make():
    fake = Factory.create()
    years = range(1970, 2015)
    first = fake.first_name()
    last = fake.last_name()
    email = '{0}{1}{2}@{3}'.format(first, last, random.choice(years), fake.domain_name())
    return email, first, last
Ejemplo n.º 17
0
    def test_crear_una_nueva_pizarra_y_guardarla_en_la_bd(self): 

        faker = Factory.create()

        nombrepiz      = faker.word()
        descripcionpiz = faker.sentence()
        now            = date.today()
        fechacreacion  = now
        fechafinal     = now.replace(day = now.day+1)
        logindueno     = User.objects.get(username = '******')
        avancepiz      = faker.randomInt(0,99)

        num_pizarras_old = len(Pizarra.objects.all())

        CreadorPizarra(
                nombrepiz      = nombrepiz,
                descripcionpiz = descripcionpiz,
                fechacreacion  = fechacreacion,
                fechafinal     = fechafinal,
                usuario        = logindueno
        )

        pizarras_new = Pizarra.objects.all()

        self.assertEquals(len(pizarras_new), num_pizarras_old + 1)
Ejemplo n.º 18
0
def make_shell_context():
    from modularodm import Q
    from framework.auth import User, Auth
    from framework.mongo import database
    from website.app import init_app
    from website.project.model import Node
    from website import models  # all models
    from website import settings
    import requests

    app = init_app()
    context = {
        "app": app,
        "db": database,
        "User": User,
        "Auth": Auth,
        "Node": Node,
        "Q": Q,
        "models": models,
        "run_tests": test,
        "rget": requests.get,
        "rpost": requests.post,
        "rdelete": requests.delete,
        "rput": requests.put,
        "settings": settings,
    }
    try:  # Add a fake factory for generating fake names, emails, etc.
        from faker import Factory

        fake = Factory.create()
        context["fake"] = fake
    except ImportError:
        pass
    return context
Ejemplo n.º 19
0
    def handle(self, *args, **options):
        fake = Factory.create()

        number = int(options['number'])

        users = User.objects.all()[1:]

        starts = (
                u'Help! Nothing happens!',
                u'I tried all, help',
                u'I do not find any solutions on the Internet, save',
                u'Following problem:',
                u'I think that someone of you faced with the question',
                u'Sorry, but I am a novice in this matters',
                u'Hi! Dates burn, need advice',
                )

        for i in range(0, number):
            q = Question()

            q.title = fake.sentence(nb_words=randint(4, 6), variable_nb_words=True)
            q.text = u"%s %s %s" % (
                    choice(starts),
                    os.linesep,
                    fake.paragraph(nb_sentences=randint(4, 17), variable_nb_sentences=True),
                    )
            q.author = choice(users)
            q.save()
            self.stdout.write('added question [%d]' % (q.id))
Ejemplo n.º 20
0
    def __init__(self, county = 'zh_CN'):

        self.fake = Factory.create(county)
        self.img = DBHelperUtils().get_imgs()
        self.img_size = len(self.img)

        self.data_format = {
            "用户名":"USER_NAME",
            "照片":"IMAGE",
            "邮箱":"EMAIL",
            "城市":"CITY",
            "字符串":"TEXT",
            "时间戳":"TIME",
            "错误代码":"ERR_CODE",
            "单词":"WORD",
            "ID":"ID",
            "对象":"OBJ"

        }

        self.erro_code_list = [
            0,
            60501,
            605002,
            605003,
            401003,
        ]
Ejemplo n.º 21
0
def main():

    # Set locale to the United States for US-formatted Social Security Numbers
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

    # Create faker factory instance
    faker = Factory.create()

    # The number of rows in the resulting CSV
    num_fake_records = 1000

    # Download the field names from Google Sheets in XLSX format
    google_sheet = pd.read_excel('https://docs.google.com/spreadsheets/d/' + 
                   '1bloqWcGFOmFLJ98iYFAEX5PDZWpqBI722-qZVyekZuU' +
                   '/export?format=xlsx',
                   sheetname=None)
    
    # If a field doesn't have weights, add 1s as weights
    # functionally, this will give each class equal weight
    for field, df in google_sheet.iteritems():
        google_sheet[field] = google_sheet[field].fillna(1)

    # Create the dataframe with dummy data
    dummy_data = pd.DataFrame([fake_record(google_sheet, faker) for _ in range(num_fake_records)])

    # Output and save data
    print dummy_data.head()

    output_file = 'dummy_data.csv'
    dummy_data.to_csv(output_file, index=False)
    print '\nDummy data saved to: ' + output_file
Ejemplo n.º 22
0
    def setUp(self):
        self._client = BaoquanClient()
        self._client.host = 'http://localhost:8080'
        self._client.access_key = 'fsBswNzfECKZH9aWyh47fc'
        self._client.pem_path = os.path.dirname(__file__) + '/resources/private_key.pem'

        self._faker = Factory.create('zh_CN')
Ejemplo n.º 23
0
def admin_populate_user():
  # Create a fake instance
  fake = Factory.create()
  form_user = PopulateUserForm()
  if form_user.validate_on_submit():
    user_dbs = []
    nr = form_user.number_of_users.data
    if nr > 1000:
      flask.flash('You cannot create more than 1000 new users at once. Try again!',\
          category='danger')
      return flask.redirect(flask.url_for('admin_populate'))
    for i in range(nr):
      user = fake.profile(fields=['name','username','mail'])
      user_dbs.append(model.User(name=user['name'],\
          username=user['username'],
          email=user['mail'],
          active=_return_state(form_user.active.data),
          admin=_return_state(form_user.admin.data),
          verified=_return_state(form_user.verified.data)))
    keys = ndb.put_multi(user_dbs)
    for key in keys:
      # run the new user function
      auth.new_user(key)
    flask.flash('Created {nr} new users'.\
          format(nr=len(user_dbs)), category='success')
  return flask.redirect(flask.url_for('admin_populate'))
    def test_mount_the_caching_adapters_on_https(case):
        faker = Factory.create()
        url = faker.uri()
        sut = JoolaBaseClient(url)

        case.assertIn("https://", sut.session.adapters)
        case.assertIsInstance(sut.session.adapters["https://"], CachingHTTPAdapter)
Ejemplo n.º 25
0
def admin_populate_tag():
  form_tag = PopulateTagForm()
  if form_tag.validate_on_submit() or True:
    if form_tag.random_tags.data:
      if form_tag.max_tags.data > 500:
        flask.flash('Not more than 500 random tags can be created at once. Try again!',\
            category='danger')
        return flask.redirect(flask.url_for('admin_populate'))

      fake = Factory.create()
      tags = fake.words(nb=form_tag.max_tags.data)
    else:
      tags = form_tag.tags.data.split(', ')
    # Are icon needed as well?
    if form_tag.icon.data:
      icon_keys, _ = model.Icon.get_dbs(keys_only=True,limit=2000, collection=model.Collection.top_key())
    else:
      icon_keys = None
    cnt = 0
    incr = True if form_tag.incr.data=='true' else False
    for tag in tags:
      icon_key = random.choice(icon_keys) if icon_keys else None
      model.Tag.add(tag,auto_incr=incr,icon_key=icon_key)
      cnt += 1
    flask.flash('Added {nr} tags'.\
          format(nr=cnt), category='success')

  return flask.redirect(flask.url_for('admin_populate'))
 def setUp(self):
     self.faker = Factory.create()
     self.portal = self.layer['portal']
     self.util = getUtility(ITodoUtility)
     self.user1 = api.user.create(
         email=self.faker.company_email(),
         username='******'
     )
     self.user2 = api.user.create(
         email=self.faker.company_email(),
         username='******'
     )
     self.all_userids = {
         self.user1.getId(),
         self.user2.getId(),
         'admin',
         'test_user_1_',
     }
     self.doc1 = api.content.create(
         container=self.portal,
         type='Document',
         id='doc1',
         title='Doc 1'
     )
     self.doc2 = api.content.create(
         container=self.portal,
         type='Document',
         id='doc2',
         title='Doc 2'
     )
    def test_select_the_api_token_authentication_mechanism_if_an_api_token_was_provided(case):
        faker = Factory.create()
        url = faker.uri()
        api_token = faker.sha256()
        sut = JoolaBaseClient(url, api_token=api_token)

        case.assertIsInstance(sut.session.auth, APITokenAuth)
Ejemplo n.º 28
0
    def handle(self, *args, **options):
        try:
            fake_bans_to_create = int(args[0])
        except IndexError:
            fake_bans_to_create = 5
        except ValueError:
            self.stderr.write("\nOptional argument should be integer.")
            sys.exit(1)

        fake = Factory.create()
        ban_fakers = (get_fake_username_ban, get_fake_email_ban, get_fake_ip_ban)

        message = "Creating %s fake bans...\n"
        self.stdout.write(message % fake_bans_to_create)

        created_count = 0
        show_progress(self, created_count, fake_bans_to_create)
        for _ in range(fake_bans_to_create):
            ban_faker = random.choice(ban_fakers)
            ban_faker(fake)

            created_count += 1
            show_progress(self, created_count, fake_bans_to_create)

        Ban.objects.invalidate_cache()

        message = "\n\nSuccessfully created %s fake bans"
        self.stdout.write(message % created_count)
Ejemplo n.º 29
0
    def handle(self, *args, **options):
        fake = Factory.create()

        number = int(options['number'])

        users = User.objects.all()[1:]

        starts = (
                u'Помогите! Ничего не получается!!!!',
                u'Я перепробовал всё, помогите.',
                u'Не нашел ни одного решения в интернете, спасите!!',
                u'Проблема следующая:',
                u'Уже третий день не сплю из-за возникшей проблемы',
                u'Я думаю, что кто-то из вас сталкивался с таким вопросом',
                u'Извините, я новичок в вопросах веба.',
                u'Привет всем! Сроки горят, нужна консультация.',
                u'Ненавижу Винду',
                u'Нашел косяк в исходниках MySQL 5.6'
                )

        for i in range(0, number):
            q = Question()

            q.title = fake.sentence(nb_words=randint(4, 6), variable_nb_words=True)
            q.text = u"%s %s %s" % (
                    choice(starts),
                    os.linesep,
                    fake.paragraph(nb_sentences=randint(4, 17), variable_nb_sentences=True),
                    )
            q.author = choice(users)
            q.save()
            self.stdout.write('added question [%d]' % (q.id))
Ejemplo n.º 30
0
def read_users(zfp):
    fp = zfp.open("ml-100k/u.user")
    users = read_csv(fp, sep="|", header=None,
             names=["id", "age", "gender", "occupation", "zip"], index_col=0)
    f = Factory.create()

    names = ["Jon Haddad",
             "Dani Traphagen",
             "Patrick McFadin",
             "Mark Quinsland",
             "Brian Hess",
             "Russell Spitzer",
             "Lorina Poland",
             "Tim Berglund",
             "Tupshin Harper",
             "Al Tobey"]

    names.reverse()

    def get_name(row):
        if names:
            return names.pop()
        return f.name()

    users['name'] = users.apply(get_name, axis=1)
    users['city'] = users.apply(lambda row: f.city(), axis=1)
    users['address'] = users.apply(lambda row: f.street_address(), axis=1)
    users['uuid'] = users.apply(lambda _: uuid.uuid4(), axis=1)

    return users
Ejemplo n.º 31
0
 def setUp(self):
     self.factory = Factory.create('ne_NP')
Ejemplo n.º 32
0
from django.core.management.base import BaseCommand, CommandError
from BOLT.models import News
from faker import Factory

fake = Factory.create('en_US')
news = [
    ('Добавлены новые задания',
     'На нашем сайте появились новые задания в категории "Теория вероятностей". Это номера из наших студенческих домашних заданий, спешим поделиться ими с вами. Напоминаем, что все возникшие вопросы можете задавать в комментариях, или можно связаться с нами напрямую, все контакты размещены в разделе "О нас". Успехов!'
     ),
    ('Обратная связь',
     'Для того, чтобы связаться с нами по какому-либо вопросу, перейдите в раздел "О нас", в нем указаны все доступные способы. Так же, зарегистрированные на нашем сайте пользователи могут оставлять комментарии под каждой задачей. В них вы можете задавать свои вопросы по ходу решения и указывать, с чем вы не согласны. Нашли ошибку? Считаете предложенное решение неверным? Пишите об этом в комментариях!'
     ),
    ('Наш сайт начал свою работу',
     'Всем доброго времени суток! Сегодня наш сайт начал свою работу. Здесь будут выкладываться подробные решения задач по основным студенческим дисциплинам. Слева представлен список разделов, выберите нужный предмет, и вы сразу попадете в архив имеющихся на данный момент задач. Кроме того, вы можете вбить в поисковую строку условие задания, а затем просто выбрать из списка предложенных. После этого вставьте свои исходные данные, и вы получите подробно расписанное решение именно вашей задачи. Успехов!'
     )
]


def create_news():
    for title, text in news:
        News.objects.create(
            title=title,
            text=text,
        )


class Command(BaseCommand):
    #     def add_arguments(self, parser):
    #         parser.add_argument('count')

    def handle(self, *args, **options):
Ejemplo n.º 33
0
from django.core.urlresolvers import reverse
from rest_framework import status
from faker import Factory
from v1.models import User
from v1.tests.base import BaseTest

fake = Factory.create()


class TestUsersView(BaseTest):
    def test_should_successfully_create_a_user(self):
        """
        Ensure we can create a new user object.
        """
        url = '/api/v1/users/'
        data = {
            'username': fake.first_name(),
            'first_name': fake.first_name(),
            'last_name': fake.last_name(),
            'email': fake.email(),
            'password': fake.password()
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response.data['email'], data['email'])
        self.assertEqual(response.data['first_name'], data['first_name'])
        self.assertTrue(response.data['id'] is not None)
        self.assertEqual(response.data['last_name'], data['last_name'])
        self.assertEqual(response.data['username'], data['username'])
        with self.assertRaises(KeyError):
            response.data['results']['password']
Ejemplo n.º 34
0
import random
import string

from factory import DjangoModelFactory, fuzzy
from factory.declarations import SubFactory, LazyAttribute
from faker import Factory
from django.contrib.gis.geos import Point

from datasets.bag import models

faker_instance = Factory.create(locale='nl_NL')


# Creating a Point
class FuzzyPoint(fuzzy.BaseFuzzyAttribute):
    def fuzz(self):
        return Point(random.uniform(-180.0, 180.0),
                     random.uniform(-90.0, 90.0))


class GemeenteFactory(DjangoModelFactory):
    class Meta:
        model = models.Gemeente
        django_get_or_create = ('code', )

    id = fuzzy.FuzzyInteger(low=1, high=994444)
    code = fuzzy.FuzzyText(length=4)
    naam = 'Amsterdam'


class BuurtcombinatieFactory(DjangoModelFactory):
Ejemplo n.º 35
0
"""

import json
import os
import unittest

from faker import Factory

from common.myCommon import Assertion
from common.myCommon.TestBaseCase import TestBaseCase
from hmpt.testAction import WebAction
from hmpt.testAction import loginAction
from hmpt.query import xqkj_query

global_dict = loginAction.global_dict
fake = Factory().create('zh_CN')


class test_025_web_urge(TestBaseCase):
    def test_001_api_78dk_platform_urge_addMessage(self):
        """
        Time       :2019-09-29
        author     : 闫红
        desc       :电话催收信息提交-v1.5.2,忘记还款
        """
        global app_user_uuid, contract_uuid
        contract_uuid = loginAction.global_dict.get('contract_uuid')
        app_user_uuid = loginAction.get_user_uuid()
        xqkj_query.get_bill_overdue(contract_uuid=contract_uuid,
                                    user_uuid=app_user_uuid)
        # app_user_uuid = "bb9a44e01ce44b56a0f1aa3d7c7d478f"
Ejemplo n.º 36
0
@Time       :2019-08-12 上午 11:00
@Author     : 闫红
@File       : test_003_web_Merchant_two.py
@desc       : 商户管理(门店)自动化测试用例 1.4版本修改及新增
"""

import json
from faker import Factory
import unittest
from common.myCommon import Assertion
from common.myCommon.TestBaseCase import TestBaseCase
from xqkj.testAction import Xqkj_web_finance_consumptionAction as PlatformAction, specialAction
from xqkj.testAction import loginAction

global_dict = loginAction.global_dict
fake = Factory().create('zh_CN')
# 商户名称
merchantname = loginAction.sign + fake.company()
name = fake.name_male() + loginAction.sign
email = loginAction.sign + fake.email()
mobile = '15388188697'
cardnumber = fake.ssn()


class test_003_web_Merchant_two(TestBaseCase):
    def test_001_api_78dk_platform_mm_base_saveMerchant(self):
        """
        新增商户基本信息
        :return:
        """
        channelid = loginAction.global_dict.get('channelid')
Ejemplo n.º 37
0
    def handle(self, *args, **kwargs):
        fake = Factory.create()
        verbosity = kwargs['verbosity']
        iterations = kwargs['iterations']
        if not iterations:
            iterations = 5

        for i in range(randint(iterations, iterations*2)):
            task_name = (fake
                         .sentence(nb_words=3, variable_nb_words=True)
                         .replace('.', '')
                         .capitalize())
            Task.objects.create(
                name=task_name,
                hourly_rate=Decimal(
                    '%d.%d' % (randint(0, 200), randint(0, 99)))
            )

        for i in range(iterations):
            Client.objects.create(name=fake.company())

        for client in Client.objects.iterator():
            project_iterations = randint(iterations, iterations*2)
            for i in range(project_iterations):
                estimated = choice([True, False])
                estimate = None
                if estimated:
                    estimate = randint(1000, 20000)
                project_name = (fake
                                .sentence(nb_words=3, variable_nb_words=True)
                                .replace('.', '')
                                .capitalize())
                Project.objects.create(
                    client=client,
                    estimate=estimate,
                    name=project_name
                )

        for i in range(iterations):
            fake_user = fake.simple_profile(sex=None)
            username = fake_user['username']
            email = fake_user['mail']
            password = fake.password(
                length=10,
                special_chars=True,
                digits=True,
                upper_case=True,
                lower_case=True
            )
            User.objects.create_user(username, email, password)

        users = User.objects.all()
        projects = Project.objects.all()
        tasks = Task.objects.all()

        for project in projects:
            entry_iterations = randint(iterations*2, iterations*4)
            for i in range(entry_iterations):
                date = fake.date_time_between(
                    start_date='-30d',
                    end_date='now',
                    tzinfo=None
                )
                duration = timedelta(
                    hours=randint(0, 3),
                    minutes=randint(1, 60)
                )
                Entry.objects.create(
                    project=project,
                    user=choice(users),
                    task=choice(tasks),
                    date=date,
                    duration=duration,
                    note=fake.sentence(nb_words=6, variable_nb_words=True)
                )

        one_week_ago = datetime.now() - timedelta(days=7)
        one_week_ago = one_week_ago.date()
        for project in Project.objects.all():
            has_paid = choice([True, False])
            if has_paid:
                paid = datetime.now(pytz.timezone('US/Eastern'))
            else:
                paid = None
            invoice = Invoice.objects.create(client=project.client, paid=paid)
            for entry in project.entries.iterator():
                if entry.date < one_week_ago:
                    invoice.entries.add(entry)

        if verbosity > 0:
            self.stdout.write(
                self.style.SUCCESS('Successfully added fake data.')
            )
Ejemplo n.º 38
0
import tempfile

import factory
from faker import Factory
from PIL import Image

from api.models import Recipe
from api.seeds.users_seeds import UserFactory

faker = Factory.create()


class RecipeFactory(factory.DjangoModelFactory):
    class Meta:
        model = Recipe

    user = factory.SubFactory(UserFactory)
    description = faker.text()
    steps = faker.text()
    difficulty = faker.random_int(0, 10)
    image = faker.file_name(category=None, extension='jpeg')
    name = faker.sentence(nb_words=4,
                          variable_nb_words=True,
                          ext_word_list=None)

    @classmethod
    def generate_recipe_json_data(cls, recipe_image=None):
        return {
            'name':
            faker.sentence(nb_words=4,
                           variable_nb_words=True,
Ejemplo n.º 39
0

dataNames = [
    'aggregation', 'circles', 'flame', 'iris', 'jane', 'moons', 'wine',
    'annual_balance_sheets', 'R15', 'vehicle'
]
variables = [[0.14, 6], [0.2, 4], [0.29, 6], [0.61, 6], [0.3, 4], [0.15, 4],
             [2.2, 5], [7.8, 11], [0.105, 4], [1.56, 6]]

# loading the data #
path = "aggregation.csv"
dataset_ = pd.read_csv(path, delimiter=' ', engine='python')
dataset = np.array(dataset_)

# initializing the variables #
color_gen = Factory.create()
eps, minPnt = varInit(path, dataNames, variables)

if (eps, minPnt) == (-1, -1):
    print("error: the dataset is not familiar to the system ")
    exit(-1)

# normalize the data #
dataset = StandardScaler().fit_transform(X=dataset)

# plotting the original data
(fig, ax1) = original_plotting(dataset, dataset.shape[1])

# creating collection of all the points #
points = []
for row in dataset:
Ejemplo n.º 40
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import factory as factory_boy
from faker import Factory as FakerFactory, Faker
from factory.fuzzy import FuzzyDateTime
from relationaldb import models
import random
import hashlib
from datetime import datetime
import pytz

fakerFactory = FakerFactory.create()
faker = Faker()


def randomSHA256():
    return hashlib.sha256(str(random.random())).hexdigest()


class BlockTimestampedFactory(factory_boy.Factory):
    creation_date_time = FuzzyDateTime(datetime.now(pytz.utc))
    creation_block = factory_boy.Sequence(lambda n: n)


class ContractFactory(factory_boy.DjangoModelFactory):
    class Meta:
        model = models.Contract

    address = factory_boy.Sequence(lambda n: '{:040d}'.format(n))

Ejemplo n.º 41
0
from faker import Factory
from bs4 import BeautifulSoup
"""
本文件用于爬取豆瓣最受欢迎影评
    目标网址: https://movie.douban.com/review/best/
"""

header_str = """Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Language:zh-CN,zh;q=0.9
Cache-Control:max-age=0
Connection:keep-alive
Host:movie.douban.com
Referer:https://movie.douban.com/
Upgrade-Insecure-Requests:1"""

UA = Factory().create().user_agent()
headers = {
    x.split(':', 1)[0]: x.split(':', 1)[1]
    for x in header_str.split('\n')
}
headers['User-Agent'] = UA

# 存放不规则页面网址
WRONG_LINK_LIST = []

# 创建连接到MongoDB
HOST = 'localhost'
PORT = 27017
CONN = pymongo.MongoClient(HOST, PORT)
DB = CONN['spider']
COLLECTION_NAME = 'doubanmovie'
Ejemplo n.º 42
0
import factory
from faker import Factory as FakerFactory

faker = FakerFactory.create('de_DE')


class SymptomDetailFactory(factory.django.DjangoModelFactory):
    localisation = 'Head'
    slug = 'head_pain_stinging'
    indication = 'Pain, stinging'
    description = 'Description for stinging head pain.'

    class Meta:
        model = 'django_chinese_medicine.Symptom'


class SymptomFactory(factory.django.DjangoModelFactory):
    localisation = factory.LazyAttribute(lambda x: faker.name())
    slug = 'foo'
    indication = factory.LazyAttribute(lambda x: faker.name())
    description = factory.LazyAttribute(lambda x: faker.text())

    class Meta:
        model = 'django_chinese_medicine.Symptom'


class EtiologieDetailFactory(factory.django.DjangoModelFactory):
    name = 'Etiologie Foo'
    slug = 'etiologie_foo'
    description = 'Description for Etiologie Foo.'
Ejemplo n.º 43
0
import random
from faker import Factory

fake = Factory().create('en_us')


def random_first_name():
    return fake.first_name()


def random_last_name():
    return fake.last_name()


def random_email():
    return fake.email()


def random_project_name(min_chars=6, max_chars=10):
    return fake.pystr(min_chars=min_chars, max_chars=max_chars)
Ejemplo n.º 44
0
class TestEnterpriseDecorators(unittest.TestCase):
    """
    Tests for enterprise decorators.
    """
    def setUp(self):
        """
        Set up test environment.
        """
        super(TestEnterpriseDecorators, self).setUp()
        faker = FakerFactory.create()
        self.provider_id = faker.slug()  # pylint: disable=no-member
        self.uuid = faker.uuid4()  # pylint: disable=no-member
        self.customer = EnterpriseCustomerFactory(uuid=self.uuid)
        EnterpriseCustomerIdentityProviderFactory(
            provider_id=self.provider_id, enterprise_customer=self.customer)
        self.session_engine = import_module(settings.SESSION_ENGINE)

    def _prepare_request(self, url, user):
        """
        Prepare request for test.
        """
        request = RequestFactory().get(url)
        request.user = user
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
        request.session = self.session_engine.SessionStore(session_key)
        return request

    def test_deprecated(self):
        """
        Calling a deprecated function emits a warning.
        """
        def func():
            """ Function to be decorated. """

        with warnings.catch_warnings(record=True) as warning:
            warnings.simplefilter('always')
            deprecated('Yep!')(func)()
            assert len(warning) == 1
            assert issubclass(warning[0].category, DeprecationWarning)
            assert str(warning[0].message
                       ) == 'You called the deprecated function `func`. Yep!'

    def test_ignore_warning(self):
        """
        Emitted warnings from a function are ignored.
        """
        def func():
            """ Function to be decorated. """

        with warnings.catch_warnings(record=True) as warning:
            warnings.simplefilter('always')
            ignore_warning(DeprecationWarning)(func)()
            deprecated('Yep!')(func)()
            assert len(warning) == 0

    @ddt.data(True, False)
    def test_disable_for_loaddata(self, raw):
        signal_handler_mock = mock.MagicMock()
        signal_handler_mock.__name__ = get_magic_name("Irrelevant")
        wrapped_handler = disable_for_loaddata(signal_handler_mock)

        wrapped_handler(raw=raw)

        assert signal_handler_mock.called != raw

    @ddt.data(
        {},  # Missing required parameter `enterprise_uuid` arguments in kwargs
        {'enterprise_uuid': ''
         },  # Required parameter `enterprise_uuid` with empty value in kwargs.
        # pylint: disable=no-member
        {'enterprise_uuid': FakerFactory.create().uuid4()
         },  # Invalid value of `enterprise_uuid` in kwargs.
    )
    def test_enterprise_login_required_raises_404(self, kwargs):
        """
        Test that the decorator `enterprise_login_required` raises `Http404`
        error when called with invalid or missing arguments.
        """
        view_function = mock_view_function()
        enterprise_launch_url = reverse(
            'enterprise_course_run_enrollment_page',
            args=[self.customer.uuid, 'course-v1:edX+DemoX+Demo_Course'],
        )
        request = self._prepare_request(enterprise_launch_url,
                                        UserFactory(is_active=True))

        with raises(Http404):
            enterprise_login_required(view_function)(request, **kwargs)

    def test_enterprise_login_required_redirects_for_anonymous_users(self):
        """
        Test that the decorator `enterprise_login_required` returns Http
        Redirect for anonymous users.
        """
        view_function = mock_view_function()
        course_id = 'course-v1:edX+DemoX+Demo_Course'
        enterprise_launch_url = reverse(
            'enterprise_course_run_enrollment_page',
            args=[self.customer.uuid, course_id],
        )
        request = self._prepare_request(enterprise_launch_url, AnonymousUser())

        response = enterprise_login_required(view_function)(
            request, enterprise_uuid=self.customer.uuid, course_id=course_id)

        # Assert that redirect status code 302 is returned when an anonymous
        # user tries to access enterprise course enrollment page.
        assert response.status_code == 302
        assert 'new_enterprise_login%3Dyes' in response.url
        assert 'tpa_hint' in response.url

    def test_enterprise_login_required_redirects_for_anonymous_users_with_querystring(
            self):
        """
        Test that the decorator `enterprise_login_required` returns Http
        Redirect for anonymous users while keeping the format of query
        parameters unchanged.
        """
        view_function = mock_view_function()
        course_id = 'course-v1:edX+DemoX+Demo_Course'
        course_enrollment_url = reverse(
            'enterprise_course_run_enrollment_page',
            args=[self.customer.uuid, course_id],
        )
        querystring = 'catalog=dummy-catalog-uuid'
        course_enrollment_url = '{course_enrollment_url}?{querystring}'.format(
            course_enrollment_url=course_enrollment_url,
            querystring=querystring)
        request = self._prepare_request(course_enrollment_url, AnonymousUser())

        response = enterprise_login_required(view_function)(
            request, enterprise_uuid=self.customer.uuid, course_id=course_id)

        # Assert that redirect status code 302 is returned when an anonymous
        # user tries to access enterprise course enrollment page.
        assert response.status_code == 302

        # Now verify that the query parameters in the querystring of next url
        # are unchanged
        next_url = parse_qs(urlparse(response.url).query)['next'][0]
        next_url_querystring = unquote(urlparse(next_url).query)
        assert 'new_enterprise_login=yes' in next_url_querystring
        assert 'tpa_hint' in next_url_querystring
        assert querystring in next_url_querystring

    def test_enterprise_login_required(self):
        """
        Test that the enterprise login decorator calls the view function.

        Test that the decorator `enterprise_login_required` calls the view
        function when:
            1. `enterprise_uuid` is provided and corresponding enterprise
                customer exists in database.
            2. User making the request is authenticated.

        """
        view_function = mock_view_function()
        course_id = 'course-v1:edX+DemoX+Demo_Course'
        enterprise_launch_url = reverse(
            'enterprise_course_run_enrollment_page',
            args=[self.customer.uuid, course_id],
        )
        request = self._prepare_request(enterprise_launch_url,
                                        UserFactory(is_active=True))

        enterprise_login_required(view_function)(
            request, enterprise_uuid=self.customer.uuid, course_id=course_id)

        # Assert that view function was called.
        assert view_function.called

    def test_force_fresh_session_anonymous_user(self):
        """
        Test that the force_fresh_session decorator calls the
        decorated view the request is made by an unauthenticated
        user.
        """
        view_function = mock_view_function()
        course_id = 'course-v1:edX+DemoX+Demo_Course'
        enterprise_launch_url = reverse(
            'enterprise_course_run_enrollment_page',
            args=[self.customer.uuid, course_id],
        )
        request = self._prepare_request(enterprise_launch_url, AnonymousUser())

        force_fresh_session(view_function)(request,
                                           enterprise_uuid=self.customer.uuid,
                                           course_id=course_id)

        # Assert that view function was called and the session flag was set.
        assert view_function.called

    @mock.patch('enterprise.decorators.get_identity_provider')
    def test_force_fresh_session_no_sso_provider(self, mock_get_idp):  # pylint: disable=unused-argument
        """
        Test that the force_fresh_session decorator calls the view function
        when no sso provider is configured.
        """
        mock_get_idp.return_value = None
        view_function = mock_view_function()
        course_id = 'course-v1:edX+DemoX+Demo_Course'
        enterprise_launch_url = reverse(
            'enterprise_course_run_enrollment_page',
            args=[self.customer.uuid, course_id],
        )
        request = self._prepare_request(enterprise_launch_url,
                                        UserFactory(is_active=True))

        force_fresh_session(view_function)(request,
                                           enterprise_uuid=self.customer.uuid,
                                           course_id=course_id)

        # Assert that view function was called.
        assert view_function.called

    def test_force_fresh_session_param_received(self):
        """
        Test that the force_fresh_session decorator calls the view function
        if the session is fresh.
        """
        view_function = mock_view_function()
        course_id = 'course-v1:edX+DemoX+Demo_Course'
        enterprise_launch_url = reverse(
            'enterprise_course_run_enrollment_page',
            args=[self.customer.uuid, course_id],
        )
        enterprise_launch_url += '?new_enterprise_login=yes'
        request = self._prepare_request(enterprise_launch_url,
                                        UserFactory(is_active=True))

        force_fresh_session(view_function)(request,
                                           enterprise_uuid=self.customer.uuid,
                                           course_id=course_id)

        # Assert that view function was called.
        assert view_function.called

    @mock.patch('enterprise.decorators.get_identity_provider')
    def test_force_fresh_session_param_not_received(
            self, mock_get_identity_provider):
        """
        Test that the force_fresh_session decorator redirects authenticated
        users with the appropriate provider config depending on the IdPs configuration.
        """
        mock_get_identity_provider.return_value.configure_mock(
            provider_id=self.provider_id, )
        view_function = mock_view_function()
        course_id = 'course-v1:edX+DemoX+Demo_Course'
        url_path = reverse(
            'enterprise_course_run_enrollment_page',
            args=[self.customer.uuid, course_id],
        )
        query = 'foo=bar'
        # Adding query parameter here to verify
        # the redirect URL is getting escaped properly.
        url = '{path}?{query}'.format(path=url_path, query=query)
        request = self._prepare_request(url, UserFactory(is_active=True))

        response = force_fresh_session(view_function)(
            request, enterprise_uuid=self.customer.uuid, course_id=course_id)

        # Assert that redirect status code 302 is returned
        assert response.status_code == 302
        # Assert the redirect URL query string is intact.
        redirect_url_query = parse_qs(urlparse(response.url).query)
        assert urlparse(unquote(
            redirect_url_query['redirect_url'][0])).query == query
Ejemplo n.º 45
0
from uuid import UUID

import factory
from faker import Factory as FakerFactory

from enterprise.models import (
    EnterpriseCourseEnrollment,
    EnterpriseCustomer,
    EnterpriseCustomerBrandingConfiguration,
    EnterpriseCustomerIdentityProvider,
    EnterpriseCustomerUser,
)
from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory

FAKER = FakerFactory.create()


class EnterpriseCustomerFactory(factory.django.DjangoModelFactory):
    """
    EnterpriseCustomer factory.

    Creates an instance of EnterpriseCustomer with minimal boilerplate - uses this class' attributes as default
    parameters for EnterpriseCustomer constructor.
    """

    class Meta:
        """
        Meta for EnterpriseCustomerFactory.
        """
Ejemplo n.º 46
0
 def setUp(self):
     self.factory = Factory.create('hu_HU')
Ejemplo n.º 47
0
 def setUp(self):
     self.factory = Factory.create('no_NO')
Ejemplo n.º 48
0
 def setUp(self):
     self.factory = Factory.create('ja')
Ejemplo n.º 49
0
from prof_education.utils.factory import choice_with_chance, random_bool, random_digits

from .models import (
    AbylimpixStatus,
    EducationDoc,
    Enrollee,
    EnrolleePassport,
    EnrolleeSpecialization,
    GosOlympiadStatus,
    GraduatedInstitution,
    ParentData,
    SportAchievement,
    WsrOlympiadStatus,
)

faker = FakerFactory.create(locale="ru_RU")

subjects = [
    "Математика", "Обществознание", "Биология", "Русский язык", "Литература"
]

sport_types = ["Футбол", "Баскетбол", "Волейбол", "Бег"]


class PassportFactory(factory.django.DjangoModelFactory):
    series = factory.LazyAttribute(lambda x: random_digits(4))
    num = factory.LazyAttribute(lambda x: random_digits(6))
    issued_at = factory.LazyAttribute(lambda x: faker.date_between_dates(
        date_start=date(1998, 1, 1), date_end=date(2005, 1, 1)))
    issued_by = factory.LazyAttribute(lambda x: faker.city())
Ejemplo n.º 50
0
 def setUp(self):
     self.factory = Factory.create('en_GB')
Ejemplo n.º 51
0
Generate human-friendly random strings. Phrases are usually of the form
"adjective" + "subjective". We try to use mostly characters from Science and
Science fiction movies.

The main entry point is the :func:`phrase` function, that simply returns a
random phrase. If you want to learn more, read the source :)

.. autofunction :: phrase
"""

import random

from faker import Factory

fake = Factory.create("en-us")

star_wars_characters = [
    "Han Solo",
    "Darth Vader",
    "C3PO",
    "R2D2",
    "Luke Skywalker",
    "Princess Leia",
    "Jabba",
    "Obi Wan",
    "Yoda",
    "Jar Jar Binks",
]
famous_scientists = [
    # Physicists
def generate_uuid():
    fake = Factory.create()
    uuid = fake.uuid4()
    uuid = uuid.replace("-", "").upper()
    return uuid
Ejemplo n.º 53
0
 def setUp(self):
     self.factory = Factory.create('pt_BR')
Ejemplo n.º 54
0
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import re
import time

from scrapy import Spider, Request, FormRequest
from scrapy.spider import CrawlSpider, Rule
from scrapy.linkextractor import LinkExtractor
from faker import Factory
from scrapy_splash import SplashRequest
# import urlparse
from JobSpider.items import JobItem, JobDetailItem

FACTORY = Factory.create()  # 初始化生成器


class JobSpider(CrawlSpider):
    """ Zhilian Job Spider """
    name = "ZhilianSpider"
    allow_domains = ['sou.zhaopin.com', 'jobs.zhaopin.com']
    """ url拼接 """
    joblocation = '选择地区'
    keyword = '大数据开发工程师'
    p = 1
    kt = 1  # 1:职位名称; 2:公司名;
    isadv = 0
    sm = 0
    sortby = 0  # 0:默认排序; 1:相关度; 2:首发日; 3: 最匹配;
    isfilter = 0
Ejemplo n.º 55
0
 def create_number(cls):
     fake = Factory.create("zh_CN")
     cls.equipment_number = fake.md5()
Ejemplo n.º 56
0
def token(request):
    fake = Factory.create()
    return generateToken(fake.user_name())
Ejemplo n.º 57
0
class TestdataGenerator(object):
    """一些生成器方法,生成随机数,手机号,以及连续数字等"""
    def __init__(self):
        self.fake = Factory().create('zh_CN')

    def random_phone_number(self):
        """随机手机号"""
        return self.fake.phone_number()

    def random_name(self):
        """随机姓名"""
        return self.fake.name()

    def random_address(self):
        """随机地址"""
        return self.fake.address()

    def random_email(self):
        """随机email"""
        return self.fake.email()

    def random_ipv4(self):
        """随机IPV4地址"""
        return self.fake.ipv4()

    def random_str(self, min_chars=0, max_chars=8):
        """长度在最大值与最小值之间的随机字符串,只包含a-zA-Z字母"""
        return self.fake.pystr(min_chars=min_chars, max_chars=max_chars)

    def random_int(self, min_value=0, max_value=9999, exclude=None):
        """返回[min_value, max_value]范围内的一随机数,可排除范围内任意数"""
        if exclude is not None:
            if not isinstance(exclude, list):
                return "exclude must a list"
        else:
            exclude = list()
        while True:
            value = self.fake.pyint(min_value=min_value, max_value=max_value)
            if value not in exclude:
                return value

    def random_letter_digit_str(self, min_chars=0, max_chars=8):
        """长度在最大值与最小值之间的随机字符串,只包含a-zA-Z字母和0-9数字"""
        if min_chars is None:
            return "".join(self.random_letters_digits(length=max_chars))
        else:
            assert (
                max_chars >= min_chars
            ), "Maximum length must be greater than or equal to minium length"
            return "".join(
                self.random_letters_digits(length=random.randint(
                    min_chars, max_chars), ), )

    def random_letters_digits(self, length=16):
        """返回一随机字母、数字字符串(a-z 、A-Z 、0-9)."""
        return self.fake.random_choices(
            getattr(string, 'letters', string.ascii_letters + string.digits),
            length=length,
        )

    def random_punctuation_str(self, min_chars=0, max_chars=8):
        """返回长度在最大值与最小值之间的随机字符串,只包含英文标点符号"""
        if min_chars is None:
            return "".join(self.random_punctuation(length=max_chars))
        else:
            assert (
                max_chars >= min_chars
            ), "Maximum length must be greater than or equal to minium length"
            return "".join(
                self.random_punctuation(length=random.randint(
                    min_chars, max_chars), ), )

    def random_punctuation(self, length=16):
        """返回一随机英文标点符号"""
        return self.fake.random_choices(
            getattr(string, 'letters', string.punctuation),
            length=length,
        )

    @classmethod
    def factory_generate_ids(cls, starting_id=1, increment=1):
        """ 返回一个生成器函数,调用这个函数产生生成器,从starting_id开始,步长为increment。 """
        def generate_started_ids():
            val = starting_id
            local_increment = increment
            while True:
                yield val
                val += local_increment

        return generate_started_ids

    @classmethod
    def factory_choice_generator(cls, values):
        """ 返回一个生成器函数,调用这个函数产生生成器,从给定的list中随机取一项。 """
        def choice_generator():
            my_list = list(values)
            while True:
                yield random.choice(my_list)

        return choice_generator
Ejemplo n.º 58
0
from faker import Factory

fake = Factory.create(locale='en_US')
Ejemplo n.º 59
0
class Command(BaseCommand):
    faker = Factory.create()

    def create_fake_data(self):

        for i in range(1, 50):
            u = User(username='******' + str(i),
                     email='email_' + str(i) + '@email.com',
                     password=make_password('qwerty123'),
                     first_name=self.faker.first_name(),
                     last_name=self.faker.last_name())
            u.save()
            p = Profile(user=u,
                        avatar="cookie.png",
                        rating=random.choice(range(1, 99)))
            p.save()

            year = random.choice(range(1950, 2001))
            month = random.choice(range(1, 13))
            day = random.choice(range(1, 29))
            post_time = random.seed(time.time())

            q = Question(author=u,
                         title=self.faker.sentence(nb_words=randint(4, 6),
                                                   variable_nb_words=True),
                         text=self.faker.paragraph(nb_sentences=randint(4, 13),
                                                   variable_nb_sentences=True),
                         likes=random.choice(range(-50, 172)),
                         date=(datetime(year, month, day, post_time)))
            q.save()
            for j in range(4):
                ans = Comment(author=u,
                              question=q,
                              text=self.faker.paragraph(
                                  nb_sentences=randint(2, 10),
                                  variable_nb_sentences=True),
                              likes=random.choice(range(-32, 172)))
                ans.save()

    def create_tags(self):
        tags = [
            'JavaScript', 'Java', 'C#', 'PHP', 'Android', 'JQuery', 'Python',
            'HTML', 'CSS', 'C++', 'iOS', 'MySQL', 'Objective-C', 'SQL', '.net',
            'RUBY', 'Swift', 'Vue', '1C'
        ]
        for tag in tags:
            if len(Tag.objects.filter(text=tag)) == 0:
                t = Tag()
                t.text = tag
                t.save()

        tags = Tag.objects.all()
        questions = Question.objects.all()
        for question in questions:
            for i in range(0, 4):
                t = choice(tags)

                if t not in question.tags.all():
                    question.tags.add(t)
            self.stdout.write('tagged question [%d]' % question.id)

    def handle(self, *args, **options):
        self.create_fake_data()
        self.create_tags()
Ejemplo n.º 60
0
 def __init__(self):
     self.fake = Factory().create('zh_CN')