Example #1
0
class OneCharStringStrategy(SearchStrategy):
    """A strategy which generates single character strings of text type."""
    specifier = text_type
    ascii_characters = (text_type('0123456789') +
                        text_type(string.ascii_letters) + text_type(' \t\n'))

    def produce_parameter(self, random):
        alphabet_size = 1 + dist.geometric(random, 0.1)
        alphabet = []
        while len(alphabet) < alphabet_size:
            char = hunichr(random.randint(0, sys.maxunicode))
            if unicodedata.category(char) != 'Cs':
                alphabet.append(char)
        return tuple(alphabet)

    def produce_template(self, context, p):
        return context.random.choice(p)

    def reify(self, value):
        return value

    def basic_simplify(self, random, x):
        if x in self.ascii_characters:
            for i in hrange(0, self.ascii_characters.index(x)):
                yield self.ascii_characters[i]
        else:
            o = ord(x)
            for c in self.ascii_characters:
                yield text_type(c)
            yield hunichr(o // 2)
            for t in hrange(o - 1, max(o - 10, -1), -1):
                yield hunichr(t)
Example #2
0
class OneCharStringStrategy(SearchStrategy):
    """A strategy which generates single character strings of text type."""
    descriptor = text_type
    ascii_characters = (text_type('0123456789') +
                        text_type(string.ascii_letters) + text_type(' \t\n'))
    parameter = params.CompositeParameter(
        ascii_chance=params.UniformFloatParameter(0, 1))

    def produce(self, random, pv):
        if dist.biased_coin(random, pv.ascii_chance):
            return random.choice(self.ascii_characters)
        else:
            while True:
                result = hunichr(random.randint(0, sys.maxunicode))
                if unicodedata.category(result) != 'Cs':
                    return result

    def simplify(self, x):
        if x in self.ascii_characters:
            for i in hrange(self.ascii_characters.index(x), -1, -1):
                yield self.ascii_characters[i]
        else:
            o = ord(x)
            for c in reversed(self.ascii_characters):
                yield text_type(c)
            if o > 0:
                yield hunichr(o // 2)
                yield hunichr(o - 1)
def test_has_ascii(x):
    if not x:
        return
    ascii_characters = (
        text_type('0123456789') + text_type(string.ascii_letters) +
        text_type(' \t\n')
    )
    assert any(c in ascii_characters for c in x)
def test_has_ascii(x):
    if not x:
        return
    ascii_characters = (
        text_type(u'0123456789') + text_type(string.ascii_letters) +
        text_type(u' \t\n')
    )
    assert any(c in ascii_characters for c in x)
Example #5
0
 def __init__(self, characters=None):
     SearchStrategy.__init__(self)
     if characters is not None and not isinstance(characters, text_type):
         raise ValueError('Invalid characters %r: Not a %s' %
                          (characters, text_type))
     self.characters = characters or (text_type('0123456789') +
                                      text_type(string.ascii_letters))
     self.parameter = params.CompositeParameter()
def test_whitelisted_characters_overlap_blacklisted_characters():
    good_chars = u'te02тест49st'
    bad_chars = u'ts94тсет'
    with pytest.raises(InvalidArgument) as exc:
        characters(min_codepoint=ord('0'), max_codepoint=ord('9'),
                   whitelist_characters=good_chars,
                   blacklist_characters=bad_chars).example()
        assert repr(good_chars) in text_type(exc)
        assert repr(bad_chars) in text_type(exc)
def test_whitelisted_characters_overlap_blacklisted_characters():
    good_chars = u'te02тест49st'
    bad_chars = u'ts94тсет'
    with pytest.raises(InvalidArgument) as exc:
        characters(min_codepoint=ord('0'),
                   max_codepoint=ord('9'),
                   whitelist_characters=good_chars,
                   blacklist_characters=bad_chars).example()
        assert repr(good_chars) in text_type(exc)
        assert repr(bad_chars) in text_type(exc)
Example #8
0
def text(alphabet=None, min_size=None, average_size=None, max_size=None):
    """Generates values of a unicode text type (unicode on python 2, str on
    python 3) with values drawn from alphabet, which should be an iterable of
    length one strings or a strategy generating such. If it is None it will
    default to generating the full unicode range. If it is an empty collection
    this will only generate empty strings.

    min_size, max_size and average_size have the usual interpretations.

    """
    from hypothesis.searchstrategy.strings import OneCharStringStrategy, \
        StringStrategy
    if alphabet is None:
        char_strategy = OneCharStringStrategy()
    elif not alphabet:
        if (min_size or 0) > 0:
            raise InvalidArgument(
                u'Invalid min_size %r > 0 for empty alphabet' % (min_size, ))
        return just(u'')
    elif isinstance(alphabet, SearchStrategy):
        char_strategy = alphabet
    else:
        char_strategy = sampled_from(text_type(alphabet))
    return StringStrategy(
        lists(char_strategy,
              average_size=average_size,
              min_size=min_size,
              max_size=max_size))
Example #9
0
def text(
    alphabet=None,
    min_size=None, average_size=None, max_size=None
):
    """Generates values of a unicode text type (unicode on python 2, str on
    python 3) with values drawn from alphabet, which should be an iterable of
    length one strings or a strategy generating such. If it is None it will
    default to generating the full unicode range. If it is an empty collection
    this will only generate empty strings.

    min_size, max_size and average_size have the usual interpretations.

    """
    from hypothesis.searchstrategy.strings import OneCharStringStrategy, \
        StringStrategy
    if alphabet is None:
        char_strategy = OneCharStringStrategy()
    elif not alphabet:
        if (min_size or 0) > 0:
            raise InvalidArgument(
                'Invalid min_size %r > 0 for empty alphabet' % (
                    min_size,
                )
            )
        return just('')
    elif isinstance(alphabet, SearchStrategy):
        char_strategy = alphabet
    else:
        char_strategy = sampled_from(text_type(alphabet))
    return StringStrategy(lists(
        char_strategy, average_size=average_size, min_size=min_size,
        max_size=max_size
    ))
Example #10
0
 def is_valid_template(self, template):
     if not (self.min_year <= template[0] <= self.max_year):
         return False
     tz = template[-1]
     if tz is None:
         return self.allow_naive
     else:
         return any(text_type(z.zone) == tz for z in self.timezones)
Example #11
0
def mutate_basic(basic, random):
    if not random.randint(0, 2):
        if isinstance(basic, text_type):
            return list(basic)
        elif isinstance(basic, integer_types):
            return float(basic)
        else:
            return text_type(repr(basic))
    return mess_with_basic_data(basic, random)
Example #12
0
def mutate_basic(basic, random):
    if not random.randint(0, 2):
        if isinstance(basic, text_type):
            return list(basic)
        elif isinstance(basic, integer_types):
            return float(basic)
        else:
            return text_type(repr(basic))
    return mess_with_basic_data(basic, random)
Example #13
0
 def gen_example(self, random):
     factory = self.factory_for(random.choice(self.locales))
     original = globalrandom.getstate()
     seed = random.getrandbits(128)
     try:
         factory.seed(seed)
         return text_type(getattr(factory, self.source)())
     finally:
         globalrandom.setstate(original)
Example #14
0
 def basic_simplify(self, random, x):
     if x in self.ascii_characters:
         for i in hrange(0, self.ascii_characters.index(x)):
             yield self.ascii_characters[i]
     else:
         o = ord(x)
         for c in self.ascii_characters:
             yield text_type(c)
         yield hunichr(o // 2)
         for t in hrange(o - 1, max(o - 10, -1), -1):
             yield hunichr(t)
Example #15
0
 def simplify(self, x):
     if x in self.ascii_characters:
         for i in hrange(self.ascii_characters.index(x), -1, -1):
             yield self.ascii_characters[i]
     else:
         o = ord(x)
         for c in reversed(self.ascii_characters):
             yield text_type(c)
         if o > 0:
             yield hunichr(o // 2)
             yield hunichr(o - 1)
Example #16
0
 def is_valid_template(self, template):
     if not (self.min_year <= template[0] <= self.max_year):
         return False
     tz = template[-1]
     if tz is None:
         return self.allow_naive
     else:
         return any(
             text_type(z.zone) == tz
             for z in self.timezones
         )
Example #17
0
 def templateize(self, dt):
     return (
         dt.year,
         dt.month,
         dt.day,
         dt.hour,
         dt.minute,
         dt.second,
         dt.microsecond,
         text_type(dt.tzinfo.zone) if dt.tzinfo else None,
     )
Example #18
0
 def templateize(self, dt):
     return (
         dt.year,
         dt.month,
         dt.day,
         dt.hour,
         dt.minute,
         dt.second,
         dt.microsecond,
         text_type(dt.tzinfo.zone) if dt.tzinfo else None,
     )
Example #19
0
def note(value):
    """Report this value in the final execution.

    Will always call string conversion function of the value even if not
    printing for consistency of execution

    """
    value = text_type(value)
    context = _current_build_context.value
    if context is None:
        raise InvalidArgument(u'Cannot make notes outside of build context')
    if context.is_final:
        report(value)
Example #20
0
 def is_valid_template(self, template):
     if not (self.min_year <= template[0] <= self.max_year):
         return False
     tz = template[-1]
     if tz is None:
         return self.allow_naive
     else:
         if not any(text_type(z.zone) == tz for z in self.timezones):
             return False
         try:
             self.reify(template)
             return True
         except (OverflowError, ValueError):
             return False
Example #21
0
def note(value):
    """Report this value in the final execution.

    Will always call string conversion function of the value even if not
    printing for consistency of execution

    """
    value = text_type(value)
    context = _current_build_context.value
    if context is None:
        raise InvalidArgument(
            u'Cannot make notes outside of build context')
    if context.is_final:
        report(value)
Example #22
0
 def is_valid_template(self, template):
     if not (self.min_year <= template[0] <= self.max_year):
         return False
     tz = template[-1]
     if tz is None:
         return self.allow_naive
     else:
         if not any(text_type(z.zone) == tz for z in self.timezones):
             return False
         try:
             self.reify(template)
             return True
         # This is covered but hard to hit reliably
         except (OverflowError, ValueError):  # pragma: no cover
             return False
Example #23
0
 def is_valid_template(self, template):
     if not (self.min_year <= template[0] <= self.max_year):
         return False
     tz = template[-1]
     if tz is None:
         return self.allow_naive
     else:
         if not any(
             text_type(z.zone) == tz
             for z in self.timezones
         ):
             return False
         try:
             self.reify(template)
             return True
         except (OverflowError, ValueError):
             return False
Example #24
0
 def __trackas__(self):
     data = list(self)
     if data[-1] is not None:
         data[-1] = text_type(data[-1].zone)
     return data
Example #25
0
 def gen_example(self, random, locales):
     factory = self.factory_for(random.choice(locales))
     factory.seed(random.getrandbits(128))
     return text_type(getattr(factory, self.source)())
Example #26
0
 def gen_example(self, random, locales):
     factory = faker.Faker(locale=random.choice(locales))
     factory.seed(random.getrandbits(128))
     for p in self.providers:
         factory.add_provider(p)
     return text_type(getattr(factory, self.source)())
Example #27
0
 def gen_example(self, random, locales):
     factory = self.factory_for(random.choice(locales))
     factory.seed(random.getrandbits(128))
     return text_type(getattr(factory, self.source)())
Example #28
0
def test_random_repr_has_seed():
    rnd = strategy(random.Random).example()
    seed = rnd.seed
    assert text_type(seed) in repr(rnd)
def test_random_repr_has_seed():
    rnd = randoms().example()
    seed = rnd.seed
    assert text_type(seed) in repr(rnd)
Example #30
0
 def pack(self, ls):
     return text_type('').join(ls)
Example #31
0
def to_text(textish):
    if inspect.isfunction(textish):
        textish = textish()
    return text_type(textish)
def test_random_repr_has_seed():
    rnd = strategy(random.Random).example()
    seed = rnd.seed
    assert text_type(seed) in repr(rnd)
Example #33
0
def test_random_repr_has_seed():
    rnd = strategy(random.Random).produce(random.Random(), None)
    seed = rnd.seed
    assert text_type(seed) in repr(rnd)
Example #34
0
def test_has_ascii(x):
    if not x:
        return
    ascii_characters = text_type(u"0123456789") + text_type(string.ascii_letters) + text_type(u" \t\n")
    assert any(c in ascii_characters for c in x)
Example #35
0
 def to_basic(self, template):
     return text_type(template)
Example #36
0
 def from_basic(self, c):
     check_data_type(text_type, c)
     return text_type(c)
Example #37
0
def strings(alphabet):
    return Strings(text_type(alphabet))
Example #38
0
 def produce_template(self, context, pv):
     factory = faker.Faker(locale=context.random.choice(pv))
     factory.seed(context.random.getrandbits(128))
     for p in self.providers:
         factory.add_provider(p)
     return text_type(getattr(factory, self.source)())
Example #39
0
def test_random_repr_has_seed():
    strat = strategy(random.Random)
    rnd = strat.reify(
        strat.produce_template(BuildContext(random.Random()), None))
    seed = rnd.seed
    assert text_type(seed) in repr(rnd)
 def __trackas__(self):
     data = list(self)
     if data[-1] is not None:
         data[-1] = text_type(data[-1].zone)
     return data
def test_random_repr_has_seed():
    rnd = randoms().example()
    seed = rnd.seed
    assert text_type(seed) in repr(rnd)
Example #42
0
 def draw_template(self, random, pv):
     factory = faker.Faker(locale=random.choice(pv))
     factory.seed(random.getrandbits(128))
     for p in self.providers:
         factory.add_provider(p)
     return text_type(getattr(factory, self.source)())