Ejemplo n.º 1
0
def fake_receipts(customers):
    fake = Faker()
    data = []
    data.append(random.randint(0, customers))  # customer_id
    data.append(random.choice(['ocr', 'turk', 'admin',
                               'tlog']))  # validation type
    data.append(fake.random_int() / 100)  # total
    data.append(random.choice(['invalid_receipt',
                               'complete']))  # processing_state
    data.append(
        random.choice(['ocr_unmatched', 'turk_matched',
                       'turk_unmatched']))  # validations
    data.append(fake.latitude().to_eng_string())  # lat
    data.append(fake.longitude().to_eng_string())  # lon
    data.append(fake.date_time_this_year())  # created_at
    data.append(fake.random_int())  # store_id
    data.append(random.randint(1, 200))  # retailer_id
    data.append(random.randint(0, 4))  # turk submit count
    data.append(random.choice(['', '1']))  # invalid_receipt
    data.append(fake.random_int())  # ref number
    data.append(fake.random_int())  # appr_code
    data.append(fake.random_int())  # receipt_doce
    data.append(fake.name())  # cashier
    data.append(" ")  # payment_trans_id
    data.append(random.choice(['iphone', 'android']))  # phone_data
    data.append(random.choice(['', '1']))  # verified_total
    data.append(fake.date_time_this_year())  # pending acceptance at
    data.append(fake.date_time_this_year())  # pending_credit at
    data.append(random.choice(['', '1']))  # store_number
    data.append(" ")  # receipt_scan_contents
    data.append(random.choice(['', 'fraud']))  # fraud
    return tuple(data)
Ejemplo n.º 2
0
class EntryDetailViewTestCase(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.fake = Faker()

    def test_future_publication_date_hidden_to_anonymous_users(self):
        '''Anonymous users should *not* see Entries whose published=True but have a publication_date set in the future.'''
        obj = EntryFactory.create(
            published=True,
            publication_date=self.fake.date_time_this_year(before_now=False, after_now=True, tzinfo=pytz.utc)
        )

        request = self.factory.get(obj.get_absolute_url())
        request.user = AnonymousUser()

        with self.assertRaises(Http404):
            response = EntryDetailView.as_view()(request, slug=obj.slug)
            self.assertEqual(response.status_code, 404)

    def test_future_publication_date_shown_to_authorized_users(self):
        '''Authorized users should see Entries whose published=True but have a publication_date set in the future.'''
        obj = EntryFactory.create(
            published=True,
            publication_date=self.fake.date_time_this_year(before_now=False, after_now=True, tzinfo=pytz.utc)
        )

        request = self.factory.get(obj.get_absolute_url())
        request.user = User.objects.create_user(
            username='******', email='*****@*****.**', password='******')

        response = EntryDetailView.as_view()(request, slug=obj.slug)
        self.assertEqual(response.status_code, 200)
Ejemplo n.º 3
0
class SiteBotTestCase(unittest.TestCase):
    def setUp(self):
        self.fake = Faker()

    def fake_event(self):
        return {
            'id': self.fake.random_number(),
            'title': self.fake.sentence(4),
            'time': self.fake.date_time_this_year(True, True),
            'excerpt': self.fake.sentence(4),
            'venue_name': self.fake.company(),
            'venue_location': self.fake.street_address()
        }

    def fake_event_old(self):
        # All times come from Meetup in milliseconds
        return {
            'created': 1000 * time.mktime(
                self.fake.date_time_this_year(True, True).timetuple()),
            'duration': 7200000,
            'id': self.fake.random_number(),
            'name': self.fake.sentence(4),
            'self': {
                'actions': [
                    'upload_photo',
                    'delete',
                    'edit_hosts',
                    'edit',
                    'comment',
                    'rsvp'
                    ]
                },
            'status': random.choice(['cancelled', 'upcoming', 'past',
                                     'proposed', 'suggested', 'draft']),
            'time': 1000 * time.mktime(
                self.fake.date_time_this_year(True, True).timetuple()),
            'updated': 1000 * time.mktime(
                self.fake.date_time_this_year(True, True).timetuple()),
            'utc_offset': -21600000,
            'venue': {
                'id': self.fake.random_number(),
                'name': self.fake.company(),
                'lat': float(self.fake.latitude()),
                'lon': float(self.fake.longitude()),
                'repinned': False,
                'address_1': self.fake.street_address(),
                'city': self.fake.city(),
                'country': 'us',
                'localized_country_name': 'USA',
                'zip': self.fake.zipcode(),
                'state': self.fake.state_abbr()
            },
            'link': self.fake.uri(),
            'description': '''
                <p>Hello <a href="http://example.com">World</a></p>
                <p>Here is some more content</p>
                ''',
            'how_to_find_us': self.fake.sentence(10),
            'visibility': random.choice([True, False])
        }
Ejemplo n.º 4
0
def forge(count, artist, music, both):
    from faker import Faker
    db.drop_all()
    db.create_all()
    fake = Faker(locale='zh_CN')
    click.echo("Now generating fake data...")
    for i in range(count):
        if both:
            musicData = Music(name=fake.sentence(),
                              author=fake.name(),
                              publish_time=fake.date_time_this_year())
            artistData = Artist(name=fake.name(),
                                birth=fake.date_time_this_year(),
                                city=fake.city())
            db.session.add(musicData)
            db.session.add(artistData)
            click.echo('Generating %d fake music and artist ' % i)
        elif artist:
            artistData = Artist(name=fake.name(),
                                birth=fake.date_time_this_year(),
                                city=fake.city())
            click.echo('Generating %d fake artist ' % i)
            db.session.add(artistData)
        elif music:
            musicData = Music(name=fake.sentence(),
                              author=fake.name(),
                              publish_time=fake.date_time_this_year())
            db.session.add(musicData)
            click.echo('Generating %d fake music' % i)
    db.session.commit()
    click.echo('Generated %d fake music %s %s' % (count, artist, music))
Ejemplo n.º 5
0
def fake_comments(count=500):
    fake=Faker()
    for i in range(count):
        comment = Comment(
            author=fake.name(),
            email=fake.email(),
            site=fake.url(),
            body=fake.sentence(),
            timestamp=fake.date_time_this_year(),
            reviewed=True,
            post=Post.query.get(random.randint(1, Post.query.count()))
        )
        db.session.add(comment)

    salt = int(count * 0.1)

    for i in range(salt):
        # unreviewed comments
        comment = Comment(
            author=fake.name(),
            email=fake.email(),
            site=fake.url(),
            body=fake.sentence(),
            timestamp=fake.date_time_this_year(),
            reviewed=False,
            post=Post.query.get(random.randint(1, Post.query.count()))
        )
        db.session.add(comment)

        # from admin
        admin = Admin.query.get(1)
        comment = Comment(
            author=admin.username,
            body=fake.sentence(),
            timestamp=fake.date_time_this_year(),
            reviewed=True,
            post=Post.query.get(random.randint(1, Post.query.count()))
        )
        db.session.add(comment)
    db.session.commit()

    # replies
    for i in range(salt):
        comment = Comment(
            author=fake.name(),
            email=fake.email(),
            site=fake.url(),
            body=fake.sentence(),
            timestamp=fake.date_time_this_year(),
            reviewed=False,
            post=Post.query.get(random.randint(1, Post.query.count())),
            replied=Comment.query.get(random.randint(1, Comment.query.count()))
        )
        db.session.add(comment)
    db.session.commit()
Ejemplo n.º 6
0
def forge(count):
    from faker import Faker
    db.drop_all()
    db.create_all()

    faker = Faker()
    click.echo("WORKING...")

    movies = [
        {
            'title': 'My Neighbor Totoro',
            'year': '1988'
        },
        {
            'title': 'Dead Poets Society',
            'year': '1989'
        },
        {
            'title': 'A Perfect World',
            'year': '1993'
        },
        {
            'title': 'Leon',
            'year': '1994'
        },
        {
            'title': 'Mahjong',
            'year': '1996'
        },
        {
            'title': 'Swallowtail Butterfly',
            'year': '1996'
        },
        {
            'title': 'King of Comedy',
            'year': '1999'
        },
        {
            'title': 'Devils on the Doorstep',
            'year': '1999'
        },
        {
            'title': 'WALL-E',
            'year': '2008'
        },
        {
            'title': 'The Pork of Music',
            'year': '2012'
        },
    ]
    for m in movies:
        movie = MovieModel(title=m['title'], year=m['year'])
        db.session.add(movie)
    for i in range(count):
        say = SayModel(name=faker.name(),
                       body=faker.sentence(),
                       timestamp=faker.date_time_this_year())
        db.session.add(say)
    db.session.commit()
    click.echo("ALL WORKS OK!")
Ejemplo n.º 7
0
 def fake_mood():
     fake = Faker("zh_CN")
     emotion_list = [
         'Confident', 'Excited', 'Fulfilled', 'Grateful', 'Happy',
         'Inspired', 'Joy', 'Loved', 'Motivated', 'Optimistic', 'Peaceful',
         'Proud', 'Relaxed', 'Relieved', 'Satisfied', 'Angry',
         'Disappointed', 'Embarrassed', 'Empty', 'Frustrated', 'Guilty',
         'Hopeless', 'Lonely', 'Nervous', 'Overwhelmed', 'Sad', 'Scared',
         'Stressed', 'Tired', 'Worried'
     ]
     entry_list = ['Good', 'Bad', 'Neutral', 'Terrible', 'Terrific']
     for i in range(50):
         mood = Mood(title=fake.street_name(),
                     companion=fake.name(),
                     location=fake.city(),
                     details=fake.text(max_nb_chars=200),
                     timestamp=fake.date_time_this_year(before_now=True,
                                                        after_now=False,
                                                        tzinfo=None),
                     entry=entry_list[fake.pyint(0, 4)],
                     emotion=emotion_list[fake.pyint(0, 29)],
                     level=str(fake.pyint(0, 2)) + ',' +
                     str(fake.pyint(0, 2)))
         db.session.add(mood)
         db.session.commit()
         click.echo('正在生成第{}条数据'.format(i))
     click.echo('Done')
Ejemplo n.º 8
0
def generate_clicks():
    from faker import Faker
    import random
    fake = Faker()
    for _ in range(5000):
        click = Click(timestamp=fake.date_time_this_year(),clicker=random.choice([random.choice(User.objects.all()),random.choice(User.objects.all()),None]),bookmark=random.choice(Bookmark.objects.all()))
        click.save()
Ejemplo n.º 9
0
  def generate_answers(self, questions, users):
    Answer.objects.all().delete()
    list_of_answers = []

    fake = Faker()
    for question in questions:
      for i in range(0, random.randint(10, self.MAX_ANSWERS_PER_QUESTION)):
        user = random.choice(users)
        text = fake.text()
        creationTime = fake.date_time_this_year(
          before_now=True,
          after_now=False,
          tzinfo=timezone('Europe/Moscow')
        )
        answer = Answer(
          text=text,
          creationTime=creationTime,
          author=user,
          question=question
        )
        list_of_answers.append(answer)

    batch_size = 10000
    start = 0
    end = 10000
    while True:
      batch = list(islice(list_of_answers, start, end))
      if not batch:
        break
      Answer.objects.bulk_create(batch)
      start = start + batch_size
      end = end + batch_size

    self.stdout.write(self.style.SUCCESS('Successfully generated answers.'))
Ejemplo n.º 10
0
def create_projects(num=1):
    fc = Faker(locale='zh_CN')
    fe = Faker()
    project_name = fc.sentence()

    orgs = Organization.objects.order_by('name')[:]
    user_profiles = UserProfile.objects.all()
    
    for _ in range(num):
        project_name = fc.sentence()
        org = orgs[random.randint(0,len(orgs) - 1)]
        end_time = fc.future_datetime()
        start_time = fc.date_time_this_year()
        introduction = fc.text()
        cost_budget = fc.pyint()
        cost = fc.random_int()
        price = fc.random_int(max=cost//100)

        project_manager = user_profiles[random.randint(0,len(user_profiles) - 1)]
        project_creator = user_profiles[random.randint(0,len(user_profiles) - 1)]

        p = Project(
            name=project_name,
            start_time=start_time,
            end_time=end_time,
            organization=org,
            location=fc.street_address(),
            introduction=introduction,
            cost_budget=cost_budget,
            cost=cost,
            price=price,
            project_manager=project_manager,
            project_creator=project_creator
        )
        p.save()
Ejemplo n.º 11
0
def generate_activities():
    import json
    from faker import Faker
    import random
    fake = Faker()
    activities=[]
    activity_list = ['running', 'biking', 'walking',
                'double dutch', 'cook a meal', 'have a snack',
                'walk the dog', 'watch a movie', 'bake a cake',
                'order pizza']
    for x in range(100):
    #     activity = {'fields':{'title':random.choice(activity_list),
    #                         'timestamp':str(fake.date_time_this_year())[:10],
    #                         'user': random.choice(User.objects.all())
    #                         },
    #                 'model':'api.Activity',}
    #     activities.append(activity)
    #     print(activity)
    # with open('activities.json', 'w') as f:
    #     f.write(json.dumps(activities))
        activity = Activity(title=random.choice(activity_list),
                             timestamp=str(fake.date_time_this_year())[:10],
                             user= random.choice(User.objects.all()))
        activity.save()
        print(activity)
Ejemplo n.º 12
0
def load_fake_data():
    '''Create some fake users and statuses'''

    # It is encouraged to import only where needed!
    from faker import Faker
    import random

    fake = Faker()

    # Need to clear existing data!
    Favorite.objects.all().delete()
    Status.objects.all().delete()
    User.objects.exclude(username='******').delete()

    users = []
    for _ in range(50):
        new_user = User(username=fake.user_name(),
                        email=fake.email(),
                        password=fake.password())
        new_user.save()
        users.append(new_user)

    statuses = []
    for _ in range(1000):
        new_status = Status(user=random.choice(users),
                            posted_at=fake.date_time_this_year(),
                            text=fake.text(max_nb_chars=141))
        new_status.save()
        statuses.append(new_status)

    for _ in range(4000):
        favorite = Favorite(user=random.choice(users),
                            status=random.choice(statuses))
        favorite.save()
Ejemplo n.º 13
0
    def forge(user_num, post_num):
        import random
        from faker import Faker
        fake = Faker()
        db.drop_all()
        db.create_all()

        click.echo('Generating fake entries in database ...')

        for i in range(user_num):
            user = User(name=fake.name())
            user.set_password('fake_password')
            db.session.add(user)
        db.session.commit()

        if user_num > 0:
            for i in range(post_num):
                user = random.choice(User.query.all())
                post = Post(title=fake.sentence(),
                            body=fake.text(),
                            created=fake.date_time_this_year())
                post.author = user
                db.session.add(post)
            db.session.commit()

        click.echo('Done!')
Ejemplo n.º 14
0
def generate_activities():
    import json
    from faker import Faker
    import random
    fake = Faker()
    activities = []
    activity_list = [
        'running', 'biking', 'walking', 'double dutch', 'cook a meal',
        'have a snack', 'walk the dog', 'watch a movie', 'bake a cake',
        'order pizza'
    ]
    for x in range(100):
        #     activity = {'fields':{'title':random.choice(activity_list),
        #                         'timestamp':str(fake.date_time_this_year())[:10],
        #                         'user': random.choice(User.objects.all())
        #                         },
        #                 'model':'api.Activity',}
        #     activities.append(activity)
        #     print(activity)
        # with open('activities.json', 'w') as f:
        #     f.write(json.dumps(activities))
        activity = Activity(title=random.choice(activity_list),
                            timestamp=str(fake.date_time_this_year())[:10],
                            user=random.choice(User.objects.all()))
        activity.save()
        print(activity)
Ejemplo n.º 15
0
def forge(count: int):
    """Generate fake message."""
    from faker import Faker
    import random

    fake = Faker()

    db.drop_all()
    db.create_all()

    click.echo("Generating a User...")
    user = User(username="******")
    user.set_password("123")

    for i in range(count):
        click.echo("Creating the item...")
        item = Item(
            user=user,
            title=fake.sentence(),
            status=random.randint(0, 1),
            create_time=fake.date_time_this_year(),
        )
        db.session.add(item)
    db.session.commit()
    click.echo(f"Created {count} fake item.")
Ejemplo n.º 16
0
    def handle(self, *args, **options):
        fake = Faker()
        for i in range(options['n'][0]):
            datetime_start = fake.date_time_this_year(before_now=False,
                                                      after_now=True)
            course = Course(
                name=fake.sentence(nb_words=3, variable_nb_words=True),
                description=fake.paragraph(nb_sentences=3,
                                           variable_nb_sentences=True),
                price=fake.pydecimal(left_digits=None,
                                     right_digits=None,
                                     positive=True),
                datetime_start=datetime_start,
                datetime_end=datetime_start + datetime.timedelta(hours=3))
            course.save()
            self.stdout.write(
                self.style.SUCCESS('Successfully faked "%s"' % course))

        for i in range(options['n'][0] * 5):
            student = Student(first_name=fake.first_name(),
                              last_name=fake.last_name(),
                              address=fake.street_address(),
                              zipcode=random.randint(1000, 9999),
                              city=fake.city(),
                              mail=fake.email(),
                              phone_number=random.randint(
                                  700000000, 799999999),
                              birthdate=fake.date_between(end_date='-18y'))
            student.save()
            self.stdout.write(
                self.style.SUCCESS('Successfully faked "%s"' % student))
Ejemplo n.º 17
0
  def generate_questions(self, users, tags):
    Question.objects.all().delete()

    fake = Faker()
    for user in users:
      for i in range(0, random.randint(10, self.MAX_QUESTIONS_PER_USER)):
        title = fake.sentence(nb_words=8)[:98]
        text = fake.text()
        creationTime = fake.date_time_this_year(
          before_now=True,
          after_now=False,
          tzinfo=timezone('Europe/Moscow')
        )
        author = user
        question = Question(
          title=title,
          text=text,
          creationTime=creationTime,
          author=author
        )
        question.save()
        tags_to_add = []
        for i in range(0, 3):
          tags_to_add.append(random.choice(tags).pk)
        question.tags.add(*tags_to_add)

    self.stdout.write(self.style.SUCCESS('Successfully generated questions.'))
    return Question.objects.all()
Ejemplo n.º 18
0
def load_fake_data():
    '''Create some fake users and statuses'''

    # It is encouraged to import only where needed!
    from faker import Faker
    import random

    fake = Faker()

    # Need to clear existing data!
    Favorite.objects.all().delete()
    Status.objects.all().delete()
    User.objects.exclude(username='******').delete()

    users = []
    for _ in range(50):
        new_user = User(username=fake.user_name(),
                        email=fake.email(),
                        password=fake.password())
        new_user.save()
        users.append(new_user)

    statuses = []
    for _ in range(1000):
        new_status = Status(user=random.choice(users),
                            posted_at=fake.date_time_this_year(),
                            text=fake.text(max_nb_chars=141))
        new_status.save()
        statuses.append(new_status)

    for _ in range(4000):
        favorite = Favorite(user=random.choice(users),
                              status=random.choice(statuses))
        favorite.save()
Ejemplo n.º 19
0
def GetFakerData(seed=0, type="name"):
    # seed>0 : the same with last value
    fake = Faker()
    if seed > 0:
        fake.seed(4321)
    if type == "useragent":
        fstr = fake.user_agent()
    if type == "password":
        #可以指定长度,也可以不指定
        len = GetRandomInt(8, 13)
        password = fake.password(len)
    elif type == "name":
        fstr = fake.name()
    elif type == "email":
        fstr = fake.email()
    elif type == "address":
        fstr = fake.address()
    elif type == "company":
        fstr = fake.company()
    elif type == "job":
        fstr = fake.job()
    elif type == "phonenumber":
        fstr = fake.phone_number()
    elif type == "ssn":
        fstr = fake.ssn()
    elif type == "profile":
        fake.profile()
    elif type == "text":
        fstr = fake.text()
    elif type == "ipv4":
        fstr = fake.ipv4()
    elif type == "ipv6":
        fstr = fake.ipv6()
    elif type == "beforenow":
        fstr = fake.date_time_this_century(before_now=True, after_now=False)
    elif type == "afterrenow":
        fstr = fake.date_time_this_century(before_now=False, after_now=True)
    elif type == "beforenowthisyear":
        fstr = fake.date_time_this_year(before_now=True, after_now=False)
    elif type == "afterrenowthisyear":
        fstr = fake.date_time_this_year(before_now=False, after_now=True)
    elif type == "beforenowthismonth":
        fstr = fake.date_time_this_month(before_now=True, after_now=False)
    elif type == "afterrenowthismonth":
        fstr = fake.date_time_this_month(before_now=False, after_now=True)

    return fstr
Ejemplo n.º 20
0
def build_test_data(
        total_companies=100,
        total_departments_per_company=10,
        total_employees_per_company=50
        ):
    """Add a context in which we can run the tests with the test data"""

    print('Building test data...')

    # Drop the database collections
    Company.get_collection().drop()
    Employee.get_collection().drop()

    # Create a faker object
    fake = Faker()
    fake.seed(11061979)
    random.seed(11061979)

    # Build companies
    companies = []
    for company_index in range(0, total_companies):
        company = Company(
            name=fake.company(),
            departments=[],
            address=fake.address(),
            tel=fake.phone_number(),
            website_url=fake.uri()
            )

        # Build departments
        for department_index in range(0, total_departments_per_company):
            department = Department(
                name=fake.word(),
                year_end=fake.date_time_this_year(False, True),
                annual_budget=fake.pyint()
                )
            company.departments.append(department)

        companies.append(company)

    Company.insert_many(companies)

    # Build employees
    for company in companies:
        for employee_index in range(0, total_employees_per_company):
            employee = Employee(
                first_name=fake.first_name(),
                last_name=fake.last_name(),
                dob=fake.date(),
                role=fake.job(),
                tel=fake.phone_number(),
                email=fake.email(),
                annual_salary=fake.pyint(),
                ssn=fake.ssn(),
                company=company,
                department=random.choice(company.departments)
                )
            employee.insert()
Ejemplo n.º 21
0
def fake_customer():
    fake = Faker()
    data = [fake.email()]  # email
    data.append(fake.zipcode())  # zip
    data.append(random.choice(['m', 'f']))  # gender
    data.append(fake.random_int())  # household income
    data.append(random.randint(1, 5))  # children in house
    data.append(random.randint(1, 3))  # adults in house
    data.append(random.choice(['Hispanic', 'Black', 'Caucasian',
                               'Asian']))  # ehtnicity
    data.append(random.choice(['Highschool', 'University',
                               'Grad School']))  # education
    data.append(fake.random_int())  # udid
    data.append(fake.phone_number())  # phone number
    data.append(fake.address().split()[0])  # address
    data.append(fake.city())  # city
    data.append(fake.state())  # staet
    data.append(fake.first_name())  # first name
    data.append(fake.last_name())  # last name
    data.append(fake.date_time_this_year())  # last_login
    data.append(fake.date_time_this_year())  # created at
    data.append(fake.date_time_this_year())  # updated at
    data.append(fake.password())  # encrypted password
    data.append(os.urandom(6).encode('hex'))  # reset passwrod token
    data.append(fake.date_time_this_year())  # reset sent at
    data.append(fake.date_time_this_year())  # remember created at
    data.append(random.randint(1, 10))  # sign in count
    data.append(fake.date_time_this_year())  # current sign in at
    data.append(fake.date_time_this_year())  # last sign in at
    data.append(fake.ipv4())  # current sign in ip
    data.append(fake.ipv4())  # last sign in ip
    data.append(os.urandom(6).encode('hex'))  # authenticatin token
    data.append(random.choice(['0', '1']))  # active
    data.append(os.urandom(6).encode('hex'))  # confirmation token
    data.append(fake.date_time_this_year())  # confirmed at
    data.append(fake.date_time_this_year())  # confirmation sent at
    data.append(fake.email())  # unconfirmed email
    data.append(random.randint(1, 3))  # failed attempts
    data.append(os.urandom(6).encode('hex'))  # unlock token
    data.append(fake.date_time_this_year())  # locked at
    data.append(os.urandom(6).encode('hex'))  # invitation token
    data.append(fake.latitude().to_eng_string())  # lat
    data.append(fake.longitude().to_eng_string())  # lon
    data.append(fake.date())  # birth date
    data.append("default")  # roles
    data.append(fake.date_time_this_year())  # referall
    data.append(fake.date_time_this_year())  # last sweep
    data.append(fake.url())  # url
    data.append(fake.date_time_this_year())  # last notification
    data.append(14)  # online_delay
    data.append(random.choice(['verizon', 'att', 'sprint',
                               't-mobile']))  # carrier
    data.append(round(random.rand(), 2))  # credit conversion ratio
    data.append(" ")  # register source
    return tuple(data)
Ejemplo n.º 22
0
def forge(count):
    """Generate fake data."""
    from faker import Faker

    db.drop_all()
    db.create_all()

    # 全局的两个变量移动到这个函数内
    name = "Five Hao"
    movies = [{
        'title': 'My Neighbor Totoro',
        'year': '1988'
    }, {
        'title': 'Dead Poets Society',
        'year': '1989'
    }, {
        'title': 'A Perfect World',
        'year': '1993'
    }, {
        'title': 'Leon',
        'year': '1994'
    }, {
        'title': 'Mahjong',
        'year': '1996'
    }, {
        'title': 'Swallowtail Butterfly',
        'year': '1996'
    }, {
        'title': 'King of Comedy',
        'year': '1999'
    }, {
        'title': 'Devils on the Doorstep',
        'year': '1999'
    }, {
        'title': 'WALL-E',
        'year': '2008'
    }, {
        'title': 'The Pork of Music',
        'year': '2012'
    }]

    user = User(name=name)
    db.session.add(user)
    for m in movies:
        movie = Movie(title=m['title'], year=m['year'])
        db.session.add(movie)

    fake = Faker()

    for i in range(count):
        message = Message(name=fake.name(),
                          body=fake.sentence(),
                          timestamp=fake.date_time_this_year())
        db.session.add(message)

    db.session.commit()
    click.echo('Done.')
Ejemplo n.º 23
0
def fakerdatafun(count):
    fake = Faker('zh-CN')
    print("working...")

    for i in range(count):
        tip = Tips(poster=fake.name(),body=fake.sentence(),posttime=fake.date_time_this_year())
        db.session.add(tip)
    db.session.commit()
    print("Created {} fake tips.".format(count))
Ejemplo n.º 24
0
def upgrade():
    fake = Faker()
    for i in range(0, 2000):
        op.execute(
            "INSERT INTO calls (first_name, last_name, call_time, duration_call, topic_id) VALUES \
            ('%s','%s','%s',%i,%i)" %
            (fake.first_name(), fake.last_name(),
             str(fake.date_time_this_year()), random.randint(
                 60, 6000), random.randint(1, 5)))
Ejemplo n.º 25
0
 def setUpTestData(cls):  # noqa
     super().setUpTestData()
     fake = Faker()
     cls.entry = factories.EntryFactory(published=True)
     cls.unpublished = factories.EntryFactory(published=False)
     cls.future = factories.EntryFactory(
         published=True,
         publication_date=fake.date_time_this_year(before_now=False,
                                                   after_now=True,
                                                   tzinfo=pytz.utc))
Ejemplo n.º 26
0
def generate_entries(how_many=10):
    fake = Faker()

    for i in range(how_many):
        post = Entry(title=fake.sentence(),
                     body='\n'.join(fake.paragraphs(15)),
                     pub_date=fake.date_time_this_year(),
                     is_published=True)
        db.session.add(post)
    db.session.commit()
Ejemplo n.º 27
0
def forge_data(count):
    from faker import Faker
    fake = Faker()
    for i in range(count):
        message = {
            "name": fake.name(),
            "body": fake.sentence(),
            "timestamp": fake.date_time_this_year()
        }
        mongo.insert_one(message)
    click.echo('Add %d fake messages.' % count)
Ejemplo n.º 28
0
def fakerdata(count):
    db.drop_all()
    db.create_all()
    fake = Faker()
    click.echo("working...")

    for i in range(count):
        tip = Tips(poster=fake.name(),body=fake.sentence(),posttime=fake.date_time_this_year())
        db.session.add(tip)
    db.session.commit()
    click.echo("Created {} fake tips.".format(count))
Ejemplo n.º 29
0
    def handle(self, *args, **options):
        """Create fake users and statuses for Mowdie."""
        from faker import Faker
        import random
        from django.conf import settings
        from PyMarkovTextGenerator import Markov

        fake = Faker()
        textgen = Markov(prob=True, level=3)
        with open(settings.BASE_DIR + "/../john_carter.txt") as file:
            textgen.parse(file.read())

        def update_text():
            return textgen.generate(
                startf=lambda db: random.choice([x for x in db
                                                 if x[0][0].isupper()]),
                endf=lambda s: len(s) > 120)

        Favorite.objects.all().delete()
        Update.objects.all().delete()
        User.objects.all().delete()

        users = []
        for _ in range(20):
            user = User(username=fake.user_name(),
                        email=fake.email())
            user.set_password("password")
            user.save()
            Profile(user=user).save()
            users.append(user)

        user = User(username="******",
                    email="*****@*****.**",
                    is_staff=True,
                    is_superuser=True)
        user.set_password("password")
        user.save()
        Profile(user=user).save()

        updates = []
        for _ in range(100):
            update = Update(text=update_text(),
                            posted_at=make_aware(fake.date_time_this_year()),
                            user=random.choice(users))
            update.save()
            updates.append(update)

        combos = random.sample([(user, update)
                                for user in users
                                for update in updates], 200)
        for user, update in combos:
            favorite = Favorite(user=user, update=update)
            favorite.save()
Ejemplo n.º 30
0
 def create_questions(self):
     questions = []
     faker = Faker()
     users = Profile.objects.all()
     for i in range(QUESTIONS_COUNT):
         questions.append(
             Question(title=faker.sentence(),
                      text=faker.text(),
                      date_published=faker.date_time_this_year(),
                      is_published=True,
                      author=random.choice(users)))
     Question.objects.bulk_create(questions, QUESTIONS_COUNT)
Ejemplo n.º 31
0
def create_initial_data(apps, schema_editor):
    Category = apps.get_model('shop', 'Category')
    Feature = apps.get_model('shop', 'Feature')
    Product = apps.get_model('shop', 'Product')
    Sale = apps.get_model('shop', 'Sale')

    fake = Faker()

    categories = [
        Category(name='Mens'),
        Category(name='Womens'),
        Category(name='Kids')
    ]
    categories = Category.objects.bulk_create(categories)

    features = [
        Feature(name='Size', value='XS'),
        Feature(name='Size', value='S'),
        Feature(name='Size', value='M'),
        Feature(name='Size', value='L'),
        Feature(name='Size', value='XL'),
    ]
    for _ in range(30):
        features.append(
            Feature(name='Colour',
                    value=fake.color_name(),
                    visible=fake.boolean(chance_of_getting_true=70)))
    features = Feature.objects.bulk_create(features)

    products = []
    for _ in range(30):
        products.append(
            Product(
                name=fake.company(),
                category=random.choice(categories),
                price=fake.pydecimal(left_digits=3,
                                     right_digits=2,
                                     positive=True),
            ))
    products = Product.objects.bulk_create(products)

    for product in products:
        product.features.add(*set(random.choices(features, k=10)))

    sales = []
    for _ in range(1000):
        sales.append(
            Sale(product=random.choice(products),
                 sale_date=fake.date_time_this_year(before_now=True,
                                                    after_now=False,
                                                    tzinfo=timezone.utc)))
    Sale.objects.bulk_create(sales)
Ejemplo n.º 32
0
    def forge(count):
        fake = Faker(locale='zh_CN')
        click.echo('生成中')

        for item in range(count):
            post = Post()
            post.title = fake.sentence(nb_words=20)
            post.time = fake.date_time_this_year()
            post.body = '<p>' + fake.text() + '</p>'
            post.pubPersonId = 1
            db.session.add(post)
        db.session.commit()
        click.echo('Done')
Ejemplo n.º 33
0
Archivo: app.py Proyecto: goodbad3/note
def forge(count):
    db.drop_all()
    db.create_all()
    fake = Faker('zh_CN')
    click.echo('Working...')
    for i in range(count):
        note = Note(title=fake.name(),
                    body=fake.sentence(),
                    timestamp=fake.date_time_this_year())
        db.session.add(note)

    db.session.commit()
    click.echo('Created %d fake notes.' % count)
Ejemplo n.º 34
0
def forge(count):
    from faker import Faker
    db.drop_all()
    db.create_all()
    fake = Faker("zh_CN")
    click.echo("working ...")
    for i in range(count):
        message = Message(name=fake.name(),
                          body=fake.sentence(),
                          timestamp=fake.date_time_this_year())
        db.session.add(message)
    db.session.commit()
    click.echo("create %d fake message" % count)
Ejemplo n.º 35
0
def generate_bookmarks():
    from faker import Faker
    import random
    fake = Faker()
    count = 1
    for _ in range(300):
        bookmark = Bookmark(title='bookmark{}'.format(count),
                            comment='Comment{}'.format(count),
                            longurl=fake.url(),
                            modified=fake.date_time_this_year(),
                            user=random.choice(User.objects.all()))
        bookmark.generate_short()
        bookmark.save()
        count += 1
Ejemplo n.º 36
0
def generate_answers():
    import json
    from faker import Faker
    import random
    fake = Faker()
    answers = []
    for _ in range(50):
        answer = {'fields':{'text':fake.bs(),
                            'timestamp':str(fake.date_time_this_year()),
                            'user': random.choice(range(1,51)),
                            'question':random.choice(range(1,51))
                            },
                    'model':'box.Answers',}
        answers.append(answer)
    with open('./box/fixtures/answers.json', 'w') as f:
        f.write(json.dumps(answers))
Ejemplo n.º 37
0
    def handle(self, *args, **options):
        """Create fake users and statuses for Mowdie."""
        from faker import Faker
        import random
        from django.conf import settings
        from PyMarkovTextGenerator import Markov

        fake = Faker()
        textgen = Markov(prob=True, level=3)
        with open(settings.BASE_DIR + "/../john_carter.txt") as file:
            textgen.parse(file.read())

        def update_text():
            return textgen.generate(
                startf=lambda db: random.choice([x for x in db if x[0][0].isupper()]), endf=lambda s: len(s) > 120
            )

        Favorite.objects.all().delete()
        Update.objects.all().delete()
        User.objects.all().delete()

        users = []
        for _ in range(20):
            user = User(username=fake.user_name(), email=fake.email())
            user.set_password("password")
            user.save()
            Profile(user=user).save()
            users.append(user)

        user = User(username="******", email="*****@*****.**", is_staff=True, is_superuser=True)
        user.set_password("password")
        user.save()
        Profile(user=user).save()

        updates = []
        for _ in range(100):
            update = Update(
                text=update_text(), posted_at=make_aware(fake.date_time_this_year()), user=random.choice(users)
            )
            update.save()
            updates.append(update)

        combos = random.sample([(user, update) for user in users for update in updates], 200)
        for user, update in combos:
            favorite = Favorite(user=user, update=update)
            favorite.save()
Ejemplo n.º 38
0
 def handle(self, *args, **options):
     fake = Faker()
     # 2. Make some fake worms
     for _ in range(6000):
         while True:
             slink = fake.password(length=7, special_chars=False)
             if len(Worm.objects.filter(slink=slink)) == 0:
                 worm = Worm(
                     user=choice(User.objects.all()),
                     flink=fake.image_url(),
                     slink=slink,
                     timestamp=make_aware(fake.date_time_this_year()),
                     wtitle=fake.text(max_nb_chars=100),
                     winfo=fake.text(max_nb_chars=255))
                 worm.save()
                 break
             continue
Ejemplo n.º 39
0
def generate_questions():
    import json
    from faker import Faker
    import random
    from .list_gen import q_list
    fake = Faker()
    questions=[]
    for x in range(50):
        question = {'fields':{'title':q_list[x],
                            'text':fake.bs(),
                            'timestamp':str(fake.date_time_this_year()),
                            'user': random.choice(range(1,51)),
                            },
                    'model':'box.Question',}
        questions.append(question)
    with open('./box/fixtures/questions.json', 'w') as f:
        f.write(json.dumps(questions))
Ejemplo n.º 40
0
def make_fake_data(num_activities=50):
    from faker import Faker
    from random import randint
    fake = Faker()

    # if delete_all:
    #     Activity.objects.all().delete()
    #     Stat.objects.all().delete()

    for _ in range(num_activities):
        a = Activity(act_title=fake.bs().title(), act_description=fake.text(max_nb_chars=200))
        a.created_on = fake.date_time_this_year()
        a.save()

        for __ in range(10):
            s = Stat(count=randint(1, 101), activity=a)
            s.created_on = fake.date_time_this_month(before_now=True, after_now=False)
            s.save()
Ejemplo n.º 41
0
def fake():
    bmnum = 100
    pfnum = 10

    tags = ['terrible', 'great', 'smelly', 'sad', 'bright', 'too bright', 'gnarly',\
            'awesome', 'happy', 'tremendous']
    faker = Faker()

    for item in tags:
        Tag.objects.create(name=item)

    tags = list(Tag.objects.all())
    for _ in range(bmnum):
        bm = Bookmark.objects.create(title=faker.name(), description=faker.address(), \
                                     _url=faker.url())
        for _ in range(3):
            bm.tag_set.add(random.choice(tags))

    bms = list(Bookmark.objects.all())
    hashid = Hashids(salt='Moddey Dhoo')
    for idx in range(pfnum):
        bm = [bms.pop(random.randint(0, bmnum - idx*10 - idx2 - 1)) for idx2 in range(10)]
        pf = Profile.objects.create(username=faker.name(), description=faker.text())
        for item in bm:
            item.profile = pf
            item.save()
            item.short = hashid.encode(item.id, pf.id)
            item.timestamp = datetime.datetime.utcnow() + datetime.timedelta(weeks=-52)
            item.timestamp = item.timestamp.replace(tzinfo=datetime.timezone(offset=datetime.timedelta()))
            item.save()

    pfs = list(Profile.objects.all())

    bms = list(Bookmark.objects.all())

    for item in bms:
        num = random.randint(1,10)
        for idx in range(num):
            pf = random.choice(pfs)
            timestamp = faker.date_time_this_year().replace(tzinfo=datetime.timezone(offset=datetime.timedelta()))
            item.click_set.create(profile=pf, timestamp=timestamp)

            item.save()
Ejemplo n.º 42
0
def generate_datapoints():
    import json
    from faker import Faker
    import random
    fake = Faker()
    datapoints = []
    for _ in range(500):
    #     datapoint = {'fields':{'value':random.randint(1,100),
    #                         'timestamp':str(fake.date_time_this_year())[:10],
    #                         'activity': random.choice(range(1,100))
    #                         },
    #                 'model':'api.DataPoint',}
    #     print(datapoint)
    #     datapoints.append(datapoint)
    # with open('datapoints.json', 'w') as f:
    #     f.write(json.dumps(datapoints))
        datapoint = DataPoint(value=random.randint(1,100),
                          timestamp=str(fake.date_time_this_year())[:10],
                          activity = random.choice(Activity.objects.all()))
        datapoint.save()
        print(datapoint)
Ejemplo n.º 43
0
    def handle(self, *args, **options):
        '''Create some fake users and statuses'''
        fake = Faker()

        Favorite.objects.all().delete()
        Status.objects.all().delete()
        Profile.objects.all().delete()
        User.objects.all().delete()

        User.objects.create_superuser(username='******', password='******', email='')

        users = []
        statuses = []

        for _ in range(50):
            new_user = User(username=fake.user_name(),
                            email=fake.email())
            new_user.set_password('password')
            new_user.save()
            profile = Profile(user=new_user, favorite_color='blue')
            profile.save()
            users.append(new_user)

        for _ in range(1000):
            new_status = Status(user=random.choice(users),
                                posted_at=make_aware(fake.date_time_this_year()),
                                text=fake.text(max_nb_chars=141))
            new_status.save()
            statuses.append(new_status)

        for _ in range(4000):
            try:
                favorite = Favorite(user=random.choice(users),
                                    status=random.choice(statuses))
                favorite.save()
            except IntegrityError:
                continue
Ejemplo n.º 44
0
def load_fake_data():
    '''Create some fake users and statuses'''

    from faker import Faker
    import random

    fake = Faker()

    Favorite.objects.all().delete()
    Status.objects.all().delete()
    User.objects.exclude(username='******').delete()

    users = []
    statuses = []

    for _ in range(50):
        new_user = User(username=fake.user_name(),
                        email=fake.email(),
                        password=fake.password())
        new_user.save()
        users.append(new_user)

    for _ in range(1000):
        new_status = Status(user=random.choice(users),
                            posted_at=fake.date_time_this_year(),
                            text=fake.text(max_nb_chars=141))
        new_status.save()
        statuses.append(new_status)

    for _ in range(4000):
        try:
            favorite = Favorite(user=random.choice(users),
                                status=random.choice(statuses))
            favorite.save()
        except IntegrityError:
            continue
        prod['unit_price'] = prod_unitprice
        prod['product_lead_time'] = int(random.uniform(1, 30))
        prod['minimum_order_quantity'] = prod_min_ord_qty
        prod['maximum_order_quantity'] = prod_max_ord_qty
        prod['average_monthly_usage'] = int(random.uniform(150, 700))
        products[i] = prod

    flag = True
    while (flag):


        store = random.choice(stores)
        product = random.choice(products)

        order = {}
        order['order_date_time'] = str(faker.date_time_this_year(before_now=True, after_now=False))
        order['store_id'] = store['id']
        order['store_zip'] = store['zip']

        for case in switch(order['store_zip']):
            if case('55328'):
                order['store_lat'] = '45.041472'
                order['store_lon'] = '-93.97792'
                order['store_city'] = 'Delano'
                order['store_state'] = 'MN'
                break
            if case('55395'):
                order['store_lat'] = '44.946121'
                order['store_lon'] = '-94.07572'
                order['store_city'] = 'Winsted'
                order['store_state'] = 'MN'
Ejemplo n.º 46
0
class TestDateTime(unittest.TestCase):

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

    def assertBetween(self, date, start_date, end_date):
        self.assertTrue(date <= end_date)
        self.assertTrue(date >= start_date)

    def test_day(self):
        day = self.factory.day_of_week()
        assert isinstance(day, string_types)

    def test_month(self):
        month = self.factory.month()
        assert isinstance(month, string_types)

    def test_past_datetime(self):
        past_datetime = self.factory.past_datetime()
        self.assertTrue(past_datetime < datetime.now())

    def test_past_date(self):
        past_date = self.factory.past_date()
        self.assertTrue(past_date < date.today())

    def test_future_datetime(self):
        future_datetime, now = self.factory.future_datetime(), datetime.now()
        self.assertTrue(future_datetime > now)

    def test_future_date(self):
        future_date = self.factory.future_date()
        self.assertTrue(future_date > date.today())

    def test_parse_date_time(self):
        timestamp = DatetimeProvider._parse_date_time('+30d')
        now = DatetimeProvider._parse_date_time('now')
        self.assertTrue(timestamp > now)
        delta = timedelta(days=-30)
        from_delta = DatetimeProvider._parse_date_time(delta)
        from_int = DatetimeProvider._parse_date_time(30)

        self.assertEqual(datetime.fromtimestamp(from_delta).date(),
                         datetime.fromtimestamp(timestamp).date())

        self.assertEqual(datetime.fromtimestamp(from_int).date(),
                         datetime.fromtimestamp(timestamp).date())

    def test_parse_date(self):
        parsed = DatetimeProvider._parse_date('+30d')
        now = DatetimeProvider._parse_date('now')
        today = DatetimeProvider._parse_date('today')
        self.assertIsInstance(parsed, date)
        self.assertIsInstance(now, date)
        self.assertIsInstance(today, date)
        self.assertEqual(today, date.today())
        self.assertEqual(now, today)
        self.assertEqual(parsed, today + timedelta(days=30))
        self.assertEqual(DatetimeProvider._parse_date(datetime.now()), today)
        self.assertEqual(DatetimeProvider._parse_date(parsed), parsed)
        self.assertEqual(DatetimeProvider._parse_date(30), parsed)
        self.assertEqual(DatetimeProvider._parse_date(timedelta(days=-30)), parsed)

    def test_timezone_conversion(self):
        from faker.providers.date_time import datetime_to_timestamp

        now = datetime.now(utc).replace(microsecond=0)
        timestamp = datetime_to_timestamp(now)
        now_back = datetime.fromtimestamp(timestamp, utc)
        self.assertEqual(now, now_back)

        today = date.today()
        timestamp = datetime_to_timestamp(today)
        today_back = datetime.fromtimestamp(timestamp, utc).date()
        self.assertEqual(today, today_back)

    def test_datetime_safe(self):
        from faker.utils import datetime_safe
        # test using example provided in module
        result = datetime_safe.date(1850, 8, 2).strftime('%Y/%m/%d was a %A')
        self.assertEqual(result, '1850/08/02 was a Friday')
        # test against certain formatting strings used on pre-1900 dates
        with self.assertRaises(TypeError):
            datetime_safe.date(1850, 8, 2).strftime('%s')
        with self.assertRaises(TypeError):
            datetime_safe.date(1850, 8, 2).strftime('%y')
        # test using 29-Feb-2012 and escaped percentage sign
        result = datetime_safe.date(2012, 2, 29).strftime('%Y-%m-%d was a 100%% %A')
        self.assertEqual(result, r'2012-02-29 was a 100% Wednesday')
        # test that certain formatting strings are allowed on post-1900 dates
        result = datetime_safe.date(2008, 2, 29).strftime('%y')
        self.assertEqual(result, r'08')

    def test_datetime_safe_new_date(self):
        from faker.utils import datetime_safe
        d = datetime_safe.date(1850, 8, 2)
        result = datetime_safe.new_date(d)
        self.assertEqual(result, date(1850, 8, 2))

    def test_datetimes_with_and_without_tzinfo(self):
        self.assertEqual(self.factory.date_time().tzinfo, None)
        self.assertEqual(self.factory.date_time(utc).tzinfo, utc)

        self.assertEqual(self.factory.date_time_ad().tzinfo, None)
        self.assertEqual(self.factory.date_time_ad(utc).tzinfo, utc)

        self.assertFalse(self.factory.iso8601().endswith('+00:00'))
        self.assertTrue(self.factory.iso8601(utc).endswith('+00:00'))

    def test_date_object(self):
        self.assertIsInstance(self.factory.date_object(), date)

    def test_time_object(self):
        self.assertIsInstance(self.factory.time_object(), datetime_time)

    def test_date_time_between_dates(self):
        timestamp_start = random.randint(0, 2000000000)
        timestamp_end = timestamp_start + 1

        datetime_start = datetime.fromtimestamp(timestamp_start)
        datetime_end = datetime.fromtimestamp(timestamp_end)

        random_date = self.factory.date_time_between_dates(datetime_start, datetime_end)
        self.assertTrue(datetime_start <= random_date)
        self.assertTrue(datetime_end >= random_date)

    def test_date_time_between_dates_with_tzinfo(self):
        timestamp_start = random.randint(0, 2000000000)
        timestamp_end = timestamp_start + 1

        datetime_start = datetime.fromtimestamp(timestamp_start, utc)
        datetime_end = datetime.fromtimestamp(timestamp_end, utc)

        random_date_naive = self.factory.date_time_between_dates(datetime_start, datetime_end)
        with self.assertRaises(TypeError):
            datetime_start <= random_date_naive

        random_date = self.factory.date_time_between_dates(datetime_start, datetime_end, utc)
        self.assertTrue(datetime_start <= random_date)
        self.assertTrue(datetime_end >= random_date)

    def test_date_between_dates(self):
        date_end = date.today()
        date_start = date_end - timedelta(days=10)

        random_date = self.factory.date_between_dates(date_start, date_end)
        self.assertTrue(date_start <= random_date)
        self.assertTrue(date_end >= random_date)

    def _datetime_to_time(self, value):
        return int(time.mktime(value.timetuple()))

    def test_date_time_this_period(self):
        # test century
        self.assertTrue(self._datetime_to_time(self.factory.date_time_this_century(after_now=False)) <= self._datetime_to_time(datetime.now()))
        self.assertTrue(self._datetime_to_time(self.factory.date_time_this_century(before_now=False, after_now=True)) >= self._datetime_to_time(datetime.now()))
        # test decade
        self.assertTrue(self._datetime_to_time(self.factory.date_time_this_decade(after_now=False)) <= self._datetime_to_time(datetime.now()))
        self.assertTrue(self._datetime_to_time(self.factory.date_time_this_decade(before_now=False, after_now=True)) >= self._datetime_to_time(datetime.now()))
        self.assertEqual(
            self._datetime_to_time(self.factory.date_time_this_decade(before_now=False, after_now=False)),
            self._datetime_to_time(datetime.now())
        )
        # test year
        self.assertTrue(self._datetime_to_time(self.factory.date_time_this_year(after_now=False)) <= self._datetime_to_time(datetime.now()))
        self.assertTrue(self._datetime_to_time(self.factory.date_time_this_year(before_now=False, after_now=True)) >= self._datetime_to_time(datetime.now()))
        self.assertEqual(
            self._datetime_to_time(self.factory.date_time_this_year(before_now=False, after_now=False)),
            self._datetime_to_time(datetime.now())
        )
        # test month
        self.assertTrue(self._datetime_to_time(self.factory.date_time_this_month(after_now=False)) <= self._datetime_to_time(datetime.now()))
        self.assertTrue(self._datetime_to_time(self.factory.date_time_this_month(before_now=False, after_now=True)) >= self._datetime_to_time(datetime.now()))
        self.assertEqual(
            self._datetime_to_time(self.factory.date_time_this_month(before_now=False, after_now=False)),
            self._datetime_to_time(datetime.now())
        )

    def test_date_time_this_period_with_tzinfo(self):
        # ensure all methods provide timezone aware datetimes
        with self.assertRaises(TypeError):
            self.factory.date_time_this_century(before_now=False, after_now=True, tzinfo=utc) >= datetime.now()
        with self.assertRaises(TypeError):
            self.factory.date_time_this_decade(after_now=False, tzinfo=utc) <= datetime.now()
        with self.assertRaises(TypeError):
            self.factory.date_time_this_year(after_now=False, tzinfo=utc) <= datetime.now()
        with self.assertRaises(TypeError):
            self.factory.date_time_this_month(after_now=False, tzinfo=utc) <= datetime.now()

        # test century
        self.assertTrue(self.factory.date_time_this_century(after_now=False, tzinfo=utc) <= datetime.now(utc))
        self.assertTrue(self.factory.date_time_this_century(before_now=False, after_now=True, tzinfo=utc) >= datetime.now(utc))
        # test decade
        self.assertTrue(self.factory.date_time_this_decade(after_now=False, tzinfo=utc) <= datetime.now(utc))
        self.assertTrue(self.factory.date_time_this_decade(before_now=False, after_now=True, tzinfo=utc) >= datetime.now(utc))

        self.assertEqual(
            self.factory.date_time_this_decade(before_now=False, after_now=False, tzinfo=utc).replace(second=0, microsecond=0),
            datetime.now(utc).replace(second=0, microsecond=0)
        )
        # test year
        self.assertTrue(self.factory.date_time_this_year(after_now=False, tzinfo=utc) <= datetime.now(utc))
        self.assertTrue(self.factory.date_time_this_year(before_now=False, after_now=True, tzinfo=utc) >= datetime.now(utc))
        self.assertEqual(
            self.factory.date_time_this_year(before_now=False, after_now=False, tzinfo=utc).replace(second=0, microsecond=0),
            datetime.now(utc).replace(second=0, microsecond=0)
        )
        # test month
        self.assertTrue(self.factory.date_time_this_month(after_now=False, tzinfo=utc) <= datetime.now(utc))
        self.assertTrue(self.factory.date_time_this_month(before_now=False, after_now=True, tzinfo=utc) >= datetime.now(utc))
        self.assertEqual(
            self.factory.date_time_this_month(before_now=False, after_now=False, tzinfo=utc).replace(second=0, microsecond=0),
            datetime.now(utc).replace(second=0, microsecond=0)
        )

    def test_date_this_period(self):
        # test century
        self.assertTrue(self.factory.date_this_century(after_today=False) <= date.today())
        self.assertTrue(self.factory.date_this_century(before_today=False, after_today=True) >= date.today())
        # test decade
        self.assertTrue(self.factory.date_this_decade(after_today=False) <= date.today())
        self.assertTrue(self.factory.date_this_decade(before_today=False, after_today=True) >= date.today())
        self.assertEqual(
            self.factory.date_this_decade(before_today=False, after_today=False),
            date.today()
        )
        # test year
        self.assertTrue(self.factory.date_this_year(after_today=False) <= date.today())
        self.assertTrue(self.factory.date_this_year(before_today=False, after_today=True) >= date.today())
        self.assertEqual(
            self.factory.date_this_year(before_today=False, after_today=False),
            date.today()
        )
        # test month
        self.assertTrue(self.factory.date_this_month(after_today=False) <= date.today())
        self.assertTrue(self.factory.date_this_month(before_today=False, after_today=True) >= date.today())
        self.assertEqual(
            self.factory.date_this_month(before_today=False, after_today=False),
            datetime.now()
        )

    def test_date_time_between(self):
        now = datetime.now()
        _30_years_ago = now.replace(year=now.year - 30)
        _20_years_ago = now.replace(year=now.year - 20)

        random_datetime = self.factory.date_time_between(start_date='-30y', end_date='-20y')

        self.assertIsInstance(random_datetime, datetime)
        self.assertBetween(random_datetime, _30_years_ago, _20_years_ago)

    def test_date_between(self):
        today = date.today()
        _30_years_ago = today.replace(year=today.year - 30)
        _20_years_ago = today.replace(year=today.year - 20)

        random_date = self.factory.date_between(start_date='-30y', end_date='-20y')

        self.assertIsInstance(random_date, date)
        self.assertBetween(random_date, _30_years_ago, _20_years_ago)

    def test_parse_timedelta(self):
        from faker.providers.date_time import Provider

        td = timedelta(days=7)
        seconds = Provider._parse_timedelta(td)
        self.assertEqual(seconds, 604800.0)

        seconds = Provider._parse_timedelta('+1w')
        self.assertEqual(seconds, 604800.0)

        seconds = Provider._parse_timedelta('+1y')
        self.assertEqual(seconds, 31556736.0)

        with self.assertRaises(ValueError):
            Provider._parse_timedelta('foobar')

    def test_time_series(self):
        series = [i for i in self.factory.time_series()]
        self.assertTrue(len(series), 30)
        self.assertTrue(series[1][0] - series[0][0], timedelta(days=1))

        uniform = lambda dt: random.uniform(0, 5)  # noqa
        series = [i for i in self.factory.time_series('now', '+1w', '+1d', uniform)]
        self.assertTrue(len(series), 7)
        self.assertTrue(series[1][0] - series[0][0], timedelta(days=1))

        end = datetime.now() + timedelta(days=7)
        series = [i for i in self.factory.time_series('now', end, '+1d', uniform)]
        self.assertTrue(len(series), 7)
        self.assertTrue(series[1][0] - series[0][0], timedelta(days=1))

        self.assertTrue(series[-1][0] <= end)

        with self.assertRaises(ValueError):
            [i for i in self.factory.time_series('+1w', 'now', '+1d', uniform)]

        with self.assertRaises(ValueError):
            [i for i in self.factory.time_series('now', '+1w', '+1d', 'uniform')]

        series = [i for i in self.factory.time_series('now', end, '+1d', uniform, tzinfo=utc)]
        self.assertTrue(len(series), 7)
        self.assertTrue(series[1][0] - series[0][0], timedelta(days=1))

        # avoid microseconds as provider's internal parsing uses POSIX timestamps which only have second granularity
        end = datetime.now(utc).replace(microsecond=0)
        start = end - timedelta(days=15)

        series = [i for i in self.factory.time_series(start_date=start, end_date=end, tzinfo=start.tzinfo)]
        self.assertEqual(series[0][0], start)
Ejemplo n.º 47
0
from faker import Faker

fake = Faker()

for x in range(30):
    first = fake.first_name()
    last = fake.last_name()
    name_string = "{}, {} X.".format(last, first)
    email = "{}.{}@arl.org".format(first, last)
    print(
        "INSERT INTO F15A4_emp(employee_name, email, phone, status_effective_date, active, is_sys_admin, is_lab_dir, is_chair, is_exec_dir, F15A4_lab_lab_id, F15A4_auth_auth_id) VALUES('{}', '{}', '{}', TO_DATE('{}','YYYY-MM-DD HH24:MI:SS'));".format(
            name_string,
            email,
            fake.random_number(digits=10),
            fake.date_time_this_year(before_now=True, after_now=False),
        )
    )
Ejemplo n.º 48
0
class TestDateTime(unittest.TestCase):

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

    def assertBetween(self, date, start_date, end_date):
        assert date <= end_date
        assert date >= start_date

    def test_day(self):
        day = self.factory.day_of_week()
        assert isinstance(day, six.string_types)

    def test_month(self):
        month = self.factory.month()
        assert isinstance(month, six.string_types)

    def test_past_datetime(self):
        past_datetime = self.factory.past_datetime()
        assert past_datetime < datetime.now()

    def test_past_date(self):
        past_date = self.factory.past_date()
        assert past_date < date.today()

    def test_future_datetime(self):
        future_datetime, now = self.factory.future_datetime(), datetime.now()
        assert future_datetime > now

    def test_future_date(self):
        future_date = self.factory.future_date()
        assert future_date > date.today()

    def test_parse_date_time(self):
        timestamp = DatetimeProvider._parse_date_time('+30d')
        now = DatetimeProvider._parse_date_time('now')
        assert timestamp > now
        delta = timedelta(days=30)
        from_delta = DatetimeProvider._parse_date_time(delta)
        from_int = DatetimeProvider._parse_date_time(30)

        assert datetime.fromtimestamp(from_delta).date() == (
                         datetime.fromtimestamp(timestamp).date())

        assert datetime.fromtimestamp(from_int).date() == (
                         datetime.fromtimestamp(timestamp).date())

    def test_parse_date(self):
        parsed = DatetimeProvider._parse_date('+30d')
        now = DatetimeProvider._parse_date('now')
        today = DatetimeProvider._parse_date('today')
        assert isinstance(parsed, date)
        assert isinstance(now, date)
        assert isinstance(today, date)
        assert today == date.today()
        assert now == today
        assert parsed == today + timedelta(days=30)
        assert DatetimeProvider._parse_date(datetime.now()) == today
        assert DatetimeProvider._parse_date(parsed) == parsed
        assert DatetimeProvider._parse_date(30) == parsed
        assert DatetimeProvider._parse_date(timedelta(days=30)) == parsed

    def test_timezone_conversion(self):
        from faker.providers.date_time import datetime_to_timestamp

        now = datetime.now(utc).replace(microsecond=0)
        timestamp = datetime_to_timestamp(now)
        now_back = datetime.fromtimestamp(timestamp, utc)
        assert now == now_back

        today = date.today()
        timestamp = datetime_to_timestamp(today)
        today_back = datetime.fromtimestamp(timestamp, utc).date()
        assert today == today_back

    def test_datetime_safe(self):
        from faker.utils import datetime_safe
        # test using example provided in module
        result = datetime_safe.date(1850, 8, 2).strftime('%Y/%m/%d was a %A')
        assert result == '1850/08/02 was a Friday'
        # test against certain formatting strings used on pre-1900 dates
        with pytest.raises(TypeError):
            datetime_safe.date(1850, 8, 2).strftime('%s')
        with pytest.raises(TypeError):
            datetime_safe.date(1850, 8, 2).strftime('%y')
        # test using 29-Feb-2012 and escaped percentage sign
        result = datetime_safe.date(2012, 2, 29).strftime('%Y-%m-%d was a 100%% %A')
        assert result == r'2012-02-29 was a 100% Wednesday'
        # test that certain formatting strings are allowed on post-1900 dates
        result = datetime_safe.date(2008, 2, 29).strftime('%y')
        assert result == r'08'

    def test_datetime_safe_new_date(self):
        from faker.utils import datetime_safe
        d = datetime_safe.date(1850, 8, 2)
        result = datetime_safe.new_date(d)
        assert result == date(1850, 8, 2)

    def test_datetimes_with_and_without_tzinfo(self):
        assert self.factory.date_time().tzinfo is None
        assert self.factory.date_time(utc).tzinfo == utc

        assert self.factory.date_time_ad().tzinfo is None
        assert self.factory.date_time_ad(utc).tzinfo == utc

        assert not self.factory.iso8601().endswith('+00:00')
        assert self.factory.iso8601(utc).endswith('+00:00')

    def test_date_object(self):
        assert isinstance(self.factory.date_object(), date)

    def test_time_object(self):
        assert isinstance(self.factory.time_object(), datetime_time)

    def test_timedelta(self):
        delta = self.factory.time_delta(end_datetime=timedelta(seconds=60))
        assert delta.seconds <= 60

        delta = self.factory.time_delta(end_datetime=timedelta(seconds=-60))
        assert delta.seconds >= -60

        delta = self.factory.time_delta(end_datetime='+60s')
        assert delta.seconds <= 60

        delta = self.factory.time_delta(end_datetime='-60s')
        assert delta.seconds >= 60

        delta = self.factory.time_delta(end_datetime='now')
        assert delta.seconds <= 0

    def test_date_time_between_dates(self):
        timestamp_start = random.randint(0, 2000000000)
        timestamp_end = timestamp_start + 1

        datetime_start = datetime.fromtimestamp(timestamp_start)
        datetime_end = datetime.fromtimestamp(timestamp_end)

        random_date = self.factory.date_time_between_dates(datetime_start, datetime_end)
        assert datetime_start <= random_date
        assert datetime_end >= random_date

    def test_date_time_between_dates_with_tzinfo(self):
        timestamp_start = random.randint(0, 2000000000)
        timestamp_end = timestamp_start + 1

        datetime_start = datetime.fromtimestamp(timestamp_start, utc)
        datetime_end = datetime.fromtimestamp(timestamp_end, utc)

        random_date_naive = self.factory.date_time_between_dates(datetime_start, datetime_end)
        with pytest.raises(TypeError):
            datetime_start <= random_date_naive

        random_date = self.factory.date_time_between_dates(datetime_start, datetime_end, utc)
        assert datetime_start <= random_date
        assert datetime_end >= random_date

    def test_past_datetime_within_second(self):
        # Should not raise a ``ValueError``
        self.factory.past_datetime(start_date='+1s')

    def test_date_between_dates(self):
        date_end = date.today()
        date_start = date_end - timedelta(days=10)

        random_date = self.factory.date_between_dates(date_start, date_end)
        assert date_start <= random_date
        assert date_end >= random_date

    def _datetime_to_time(self, value):
        return int(time.mktime(value.timetuple()))

    @unittest.skipUnless(is64bit(), "requires 64bit")
    def test_date_time_this_period(self):
        # test century
        this_century_start = self._datetime_to_time(
            datetime(datetime.now().year - (datetime.now().year % 100), 1, 1),
        )

        assert (
            self._datetime_to_time(self.factory.date_time_this_century(after_now=False)) <=
            self._datetime_to_time(datetime.now())
        )
        assert (
            self._datetime_to_time(self.factory.date_time_this_century(before_now=False, after_now=True)) >=
            self._datetime_to_time(datetime.now())
        )
        assert (
            self._datetime_to_time(self.factory.date_time_this_century(before_now=True, after_now=True)) >=
            this_century_start
        )

        # test decade
        this_decade_start = self._datetime_to_time(
            datetime(datetime.now().year - (datetime.now().year % 10), 1, 1),
        )

        assert (
            self._datetime_to_time(self.factory.date_time_this_decade(after_now=False)) <=
            self._datetime_to_time(datetime.now())
        )
        assert (
            self._datetime_to_time(self.factory.date_time_this_decade(before_now=False, after_now=True)) >=
            self._datetime_to_time(datetime.now())
        )
        assert (
            self._datetime_to_time(self.factory.date_time_this_decade(before_now=False, after_now=False)) ==
            self._datetime_to_time(datetime.now())
        )
        assert (
            self._datetime_to_time(self.factory.date_time_this_decade(before_now=True, after_now=True)) >=
            this_decade_start
        )
        # test year
        assert (
            self._datetime_to_time(self.factory.date_time_this_year(after_now=False)) <=
            self._datetime_to_time(datetime.now())
        )
        assert (
            self._datetime_to_time(self.factory.date_time_this_year(before_now=False, after_now=True)) >=
            self._datetime_to_time(datetime.now())
        )
        assert (
            self._datetime_to_time(self.factory.date_time_this_year(before_now=False, after_now=False)) ==
            self._datetime_to_time(datetime.now())
        )
        # test month
        assert (
            self._datetime_to_time(self.factory.date_time_this_month(after_now=False)) <=
            self._datetime_to_time(datetime.now())
        )
        assert (
            self._datetime_to_time(self.factory.date_time_this_month(before_now=False, after_now=True)) >=
            self._datetime_to_time(datetime.now())
        )
        assert (
            self._datetime_to_time(self.factory.date_time_this_month(before_now=False, after_now=False)) ==
            self._datetime_to_time(datetime.now())
        )

    @unittest.skipUnless(is64bit(), "requires 64bit")
    def test_date_time_this_period_with_tzinfo(self):
        # ensure all methods provide timezone aware datetimes
        with pytest.raises(TypeError):
            self.factory.date_time_this_century(before_now=False, after_now=True, tzinfo=utc) >= datetime.now()
        with pytest.raises(TypeError):
            self.factory.date_time_this_decade(after_now=False, tzinfo=utc) <= datetime.now()
        with pytest.raises(TypeError):
            self.factory.date_time_this_year(after_now=False, tzinfo=utc) <= datetime.now()
        with pytest.raises(TypeError):
            self.factory.date_time_this_month(after_now=False, tzinfo=utc) <= datetime.now()

        # test century
        assert self.factory.date_time_this_century(after_now=False, tzinfo=utc) <= datetime.now(utc)
        assert self.factory.date_time_this_century(before_now=False, after_now=True, tzinfo=utc) >= datetime.now(utc)
        # test decade
        assert self.factory.date_time_this_decade(after_now=False, tzinfo=utc) <= datetime.now(utc)
        assert self.factory.date_time_this_decade(before_now=False, after_now=True, tzinfo=utc) >= datetime.now(utc)

        assert (
            self.factory.date_time_this_decade(before_now=False, after_now=False, tzinfo=utc).
            replace(second=0, microsecond=0) == datetime.now(utc).replace(second=0, microsecond=0)
        )
        # test year
        assert self.factory.date_time_this_year(after_now=False, tzinfo=utc) <= datetime.now(utc)
        assert self.factory.date_time_this_year(before_now=False, after_now=True, tzinfo=utc) >= datetime.now(utc)
        assert (
            self.factory.date_time_this_year(before_now=False, after_now=False, tzinfo=utc).
            replace(second=0, microsecond=0) == datetime.now(utc).replace(second=0, microsecond=0)
        )
        # test month
        assert self.factory.date_time_this_month(after_now=False, tzinfo=utc) <= datetime.now(utc)
        assert self.factory.date_time_this_month(before_now=False, after_now=True, tzinfo=utc) >= datetime.now(utc)
        assert (
            self.factory.date_time_this_month(before_now=False, after_now=False, tzinfo=utc).
            replace(second=0, microsecond=0) == datetime.now(utc).replace(second=0, microsecond=0)
        )

    @unittest.skipUnless(is64bit(), "requires 64bit")
    def test_date_this_period(self):
        # test century
        assert self.factory.date_this_century(after_today=False) <= date.today()
        assert self.factory.date_this_century(before_today=False, after_today=True) >= date.today()
        # test decade
        assert self.factory.date_this_decade(after_today=False) <= date.today()
        assert self.factory.date_this_decade(before_today=False, after_today=True) >= date.today()
        assert (
            self.factory.date_this_decade(before_today=False, after_today=False)) == (
            date.today()
        )
        # test year
        assert self.factory.date_this_year(after_today=False) <= date.today()
        assert self.factory.date_this_year(before_today=False, after_today=True) >= date.today()
        assert (
            self.factory.date_this_year(before_today=False, after_today=False)) == (
            date.today()
        )
        # test month
        assert self.factory.date_this_month(after_today=False) <= date.today()
        assert self.factory.date_this_month(before_today=False, after_today=True) >= date.today()
        assert (
            self.factory.date_this_month(before_today=False, after_today=False)) == (
            datetime.now()
        )

    def test_date_time_between(self):
        now = datetime.now()
        _30_years_ago = now.replace(year=now.year - 30)
        _20_years_ago = now.replace(year=now.year - 20)

        random_datetime = self.factory.date_time_between(start_date='-30y', end_date='-20y')

        assert isinstance(random_datetime, datetime)
        self.assertBetween(random_datetime, _30_years_ago, _20_years_ago)

    def test_date_between(self):
        today = date.today()
        _30_years_ago = today.replace(year=today.year - 30)
        _20_years_ago = today.replace(year=today.year - 20)

        random_date = self.factory.date_between(start_date='-30y', end_date='-20y')

        assert isinstance(random_date, date)
        self.assertBetween(random_date, _30_years_ago, _20_years_ago)

    def test_date_between_months(self):
        today = date.today()
        _2_months_ago = today - timedelta(days=2 * (365.24/12))
        _9_months_ago = today - timedelta(days=9 * (365.24/12))

        random_date = self.factory.date_between(start_date='-9M', end_date='-2M')

        assert isinstance(random_date, date)
        self.assertBetween(random_date, _9_months_ago, _2_months_ago)

    def test_parse_timedelta(self):
        from faker.providers.date_time import Provider

        td = timedelta(days=7)
        seconds = Provider._parse_timedelta(td)
        assert seconds == 604800.0

        seconds = Provider._parse_timedelta('+1w')
        assert seconds == 604800.0

        seconds = Provider._parse_timedelta('+1y')
        assert seconds == 31556736.0

        with pytest.raises(ValueError):
            Provider._parse_timedelta('foobar')

    def test_time_series(self):
        series = [i for i in self.factory.time_series()]
        assert len(series), 30
        assert series[1][0] - series[0][0], timedelta(days=1)

        uniform = lambda dt: random.uniform(0, 5)  # noqa
        series = [i for i in self.factory.time_series('now', '+1w', '+1d', uniform)]
        assert len(series), 7
        assert series[1][0] - series[0][0], timedelta(days=1)

        end = datetime.now() + timedelta(days=7)
        series = [i for i in self.factory.time_series('now', end, '+1d', uniform)]
        assert len(series), 7
        assert series[1][0] - series[0][0], timedelta(days=1)

        assert series[-1][0] <= end

        with pytest.raises(ValueError):
            [i for i in self.factory.time_series('+1w', 'now', '+1d', uniform)]

        with pytest.raises(ValueError):
            [i for i in self.factory.time_series('now', '+1w', '+1d', 'uniform')]

        series = [i for i in self.factory.time_series('now', end, '+1d', uniform, tzinfo=utc)]
        assert len(series), 7
        assert series[1][0] - series[0][0], timedelta(days=1)

        # avoid microseconds as provider's internal parsing uses POSIX timestamps which only have second granularity
        end = datetime.now(utc).replace(microsecond=0)
        start = end - timedelta(days=15)

        series = [i for i in self.factory.time_series(start_date=start, end_date=end, tzinfo=start.tzinfo)]
        assert series[0][0] == start

    def test_unix_time(self):
        from faker.providers.date_time import datetime_to_timestamp

        for _ in range(100):
            now = datetime.now(utc).replace(microsecond=0)
            epoch_start = datetime(1970, 1, 1, tzinfo=utc)

            # Ensure doubly-constrained unix_times are generated correctly
            start_datetime = datetime(2001, 1, 1, tzinfo=utc)
            end_datetime = datetime(2001, 1, 2, tzinfo=utc)

            constrained_unix_time = self.factory.unix_time(end_datetime=end_datetime, start_datetime=start_datetime)

            self.assertIsInstance(constrained_unix_time, int)
            self.assertBetween(
                constrained_unix_time,
                datetime_to_timestamp(start_datetime),
                datetime_to_timestamp(end_datetime),
            )

            # Ensure relative unix_times partially-constrained by a start time are generated correctly
            one_day_ago = datetime.today()-timedelta(days=1)

            recent_unix_time = self.factory.unix_time(start_datetime=one_day_ago)

            self.assertIsInstance(recent_unix_time, int)
            self.assertBetween(recent_unix_time, datetime_to_timestamp(one_day_ago), datetime_to_timestamp(now))

            # Ensure relative unix_times partially-constrained by an end time are generated correctly
            one_day_after_epoch_start = datetime(1970, 1, 2, tzinfo=utc)

            distant_unix_time = self.factory.unix_time(end_datetime=one_day_after_epoch_start)

            self.assertIsInstance(distant_unix_time, int)
            self.assertBetween(
                distant_unix_time,
                datetime_to_timestamp(epoch_start),
                datetime_to_timestamp(one_day_after_epoch_start),
            )

            # Ensure wide-open unix_times are generated correctly
            self.factory.unix_time()

            self.assertIsInstance(constrained_unix_time, int)
            self.assertBetween(constrained_unix_time, 0, datetime_to_timestamp(now))