Exemple #1
0
 class Params:
     is_secure = False
     key_pair = factory.LazyFunction(generate_new_rsa_identity)
Exemple #2
0
class LeaveFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.Leave

    description = factory.LazyFunction(lambda: fake.text(max_nb_chars=200))
Exemple #3
0
class ProjectContractFactory(ContractFactory):
    class Meta:
        model = models.ProjectContract

    fixed_fee = factory.LazyFunction(lambda: random.randint(0, 9999))
Exemple #4
0
class CorporateEndorsementFactory(DictFactoryBase):
    corporation_name = factory.Faker('company')
    image = ImageFactory()
    individual_endorsements = factory.LazyFunction(
        partial(generate_instances, EndorserFactory))
Exemple #5
0
class SeatFactory(DictFactoryBase):
    currency = 'USD'
    price = factory.Faker('random_int')
    sku = factory.LazyFunction(generate_seat_sku)
    type = 'verified'
    upgrade_deadline = factory.LazyFunction(generate_zulu_datetime)
Exemple #6
0
class ProjectFactory(WarehouseFactory):
    class Meta:
        model = Project

    id = factory.LazyFunction(uuid.uuid4)
    name = factory.fuzzy.FuzzyText(length=12)
Exemple #7
0
class IssueFactory(TitledFactory):
    class Meta:
        model = all_models.Issue

    due_date = factory.LazyFunction(datetime.datetime.utcnow)
class GoodChangesetFactory(HarmfulChangesetFactory):
    harmful = False
    checked = True
    check_user = factory.SubFactory(UserFactory)
    check_date = factory.LazyFunction(timezone.now)
Exemple #9
0
class Annotation(ModelFactory):
    class Meta:
        model = models.Annotation
        sqlalchemy_session_persistence = (
            "flush"  # Always flush the db to generate annotation.id.
        )

    tags = factory.LazyFunction(lambda: FAKER.words(nb=random.randint(0, 5)))
    target_uri = factory.Faker("uri")
    text = factory.Faker("paragraph")
    userid = factory.LazyFunction(lambda: "acct:{username}@{authority}".format(
        username=FAKER.user_name(), authority=FAKER.domain_name(levels=1)))
    document = factory.SubFactory(Document)
    groupid = "__world__"

    @factory.lazy_attribute
    def target_selectors(self):
        return [
            {
                "endContainer":
                "/div[1]/article[1]/section[1]/div[1]/div[2]/div[1]",
                "endOffset": 76,
                "startContainer":
                "/div[1]/article[1]/section[1]/div[1]/div[2]/div[1]",
                "startOffset": 0,
                "type": "RangeSelector",
            },
            {
                "end": 362,
                "start": 286,
                "type": "TextPositionSelector"
            },
            {
                "exact":
                "If you wish to install Hypothesis on your own site then head over to GitHub.",
                "prefix": " browser extension.\n            ",
                "suffix": "\n          \n        \n      \n    ",
                "type": "TextQuoteSelector",
            },
        ]

    @factory.post_generation
    def make_metadata(self, create, extracted, **kwargs):
        """Create associated document metadata for the annotation."""
        # The metadata objects are going to be added to the db, so if we're not
        # using the create strategy then simply don't make any.
        if not create:
            return

        def document_uri_dict():
            """
            Return a randomly generated DocumentURI dict for this annotation.

            This doesn't add anything to the database session yet.
            """
            document_uri = DocumentURI.build(document=None,
                                             claimant=self.target_uri,
                                             uri=self.target_uri)
            return dict(
                claimant=document_uri.claimant,
                uri=document_uri.uri,
                type=document_uri.type,
                content_type=document_uri.content_type,
            )

        document_uri_dicts = [
            document_uri_dict() for _ in range(random.randint(1, 3))
        ]

        def document_meta_dict(type_=None):
            """
            Return a randomly generated DocumentMeta dict for this annotation.

            This doesn't add anything to the database session yet.
            """
            kwargs = {"document": None, "claimant": self.target_uri}

            if type_ is not None:
                kwargs["type"] = type_

            document_meta = DocumentMeta.build(**kwargs)

            return dict(
                claimant=document_meta.claimant,
                type=document_meta.type,
                value=document_meta.value,
            )

        document_meta_dicts = [
            document_meta_dict() for _ in range(random.randint(1, 3))
        ]

        # Make sure that there's always at least one DocumentMeta with
        # type='title', so that we never get annotation.document.title is None:
        if "title" not in [m["type"] for m in document_meta_dicts]:
            document_meta_dicts.append(document_meta_dict(type_="title"))

        self.document = update_document_metadata(
            orm.object_session(self),
            self.target_uri,
            document_meta_dicts=document_meta_dicts,
            document_uri_dicts=document_uri_dicts,
            created=self.created,
            updated=self.updated,
        )

    @factory.post_generation
    def make_id(self, create, extracted, **kwargs):
        """Add a randomly ID if the annotation doesn't have one yet."""
        # If using the create strategy don't generate an id.
        # models.Annotation.id's server_default function will generate one
        # when the annotation is saved to the DB.
        if create:
            return

        # Don't generate an id if the user passed in one of their own.
        if getattr(self, "id", None):
            return

        self.id = uuid.uuid4().hex

    @factory.post_generation
    def timestamps(self, create, extracted, **kwargs):
        # If using the create strategy let sqlalchemy set the created and
        # updated times when saving to the DB.
        if create:
            return

        # When using the build or stub strategy sqlalchemy won't set created or updated
        # times for us, so do it ourselves instead.
        #
        # We're generating created and updated separately (calling now() twice
        # instead of just once) so created and updated won't be exactly the
        # same. This is consistent with how models.Annotation does it when
        # saving to the DB.
        self.created = self.created or datetime.datetime.now()
        self.updated = self.updated or datetime.datetime.now()
Exemple #10
0
class CarModelFactory(factory.DjangoModelFactory):
    brand = factory.SubFactory(CarBrandFactory)
    name = factory.LazyFunction(lambda: uuid4().hex)

    class Meta:
        model = CarModel
class HarmfulChangesetFactory(SuspectChangesetFactory):
    checked = True
    check_user = factory.SubFactory(UserFactory)
    check_date = factory.LazyFunction(timezone.now)
    harmful = True
Exemple #12
0
class OrderFactory(factory.django.DjangoModelFactory):
    """Order factory."""

    created_by = factory.SubFactory(AdviserFactory)
    modified_by = factory.SelfAttribute('created_by')
    company = factory.SubFactory(CompanyFactory)
    contact = factory.SubFactory(
        ContactFactory,
        company=factory.SelfAttribute('..company'),
    )
    primary_market_id = Country.france.value.id
    sector_id = Sector.aerospace_assembly_aircraft.value.id
    uk_region_id = UKRegion.england.value.id
    description = factory.Faker('text')
    contacts_not_to_approach = factory.Faker('text')
    product_info = factory.Faker('text')
    further_info = factory.Faker('text')
    existing_agents = factory.Faker('text')
    permission_to_approach_contacts = factory.Faker('text')
    delivery_date = factory.LazyFunction(
        lambda: (now() + datetime.timedelta(days=60)).date(), )
    contact_email = factory.Faker('email')
    contact_phone = '+44 (0)7123 123456'
    status = OrderStatus.DRAFT
    po_number = factory.Faker('text', max_nb_chars=50)
    discount_value = factory.Faker('random_int', max=100)
    discount_label = factory.Faker('text', max_nb_chars=50)
    vat_status = VATStatus.EU
    vat_number = '0123456789'
    vat_verified = True
    billing_company_name = factory.LazyAttribute(lambda o: o.company.name)
    billing_contact_name = factory.Faker('name')
    billing_email = factory.Faker('email')
    billing_phone = '+44 (0)444 123456'
    billing_address_1 = factory.Sequence(lambda n: f'Apt {n}.')
    billing_address_2 = factory.Sequence(lambda n: f'{n} Foo st.')
    billing_address_country_id = Country.united_kingdom.value.id
    billing_address_county = factory.Faker('text')
    billing_address_postcode = factory.Faker('postcode')
    billing_address_town = factory.Faker('city')

    @to_many_field
    def service_types(self):
        """
        Add support for setting service_types.
        If nothing specified when instantiating the object, the value returned by
        this method will be used by default.
        """
        return ServiceType.objects.filter(
            disabled_on__isnull=True).order_by('?')[:2]

    @to_many_field
    def assignees(self):
        """
        Add support for setting assignees.
        If nothing specified when instantiating the object, the value returned by
        this method will be used by default.
        """
        return OrderAssigneeFactory.create_batch(1, order=self, is_lead=True)

    class Meta:
        model = 'order.Order'
 class Params:
     hq = factory.Trait(headquarter_type=factory.LazyFunction(
         lambda: random_obj_for_model(HeadquarterType)), )
Exemple #14
0
class GroupFactory(factory.alchemy.SQLAlchemyModelFactory):
    class Meta(BaseMeta):
        model = Group

    name = factory.LazyFunction(lambda: str(uuid.uuid4()))
    users = []
Exemple #15
0
class PublicKeyFactory(factory.Factory):
    class Meta:
        model = keys.PublicKey

    public_key_bytes = factory.LazyFunction(_mk_public_key_bytes)
Exemple #16
0
class EventStockFactory(StockFactory):
    offer = factory.SubFactory(EventOfferFactory)
    beginningDatetime = factory.LazyFunction(
        lambda: datetime.datetime.now() + datetime.timedelta(days=5))
    bookingLimitDatetime = factory.LazyAttribute(
        lambda stock: stock.beginningDatetime - datetime.timedelta(minutes=60))
Exemple #17
0
    users = utils.session.query(models.User)
    users = {u.id: u for u in list(users)}
    print(f'{len(users)} created.')

    print('Creating Pictures...', end=' ', flush=True)
    pictures = PictureFactory.build_batch(size=NUM_PICTURES)
    utils.session.bulk_save_objects(pictures)
    utils.session.commit()
    pictures = list(utils.session.query(models.Picture))
    all_user_ids = set(users.keys())
    print(f'{len(pictures)} created.')

    print('Creating Listings...', end=' ', flush=True)
    listings = ListingFactory.build_batch(
        size=NUM_LISTINGS,
        seller_id=factory.LazyFunction(
            lambda: fake.random_element(all_user_ids)))
    utils.session.bulk_save_objects(listings)
    utils.session.commit()
    listings = {l.id: l for l in utils.session.query(models.Listing)}
    print(f'{len(listings)} created.')

    print('Creating Bids...', end=' ', flush=True)
    max_bids_data = []
    all_bids = []
    for l in listings.values():
        user_ids = all_user_ids - {l.seller_id}
        bids_size = random.randint(MIN_BIDS, MAX_BIDS)
        bidders = random.choices([x for x in users.values()], k=bids_size)
        bidder_gen1 = (x for x in bidders)
        bidder_gen2 = (x for x in bidders)
        bids = BidFactory.build_batch(
Exemple #18
0
from app.api.mines.incidents.models.mine_incident import MineIncident
from app.api.mines.status.models.mine_status import MineStatus
from app.api.mines.subscription.models.subscription import Subscription
from app.api.mines.tailings.models.tailings import MineTailingsStorageFacility
from app.api.parties.party.models.party import Party
from app.api.parties.party.models.address import Address
from app.api.parties.party_appt.models.mine_party_appt import MinePartyAppointment
from app.api.mines.permits.permit.models.permit import Permit
from app.api.mines.permits.permit_amendment.models.permit_amendment import PermitAmendment
from app.api.mines.permits.permit_amendment.models.permit_amendment_document import PermitAmendmentDocument
from app.api.users.core.models.core_user import CoreUser, IdirUserDetail
from app.api.users.minespace.models.minespace_user import MinespaceUser
from app.api.variances.models.variance import Variance
from app.api.parties.party_appt.models.party_business_role_appt import PartyBusinessRoleAppointment

GUID = factory.LazyFunction(uuid.uuid4)
TODAY = factory.LazyFunction(datetime.now)

FACTORY_LIST = []


class FactoryRegistry:
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        FACTORY_LIST.append(cls)


class BaseFactory(factory.alchemy.SQLAlchemyModelFactory, FactoryRegistry):
    class Meta:
        abstract = True
        sqlalchemy_session = db.session
Exemple #19
0
class CourseCredential(DictFactoryBase):
    credential_id = factory.Faker('random_int')
    course_id = factory.LazyFunction(generate_course_run_key)
    certificate_type = 'verified'
Exemple #20
0
class MineFactory(BaseFactory):
    class Meta:
        model = Mine

    class Params:
        minimal = factory.Trait(
            mine_no=None,
            mine_note=None,
            mine_region='NE',
            mine_location=None,
            mine_type=None,
            verified_status=None,
            mine_status=None,
            mine_tailings_storage_facilities=0,
            mine_permit=0,
            mine_expected_documents=0,
            mine_incidents=0,
            mine_variance=0,
        )

    mine_guid = GUID
    mine_no = factory.Faker('ean', length=8)
    mine_name = factory.Faker('company')
    mine_note = factory.Faker('sentence', nb_words=6, variable_nb_words=True)
    major_mine_ind = factory.Faker('boolean', chance_of_getting_true=50)
    mine_region = factory.LazyFunction(RandomMineRegionCode)
    ohsc_ind = factory.Faker('boolean', chance_of_getting_true=50)
    union_ind = factory.Faker('boolean', chance_of_getting_true=50)
    mine_location = factory.RelatedFactory(MineLocationFactory, 'mine')
    mine_type = factory.RelatedFactory(MineTypeFactory, 'mine')
    verified_status = factory.RelatedFactory(MineVerifiedStatusFactory, 'mine')
    mine_status = factory.RelatedFactory(MineStatusFactory, 'mine')
    mine_tailings_storage_facilities = []
    mine_permit = []
    mine_expected_documents = []
    mine_incidents = []
    mine_variance = []

    @factory.post_generation
    def mine_tailings_storage_facilities(obj, create, extracted, **kwargs):
        if not create:
            return

        if not isinstance(extracted, int):
            extracted = 1

        MineTailingsStorageFacilityFactory.create_batch(size=extracted, mine=obj, **kwargs)

    @factory.post_generation
    def mine_permit(obj, create, extracted, **kwargs):
        if not create:
            return

        if not isinstance(extracted, int):
            extracted = 1

        PermitFactory.create_batch(size=extracted, mine=obj, **kwargs)

    @factory.post_generation
    def mine_expected_documents(obj, create, extracted, **kwargs):
        if not create:
            return

        if not isinstance(extracted, int):
            extracted = 1

        MineExpectedDocumentFactory.create_batch(size=extracted, mine=obj, **kwargs)

    @factory.post_generation
    def mine_incidents(obj, create, extracted, **kwargs):
        if not create:
            return

        if not isinstance(extracted, int):
            extracted = 1

        MineIncidentFactory.create_batch(size=extracted, mine_guid=obj.mine_guid, **kwargs)

    @factory.post_generation
    def mine_variance(obj, create, extracted, **kwargs):
        if not create:
            return

        if not isinstance(extracted, int):
            extracted = 1

        VarianceFactory.create_batch(size=extracted, mine=obj, **kwargs)
Exemple #21
0
class EventFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Event

    id = factory.Sequence(lambda n: f"evt_{n}")
    data = factory.LazyFunction(lambda: {})
Exemple #22
0
 class Params:
     expired = factory.Trait(
         expiration_date=factory.LazyFunction(timezone.now))
Exemple #23
0
class ProgramTypeFactory(DictFactoryBase):
    name = factory.Faker('word')
    logo_image = factory.LazyFunction(generate_sized_stdimage)
Exemple #24
0
class ProgramFactory(factory.django.DjangoModelFactory):
    class Meta(object):
        model = Program

    title = factory.Sequence(lambda n: 'test-program-{}'.format(n))  # pylint: disable=unnecessary-lambda
    uuid = factory.LazyFunction(uuid4)
    subtitle = FuzzyText()
    type = factory.SubFactory(ProgramTypeFactory)
    status = ProgramStatus.Active
    marketing_slug = factory.Sequence(lambda n: 'test-slug-{}'.format(n))  # pylint: disable=unnecessary-lambda
    banner_image_url = FuzzyText(prefix='https://example.com/program/banner')
    card_image_url = FuzzyText(prefix='https://example.com/program/card')
    partner = factory.SubFactory(PartnerFactory)
    overview = FuzzyText()
    weeks_to_complete = FuzzyInteger(1)
    min_hours_effort_per_week = FuzzyInteger(2)
    max_hours_effort_per_week = FuzzyInteger(4)
    credit_redemption_overview = FuzzyText()
    order_courses_by_start_date = True

    @factory.post_generation
    def courses(self, create, extracted, **kwargs):
        if create:  # pragma: no cover
            add_m2m_data(self.courses, extracted)

    @factory.post_generation
    def excluded_course_runs(self, create, extracted, **kwargs):
        if create:  # pragma: no cover
            add_m2m_data(self.excluded_course_runs, extracted)

    @factory.post_generation
    def authoring_organizations(self, create, extracted, **kwargs):
        if create:  # pragma: no cover
            add_m2m_data(self.authoring_organizations, extracted)

    @factory.post_generation
    def corporate_endorsements(self, create, extracted, **kwargs):
        if create:  # pragma: no cover
            add_m2m_data(self.corporate_endorsements, extracted)

    @factory.post_generation
    def credit_backing_organizations(self, create, extracted, **kwargs):
        if create:  # pragma: no cover
            add_m2m_data(self.credit_backing_organizations, extracted)

    @factory.post_generation
    def expected_learning_items(self, create, extracted, **kwargs):
        if create:  # pragma: no cover
            add_m2m_data(self.expected_learning_items, extracted)

    @factory.post_generation
    def faq(self, create, extracted, **kwargs):
        if create:  # pragma: no cover
            add_m2m_data(self.faq, extracted)

    @factory.post_generation
    def individual_endorsements(self, create, extracted, **kwargs):
        if create:  # pragma: no cover
            add_m2m_data(self.individual_endorsements, extracted)

    @factory.post_generation
    def job_outlook_items(self, create, extracted, **kwargs):
        if create:  # pragma: no cover
            add_m2m_data(self.job_outlook_items, extracted)
Exemple #25
0
class LeaveTypeFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.LeaveType

    name = factory.Sequence(lambda n: 'LeaveType%d' % n)
    description = factory.LazyFunction(lambda: fake.text(max_nb_chars=200))
Exemple #26
0
class UserFactory(factory.django.DjangoModelFactory):
    email = factory.LazyFunction(faker.email)
    username = factory.LazyAttribute(lambda a: a.email)

    class Meta:
        model = get_user_model()
Exemple #27
0
class LeaveDateFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.LeaveDate

    starts_at = factory.LazyFunction(lambda: fake.date_time_between(start_date='-1h', end_date='now', tzinfo=utc))
    ends_at = factory.LazyFunction(lambda: fake.date_time_between(start_date='now', end_date='+1h', tzinfo=utc))
Exemple #28
0
class PrivateKeyFactory(factory.Factory):
    class Meta:
        model = keys.PrivateKey

    private_key_bytes = factory.LazyFunction(_mk_private_key_bytes)
Exemple #29
0
class ConsultancyContractFactory(ContractFactory):
    class Meta:
        model = models.ConsultancyContract

    duration = factory.LazyFunction(lambda: random.randint(0, 9999))
    day_rate = factory.LazyFunction(lambda: random.randint(0, 9999))
Exemple #30
0
 class Params:
     is_secure = False
     key_pair = factory.LazyFunction(generate_new_rsa_identity)
     muxer_opt = {MPLEX_PROTOCOL_ID: Mplex}