def field_mappings(): global __default_field_mappings if __default_field_mappings is None: __default_field_mappings = { dm.SmallIntegerField: st.integers(-32768, 32767), dm.IntegerField: st.integers(-2147483648, 2147483647), dm.BigIntegerField: st.integers(-9223372036854775808, 9223372036854775807), dm.PositiveIntegerField: st.integers(0, 2147483647), dm.PositiveSmallIntegerField: st.integers(0, 32767), dm.BinaryField: st.binary(), dm.BooleanField: st.booleans(), dm.CharField: st.text(), dm.TextField: st.text(), dm.DateTimeField: datetimes(allow_naive=False), dm.EmailField: ff.fake_factory(u'email'), dm.FloatField: st.floats(), dm.NullBooleanField: st.one_of(st.none(), st.booleans()), } return __default_field_mappings
def _get_strategy_for_field(f): if isinstance(f, dm.AutoField): return default_value elif f.choices: choices = [value for (value, name) in f.choices] if isinstance(f, (dm.CharField, dm.TextField)) and f.blank: choices.append(u'') strategy = st.sampled_from(choices) elif isinstance(f, dm.EmailField): return ff.fake_factory(u'email') elif type(f) in (dm.TextField, dm.CharField): strategy = st.text(min_size=(None if f.blank else 1), max_size=f.max_length) elif type(f) == dm.DecimalField: m = 10**f.max_digits - 1 div = 10**f.decimal_places q = Decimal('1.' + ('0' * f.decimal_places)) strategy = (st.integers( min_value=-m, max_value=m).map(lambda n: (Decimal(n) / div).quantize(q))) else: try: strategy = field_mappings()[type(f)] except KeyError: if f.null: return None else: raise UnmappedFieldError(f) if f.validators: strategy = strategy.filter(validator_to_filter(f)) if f.null: strategy = st.one_of(st.none(), strategy) return strategy
def _get_strategy_for_field(f): if isinstance(f, dm.AutoField): return default_value elif f.choices: choices = [value for (value, name) in f.choices] if isinstance(f, (dm.CharField, dm.TextField)) and f.blank: choices.append(u'') strategy = st.sampled_from(choices) elif isinstance(f, dm.EmailField): return ff.fake_factory(u'email') elif type(f) in (dm.TextField, dm.CharField): strategy = st.text(min_size=(None if f.blank else 1), max_size=f.max_length) elif type(f) == dm.DecimalField: m = 10 ** f.max_digits - 1 div = 10 ** f.decimal_places q = Decimal('1.' + ('0' * f.decimal_places)) strategy = ( st.integers(min_value=-m, max_value=m) .map(lambda n: (Decimal(n) / div).quantize(q))) else: try: strategy = field_mappings()[type(f)] except KeyError: if f.null: return None else: raise UnmappedFieldError(f) if f.validators: strategy = strategy.filter(validator_to_filter(f)) if f.null: strategy = st.one_of(st.none(), strategy) return strategy
def _generate_item(atom=False): link = fake_factory('url') item = { 'title': _valid_text(allow_empty=False), 'link': link, 'description': _valid_text(), } optional = { 'content': _valid_text(), 'author_email': fake_factory('email'), 'author_name': fake_factory('name'), 'author_link': fake_factory('url'), 'pubdate': datetimes(), 'updateddate': datetimes(), # 'comments': to_unicode(comments), 'unique_id': link if atom else _valid_text(), # # 'enclosure': enclosure, # # 'categories': st.lists(_valid_text()), 'item_copyright': _valid_text(), 'ttl': st.integers(min_value=0), } item.update([(k, _optional(v)) for (k, v) in optional.items()]) return item
def field_mappings(): global __default_field_mappings if __default_field_mappings is None: __default_field_mappings = { dm.SmallIntegerField: st.integers(-32768, 32767), dm.IntegerField: st.integers(-2147483648, 2147483647), dm.BigIntegerField: st.integers(-9223372036854775808, 9223372036854775807), dm.PositiveIntegerField: st.integers(0, 2147483647), dm.PositiveSmallIntegerField: st.integers(0, 32767), dm.BinaryField: st.binary(), dm.BooleanField: st.booleans(), dm.CharField: st.text(), dm.TextField: st.text(), dm.DateTimeField: datetimes(allow_naive=False), dm.EmailField: ff.fake_factory(u"email"), dm.FloatField: st.floats(), dm.NullBooleanField: st.one_of(st.none(), st.booleans()), } return __default_field_mappings
def _generate_feed(atom=False): feed = { 'title': _valid_text(), 'link': fake_factory('url'), 'description': _valid_text(), } optional = { 'language': fake_factory('locale').map(lambda x: x.replace('_', '-')), 'author_email': fake_factory('email'), 'author_name': fake_factory('name'), 'author_link': fake_factory('url'), 'subtitle': _valid_text(), 'categories': st.lists(_valid_text()), 'feed_url': fake_factory('url'), 'feed_copyright': _valid_text(), 'id': fake_factory('url') if atom else _valid_text(), 'ttl': st.integers(min_value=0), } feed.update([(k, _optional(v)) for (k, v) in optional.items()]) return feed
def test_fake_factory_errors_if_any_locale_is_unsupported(): with pytest.raises(ValueError): fake_factory("name", locales=["fr_FR", "en_US", "mushroom_MUSHROOM"])
def test_fake_factory_errors_with_unsupported_locale(): with pytest.raises(ValueError): fake_factory("name", locale="badger_BADGER")
def test_fake_factory_errors_with_both_locale_and_locales(): with pytest.raises(ValueError): fake_factory("name", locale="fr_FR", locales=["fr_FR", "en_US"])
def test_email(): @given(fake_factory(u'email')) def inner(email): assert u'@' in email inner()
def test_fake_factory_errors_if_private_ish_method(): with pytest.raises(ValueError): fake_factory(u'_Generator__config')
def test_english_names_are_ascii(): @given(fake_factory(u'name', locale=u'en_US')) def inner(name): name.encode(u'ascii') inner()
def test_french_names_may_have_an_accent(): minimal( fake_factory(u'name', locale=u'fr_FR'), lambda x: u'é' not in x )
import pytest from hypothesis import given from faker.providers import BaseProvider from hypothesis.strategytests import strategy_test_suite from hypothesis.internal.debug import minimal from hypothesis.searchstrategy import strategy from hypothesis.extra.fakefactory import fake_factory class KittenProvider(BaseProvider): def kittens(self): return 'meow %d' % (self.random_number(digits=10), ) @given(fake_factory('kittens', providers=[KittenProvider])) def test_kittens_meow(kitten): assert 'meow' in kitten @given(fake_factory('email')) def test_email(email): assert '@' in email @given(fake_factory('name', locale='en_US')) def test_english_names_are_ascii(name): name.encode('ascii') def test_french_names_may_have_an_accent():
from hypothesis import settings, given from hypothesis.extra.fakefactory import fake_factory from hypothesis.strategies import sampled_from from infrastructure.kanban_application import get_kanban_application from tests.test_app import VALID_PASSWORDS init_kanban_application_w_sqlalchemy() @settings(max_examples=2) @given(name=fake_factory('name'), password=sampled_from(VALID_PASSWORDS), email=fake_factory('email'), default_domain=fake_factory('domain_name')) def test_new_user(name, password, email, default_domain): app = get_kanban_application()
def test_kittens_meow(): @given(fake_factory(u'kittens', providers=[KittenProvider])) def inner(kitten): assert u'meow' in kitten inner()
profile = Profile('12345678', Name('Foo Bar', 'Bar, Foo'), '0000-0002-1825-0097') assert normalize(profile) == { 'id': '12345678', 'name': { 'preferred': 'Foo Bar', 'index': 'Bar, Foo', }, 'emailAddresses': [], 'affiliations': [], 'orcid': '0000-0002-1825-0097' } @given(text(), text(), text(), text(), fake_factory('email')) def test_it_normalizes_profile_with_single_email_address( id_, preferred, index, orcid, email): profile = Profile(id_, Name(preferred, index), orcid) profile.add_email_address(email) normalized_profile = normalize(profile) assert len(normalized_profile['emailAddresses']) == 1 @given(text(), text(), text(), text(), fake_factory('email')) def test_it_normalizes_profile_with_multiple_email_addresses( id_, preferred, index, orcid, email): profile = Profile(id_, Name(preferred, index), orcid) profile.add_email_address(email)
import pytest from hypothesis import given from faker.providers import BaseProvider from hypothesis.strategytests import strategy_test_suite from hypothesis.internal.debug import minimal from hypothesis.searchstrategy import strategy from hypothesis.extra.fakefactory import fake_factory class KittenProvider(BaseProvider): def kittens(self): return u'meow %d' % (self.random_number(digits=10), ) @given(fake_factory(u'kittens', providers=[KittenProvider])) def test_kittens_meow(kitten): assert u'meow' in kitten @given(fake_factory(u'email')) def test_email(email): assert u'@' in email @given(fake_factory(u'name', locale=u'en_US')) def test_english_names_are_ascii(name): name.encode(u'ascii') def test_french_names_may_have_an_accent():
def test_fake_factory_errors_with_unsupported_locale(): with pytest.raises(ValueError): fake_factory( u'name', locale=u'badger_BADGER' )
def test_fake_factory_errors_if_any_locale_is_unsupported(): with pytest.raises(ValueError): fake_factory( u'name', locales=[u'fr_FR', u'en_US', u'mushroom_MUSHROOM'] )
from hypothesis import given, settings from hypothesis.extra.fakefactory import fake_factory from hypothesis.strategies import lists, sets from elvanto_sync import utils with settings(suppress_health_check=[3]): @given(sets(fake_factory('email')), sets(fake_factory('email'))) def test_clean_emails(email_set1, email_set2): utils.clean_emails(elvanto_emails=email_set1, google_emails=email_set2) with settings(suppress_health_check=[3]): @given(lists(fake_factory('email'))) def test_convert_aliases_any_email(emails): utils.generate_all_aliases(emails) def test_convert_aliases_removes_googlemail(): emails = utils.generate_all_aliases([ '*****@*****.**', '*****@*****.**', '*****@*****.**', ]) assert set(emails) == set([ '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**',
from faker.providers import BaseProvider from hypothesis import given from hypothesis.strategytests import strategy_test_suite from hypothesis.internal.debug import minimal from hypothesis.searchstrategy import strategy from hypothesis.extra.fakefactory import fake_factory class KittenProvider(BaseProvider): def kittens(self): return u'meow %d' % (self.random_number(digits=10),) @given(fake_factory(u'kittens', providers=[KittenProvider])) def test_kittens_meow(kitten): assert u'meow' in kitten @given(fake_factory(u'email')) def test_email(email): assert u'@' in email @given(fake_factory(u'name', locale=u'en_US')) def test_english_names_are_ascii(name): name.encode(u'ascii') def test_french_names_may_have_an_accent():
from hypothesis import given from hypothesis.extra.fakefactory import fake_factory from hypothesis.strategies import sampled_from from pytest import raises from kanban.domain.model.user import User PASSWORDS = [ '$pbkdf2-sha512$200000$rrU25pxTSsn5n5NyjvH.Pw$PKLSamXKl5S/guVvYVAodJr3tcCGkvEdRt0OtnZizsuGrWowhqVxzumih13hfnssE2jbJONXaAYXcm0ZZTa/dw', '$pbkdf2-sha512$200000$9b43hhCCsPb./z.ntDbGmA$613qQeZZpUOwsuauA1mwMFJM5r/hJt4sOV3agBEOVC84ix.sxISGCeo/wrXM2mIJ3PVQR.7Y92YPdC1XYxph0g' ] @given(name=fake_factory('name'), email=fake_factory('email'), password=sampled_from(PASSWORDS), default_domain=fake_factory('domain_name')) def test_create_user(name, email, password, default_domain): user = User.create(name=name, password=password, email=email, default_domain=default_domain) assert user.name == name assert user.email == email assert user.password == password assert user.default_domain == default_domain assert default_domain in user.domains @given(password=sampled_from(PASSWORDS)) def test_create_user_w_invalid_name_raises_attribute_error(password):
def test_fake_factory_errors_with_both_locale_and_locales(): with pytest.raises(ValueError): fake_factory( u'name', locale=u'fr_FR', locales=[u'fr_FR', u'en_US'] )
# -*- coding: utf-8 -*- from hypothesis import given from hypothesis.extra.fakefactory import fake_factory from hypothesis.strategies import sets from elvanto_sync import utils @given(sets(fake_factory('email')), sets(fake_factory('email')) ) def test_clean_emails(email_set1, email_set2): utils.clean_emails(elvanto_emails=email_set1, google_emails=email_set2) def test_retry_request200(): r = utils.retry_request('http://www.example.com/', 'get') r.status_code == 200 def test_retry_request404(): r = utils.retry_request('http://www.github.com/monty5811/DoesNotExist', 'get') r.status_code == 404
def test_factory_errors_with_source_for_unsupported_locale(): with pytest.raises(ValueError): fake_factory(u'state', locale=u'ja_JP')
import pytest from hypothesis import given from faker.providers import BaseProvider from hypothesis.strategytests import strategy_test_suite from hypothesis.internal.debug import minimal from hypothesis.searchstrategy import strategy from hypothesis.extra.fakefactory import fake_factory class KittenProvider(BaseProvider): def kittens(self): return "meow %d" % (self.random_number(digits=10),) @given(fake_factory("kittens", providers=[KittenProvider])) def test_kittens_meow(kitten): assert "meow" in kitten @given(fake_factory("email")) def test_email(email): assert "@" in email @given(fake_factory("name", locale="en_US")) def test_english_names_are_ascii(name): name.encode("ascii") def test_french_names_may_have_an_accent():
def test_fake_factory_errors_if_unsupported_method(): with pytest.raises(ValueError): fake_factory(u'spoon')
def test_french_names_may_have_an_accent(): minimal(fake_factory("name", locale="fr_FR"), lambda x: "é" not in x)
def test_can_get_specification_for_fake_factory(): ff = fake_factory(u'email') strategy(ff)