def test_is_blocked(self): # A place without blocking dates is expected to be unblocked. place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=None, blocked_until=None) self.assertFalse(place.is_blocked) # A place with blocking start date and without unblocking date is expected to be blocked. place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=Faker('past_date'), blocked_until=None) self.assertTrue(place.is_blocked) place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=date.today(), blocked_until=None) self.assertTrue(place.is_blocked) place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=Faker('future_date'), blocked_until=None) self.assertTrue(place.is_blocked) # A place without blocking start date and with unblocking date in the past is expected to be unblocked. place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=None, blocked_until=Faker('past_date')) self.assertFalse(place.is_blocked) # A place without blocking start date and with future unblocking date is expected to be blocked. place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=None, blocked_until=date.today()) self.assertTrue(place.is_blocked) place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=None, blocked_until=Faker('future_date')) self.assertTrue(place.is_blocked) # A place with blocking dates in the past is expected to be unblocked. place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=Faker('date_between', start_date='-2y', end_date='-1y'), blocked_until=Faker('date_between', start_date='-11M', end_date='-1d')) self.assertFalse(place.is_blocked) # A place with blocking start date in the past and with future unblocking date is expected to be blocked. place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=Faker('date_between', start_date='-2y', end_date='-1y'), blocked_until=date.today()) self.assertTrue(place.is_blocked) place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=Faker('date_between', start_date='-2y', end_date='-1y'), blocked_until=Faker('future_date')) self.assertTrue(place.is_blocked) # A place with future blocking start date is expected to be blocked. place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=date.today(), blocked_until=date.today()) self.assertTrue(place.is_blocked) place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=date.today(), blocked_until=Faker('future_date')) self.assertTrue(place.is_blocked) place = PlaceFactory.build(owner=self.basic_place.owner, blocked_from=Faker('date_between', start_date='+1d', end_date='+11M'), blocked_until=Faker('date_between', start_date='+1y', end_date='+2y')) self.assertTrue(place.is_blocked)
class CompanyFactory(DjangoModelFactory): name = Faker('company') class Meta: model = Company
class UserFactory(DjangoModelFactory): class Meta: model = User email = Faker('email')
class MemoryMetricsFactory(Factory): class Meta: model = MemoryMetrics rss = Faker('random_int') vms = Faker('random_int')
class TypeFactory(DjangoModelFactory): class Meta: model = Type name = Faker('file_extension')
"""Factory for location JSON""" cities = [ "Kathmandu, मध्यमाञ्चल विकास क्षेत्र, Nepal", "Paris, Île-de-France, France", "Cairo, محافظة القاهرة, Egypt", "Tokyo, 東京都, Japan", "Medellín, Antioquia, Colombia", ] def location(self): """Return location JSON with random city name""" return {"value": self.random_element(self.cities)} Faker.add_provider(LocationProvider) class ProfileFactory(DjangoModelFactory): """Factory for Profiles""" name = Faker("name") image = Faker("file_path", extension="jpg") image_small = Faker("file_path", extension="jpg") image_medium = Faker("file_path", extension="jpg") image_file = ImageField() image_small_file = ImageField() image_medium_file = ImageField()
class PlaceFactory(DjangoModelFactory): address = Faker('street_address') name = Faker('company') class Meta: model = Place
def handle(self, *args, **options): try: User.objects.get(username='******') print('super user already exists') except ObjectDoesNotExist: password = Faker('password', length=16, special_chars=True, digits=True, upper_case=True, lower_case=True).generate({}) User.objects.create_superuser('admin', '*****@*****.**', password) pr_number = settings.HEROKU_PR_NUMBER reviewapp_name = settings.HEROKU_APP_NAME branch_name = settings.HEROKU_BRANCH # As of 01/2020 we can only get the PR number if the review app was automatically created # (https://devcenter.heroku.com/articles/github-integration-review-apps#injected-environment-variables). # For review app manually created, we have to use the branch name instead. if pr_number: # Get PR's title from Github token = settings.GITHUB_TOKEN org = 'mozilla' repo = 'donate-wagtail' headers = {'Authorization': f'token {token}'} r = requests.get( f'https://api.github.com/repos/{org}/{repo}/pulls/{pr_number}', headers=headers) r.raise_for_status() try: pr_title = ': ' + r.json()['title'] except KeyError: pr_title = '' for l in r.json()['labels']: if l['name'] == 'dependencies': color = '#BA55D3' break else: color = '#7CD197' fallback_text = f'''New review app deployed: It will be ready in a minute!\n PR {pr_number}{pr_title}\n Login: admin\n Password: {password}\n URL: https://{reviewapp_name}.herokuapp.com''' message_title = f'PR {pr_number}{pr_title}\n' github_url = f'https://github.com/mozilla/donate-wagtail/pull/{pr_number}' github_button_text = 'View PR on Github' else: color = '#7CD197' fallback_text = f'''New review app deployed: It will be ready in a minute!\n Branch: {branch_name}\n Login: admin\n Password: {password}\n URL: https://{reviewapp_name}.herokuapp.com''' message_title = f'Branch: {branch_name}\n' github_url = f'https://github.com/mozilla/donate-wagtail/tree/{branch_name}' github_button_text = 'View branch on Github' slack_payload = { 'attachments': [{ 'fallback': f'{fallback_text}', 'pretext': 'New review app deployed. It will be ready in a minute!', 'title': f'{message_title}', 'text': 'Login: admin\n' f'Password: {password}\n', 'color': f'{color}', 'actions': [{ 'type': 'button', 'text': 'View review app', 'url': f'https://{reviewapp_name}.herokuapp.com' }, { 'type': 'button', 'text': f'{github_button_text}', 'url': f'{github_url}' }] }] } slack_webhook = settings.SLACK_WEBHOOK_RA r = requests.post(f'{slack_webhook}', json=slack_payload, headers={'Content-Type': 'application/json'}) # Raise if post request was a 4xx or 5xx r.raise_for_status() print('Done!')
class ManufacturerFactory(factory.django.DjangoModelFactory): class Meta: model = Manufacturer name = Faker('company_suffix') country = Faker('country_code')
class NewsAgencyFactory(DjangoModelFactory): website = Faker('url') class Meta: model = NewsAgency
class CoreGroup(DjangoModelFactory): name = Faker('name') class Meta: model = CoreGroupM
class CollectionFactory(MP_NodeFactory): name = Faker('text', max_nb_chars=60) class Meta: model = Collection
class ProfileFactory(DjangoModelFactory): """Factory for Profiles""" user = SubFactory(UserFactory) fake_user = True filled_out = Faker('boolean') agreed_to_terms_of_service = Faker('boolean') first_name = Faker('first_name') last_name = Faker('last_name') preferred_name = Faker('name') account_privacy = FuzzyChoice( [choice[0] for choice in Profile.ACCOUNT_PRIVACY_CHOICES]) email_optin = Faker('boolean') edx_employer = FuzzyText(suffix=" corp") edx_job_title = FuzzyText(suffix=" consultant") edx_name = FuzzyText(prefix="User ") edx_bio = FuzzyText() about_me = FuzzyText() romanized_first_name = Faker('first_name') romanized_last_name = Faker('last_name') address = LazyFunction( lambda: '{} {}'.format(FAKE.building_number(), FAKE.street_name())) city = Faker('city') country = Faker('country_code') state_or_territory = Faker('state') @lazy_attribute def postal_code(self): """Postal codes are only required for US and Canada""" if self.country in ("US", "CA"): return FAKE.postcode() return None phone_number = Faker('numerify', text='+# (###) ###-####') birth_country = Faker('country_code') nationality = Faker('country_code') edx_requires_parental_consent = Faker('boolean') date_of_birth = FuzzyDate(date(1850, 1, 1)) edx_level_of_education = FuzzyChoice( [None] + [choice[0] for choice in Profile.LEVEL_OF_EDUCATION_CHOICES]) edx_goals = FuzzyText() preferred_language = Faker('language_code') edx_language_proficiencies = LazyFunction( lambda: [FAKE.text() for _ in range(3)]) gender = FuzzyChoice([choice[0] for choice in Profile.GENDER_CHOICES]) edx_mailing_address = FuzzyText() date_joined_micromasters = FuzzyDateTime( datetime(1850, 1, 1, tzinfo=timezone.utc)) student_id = None mail_id = LazyFunction(uuid.uuid4) image = ImageField() image_small = ImageField() image_medium = ImageField() updated_on = FuzzyDateTime(datetime(1850, 1, 1, tzinfo=timezone.utc)) class Meta: model = Profile class Params: validated = Trait( filled_out=True, phone_number='+1-800-888-8888', country='US', state_or_territory='US-MA', postal_code='02142', agreed_to_terms_of_service=True, ) @classmethod def create_batch(cls, *args, **kwargs): """ Ensure that signals are muted before running the base create_batch method """ with mute_signals(post_save): return super().create_batch(*args, **kwargs)
class FormFactory(factory.django.DjangoModelFactory): class Meta: model = models.Form name = Faker('company') section = Faker('bs')
class TeacherFactory(CommonUserFactory): class Meta: model = Teacher bio = Faker('text', max_nb_chars=500, ext_word_list=None)
class Profile_SubFactory(MongoEngineFactory): class Meta: model = Profile id = Sequence(lambda n: '1%07d' % n) name = Faker(provider='name', locale='nl_NL')
class VideoCategoryFactory(DjangoModelFactory): name = Faker('name') class Meta: model = VideoCategory
class TagFactory(DjangoModelFactory): class Meta: model = Tag name = Faker('sentence')
class BlogAuthorFactory(DjangoModelFactory): class Meta: model = BlogAuthor name = Faker('name')
class ResourceFactory(DjangoModelFactory): class Meta: model = Resource name = Faker('word') url = Faker('url')
class AgencyFactory(DjangoModelFactory): class Meta: model = Agency name = Faker("company")
class FileFactory(DjangoModelFactory): name = Faker("file_name") class Meta: model = models.File
from datetime import timezone from factory import ( DjangoModelFactory, Faker, Trait, LazyAttribute, post_generation, ) from networkapi.utility.faker_providers import ImageProvider from networkapi.highlights.models import Highlight Faker.add_provider(ImageProvider) class HighlightFactory(DjangoModelFactory): class Meta: model = Highlight exclude = ( 'title_sentence', 'link_label_words', 'footer_sentence', ) class Params: unpublished = Trait(publish_after=Faker( 'future_datetime', end_date='+30d', tzinfo=timezone.utc)) has_expiry = Trait(expires=Faker( 'future_datetime', end_date='+30d', tzinfo=timezone.utc)) expired = Trait(expires=Faker(
class UserFactory(DjangoModelFactory): username = Faker('user_name') password = PostGenerationMethodCall('set_password', 'secret') class Meta: model = User
def image_name(self, create, extracted, **kwargs): self.image.name = Faker('generic_image').generate({})
class MemoryItemSummaryFactory(Factory): class Meta: model = MemoryItemSummary avg = Faker('pydecimal', left_digits=10, right_digits=4, positive=True)
class CatFactory(DjangoModelFactory): name = Faker("first_name") class Meta: model = Cat django_get_or_create = ["name"]
class FoodFactory(DjangoModelFactory): name = Faker('food') # category = Faker('sentence') class Meta: model = Food
import random from bson import ObjectId from factory import Dict, Faker, LazyAttribute, SelfAttribute, Sequence, SubFactory, sequence from factory.fuzzy import reseed_random, FuzzyInteger, FuzzyChoice from factory.mongoengine import MongoEngineFactory from profilehooks import profile from facebook_objects import * # Set random to generate the same data set each time seed = 4 random.seed(seed) reseed_random(seed) # set random seed for factory.fuzzy Faker._get_faker().seed(seed) # set random state for factory.Faker # ToDo: implement different FbRawPost instances with the same profile # see: http://stackoverflow.com/questions/39345286/how-to-create-factory-boy-factories-for-django-models-with-the-same-foreign-key # ToDo: why does 'create' upserts document ? # Tweak: make length of lists (comment, likes,..) random, and not =n # Tweak: Make like_count and comment_count the numer of likes and comments iso random int class Profile_SubFactory(MongoEngineFactory): class Meta: model = Profile id = Sequence(lambda n: '1%07d' % n) name = Faker(provider='name', locale='nl_NL')
import pytest from factory import Faker from factory.base import FactoryMetaClass from graphene import ResolveInfo from graphql.error import format_error from pytest_factoryboy import register from snapshottest.pytest import PyTestSnapshotTest from .core.faker import MultilangProvider from .form import factories as form_factories from .schema import schema from .user.models import AnonymousUser, OIDCUser from .workflow import factories as workflow_factories Faker.add_provider(MultilangProvider) def register_module(module): for name, obj in inspect.getmembers(module): if isinstance(obj, FactoryMetaClass) and not obj._meta.abstract: register(obj) register_module(form_factories) register_module(workflow_factories) @pytest.fixture def snapshot(request): class GraphQlSnapshotTest(PyTestSnapshotTest):
""" pattern = "{{first_name}}{{city_suffix}}" return self.generator.parse(pattern) def municipality(self): """ Formatter for generating danish municipality names """ return self.generator.parse("{{city}} kommune") def street_name(self): """ Formatter for generating danish street names """ return self.generator.parse("{{name}}s {{street_suffix}}") Faker.add_provider(CodingPiratesProvider, locale="dk_DK") Faker.add_provider(DanishProvider, locale="dk_DK") LOCALE = "dk_DK" TIMEZONE = pytz.timezone("Europe/Copenhagen") # Setting default locale (this is not documented or intended by factory_boy) Faker._DEFAULT_LOCALE = LOCALE def datetime_after(dt): """ For use with lazy attribute to generate DateTime's after the given datetime. """ END_OF_TIME = date.today() + timedelta(days=60 * 365)