示例#1
0
 def complete_details_with_not_lived_abroad_option(self, first_name, last_name):
     driver = self.web_util.get_driver()
     page_title = "Register as a nanny"
     self.web_util.wait_until_page_load(page_title)
     self.assertEqual("To do", driver.find_element_by_xpath("//tr[@id='personal_details']/td/a/strong").text)
     self.web_util.click_element_by_xpath("//tr[@id='personal_details']/td/a/span")
     self.web_util.click_element_by_id("id_first_name")
     self.web_util.send_keys_by_id("id_first_name", first_name)
     self.web_util.send_keys_by_id("id_middle_names", "MiddleName")
     self.web_util.send_keys_by_id("id_last_name", last_name)
     self.web_util.click_element_by_name("action")
     self.web_util.send_keys_by_id("id_date_of_birth_0", random.randint(1, 28))
     self.web_util.send_keys_by_id("id_date_of_birth_1", random.randint(1, 12))
     self.web_util.send_keys_by_id("id_date_of_birth_2", random.randint(1950, 1990))
     self.web_util.click_element_by_name("action")
     self.web_util.click_element_by_id("manual")
     self.web_util.send_keys_by_id("id_street_line1", "AddressLine1")
     self.web_util.send_keys_by_id("id_street_line2", "Line2")
     self.web_util.send_keys_by_id("id_town", "Town")
     self.web_util.send_keys_by_id("id_county", "County")
     self.web_util.send_keys_by_id("id_postcode", "WA14 4PA")
     self.web_util.click_element_by_xpath("//input[@value='Save and continue']")
     self.web_util.click_element_by_name("action")
     self.web_util.click_element_by_id("id_lived_abroad_1")
     self.web_util.click_element_by_name("action")
     self.web_util.assert_page_title("Check your answers: your personal details")
     self.web_util.click_element_by_xpath("//input[@value='Confirm and continue']")
     self.web_util.wait_until_page_load(page_title)
     self.assertEqual("Done", driver.find_element_by_xpath("//tr[@id='personal_details']/td/a/strong").text)
示例#2
0
 def ipv4(self, network=False):
     """ Produce a random IPv4 address or network with a valid CIDR. """
     address = str(ip_address(random.randint(0, (2**IPV4LENGTH) - 1)))
     if network:
         address += '/' + str(random.randint(0, IPV4LENGTH))
         address = str(ip_network(address, strict=False))
     return address
示例#3
0
文件: __init__.py 项目: 4sp1r3/faker
    def firefox(cls):
        ver = (
            'Gecko/{0} Firefox/{1}.0'.format(
                DatetimeProvider.date_time_between(
                    datetime(2011, 1, 1)), random.randint(4, 15)),
            'Gecko/{0} Firefox/3.6.{1}'.format(
                DatetimeProvider.date_time_between(
                    datetime(2010, 1, 1)), random.randint(1, 20)),
            'Gecko/{0} Firefox/3.8'.format(
                DatetimeProvider.date_time_between(
                    datetime(2010, 1, 1)), ),
        )
        tmplt_win = '({0}; {1}; rv:1.9.{2}.20) {3}'
        tmplt_lin = '({0}; rv:1.9.{1}.20) {2}'
        tmplt_mac = '({0}; rv:1.9.{1}.20) {2}'
        platforms = (
            tmplt_win.format(cls.windows_platform_token(),
                             cls.random_element(cls.langs),
                             random.randint(0, 2),
                             random.choice(ver)),
            tmplt_lin.format(cls.linux_platform_token(),
                             random.randint(5, 7),
                             random.choice(ver)),
            tmplt_mac.format(cls.mac_platform_token(),
                             random.randint(2, 6),
                             random.choice(ver)),
        )

        return 'Mozilla/5.0 ' + cls.random_element(platforms)
示例#4
0
    def firefox(cls):
        ver = (
            'Gecko/{0} Firefox/{1}.0'.format(
                DatetimeProvider.date_time_between(datetime(2011, 1, 1)),
                random.randint(4, 15)),
            'Gecko/{0} Firefox/3.6.{1}'.format(
                DatetimeProvider.date_time_between(datetime(2010, 1, 1)),
                random.randint(1, 20)),
            'Gecko/{0} Firefox/3.8'.format(
                DatetimeProvider.date_time_between(datetime(2010, 1, 1)), ),
        )
        tmplt_win = '({0}; {1}; rv:1.9.{2}.20) {3}'
        tmplt_lin = '({0}; rv:1.9.{1}.20) {2}'
        tmplt_mac = '({0}; rv:1.9.{1}.20) {2}'
        platforms = (
            tmplt_win.format(cls.windows_platform_token(),
                             MiscProvider.locale().replace('_', '-'),
                             random.randint(0, 2), random.choice(ver)),
            tmplt_lin.format(cls.linux_platform_token(), random.randint(5, 7),
                             random.choice(ver)),
            tmplt_mac.format(cls.mac_platform_token(), random.randint(2, 6),
                             random.choice(ver)),
        )

        return 'Mozilla/5.0 ' + cls.random_element(platforms)
示例#5
0
 def ipv6(self, network=False):
     """Produce a random IPv6 address or network with a valid CIDR"""
     address = str(ip_address(random.randint(
         2 ** IPV4LENGTH, (2 ** IPV6LENGTH) - 1)))
     if network:
         address += '/' + str(random.randint(0, IPV6LENGTH))
         address = str(ip_network(address, strict=False))
     return address
示例#6
0
文件: __init__.py 项目: 4sp1r3/faker
 def random_digit_not_null_or_empty(cls):
     """
     Returns a random non-zero digit/number
     between 1 and 9 or and empty string.
     """
     if random.randint(0, 1):
         return random.randint(1, 9)
     else:
         return ''
示例#7
0
文件: __init__.py 项目: 4sp1r3/faker
 def random_digit_or_empty(cls):
     """
     Returns a random digit/number
     between 0 and 9 or an empty string.
     """
     if random.randint(0, 1):
         return random.randint(0, 9)
     else:
         return ''
示例#8
0
 def random_digit_or_empty(cls):
     """
     Returns a random digit/number
     between 0 and 9 or an empty string.
     """
     if random.randint(0, 1):
         return random.randint(0, 9)
     else:
         return ''
示例#9
0
 def random_digit_not_null_or_empty(cls):
     """
     Returns a random non-zero digit/number
     between 1 and 9 or and empty string.
     """
     if random.randint(0, 1):
         return random.randint(1, 9)
     else:
         return ''
示例#10
0
 def opera(cls):
     platform = '({0}; {1}) Presto/2.9.{2} Version/{3}.00'.format(
         (cls.linux_platform_token()
          if random.getrandbits(1) else cls.windows_platform_token()),
         MiscProvider.locale().replace('_', '-'),
         random.randint(160, 190),
         random.randint(10, 12),
     )
     return 'Opera/{0}.{1}.{2}'.format(
         random.randint(8, 9),
         random.randint(10, 99),
         platform,
     )
示例#11
0
 def opera(cls):
     platform = '({0}; {1}) Presto/2.9.{2} Version/{3}.00'.format(
         (
             cls.linux_platform_token() if random.getrandbits(1)
             else cls.windows_platform_token()
         ),
         MiscProvider.locale().replace('_', '-'),
         random.randint(160, 190),
         random.randint(10, 12),
     )
     return 'Opera/{0}.{1}.{2}'.format(
         random.randint(8, 9),
         random.randint(10, 99),
         platform,
     )
示例#12
0
文件: stats.py 项目: l-k-/faker
def reservoir_sampling(iterator, n=2):
    """
    Reservoir sampling method to generate a random sample of n elements
    from a given element stream (implementation of algorithm R).
    https://en.wikipedia.org/wiki/Reservoir_sampling
    This method is suitable for generating a large number of elements
    because time complexity is dominated by the size of the original stream,
    not the number of elements selected from it.
    """
    res = []

    # initialize the reservoir with the first n elements of the stream
    for _ in range(n):
        res.append(next(iterator))

    # replace elements in the reservoir with gradually decreasing probability
    i = 0

    for value in iterator:
        j = random.randint(0, i)  # important: inclusive range
        if j < n:
            res[j] = value
        i += 1

    return res
示例#13
0
文件: __init__.py 项目: l-k-/faker
 def random_digits(cls, digits=1):
     """
     Return a random string of digits of specified length.
     """
     res = str(random.randint(0, pow(10, digits) - 1))
     n_zeros = digits - len(res)
     return '0' * n_zeros + res
示例#14
0
def generate_post() -> dict:
    """
    Generate random post
    @return: dict with title, short_description, image,
             full_description, user, posted
    """
    dict_post = {
        'title': '',
        'short_description': '',
        'image': '',
        'full_description': '',
        'user': 1,
        'posted': False
    }
    fake = Faker(['en_US'])
    dict_post['title'] = get_word(count=1)
    dict_post['short_description'] = get_sentence(count=1,
                                                  word_range=(4, 8),
                                                  sep=' ')
    dict_post['image'] = fake.image_url()
    dict_post['full_description'] = get_paragraph(count=3,
                                                  comma=(0, 2),
                                                  word_range=(4, 8),
                                                  sentence_range=(5, 10),
                                                  sep=os.linesep)
    dict_post['user'] = random.randint(1, 2)
    dict_post['posted'] = random.choice([True, False])
    return dict_post
示例#15
0
文件: __init__.py 项目: l-k-/faker
    def age(cls, minor=False):
        if minor:
            # kids' ages are pretty evenly distributed..
            return cls.random_int(0, 20)

        random_range = choice_distribution(cls.age_ranges_US, cls.age_freq_US)
        return random.randint(*random_range)
示例#16
0
文件: __init__.py 项目: l-k-/faker
    def zipcode(cls, state=None, n=1):
        if not state:
            if n == 1:
                return "%05d" % random.randint(501, 99950)
            ["%05d" % random.randint(501, 99950) for _ in range(n)]
        else:
            if n == 1:
                # the zip code table only contains the first 3 digits of the code,
                # so we'll make up the remaining two
                try:
                    return random.choice(cls.state_abbr_to_zipcodes[state]) + cls.random_digits(2)
                except:
                    raise Exception('Invalid state "{0}"'.format(state))

            # if n>1, state will contain an array of states
            return [random.choice(cls.state_abbr_to_zipcodes[s]) + cls.random_digits(2) for s in state]
示例#17
0
    def random_number(cls, digits=None, fix_len=False):
        """
        Returns a random number with 1 digit (default, when digits==None),
        a random number with 0 to given number of digits, or a random number
        with given number to given number of digits (when ``fix_len==True``).

        :param digits: maximum number of digits
        :param fix_len:  should the number have fixed length?
        :returns: random number with 0 to given number of digits or
            fixed length number
        """
        if digits is None:
            digits = BaseProvider.random_digit()
        if fix_len:
            return random.randint(pow(10, digits - 1), pow(10, digits) - 1)
        else:
            return random.randint(0, pow(10, digits) - 1)
示例#18
0
    def random_number(cls, digits=None, fix_len=False):
        """
        Returns a random number with 1 digit (default, when digits==None),
        a random number with 0 to given number of digits, or a random number
        with given number to given number of digits (when ``fix_len==True``).

        :param digits: maximum number of digits
        :param fix_len:  should the number have fixed length?
        :returns: random number with 0 to given number of digits or
            fixed length number
        """
        if digits is None:
            digits = BaseProvider.random_digit()
        if fix_len:
            return random.randint(pow(10, digits - 1), pow(10, digits) - 1)
        else:
            return random.randint(0, pow(10, digits) - 1)
示例#19
0
文件: __init__.py 项目: 4sp1r3/faker
    def random_int(cls, min=0, max=9999):
        """
        Returns a random integer between two values.

        :param min: lower bound value (inclusive; default=0)
        :param max: upper bound value (inclusive; default=9999)
        :returns: random integer between min and max
        """
        return random.randint(min, max)
示例#20
0
 def geo_coordinate(cls, center=None, radius=0.001):
     """
     Optionally center the coord and pick a point within radius.
     """
     if not center:
         return Decimal(str(random.randint(-180000000, 180000000) / 1000000.0)).quantize(Decimal('.000001'))
     else:
         geo = random.uniform(center - radius, center + radius)
         return Decimal(str(geo))
示例#21
0
    def test_binary(self):
        from faker.providers.misc import Provider

        for _ in range(999):
            length = random.randint(0, 2 ** 10)
            binary = Provider.binary(length)

            self.assertTrue(isinstance(binary, six.binary_type))
            self.assertTrue(len(binary) == length)
示例#22
0
 def ipv4(self):
     """
     Convert 32-bit integer to dotted IPv4 address.
     """
     return ".".join(
         map(
             lambda n: str(
                 random.randint(-2147483648, 2147483647) >> n & 0xFF),
             [24, 16, 8, 0]))
示例#23
0
文件: __init__.py 项目: yileye/faker
    def test_binary(self):
        from faker.providers.misc import Provider

        for _ in range(999):
            length = random.randint(0, 2**10)
            binary = Provider.binary(length)

            self.assertTrue(isinstance(binary, six.binary_type))
            self.assertTrue(len(binary) == length)
示例#24
0
    def random_int(cls, min=0, max=9999):
        """
        Returns a random integer between two values.

        :param min: lower bound value (inclusive; default=0)
        :param max: upper bound value (inclusive; default=9999)
        :returns: random integer between min and max
        """
        return random.randint(min, max)
示例#25
0
文件: __init__.py 项目: 4sp1r3/faker
    def random_number(cls, digits=None):
        """
        Returns a random number with 1 digit (default, when digits==None)
        or a random number with 0 to given number of digits.

        :param digits: maximum number of digits
        :returns: random number with 0 to given number of digits
        """
        if digits is None:
            digits = BaseProvider.random_digit()
        return random.randint(0, pow(10, digits) - 1)
示例#26
0
    def random_number(cls, digits=None):
        """
        Returns a random number with 1 digit (default, when digits==None)
        or a random number with 0 to given number of digits.

        :param digits: maximum number of digits
        :returns: random number with 0 to given number of digits
        """
        if digits is None:
            digits = BaseProvider.random_digit()
        return random.randint(0, pow(10, digits) - 1)
示例#27
0
 def date_time_ad(cls):
     """
     Get a datetime object for a date between January 1, 001 and now
     :example DateTime('1265-03-22 21:15:52')
     :return datetime
     """
     ts = random.randint(-62135600400, int(time()))
     # NOTE: using datetime.fromtimestamp(ts) directly will raise
     #       a "ValueError: timestamp out of range for platform time_t"
     #       on some platforms due to system C functions;
     #       see http://stackoverflow.com/a/10588133/2315612
     return datetime.fromtimestamp(0) + timedelta(seconds=ts)
示例#28
0
 def pystr(cls, min_chars=None, max_chars=20):
     """
     Generates a random string of upper and lowercase letters.
     :type min_chars: int
     :type max_chars: int
     :return: String. Random of random length between min and max characters.
     """
     if min_chars is None:
         return "".join(cls.random_letter() for i in range(max_chars))
     else:
         assert (max_chars >= min_chars), "Maximum length must be greater than or equal to minium length"
         return "".join(cls.random_letter() for i in range(0, random.randint(min_chars, max_chars)))
示例#29
0
文件: __init__.py 项目: DACN/faker
 def pystr(cls, min_chars=None, max_chars=20):
     """
     Generates a random string of upper and lowercase letters.
     :type min_chars: int
     :type max_chars: int
     :return: String. Random of random length between min and max characters.
     """
     if min_chars is None:
         return "".join(cls.random_letter() for i in range(max_chars))
     else:
         assert (max_chars >= min_chars), "Maximum length must be greater than or equal to minium length"
         return "".join(cls.random_letter() for i in range(0, random.randint(min_chars, max_chars)))
示例#30
0
文件: __init__.py 项目: l-k-/faker
    def birthdate(self, age=None):
        if age is None:
            try:
                age = self.generator.age()
            except:
                # if teh age generator isn't defined for this locale,
                # get a date string between January 1, 1970 and now
                return self.generator.date()

        today = date.today()

        # The oldest (in days) person of age X is the person whose birthday
        # is today (i.e. they officially turn X+1 years old when the date
        # rolls to tomorrow).
        # But if today is Feb 29th and (current year - X) wasn't a leap year,
        # then the oldest person for that age has a March 1st birthday.

        if today.month == 2 and today.day == 29:
            try:
                earliest_bdate = today.replace(year=today.year - age - 1)
            except ValueError:
                earliest_bdate = today.replace(year=today.year - age - 1,
                                               month=3,
                                               day=1)
        else:
            earliest_bdate = today.replace(year=today.year - age - 1)

        # The youngest (in days) person of age X is the person whose birthday
        # was yesterday (i.e. today is the first day they are officially
        # X years old).
        # But if yesterday was Feb 29th and (current year - X - 1) wasn't
        # a leap year, then the youngest person for that age has a Feb 28
        # birthday.

        yesterday = today - timedelta(days=1)
        if yesterday.month == 2 and yesterday.day == 29:
            try:
                latest_bdate = yesterday.replace(year=yesterday.year - age)
            except ValueError:
                latest_bdate = yesterday.replace(year=yesterday.year - age,
                                                 day=28)
        else:
            latest_bdate = yesterday.replace(year=yesterday.year - age)

        # number of potential birthdays for the given age will be 364 or 365,
        # depending on whether the date range includes a Feb 29th
        max_delta = latest_bdate - earliest_bdate

        # now pick a random date within the acceptable range
        delta = timedelta(days=random.randint(0, max_delta.days))

        return (earliest_bdate + delta).strftime('%Y-%m-%d')
示例#31
0
 def date_time_ad(cls, tzinfo=None):
     """
     Get a datetime object for a date between January 1, 001 and now
     :param tzinfo: timezone, instance of datetime.tzinfo subclass
     :example DateTime('1265-03-22 21:15:52')
     :return datetime
     """
     ts = random.randint(-62135600400, int(time()))
     # NOTE: using datetime.fromtimestamp(ts) directly will raise
     #       a "ValueError: timestamp out of range for platform time_t"
     #       on some platforms due to system C functions;
     #       see http://stackoverflow.com/a/10588133/2315612
     return datetime.fromtimestamp(0, tzinfo) + timedelta(seconds=ts)
示例#32
0
    def test_date_time_between_dates(self):
        from faker.providers.date_time import Provider
        provider = Provider

        timestamp_start = random.randint(0,10000000000)
        timestamp_end = timestamp_start+1

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

        random_date = provider.date_time_between_dates(datetime_start, datetime_end)
        self.assertTrue(datetime_start <= random_date)
        self.assertTrue(datetime_end >= random_date)
示例#33
0
    def test_date_time_between_dates(self):
        from faker.providers.date_time import Provider
        provider = Provider

        timestamp_start = random.randint(0,10000000000)
        timestamp_end = timestamp_start+1

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

        random_date = provider.date_time_between_dates(datetime_start, datetime_end)
        self.assertTrue(datetime_start <= random_date)
        self.assertTrue(datetime_end >= random_date)
示例#34
0
文件: __init__.py 项目: hkmshb/faker
    def random_sample_unique(cls, elements=("a", "b", "c"), length=None):
        """
        Returns a `set` of random unique elements for the specified length.
        """
        if length is None:
            length = random.randint(1, len(elements))

        if length > len(elements):
            raise ValueError("Sample length cannot be longer than the number of elements to pick from.")
        sample = set()
        while len(sample) < length:
            sample.add(cls.random_element(elements))
        return sample
示例#35
0
    def random_sample_unique(cls, elements=('a', 'b', 'c'), length=None):
        """
        Returns a `set` of random unique elements for the specified length.
        """
        if length is None:
            length = random.randint(1, len(elements))

        if length > len(elements):
            raise ValueError("Sample length cannot be longer than the number of elements to pick from.")
        sample = set()
        while len(sample) < length:
            sample.add(cls.random_element(elements))
        return sample
示例#36
0
 def complete_details_with_lived_abroad_option(self, first_name, last_name):
     driver = self.web_util.get_driver()
     page_title = "Register as a nanny"
     self.web_util.wait_until_page_load(page_title)
     self.assertEqual("To do", driver.find_element_by_xpath("//tr[@id='personal_details']/td/a/strong").text)
     self.web_util.click_element_by_xpath("//tr[@id='personal_details']/td/a/span")
     self.web_util.click_element_by_id("id_first_name")
     self.web_util.send_keys_by_id("id_first_name", first_name)
     self.web_util.send_keys_by_id("id_middle_names", "MiddleName")
     self.web_util.send_keys_by_id("id_last_name", last_name)
     self.web_util.click_element_by_name("action")
     self.web_util.send_keys_by_id("id_date_of_birth_0", random.randint(1, 28))
     self.web_util.send_keys_by_id("id_date_of_birth_1", random.randint(1, 12))
     self.web_util.send_keys_by_id("id_date_of_birth_2", random.randint(1950, 1990))
     self.web_util.click_element_by_name("action")
     self.web_util.click_element_by_id("id_postcode")
     self.web_util.send_keys_by_id("id_postcode", "LS10 1ED")
     self.web_util.click_element_by_name("postcode-search")
     self.web_util.click_element_by_id("id_address")
     Select(driver.find_element_by_id("id_address")).select_by_visible_text(
         "FORTIS DEVELOPMENTS LTD, BANK HOUSE, OLD MARKET PLACE, ALTRINCHAM, WA14 4PA")
     self.web_util.click_element_by_id("id_address")
     self.web_util.click_element_by_xpath(
         "(.//*[normalize-space(text()) and normalize-space(.)='Select address'])[1]/following::input[2]")
     self.web_util.click_element_by_name("action")
     self.web_util.click_element_by_id("id_lived_abroad_0")
     self.assertTrue(self.web_util.is_return_link_present())
     self.web_util.click_element_by_xpath("//input[@value='Save and continue']")
     self.web_util.assert_page_title("Certificates of good conduct")
     self.web_util.click_element_by_link_text("Continue")
     self.assertTrue(self.web_util.is_return_link_present())
     self.web_util.assert_page_title("Post certificates of good conduct")
     self.assertTrue(self.web_util.is_return_link_present())
     self.web_util.click_element_by_link_text("Save and continue")
     self.web_util.assert_page_title("Check your answers: your personal details")
     self.web_util.click_element_by_xpath("//input[@value='Confirm and continue']")
     self.web_util.wait_until_page_load(page_title)
     self.assertEqual("Done", driver.find_element_by_xpath("//tr[@id='personal_details']/td/a/strong").text)
示例#37
0
    def randomize_nb_elements(cls, number=10, le=False, ge=False):
        """
        Returns a random value near number.

        :param number: value to which the result must be near
        :param le: result must be lower or equal to number
        :param ge: result must be greater or equal to number
        :returns: a random int near number
        """
        if le and ge:
            return number
        _min = 100 if ge else 60
        _max = 100 if le else 140
        return int(number * random.randint(_min, _max) / 100) + 1
示例#38
0
文件: __init__.py 项目: 4sp1r3/faker
    def randomize_nb_elements(cls, number=10, le=False, ge=False):
        """
        Returns a random value near number.

        :param number: value to which the result must be near
        :param le: result must be lower or equal to number
        :param ge: result must be greater or equal to number
        :returns: a random int near number
        """
        if le and ge:
            return number
        _min = 100 if ge else 60
        _max = 100 if le else 140
        return int(number * random.randint(_min, _max) / 100) + 1
示例#39
0
    def date_time_between(cls, start_date="-30y", end_date="now"):
        """
        Get a DateTime object based on a random date between two given dates.
        Accepts date strings that can be recognized by strtotime().

        :param start_date Defaults to 30 years ago
        :param end_date Defaults to "now"
        :example DateTime('1999-02-02 11:42:52')
        :return DateTime
        """
        start_date = cls._parse_date_time(start_date)
        end_date = cls._parse_date_time(end_date)
        timestamp = random.randint(start_date, end_date)
        return datetime.fromtimestamp(timestamp)
示例#40
0
    def chrome(cls):
        saf = str(random.randint(531, 536)) + str(random.randint(0, 2))
        tmplt = '({0}) AppleWebKit/{1} (KHTML, like Gecko)' \
                ' Chrome/{2}.0.{3}.0 Safari/{4}'
        platforms = (
            tmplt.format(cls.linux_platform_token(), saf,
                         random.randint(13, 15), random.randint(800,
                                                                899), saf),
            tmplt.format(cls.windows_platform_token(), saf,
                         random.randint(13, 15), random.randint(800, 899),
                         saf),
            tmplt.format(cls.mac_platform_token(), saf, random.randint(13, 15),
                         random.randint(800, 899), saf),
        )

        return 'Mozilla/5.0 ' + cls.random_element(platforms)
示例#41
0
    def date_time_between(cls, start_date='-30y', end_date='now', tzinfo=None):
        """
        Get a DateTime object based on a random date between two given dates.
        Accepts date strings that can be recognized by strtotime().

        :param start_date Defaults to 30 years ago
        :param end_date Defaults to "now"
        :param tzinfo: timezone, instance of datetime.tzinfo subclass
        :example DateTime('1999-02-02 11:42:52')
        :return DateTime
        """
        start_date = cls._parse_date_time(start_date)
        end_date = cls._parse_date_time(end_date)
        timestamp = random.randint(start_date, end_date)
        return datetime.fromtimestamp(timestamp, tzinfo)
示例#42
0
    def test_date_time_between_dates_with_tzinfo(self):
        from faker.providers.date_time import Provider
        provider = Provider

        timestamp_start = random.randint(0, 10000000000)
        timestamp_end = timestamp_start+1

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

        random_date_naive = provider.date_time_between_dates(datetime_start, datetime_end)
        self.assertRaises(TypeError, lambda: datetime_start <= random_date_naive)

        random_date = provider.date_time_between_dates(datetime_start, datetime_end, utc)
        self.assertTrue(datetime_start <= random_date)
        self.assertTrue(datetime_end >= random_date)
示例#43
0
    def test_date_time_between_dates_with_tzinfo(self):
        from faker.providers.date_time import Provider
        provider = Provider

        timestamp_start = random.randint(0, 10000000000)
        timestamp_end = timestamp_start+1

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

        random_date_naive = provider.date_time_between_dates(datetime_start, datetime_end)
        self.assertRaises(TypeError, lambda: datetime_start <= random_date_naive)

        random_date = provider.date_time_between_dates(datetime_start, datetime_end, utc)
        self.assertTrue(datetime_start <= random_date)
        self.assertTrue(datetime_end >= random_date)
示例#44
0
    def password(cls,
                 length=10,
                 special_chars=True,
                 digits=True,
                 upper_case=True,
                 lower_case=True):
        """
        Generates a random password.
        @param length: Integer. Length of a password
        @param special_chars: Boolean. Whether to use special characters !@#$%^&*()_+
        @param digits: Boolean. Whether to use digits
        @param upper_case: Boolean. Whether to use upper letters
        @param lower_case: Boolean. Whether to use lower letters
        @return: String. Random password
        """
        choices = ""
        required_tokens = []
        if special_chars:
            required_tokens.append(random.choice("!@#$%^&*()_+"))
            choices += "!@#$%^&*()_+"
        if digits:
            required_tokens.append(random.choice(string.digits))
            choices += string.digits
        if upper_case:
            required_tokens.append(random.choice(string.ascii_uppercase))
            choices += string.ascii_uppercase
        if lower_case:
            required_tokens.append(random.choice(string.ascii_lowercase))
            choices += string.ascii_lowercase

        assert len(
            required_tokens
        ) <= length, "Required length is shorter than required characters"

        # Generate a first version of the password
        chars = [random.choice(choices) for x in range(length)]

        # Pick some unique locations
        random_indexes = set()
        while len(random_indexes) < len(required_tokens):
            random_indexes.add(random.randint(0, len(chars) - 1))

        # Replace them with the required characters
        for i, index in enumerate(random_indexes):
            chars[index] = required_tokens[i]

        return ''.join(chars)
示例#45
0
    def handle(self, *args, **options):
        records = options['record']

        list_user = User.objects.all()

        for _ in range(0, records):
            id = random.randint(1, 4)
            title = fake.name()
            status = random.choice(['published', 'draft'])
            Post.objects.create(
                title=title + " Post!!!",
                author=random.choice(list_user),
                slug="-".join(title.lower().split()),
                body=fake.text(),
                created=fake.date(),
                updated=fake.date(),
            )
示例#46
0
    def test_binary(self):
        from faker.providers.misc import Provider

        for _ in range(999):
            length = random.randint(0, 2 ** 10)
            binary = Provider.binary(length)

            self.assertTrue(isinstance(binary, (bytes, bytearray)))
            self.assertTrue(len(binary) == length)

        for _ in range(999):
            self.generator.seed(_)
            binary1 = Provider.binary(_)
            self.generator.seed(_)
            binary2 = Provider.binary(_)

            self.assertTrue(binary1 == binary2)
示例#47
0
    def test_binary(self):
        from faker.providers.misc import Provider

        for _ in range(999):
            length = random.randint(0, 2 ** 10)
            binary = Provider.binary(length)

            self.assertTrue(isinstance(binary, (bytes, bytearray)))
            self.assertTrue(len(binary) == length)

        for _ in range(999):
            self.generator.seed(_)
            binary1 = Provider.binary(_)
            self.generator.seed(_)
            binary2 = Provider.binary(_)

            self.assertTrue(binary1 == binary2)
示例#48
0
    def test_binary(self):
        from faker.providers.misc import Provider
        provider = Provider(self.generator)

        for _ in range(999):
            length = random.randint(0, 2**10)
            binary = provider.binary(length)

            assert isinstance(binary, (bytes, bytearray))
            assert len(binary) == length

        for _ in range(999):
            self.generator.seed(_)
            binary1 = provider.binary(_)
            self.generator.seed(_)
            binary2 = provider.binary(_)

            assert binary1 == binary2
示例#49
0
    def date_time_between_dates(cls, datetime_start=None, datetime_end=None):
        """
        Takes two DateTime objects and returns a random date between the two given dates.
        Accepts DateTime objects.

        :param datetime_start DateTime
        :param datetime_end DateTime
        :example DateTime('1999-02-02 11:42:52')
        :return DateTime
        """
        if datetime_start is None:
            datetime_start = datetime.now()

        if datetime_end is None:
            datetime_end = datetime.now()

        timestamp = random.randint(datetime_to_timestamp(datetime_start), datetime_to_timestamp(datetime_end))
        return datetime.fromtimestamp(timestamp)
示例#50
0
    def test_binary(self):
        from faker.providers.misc import Provider
        provider = Provider(self.generator)

        for _ in range(999):
            length = random.randint(0, 2 ** 10)
            binary = provider.binary(length)

            assert isinstance(binary, (bytes, bytearray))
            assert len(binary) == length

        for _ in range(999):
            self.generator.seed(_)
            binary1 = provider.binary(_)
            self.generator.seed(_)
            binary2 = provider.binary(_)

            assert binary1 == binary2
示例#51
0
    def pystr_with_prefix(cls, min_chars=None, max_chars=20, prefix=''):
        """ Generates a random string of upper and lowercase letters.

        :type min_chars: int
        :type max_chars: int
        :return: String. Random of random length between min and max
            characters.
        """
        if min_chars is None:
            return "".join(cls.random_letter() for i in range(max_chars))
        else:
            assert (max_chars >= min_chars), "Maximum length must be " \
                                             "greater than or equal to " \
                                             "minium length"
            pystr = "".join(
                cls.random_letter()
                for i in range(0, random.randint(min_chars, max_chars)))
            return "%s%s" % (prefix, pystr)
示例#52
0
 def opera(cls):
     tmplt = '({0}; {1}) Presto/2.9.{2} Version/{3}.00'
     platforms = (
         tmplt.format(cls.linux_platform_token(),
                      cls.random_element(cls.langs),
                      random.randint(160, 190), random.randint(10, 12)),
         tmplt.format(cls.windows_platform_token(),
                      cls.random_element(cls.langs),
                      random.randint(160, 190), random.randint(10, 12)),
     )
     return 'Opera/{0}.{1}.{2}'.format(random.randint(8, 9),
                                       random.randint(10, 99),
                                       cls.random_element(platforms))
    def pystr_with_prefix(cls, min_chars=None, max_chars=20, prefix=''):
        """ Generates a random string of upper and lowercase letters.

        :type min_chars: int
        :type max_chars: int
        :return: String. Random of random length between min and max
            characters.
        """
        if min_chars is None:
            return "".join(cls.random_letter() for i in range(max_chars))
        else:
            assert (max_chars >= min_chars), "Maximum length must be " \
                                             "greater than or equal to " \
                                             "minium length"
            pystr = "".join(
                cls.random_letter()
                for i
                in range(0, random.randint(min_chars, max_chars))
            )
            return "%s%s" % (prefix, pystr)
示例#54
0
def generate_comment() -> dict:
    """
    Generate random post
    @return: dict with title, short_description, image,
             full_description, user, posted
    """
    dict_comment = {
        'username': '',
        'text': '',
        'post': 1,
        'moderated': False
    }
    fake = Faker(['en_US'])
    dict_comment['username'] = fake.first_name()
    dict_comment['text'] = get_sentence(count=1,
                                        word_range=(4, 8),
                                        sep=' ')
    dict_comment['post'] = random.randint(1, POSTS_NUMBER)
    dict_comment['moderated'] = random.choice([True, False])
    return dict_comment
示例#55
0
文件: __init__.py 项目: 4sp1r3/faker
 def opera(cls):
     tmplt = '({0}; {1}) Presto/2.9.{2} Version/{3}.00'
     platforms = (
         tmplt.format(cls.linux_platform_token(),
                      cls.random_element(cls.langs),
                      random.randint(160, 190),
                      random.randint(10, 12)),
         tmplt.format(cls.windows_platform_token(),
                      cls.random_element(cls.langs),
                      random.randint(160, 190),
                      random.randint(10, 12)),
     )
     return 'Opera/{0}.{1}.{2}'.format(random.randint(8, 9),
                                       random.randint(10, 99),
                                       cls.random_element(platforms))
示例#56
0
文件: __init__.py 项目: 4sp1r3/faker
    def chrome(cls):
        saf = str(random.randint(531, 536)) + str(random.randint(0, 2))
        tmplt = '({0}) AppleWebKit/{1} (KHTML, like Gecko)' \
                ' Chrome/{2}.0.{3}.0 Safari/{4}'
        platforms = (
            tmplt.format(cls.linux_platform_token(),
                         saf,
                         random.randint(13, 15),
                         random.randint(800, 899),
                         saf),
            tmplt.format(cls.windows_platform_token(),
                         saf,
                         random.randint(13, 15),
                         random.randint(800, 899),
                         saf),
            tmplt.format(cls.mac_platform_token(),
                         saf,
                         random.randint(13, 15),
                         random.randint(800, 899),
                         saf),
        )

        return 'Mozilla/5.0 ' + cls.random_element(platforms)
示例#57
0
文件: __init__.py 项目: 4sp1r3/faker
    def password(cls, length=10, special_chars=True, digits=True, upper_case=True, lower_case=True):
        """
        Generates a random password.
        @param length: Integer. Length of a password
        @param special_chars: Boolean. Whether to use special characters !@#$%^&*()_+
        @param digits: Boolean. Whether to use digits
        @param upper_case: Boolean. Whether to use upper letters
        @param lower_case: Boolean. Whether to use lower letters
        @return: String. Random password
        """
        choices = ""
        required_tokens = []
        if special_chars:
            required_tokens.append(random.choice("!@#$%^&*()_+"))
            choices += "!@#$%^&*()_+"
        if digits:
            required_tokens.append(random.choice(string.digits))
            choices += string.digits
        if upper_case:
            required_tokens.append(random.choice(string.ascii_uppercase))
            choices += string.ascii_uppercase
        if lower_case:
            required_tokens.append(random.choice(string.ascii_lowercase))
            choices += string.ascii_lowercase

        assert len(required_tokens) <= length, "Required length is shorter than required characters"

        # Generate a first version of the password
        chars = [random.choice(choices) for x in range(length)]

        # Pick some unique locations
        random_indexes = set()
        while len(random_indexes) < len(required_tokens):
            random_indexes.add(random.randint(0, len(chars) - 1))

        # Replace them with the required characters
        for i, index in enumerate(random_indexes):
            chars[index] = required_tokens[i]

        return ''.join(chars)
示例#58
0
    def date_time_between_dates(cls, datetime_start=None, datetime_end=None, tzinfo=None):
        """
        Takes two DateTime objects and returns a random date between the two given dates.
        Accepts DateTime objects.

        :param datetime_start DateTime
        :param datetime_end DateTime
        :param tzinfo: timezone, instance of datetime.tzinfo subclass
        :example DateTime('1999-02-02 11:42:52')
        :return DateTime
        """
        if datetime_start is None:
            datetime_start = datetime.now(tzinfo)

        if datetime_end is None:
            datetime_end = datetime.now(tzinfo)

        timestamp = random.randint(
            datetime_to_timestamp(datetime_start),
            datetime_to_timestamp(datetime_end),
        )
        return datetime.fromtimestamp(timestamp, tzinfo)