Пример #1
0
class ServiceFactory(WorkspaceObjectFactory):
    name = FuzzyText()
    description = FuzzyText()
    port = FuzzyIncrementalInteger(1, 65535)
    protocol = FuzzyChoice(['TCP', 'UDP'])
    host = factory.SubFactory(HostFactory,
                              workspace=factory.SelfAttribute('..workspace'))
    status = FuzzyChoice(Service.STATUSES)
    creator = factory.SubFactory(UserFactory)

    class Meta:
        model = Service
        sqlalchemy_session = db.session

    @classmethod
    def build_dict(cls, **kwargs):
        ret = super().build_dict(**kwargs)
        ret['host'].workspace = kwargs['workspace']
        ret['parent'] = ret['host'].id
        ret['ports'] = [ret['port']]
        ret.pop('host')
        return ret
Пример #2
0
class PermitAmendmentFactory(BaseFactory):
    class Meta:
        model = PermitAmendment

    class Params:
        initial_permit = factory.Trait(
            description='Initial permit issued.',
            permit_amendment_type_code='OGP',
        )
        permit = factory.SubFactory(PermitFactory, permit_amendments=0)

    permit_amendment_guid = GUID
    permit_id = factory.SelfAttribute('permit.permit_id')
    received_date = TODAY
    issue_date = TODAY
    authorization_end_date = factory.Faker('date_between',
                                           start_date='+31d',
                                           end_date='+90d')
    permit_amendment_status_code = 'ACT'
    permit_amendment_type_code = 'AMD'
    description = factory.Faker('sentence', nb_words=6, variable_nb_words=True)
    related_documents = []
Пример #3
0
class IdentityFactory(ModelFactory):
    id = GUIDFactory()
    user = factory.SubFactory('zeus.factories.UserFactory')
    user_id = factory.SelfAttribute('user.id')
    external_id = factory.Faker('email')

    class Meta:
        model = models.Identity

    class Params:
        github = factory.Trait(provider='github',
                               config={
                                   'access_token': 'access-token',
                                   'refresh_token': 'refresh-token',
                                   'scopes': ['user:email', 'repo'],
                               })
        github_basic = factory.Trait(provider='github',
                                     config={
                                         'access_token': 'access-token',
                                         'refresh_token': 'refresh-token',
                                         'scopes': ['user:email']
                                     })
Пример #4
0
class FOIARequestFactory(factory.django.DjangoModelFactory):
    """A factory for creating FOIARequest test objects."""
    class Meta:
        model = FOIARequest

    title = factory.Sequence(lambda n: "FOIA Request %d" % n)
    slug = factory.LazyAttribute(lambda obj: slugify(obj.title))
    user = factory.SubFactory(UserFactory)
    jurisdiction = factory.SubFactory('muckrock.factories.JurisdictionFactory')
    agency = factory.SubFactory(
        'muckrock.factories.AgencyFactory',
        jurisdiction=factory.SelfAttribute('..jurisdiction'))
    email = factory.SubFactory(
        'muckrock.communication.factories.EmailAddressFactory', )

    @factory.post_generation
    def cc_emails(self, create, extracted, **kwargs):
        """Adds M2M cc emails"""
        # pylint: disable=unused-argument
        if create and extracted:
            # A list of emails were passed in, use them
            self.cc_emails.set(EmailAddress.objects.fetch_many(extracted))
Пример #5
0
class MineIncidentFactory(BaseFactory):
    class Meta:
        model = MineIncident

    class Params:
        mine = factory.SubFactory('tests.factories.MineFactory', minimal=True)
        do_subparagraph_count = 2

    mine_incident_id_year = 2019
    mine_incident_guid = GUID
    mine_guid = factory.SelfAttribute('mine.mine_guid')
    incident_timestamp = factory.Faker('past_datetime')
    incident_description = factory.Faker('sentence',
                                         nb_words=20,
                                         variable_nb_words=True)
    reported_timestamp = factory.Faker('past_datetime')
    reported_by_name = factory.Faker('name')
    determination_type_code = factory.LazyFunction(
        RandomIncidentDeterminationTypeCode)
    status_code = factory.LazyFunction(RandomIncidentStatusCode)
    followup_investigation_type_code = 'NO'
    dangerous_occurrence_subparagraphs = factory.LazyAttribute(
        lambda o: SampleDangerousOccurrenceSubparagraphs(o.
                                                         do_subparagraph_count)
        if o.determination_type_code == 'DO' else [])
    documents = []

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

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

        MineIncidentDocumentFactory.create_batch(size=extracted,
                                                 incident=obj,
                                                 mine_document__mine=None,
                                                 **kwargs)
Пример #6
0
class SPIREFootnoteEntryFactory(BaseFactory):
    batch = factory.SubFactory(SPIREBatchFactory)
    footnote = factory.SubFactory(SPIREFootnoteFactory)
    application = factory.SubFactory(SPIREApplicationFactory,
                                     batch=factory.SelfAttribute('..batch'))

    media_footnote_detail = None

    goods_item_id = factory.Faker('random_int', min=1, max=200)
    country_id = None
    fnr_id = None
    start_date = factory.Faker('date_time_between',
                               start_date='-2y',
                               end_date='-1y')
    version_no = factory.Faker('random_int', min=1, max=3)
    status_control = factory.Faker('random_element', elements=['A', 'C'])

    @factory.lazy_attribute
    def fne_id(self):
        return set_pk(SPIREFootnoteEntry, 'fne_id')

    @factory.lazy_attribute
    def mf_free_text(self):
        if self.footnote:
            return
        if self.media_footnote_detail:
            return
        return factory.Faker('sentence').generate({})

    @factory.lazy_attribute
    def mf_grp_id(self):
        if self.footnote:
            return
        if self.mf_free_text or self.media_footnote_detail:
            return factory.Faker('random_element', elements=[1, 2,
                                                             3]).generate({})

    class Meta:
        model = SPIREFootnoteEntry
Пример #7
0
class BookingFactory(BaseFactory):
    class Meta:
        model = models.Booking

    quantity = 1
    stock = factory.SubFactory(offers_factories.StockFactory)
    token = factory.LazyFunction(random_token)
    user = None
    amount = factory.SelfAttribute("stock.price")
    status = models.BookingStatus.CONFIRMED

    @factory.post_generation
    def cancellation_limit_date(self, create, extracted, **kwargs):
        if extracted:
            self.cancellationLimitDate = extracted
        else:
            self.cancellationLimitDate = api.compute_cancellation_limit_date(
                self.stock.beginningDatetime, self.dateCreated)
        db.session.add(self)
        db.session.commit()

    @factory.post_generation
    def cancellation_date(self, create, extracted, **kwargs):
        # the public.save_cancellation_date() psql trigger overrides the extracted cancellationDate
        if extracted:
            self.cancellationDate = extracted
            db.session.add(self)
            db.session.flush()

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        if not kwargs.get("isCancelled", False):
            stock = kwargs.get("stock")
            stock.dnBookedQuantity = stock.dnBookedQuantity + kwargs.get(
                "quantity", 1)
            kwargs["stock"] = stock
        kwargs["venue"] = kwargs["stock"].offer.venue
        kwargs["offerer"] = kwargs["stock"].offer.venue.managingOfferer
        return super()._create(model_class, *args, **kwargs)
Пример #8
0
class StationFactory(AbstractLocationFactory):
    name = factory.Sequence(lambda n: 'Smogly Station %04d' % n)
    type = factory.fuzzy.FuzzyChoice([type_choice[0] for type_choice in Station.TYPE_CHOICES])
    notes = factory.Faker('sentences', nb=3)
    altitude = factory.fuzzy.FuzzyFloat(0.0, 40.0)
    project = factory.SubFactory(ProjectFactory, **{
        'position': factory.SelfAttribute('position'),
        'country': factory.SelfAttribute('country'),
        'state': factory.SelfAttribute('state'),
        'county': factory.SelfAttribute('county'),
        'community': factory.SelfAttribute('community'),
        'district': factory.SelfAttribute('district')
    })
    owner = factory.SubFactory(UserFactory)

    class Meta:
        model = Station
Пример #9
0
class VarianceFactory(BaseFactory):
    class Meta:
        model = Variance

    class Params:
        mine = factory.SubFactory('tests.factories.MineFactory', minimal=True)
        inspector = factory.SubFactory(
            'tests.factories.PartyBusinessRoleFactory')
        approved = factory.Trait(
            variance_application_status_code='APP',
            issue_date=TODAY,
            expiry_date=TODAY,
            inspector_party_guid=factory.SelfAttribute('inspector.party_guid'))
        denied = factory.Trait(
            variance_application_status_code='DEN',
            inspector_party_guid=factory.SelfAttribute('inspector.party_guid'))
        not_applicable = factory.Trait(variance_application_status_code='NAP')

    variance_guid = GUID
    compliance_article_id = factory.LazyFunction(RandomComplianceArticleId)
    mine_guid = factory.SelfAttribute('mine.mine_guid')
    note = factory.Faker('sentence', nb_words=6, variable_nb_words=True)
    parties_notified_ind = factory.Faker('boolean', chance_of_getting_true=50)
    received_date = TODAY
    documents = []

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

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

        VarianceDocumentFactory.create_batch(size=extracted,
                                             variance=obj,
                                             mine_document__mine=None,
                                             **kwargs)
Пример #10
0
class PhaseFactory(factory.Factory):
    class Meta:
        model = Phase

    class Params:
        num_actions = factory.Faker('random_int', min=1, max=5)

    name = factory.Faker('word')
    actions = ListSubFactory(ActionFactory, count=factory.SelfAttribute('num_actions'))
    stage = factory.PostGeneration(
        lambda obj, create, extracted, **kwargs: StageFactory.build(phases=[obj])
    )

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        actions = kwargs.pop('actions')
        new_class = type(model_class.__name__, (model_class,), {'actions': actions})
        return new_class(*args, **kwargs)

    @classmethod
    def _build(cls, model_class, *args, **kwargs):
        # defer to create because parent uses build
        return cls._create(model_class, *args, **kwargs)
Пример #11
0
class SampleVariantStatisticsFactory(factory.django.DjangoModelFactory):
    """Factory for ``SampleVariantStatisticsFactory`` model."""
    class Meta:
        model = SampleVariantStatistics
        exclude = ["variant_set"]

    stats = factory.SubFactory(
        CaseVariantStatsFactory,
        variant_set=factory.SelfAttribute("factory_parent.variant_set"))
    sample_name = factory.Sequence(lambda n: "Donor%d" % n)
    ontarget_transitions = factory.Sequence(lambda n: n + 1)
    ontarget_transversions = factory.Sequence(lambda n: n + 1)
    ontarget_snvs = factory.Sequence(lambda n: n + 1)
    ontarget_indels = factory.Sequence(lambda n: n + 1)
    ontarget_mnvs = factory.Sequence(lambda n: n + 1)
    ontarget_effect_counts = {}
    ontarget_indel_sizes = {}
    ontarget_dps = {}
    ontarget_dp_quantiles = [0.1, 0.2, 0.3, 0.4, 0.5]
    het_ratio = 1.0
    chrx_het_hom = 1.0
    # Dummy argument to pass to CaseCariantStatsFactory
    variant_set = None
Пример #12
0
class UserFactory(factory.alchemy.SQLAlchemyModelFactory):
    class Meta:
        model = User
        sqlalchemy_session = db.session

    id = factory.Sequence(lambda n: n)
    first_name = 'Test'
    last_name = 'Surname'
    email = factory.Faker('email')
    department = factory.SubFactory(DepartmentFactory)
    address_1 = factory.Faker('address')
    address_2 = factory.Faker('address')
    city = factory.Faker('city')
    region = factory.Faker('city')
    postal_code = "00345"
    country = factory.Faker('country')
    shipping_region_id = 1
    day_phone = '555-10101011'
    eve_phone = '555-10101021'
    mob_phone = '555-10101031'
    password_hash = factory.Faker('password')

    department_id = factory.SelfAttribute('department.id')
Пример #13
0
class VenueFactory(BaseFactory):
    class Meta:
        model = models.Venue

    name = factory.Sequence("Le Petit Rintintin {}".format)
    departementCode = factory.LazyAttribute(lambda o: None if o.isVirtual else "75")
    latitude = 48.87004
    longitude = 2.37850
    managingOfferer = factory.SubFactory(OffererFactory)
    address = factory.LazyAttribute(lambda o: None if o.isVirtual else "1 boulevard Poissonnière")
    postalCode = factory.LazyAttribute(lambda o: None if o.isVirtual else "75000")
    city = factory.LazyAttribute(lambda o: None if o.isVirtual else "Paris")
    publicName = factory.SelfAttribute("name")
    siret = factory.LazyAttributeSequence(lambda o, n: f"{o.managingOfferer.siren}{n:05}")
    isVirtual = False
    venueTypeCode = offerers_models.VenueTypeCode.OTHER
    description = factory.Faker("text", max_nb_chars=64)
    audioDisabilityCompliant = False
    mentalDisabilityCompliant = False
    motorDisabilityCompliant = False
    visualDisabilityCompliant = False

    contact = factory.RelatedFactory("pcapi.core.offerers.factories.VenueContactFactory", factory_related_name="venue")
Пример #14
0
class EstimatorFactory(SQLAlchemyModelFactory):
    class Meta:
        model = Estimator
        sqlalchemy_session = db.Session

    id = factory.Sequence(lambda n: n)
    create_date = factory.LazyFunction(datetime.now)

    _estimator = factory.Iterator([
        RandomForestRegressor(),
        RandomForestClassifier(),
    ])
    estimator = factory.SelfAttribute('_estimator')

    _hash = factory.LazyAttribute(lambda o: compute_hash(o.estimator))
    _file_name = factory.LazyAttribute(
        lambda o: 'files/estimators/%s' % o._hash)
    byte_size = factory.LazyAttribute(lambda o: compute_size(o.estimator))

    @factory.post_generation
    def persist_file(self, create, extracted, **kwargs):
        self.persist()
        return self.is_persisted
Пример #15
0
class MineReportFactory(BaseFactory):
    class Meta:
        model = MineReport

    class Params:
        mine = factory.SubFactory('tests.factories.MineFactory', minimal=True)

    mine_report_guid = GUID
    mine_guid = factory.SelfAttribute('mine.mine_guid')
    mine_report_definition_id = factory.LazyFunction(RandomMineReportDefinition)
    due_date = factory.Faker('future_datetime', end_date='+30d')
    submission_year = factory.fuzzy.FuzzyInteger(2020, 3000)
    mine_report_submissions = []

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

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

        MineReportSubmissionFactory.create_batch(size=extracted, report=obj, **kwargs)
Пример #16
0
class EvaluationFactory(factory.alchemy.SQLAlchemyModelFactory):
    class Meta:
        model = schema.TestEvaluation
        sqlalchemy_session = session

    model_rel = factory.SubFactory(ModelFactory)
    subset_hash = ''
    evaluation_start_time = factory.fuzzy.FuzzyNaiveDateTime(datetime(2008, 1, 1))
    evaluation_end_time = factory.fuzzy.FuzzyNaiveDateTime(datetime(2008, 1, 1))
    as_of_date_frequency = "3d"
    metric = "precision@"
    parameter = "100_abs"
    num_labeled_examples = 10
    num_labeled_above_threshold = 8
    num_positive_labels = 5
    sort_seed = 8
    best_value = factory.fuzzy.FuzzyDecimal(0, 1)
    worst_value = factory.fuzzy.FuzzyDecimal(0, 1)
    stochastic_value = factory.fuzzy.FuzzyDecimal(0, 1)
    num_sort_trials = 5
    standard_deviation = 0.05
    matrix_rel = factory.SubFactory(MatrixFactory)
    matrix_uuid = factory.SelfAttribute("matrix_rel.matrix_uuid")
Пример #17
0
class CommunitySignupUnderwayScenario(NewRoundScenario):
    # NOTE - update README.md if you change the documentation for this class
    """
    The `CommunitySignupUnderwayScenario` scenario represents the time when community coordinators are signing communities up to participate in Outreachy. One mentor has submitted their project.

    This scenario creates the following accounts:
     - Community coordinator account (username 'coordinator1'). The coordinator is approved as a coordinator for this community.
     - An initial application reviewer (username 'reviewer1'). The reviewer is approved to see initial applications.
     - Mentor (username 'mentor1')

    This scenario will also create the following database objects:
     - The community will be marked as being approved to participate in the current internship round (`class Participation`).
     - Information about which organization is sponsoring that community's interns this internship round (`class Sponsorship`).
     - One project has been submitted (`class Project`) by mentor1 for this community. The project has been approved by the coordinator. The project title will be randomly generated.

    """

    round__start_from = 'pingold'

    mentor = factory.SubFactory(factories.MentorFactory)

    participation = factory.SubFactory(
        factories.ParticipationFactory,
        community=factory.SelfAttribute('..community'),
        participating_round=factory.SelfAttribute('..round'),
        approval_status=ApprovalStatus.APPROVED,
    )

    sponsorship = factory.SubFactory(
        factories.SponsorshipFactory,
        participation=factory.SelfAttribute('..participation'),
    )

    project = factory.SubFactory(
        factories.ProjectFactory,
        project_round=factory.SelfAttribute('..participation'),
        approval_status=ApprovalStatus.APPROVED,
    )

    mentor_approval = factory.SubFactory(
        factories.MentorApprovalFactory,
        mentor=factory.SelfAttribute('..mentor'),
        project=factory.SelfAttribute('..project'),
        approval_status=ApprovalStatus.APPROVED,
    )
Пример #18
0
class StructureTypeFactory(factory.DjangoModelFactory):
    structure_type_name = faker.text(max_nb_chars=10, ext_word_list=None)
    description = faker.sentence(100)
    is_active = faker.boolean(chance_of_getting_true=50)
    parent = factory.SubFactory(
        'stock_setup_info.factory.StructureTypeFactory')

    class Meta:
        model = StructureType
        exclude = ('child_depth_temp', )

    class Params:
        child_depth = 10

    child_depth_temp = factory.LazyAttribute(lambda o: o.child_depth - 1)
    parent = factory.Maybe(
        factory.LazyAttribute(lambda o: o.child_depth > 0),
        yes_declaration=factory.SubFactory(
            'stock_setup_info.factory.StructureTypeFactory',
            child_depth=factory.SelfAttribute('..child_depth_temp'),
        ),
        no_declaration=None,
    )
Пример #19
0
class EventFactory(factory.django.DjangoModelFactory):
    """Event factory."""

    created_by = factory.SubFactory(AdviserFactory)
    modified_by = factory.SelfAttribute('created_by')
    name = factory.Faker('text')
    event_type_id = EventType.seminar.value.id
    start_date = factory.Faker('date_object')
    end_date = factory.LazyAttribute(lambda event: event.start_date)
    location_type_id = LocationType.hq.value.id
    address_1 = factory.Faker('text')
    address_2 = factory.Faker('text')
    address_town = factory.Faker('text')
    address_postcode = factory.Faker('text')
    address_country_id = Country.united_kingdom.value.id
    uk_region_id = UKRegion.east_of_england.value.id
    notes = factory.Faker('text')
    organiser = factory.SubFactory(AdviserFactory)
    lead_team_id = Team.crm.value.id
    service_id = Service.inbound_referral.value.id
    archived_documents_url_path = factory.Faker('uri_path')
    has_related_trade_agreements = True

    @to_many_field
    def teams(self):  # noqa: D102
        return [Team.crm.value.id, Team.healthcare_uk.value.id]

    @to_many_field
    def related_programmes(self):  # noqa: D102
        return [Programme.great_branded.value.id]

    @to_many_field
    def related_trade_agreements(self):  # noqa: D102
        return [TradeAgreement.uk_japan.value.id]

    class Meta:
        model = 'event.Event'
Пример #20
0
class ActivitySummaryBaseFactory(BaseFactory):
    class Meta:
        model = app_models.ActivitySummaryBase

    class Params:
        now_application = factory.SubFactory(
            'tests.factories.NOWApplicationFactory')

    now_application_id = factory.SelfAttribute(
        'now_application.now_application_id')

    reclamation_description = factory.Faker('sentence',
                                            nb_words=40,
                                            variable_nb_words=True)
    reclamation_cost = factory.Faker('pydecimal',
                                     right_digits=2,
                                     positive=True,
                                     max_value=500000)
    total_disturbed_area = factory.Faker('pydecimal',
                                         right_digits=2,
                                         positive=True,
                                         max_value=500000)
    total_disturbed_area_unit_type_code = factory.LazyFunction(
        RandomUnitTypeCode)
Пример #21
0
class TravelActivityFactory(factory.django.DjangoModelFactory):
    travel_type = models.TravelType.PROGRAMME_MONITORING
    partner = factory.SelfAttribute('partnership.agreement.partner')
    partnership = factory.SubFactory(InterventionFactory)
    result = factory.SubFactory(ResultFactory)
    primary_traveler = factory.SubFactory(UserFactory)
    date = factory.LazyAttribute(lambda o: timezone.now())

    class Meta:
        model = models.TravelActivity

    @factory.post_generation
    def populate_locations(self, create, extracted, **kwargs):
        location = LocationFactory()
        self.locations.add(location)

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

        if extracted:
            for travel in extracted:
                self.travels.add(travel)
Пример #22
0
class BackupScheduleFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.BackupSchedule

    instance = factory.SubFactory(InstanceFactory)
    state = models.BackupSchedule.States.OK
    service_project_link = factory.SelfAttribute('instance.service_project_link')
    retention_time = 10
    is_active = True
    maximal_number_of_resources = 3
    schedule = '0 * * * *'

    @classmethod
    def get_url(cls, schedule, action=None):
        if schedule is None:
            schedule = BackupScheduleFactory()
        url = 'http://testserver' + reverse(
            'openstacktenant-backup-schedule-detail', kwargs={'uuid': schedule.uuid.hex}
        )
        return url if action is None else url + action + '/'

    @classmethod
    def get_list_url(cls):
        return 'http://testserver' + reverse('openstacktenant-backup-schedule-list')
Пример #23
0
class OfferingFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.Offering

    issue = factory.SubFactory(IssueFactory)
    unit_price = fuzzy.FuzzyInteger(1, 10)
    project = factory.SelfAttribute('issue.project')

    @classmethod
    def get_url(cls, offering=None, action=None):
        if offering is None:
            offering = OfferingFactory()
        url = 'http://testserver' + reverse('support-offering-detail',
                                            kwargs={'uuid': offering.uuid.hex})
        return url if action is None else url + action + '/'

    @classmethod
    def get_list_url(cls):
        return 'http://testserver' + reverse('support-offering-list')

    @classmethod
    def get_list_action_url(cls, action=None):
        url = 'http://testserver' + reverse('support-offering-list')
        return url if action is None else url + action + '/'
Пример #24
0
class ContactRecordFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = 'mypartners.ContactRecord'

    contact_type = 'email'
    contact_email = '*****@*****.**'
    subject = 'Test Subject'
    notes = 'Some notes go here.'
    date_time = datetime.now()

    contact = factory.SubFactory(ContactFactory,
                                 name='example-contact',
                                 partner=factory.SelfAttribute('..partner'))
    partner = factory.SubFactory(PartnerFactory)
    approval_status = factory.SubFactory(StatusFactory)

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

        if extracted:
            for tag in extracted:
                self.tags.add(tag)
Пример #25
0
class OrganizationWithProfile(factory.django.DjangoModelFactory):
  """ Includes User. Does not includes staff-entered or fiscal sponsor fields """

  class Meta:
    model = 'grants.Organization'

  name = factory.Sequence(lambda n: '{}{}'.format(fake.company(), n))
  user = factory.SubFactory(OrgUser, first_name=factory.SelfAttribute('..name'))

  address = factory.Faker('street_address')
  city = factory.Faker('city')
  state = factory.LazyAttribute(lambda o: random.choice(gc.STATE_CHOICES)[0])
  zip = factory.Faker('zipcode')
  telephone_number = factory.Faker('phone_number')
  fax_number = factory.Faker('phone_number')
  email_address = factory.Faker('email')
  website = factory.Faker('url')
  contact_person = factory.Faker('name')
  contact_person_title = factory.Faker('job')

  status = factory.LazyAttribute(lambda o: random.choice(gc.STATUS_CHOICES[:3])[0])
  ein = factory.Faker('ean8')
  founded = factory.LazyAttribute(lambda o: random.randrange(1999, 2016))
  mission = factory.Faker('text')
Пример #26
0
class ProfileFactory(factory.django.DjangoModelFactory):
    name = factory.Faker("name")
    email = factory.Faker("safe_email")
    handle = factory.SelfAttribute("email")
    guid = factory.Faker("uuid4")

    # Dummy strings as keys since generating these is expensive
    rsa_private_key = fuzzy.FuzzyText()
    rsa_public_key = fuzzy.FuzzyText()

    # Dummy image urls
    image_url_small = "https://127.0.0.1:8000/foo/small.png"
    image_url_medium = "https://127.0.0.1:8000/foo/medium.png"
    image_url_large = "/foo/large.png"

    class Meta:
        model = "users.Profile"

    @factory.post_generation
    def with_key(self, extracted, created, **kwargs):
        if not extracted:
            return

        self.generate_new_rsa_key(bits=1024)
class AbstractLeaseFactory(factory.django.DjangoModelFactory):
    comment = factory.Faker("text")
    boat = factory.SubFactory(BoatFactory, owner=factory.SelfAttribute("..customer"))
    customer = factory.SubFactory(CustomerProfileFactory)
class NOWSubmissionFactory(BaseFactory):
    class Meta:
        model = NOWApplication

    class Params:
        mine = factory.SubFactory('tests.factories.MineFactory', minimal=True)
        applicant = factory.SubFactory('tests.factories.NOWClientFactory')
        submitter = factory.SubFactory('tests.factories.NOWClientFactory')
        #now_application_identity = factory.SubFactory('tests.factories.NOWApplicationIdentityFactory')
        all_activites = factory.Trait(
            blasting_operation=True,
            state_of_land=True,
            camps=True,
            cut_lines_polarization_survey=True,
            exploration_access=True,
            exploration_surface_drilling=True,
            mechanical_trenching=True,
            placer_operation=True,
            sand_and_gravel=True,
            surface_bulk_sample=True,
            settling_pond=True,
            underground_exploration=True)
        camps = factory.Trait(
            cbsfreclamation=factory.Faker('sentence', nb_words=3),
            cbsfreclamationcost=factory.fuzzy.FuzzyDecimal(100),
            campbuildstgetotaldistarea=factory.fuzzy.FuzzyDecimal(100),
            fuellubstoreonsite=factory.LazyFunction(randomYesNo)
        )                                                               #details=factory.SubFactory('tests.now_submission_factories.NOWCampDetails'))

        blasting_operation = factory.Trait(
            bcexplosivespermitissued=factory.LazyFunction(randomYesNo),
            bcexplosivespermitnumber=factory.Faker(
                'bothify', text='???#####', letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
            bcexplosivespermitexpiry=factory.Faker('future_datetime', end_date='+30d'),
            storeexplosivesonsite=factory.LazyFunction(randomYesNo))

        state_of_land = factory.Trait(
            landcommunitywatershed=factory.LazyFunction(randomYesNo),
            archsitesaffected=factory.LazyFunction(randomYesNo))

        cut_lines_polarization_survey = factory.Trait(
            cutlinesreclamation=factory.Faker('sentence', nb_words=3),
            cutlinesreclamationcost=factory.fuzzy.FuzzyDecimal(100),
            cutlinesexplgriddisturbedarea=factory.fuzzy.FuzzyDecimal(100))

        exploration_access = factory.Trait(
            expaccessreclamation=factory.Faker('sentence', nb_words=3),
            expaccessreclamationcost=factory.fuzzy.FuzzyDecimal(100),
            expaccesstotaldistarea=factory.fuzzy.FuzzyDecimal(100))

        exploration_surface_drilling = factory.Trait(
            expsurfacedrillreclcorestorage=factory.Faker('sentence', nb_words=1),
            expsurfacedrillreclamationcost=factory.fuzzy.FuzzyDecimal(100),
            expsurfacedrilltotaldistarea=factory.fuzzy.FuzzyDecimal(100))

        mechanical_trenching = factory.Trait(
            mechtrenchingreclamation=factory.Faker('sentence', nb_words=3),
            mechtrenchingreclamationcost=factory.fuzzy.FuzzyDecimal(100),
            mechtrenchingtotaldistarea=factory.fuzzy.FuzzyDecimal(100))

        placer_operation = factory.Trait(
            placerundergroundoperations=factory.LazyFunction(randomYesNo),
            placerhandoperations=factory.LazyFunction(randomYesNo),
            placerreclamationarea=factory.fuzzy.FuzzyDecimal(1000),
            placerreclamation=factory.Faker('sentence', nb_words=2),
            placerreclamationcost=factory.fuzzy.FuzzyDecimal(1000))

        sand_and_gravel = factory.Trait(
            sandgrvqrydepthoverburden=factory.fuzzy.FuzzyDecimal(1000),
            sandgrvqrydepthtopsoil=factory.fuzzy.FuzzyDecimal(1000),
            sandgrvqrystabilizemeasures=factory.Faker('sentence', nb_words=2),
            sandgrvqrywithinaglandres=factory.LazyFunction(randomYesNo),
            sandgrvqryalrpermitnumber=factory.Faker('sentence', nb_words=2),
            sandgrvqrylocalgovsoilrembylaw=factory.LazyFunction(randomYesNo),
            sandgrvqryofficialcommplan=factory.Faker('sentence', nb_words=2),
            sandgrvqrylandusezoning=factory.Faker('sentence', nb_words=2),
            sandgrvqryendlanduse=factory.Faker('sentence', nb_words=2),
            sandgrvqrytotalmineres=factory.fuzzy.FuzzyInteger(1, 100),
            sandgrvqrytotalmineresunits=factory.LazyFunction(randomUnitDescription),
            sandgrvqryannualextrest=factory.fuzzy.FuzzyInteger(1, 100),
            sandgrvqryannualextrestunits=factory.LazyFunction(randomUnitDescription),
            sandgrvqryreclamation=factory.Faker('sentence', nb_words=2),
            sandgrvqryreclamationbackfill=factory.Faker('sentence', nb_words=2),
            sandgrvqryreclamationcost=factory.fuzzy.FuzzyDecimal(1000),
            sandgrvqrygrdwtravgdepth=factory.fuzzy.FuzzyDecimal(100),
            sandgrvqrygrdwtrexistingareas=factory.LazyFunction(randomYesNo),
            sandgrvqrygrdwtrtestpits=factory.LazyFunction(randomYesNo),
            sandgrvqrygrdwtrtestwells=factory.LazyFunction(randomYesNo),
            sandgrvqrygrdwtrother=factory.Faker('sentence', nb_words=2),
            sandgrvqrygrdwtrmeasprotect=factory.Faker('sentence', nb_words=2),
            sandgrvqryimpactdistres=factory.fuzzy.FuzzyInteger(1, 100),
            sandgrvqryimpactdistwater=factory.fuzzy.FuzzyInteger(1, 100),
            sandgrvqryimpactnoise=factory.Faker('sentence', nb_words=3),
            sandgrvqryimpactprvtaccess=factory.Faker('sentence', nb_words=3),
            sandgrvqryimpactprevtdust=factory.Faker('sentence', nb_words=3),
            sandgrvqryimpactminvisual=factory.Faker('sentence', nb_words=3))

        surface_bulk_sample = factory.Trait(
            surfacebulksampleprocmethods=factory.Faker('sentence', nb_words=3),
            surfacebulksamplereclsephandl=factory.Faker('sentence', nb_words=3),
            surfacebulksamplereclamation=factory.Faker('sentence', nb_words=3),
            surfacebulksamplerecldrainmiti=factory.Faker('sentence', nb_words=3),
            surfacebulksamplereclcost=factory.fuzzy.FuzzyDecimal(100),
            surfacebulksampletotaldistarea=factory.fuzzy.FuzzyDecimal(100))

        settling_pond = factory.Trait(
            pondsreclamation=factory.Faker('sentence', nb_words=3),
            pondsreclamationcost=factory.fuzzy.FuzzyDecimal(100),
            pondstotaldistarea=factory.fuzzy.FuzzyDecimal(100),
            pondsexfiltratedtoground=factory.LazyFunction(randomYesNo),
            pondsrecycled=factory.LazyFunction(randomYesNo),
            pondsdischargedtoenv=factory.LazyFunction(randomYesNo))

        underground_exploration = factory.Trait(
            underexptotalore=factory.fuzzy.FuzzyInteger(1, 100),
            underexptotaloreunits=factory.LazyFunction(randomUnitDescription),
            underexpreclamation=factory.Faker('sentence', nb_words=3),
            underexpreclamationcost=factory.fuzzy.FuzzyDecimal(100),
            underexptotalwaste=factory.fuzzy.FuzzyInteger(1, 100),
            underexptotalwasteunits=factory.LazyFunction(randomUnitDescription),
            underexptotaldistarea=factory.fuzzy.FuzzyDecimal(100))

    all_activites = True

    application_guid = GUID
    mine_guid = factory.SelfAttribute('mine.mine_guid')
    messageid = factory.Sequence(lambda n: n)
    applicantclientid = factory.SelfAttribute('applicant.clientid')
    submitterclientid = factory.SelfAttribute('submitter.clientid')
    noticeofworktype = factory.LazyFunction(
        lambda: random.choice([x.description for x in NOWApplicationType.query.all()]))
    trackingnumber = factory.fuzzy.FuzzyInteger(1, 100)
    status = factory.LazyFunction(
        lambda: random.choice([x.description for x in NOWApplicationStatus.query.all()]))
    submitteddate = factory.Faker('past_datetime')
    receiveddate = factory.Faker('past_datetime')
    minenumber = factory.Faker('word')
    originating_system = random.choice(['NROS', 'VFCBC'])

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

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

        NOWDocumentFactory.create_batch(size=extracted, application=obj, **kwargs)

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

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

        NOWContactFactory.create_batch(size=extracted, application=obj, **kwargs)

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

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

        NOWSandGrvQryActivityFactory.create_batch(size=extracted, application=obj, **kwargs)

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

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

        NOWUnderExpNewActivityFactory.create_batch(size=extracted, application=obj, **kwargs)

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

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

        NOWUnderExpRehabActivityFactory.create_batch(size=extracted, application=obj, **kwargs)

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

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

        NOWUnderExpSurfaceActivityFactory.create_batch(size=extracted, application=obj, **kwargs)

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

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

        NOWWaterSourceActivityFactory.create_batch(size=extracted, application=obj, **kwargs)

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

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

        NOWExistingPlacerActivityXrefFactory.create_batch(size=extracted, application=obj, **kwargs)

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

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

        NOWProposedPlacerActivityXrefFactory.create_batch(size=extracted, application=obj, **kwargs)

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

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

        NOWExistingSettlingPondXrefFactory.create_batch(size=extracted, application=obj, **kwargs)

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

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

        NOWProposedSettlingPondXrefFactory.create_batch(size=extracted, application=obj, **kwargs)
Пример #29
0
class InternSelectionFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.InternSelection
        django_get_or_create = ('applicant', 'project')

    class Params:
        round = factory.SubFactory(RoundPageFactory, start_from='internannounce')

        signed = factory.Trait(
            intern_contract=factory.SubFactory(SignedContractFactory)
        )

        active = factory.Trait(
            # checked by home.views.intern_in_good_standing()
            organizer_approved=True,
            in_good_standing=True,

            # but these also ought to be set
            signed=True,
            funding_source=models.InternSelection.ORG_FUNDED,
            # mentors=1, # the post_generation function is not called if this is set
        )

    # set all the approval_status fields to APPROVED, because an
    # InternSelection object can only be created if
    # home.views.set_project_and_applicant succeeds

    applicant = factory.SubFactory(
        ApplicantApprovalFactory,
        application_round=factory.SelfAttribute('..round'),
        approval_status=models.ApprovalStatus.APPROVED,
    )
    project = factory.SubFactory(
        ProjectFactory,
        project_round__participating_round=factory.SelfAttribute('...round'),
        approval_status=models.ApprovalStatus.APPROVED,
        project_round__approval_status=models.ApprovalStatus.APPROVED,
    )

    intern_starts = factory.SelfAttribute('round.internstarts')
    initial_feedback_due = factory.SelfAttribute('round.initialfeedback')
    initial_feedback_opens = factory.LazyAttribute(lambda o: o.initial_feedback_due - datetime.timedelta(days=7))
    midpoint_feedback_due = factory.SelfAttribute('round.midfeedback')
    midpoint_feedback_opens = factory.LazyAttribute(lambda o: o.midpoint_feedback_due - datetime.timedelta(days=7))
    final_feedback_due = factory.SelfAttribute('round.finalfeedback')
    final_feedback_opens = factory.LazyAttribute(lambda o: o.final_feedback_due - datetime.timedelta(days=7))
    intern_ends = factory.SelfAttribute('round.internends')

    @factory.post_generation
    def mentors(self, create, extracted, **kwargs):
        # create a mentor unless mentors=0 is explicitly specified
        if extracted is None:
            extracted = 1

        if not create:
            return

        defaults = {
            'mentor__approval_status': models.ApprovalStatus.APPROVED,
        }
        defaults.update(kwargs)

        # allow mentors=3 to generate 3 new mentors
        for _ in range(extracted):
            MentorRelationshipFactory.create(
                intern_selection=self,
                mentor__project=self.project,
                **defaults
            )

    @factory.post_generation
    def finalapplication(self, create, extracted, **kwargs):
        # ignore finalapplication=0 because we always want to create one final application
        if not create or extracted:
            return

        FinalApplicationFactory.create(
            applicant=self.applicant,
            project=self.project,
            round=self.applicant.application_round,
        )
Пример #30
0
class PlaceFactory(factory.django.DjangoModelFactory):
    """Creates Place object with at least 1 PlaceTag related object.

    Requirements:
        - it doesn't create related PlaceTag objects but rely on them. Be sure
        they are created before use

    Keyword arguments:

        - "tags__num" if passed creates object with amount of "tags__num" tags.
        But not more than tags in db. The factory assumes that PlaceTag table
        is small otherwise it could take enormous time to order_by("?").

        - "tags" expects list of PlaceTags objects and pass it to
        object during creation.

    Examples:
        ========================
        PlaceFactory(tags__num=2)
        =========================
        Creates Place obj with 2 random tags (if there are 2 or more tags
        in DB).

        =========================
        tag_1 = PlaceTagFactory(...)
        tag_2 = PlaceTagFactory(...)
        tags = [tag_1, tag_2]
        PlaceFactory(tags=*tags)
        =========================
        Creates Place obj with exact tag1 and tag2
    """
    class Meta:
        model = Place

    chosen = factory.Faker("boolean", chance_of_getting_true=50)
    published = factory.Faker("boolean", chance_of_getting_true=90)
    title = factory.Sequence(lambda n: fake.unique.sentence(nb_words=7))
    city = factory.Iterator(City.objects.all())
    address = factory.Faker("address")
    gender = factory.LazyFunction(
        lambda: random.choice(Place.Genders.choices)[0])
    age = factory.LazyFunction(lambda: random.randint(5, 17))
    activity_type = factory.LazyFunction(
        lambda: random.choice(Place.ActivityTypes.choices)[0])
    description = factory.Faker("text")
    image_url = factory.django.ImageField(
        color=factory.LazyFunction(
            lambda: random.choice(["blue", "yellow", "green", "orange"])),
        width=factory.LazyFunction(lambda: random.randint(10, 1000)),
        height=factory.SelfAttribute("width"),
    )
    link = factory.Sequence(lambda n: fake.unique.domain_name())

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

        if extracted:
            tags = extracted
            self.tags.add(*tags)
            return

        at_least = 1
        num = kwargs.get("num", None)
        how_many = num or at_least

        tags_count = PlaceTag.objects.count()
        how_many = min(tags_count, how_many)

        tags = PlaceTag.objects.order_by("?")[:how_many]
        self.tags.add(*tags)