Exemplo n.º 1
0
    def fuzz(self):
        protocol = FuzzyChoice(('http', 'https',))
        domain = FuzzyDomain()

        return "{protocol}://{domain}".format(
            protocol=protocol.fuzz(),
            domain=domain.fuzz()
        )
Exemplo n.º 2
0
    def fuzz(self):
        subdomain = FuzzyText()
        domain = FuzzyText()
        tld = FuzzyChoice(('com', 'net', 'org', 'biz', 'pizza', 'coffee', 'diamonds', 'fail', 'win', 'wtf',))

        return "{subdomain}.{domain}.{tld}".format(
            subdomain=subdomain.fuzz(),
            domain=domain.fuzz(),
            tld=tld.fuzz()
        )
Exemplo n.º 3
0
 def fuzz(self):
     protocol = FuzzyChoice(('http', 'https',))
     subdomain = FuzzyText()
     domain = FuzzyText()
     tld = FuzzyChoice(('com', 'net', 'org', 'biz', 'pizza', 'coffee', 'diamonds', 'fail', 'win', 'wtf',))
     resource = FuzzyText()
     return "{protocol}://{subdomain}.{domain}.{tld}/{resource}".format(
         protocol=protocol.fuzz(),
         subdomain=subdomain.fuzz(),
         domain=domain.fuzz(),
         tld=tld.fuzz(),
         resource=resource.fuzz()
     )
Exemplo n.º 4
0
class CaseFactory(DjangoModelFactory):
    tenant = SubFactory(TenantFactory)
    status = SubFactory(CaseStatusFactory, tenant=SelfAttribute('..tenant'))
    priority = FuzzyChoice(dict(Case.PRIORITY_CHOICES).keys())
    subject = LazyAttribute(lambda o: faker.word())
    account = SubFactory(AccountFactory, tenant=SelfAttribute('..tenant'))
    expires = FuzzyDate(datetime.date(2015, 1, 1), datetime.date(2016, 1, 1))
    assigned_to = SubFactory(LilyUserFactory, tenant=SelfAttribute('..tenant'))
    type = SubFactory(CaseTypeFactory, tenant=SelfAttribute('..tenant'))

    class Meta:
        model = Case
Exemplo n.º 5
0
class CourseEntitlementFactory(factory.django.DjangoModelFactory):  # lint-amnesty, pylint: disable=missing-class-docstring
    class Meta(object):
        model = CourseEntitlement

    uuid = factory.LazyFunction(uuid4)
    course_uuid = factory.LazyFunction(uuid4)
    expired_at = None
    mode = FuzzyChoice([CourseMode.VERIFIED, CourseMode.PROFESSIONAL])
    user = factory.SubFactory(UserFactory)
    order_number = FuzzyText(prefix='TEXTX', chars=string.digits)
    enrollment_course_run = None
    policy = factory.SubFactory(CourseEntitlementPolicyFactory)
Exemplo n.º 6
0
class PostFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Post

    title = factory.Faker("word")
    text = factory.Faker("text", max_nb_chars=1000)
    author = factory.SubFactory(UserFactory)
    published = FuzzyChoice([True, False])
    img = factory.django.ImageField(width=200,
                                    height=200,
                                    color=FuzzyChoice(
                                        ["blue", "yellow", "green", "orange"]))

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

        if extracted:
            for tag in extracted:
                self.tags.add(tag)
Exemplo n.º 7
0
class SupplementStackCompositionFactory(DjangoModelFactory):
    user = SubFactory(UserFactory)
    # create the first user and pass it downwards
    supplement = SubFactory(
        SupplementFactory, user=LazyAttribute(lambda a: a.factory_parent.user))
    stack = SubFactory(SupplementStackFactory,
                       user=LazyAttribute(lambda a: a.factory_parent.user))
    notes = FuzzyChoice(NOTES_TO_USE_WITH_EMPTY_SPACES)

    class Meta:
        model = SupplementStackComposition
        django_get_or_create = ["user", "supplement", "stack"]
Exemplo n.º 8
0
class OutputTagFactory(factory.Factory):
    name = factory.Sequence(
        lambda n:
        f"name{n}|{n:08}-{n:04}-{n:04}-{n:04}-{n:012}|anomaly-confidence")
    time_series_id = factory.Sequence(
        lambda n: f"{n:08}-{n:04}-{n:04}-{n:04}-{n:012}")
    type = FuzzyChoice(OutputTagTypeChoices)
    description = factory.Sequence(lambda n: f"description{n}")
    derived_from = factory.Sequence(lambda n: f"derived{n}")

    class Meta:
        model = OutputTag
Exemplo n.º 9
0
class BookLoanFactory(DjangoModelFactory):
    id = factory.Faker("uuid4")
    book = factory.SubFactory(BookFactory)
    imprint = factory.Faker("name")
    loan_start = NOW
    due_back = factory.LazyAttribute(
        lambda x: x.loan_start + timedelta(weeks=2))
    borrower = factory.SubFactory(UserFactory)
    status = FuzzyChoice(dict(BookLoan.LOAN_STATUS).keys())

    class Meta:
        model = BookLoan
Exemplo n.º 10
0
class PathwayFactory(factory.DjangoModelFactory):
    uuid = factory.LazyFunction(uuid4)
    partner = factory.SubFactory(PartnerFactory)
    name = FuzzyText()
    org_name = FuzzyText()
    email = factory.Sequence(lambda n: 'test-email-{}@test.com'.format(n))  # pylint: disable=unnecessary-lambda
    description = FuzzyText()
    destination_url = FuzzyURL()
    pathway_type = FuzzyChoice((path_type.value for path_type in PathwayType))

    class Meta:
        model = Pathway
Exemplo n.º 11
0
class AccountFactory(DjangoModelFactory):
    username = fuzzy_lower_text(prefix='account-')
    foreign_id = FuzzyText()
    person = factory.SubFactory(PersonFactory)
    machine_category = factory.SubFactory(MachineCategoryFactory)
    date_created = factory.LazyAttribute(lambda a: datetime.datetime.today())
    default_project = factory.SubFactory(ProjectFactory)
    shell = FuzzyChoice(settings.SHELLS)

    class Meta:
        model = karaage.machines.models.Account
        django_get_or_create = ('person', 'username', 'machine_category')
Exemplo n.º 12
0
class CommentFactory(WorkspaceObjectFactory):
    """
        A command without command objects.
    """
    text = FuzzyText()
    object_id = FuzzyInteger(1)
    object_type = FuzzyChoice(['host', 'service', 'comment'])


    class Meta:
        model = Comment
        sqlalchemy_session = db.session
Exemplo n.º 13
0
class MovieVoteFactory(factory.django.DjangoModelFactory):
    """
    Creates a MovieVote
    """

    user = factory.SubFactory(UserFactory)
    movie = factory.SubFactory(MovieFactory)
    vote = FuzzyChoice(choices=MovieVote.CHOICES)

    class Meta:
        model = MovieVote
        django_get_or_create = ('user', 'movie')
class RecommendationFactory(factory.Factory):
    """ Creates fake recommendations that you don't have to feed """
    class Meta:
        model = Recommendation

    id = factory.Sequence(lambda n: n)
    product_id = factory.Sequence(lambda n: n + 1)
    customer_id = factory.Sequence(lambda n: n + 2)
    recommend_type = FuzzyChoice(
        choices=["upsell", "crosssell", "accessory", "downsell"])
    recommend_product_id = factory.Sequence(lambda n: n + 3)
    rec_success = 0
Exemplo n.º 15
0
class PathwayFactory(factory.django.DjangoModelFactory):
    uuid = factory.LazyFunction(uuid4)
    partner = factory.SubFactory(PartnerFactory)
    name = FuzzyText()
    org_name = FuzzyText()
    email = factory.Sequence(lambda n: f'test-email-{n}@test.com')
    description = FuzzyText()
    destination_url = FuzzyURL()
    pathway_type = FuzzyChoice(path_type.value for path_type in PathwayType)

    class Meta:
        model = Pathway
Exemplo n.º 16
0
class SupernovaFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Supernova

    sntype = FuzzyChoice(choices=[u'Ia', u'II', u'IIb'])
    ra_hours = FuzzyFloat(0.0, 23.0)
    ra_minutes = FuzzyFloat(0.0, 59.0)
    ra_seconds = FuzzyFloat(0.0, 59.0)
    dec_sign = FuzzyChoice(choices=['+', '-'])
    dec_deg = FuzzyInteger(0, 89)
    dec_min = FuzzyFloat(0.0, 59.0)
    dec_seconds = FuzzyFloat(0.0, 59)
    z = FuzzyFloat(0, 0.5)
    name = factory.Sequence(lambda n: "SN/{0}".format(n))
    points = FuzzyInteger(0, 100)
    date_added = timezone.now()
    discovery_date = FuzzyDateTime(start_dt=timezone.now() -
                                   datetime.timedelta(days=29),
                                   end_dt=timezone.now())

    astro_object = factory.SubFactory(AstroObjectFactory)
Exemplo n.º 17
0
class EmailAccountFactory(DjangoModelFactory):
    tenant = SubFactory(TenantFactory)
    owner = SubFactory(LilyUserFactory)
    email_address = LazyAttribute(lambda o: unicodedata.normalize(
        'NFD', faker.safe_email()).encode('ascii', 'ignore'))
    from_name = LazyAttribute(lambda o: faker.name())
    label = LazyAttribute(lambda o: faker.word())
    is_authorized = True
    privacy = FuzzyChoice(dict(EmailAccount.PRIVACY_CHOICES).keys())

    class Meta:
        model = EmailAccount
Exemplo n.º 18
0
class PatientFactory(factory.django.DjangoModelFactory):
    last_name = factory.Faker("last_name")
    id_document_number = FuzzyText(length=10, chars=string.digits)
    job_title = factory.Faker("job")
    birthdate = FuzzyDate(datetime.date(1920, 1, 1))
    phone = FuzzyChoice([
        "+593983761752",
        "+13053991321",
        "+593987309076",
        "+16262005695",
        "+918668999704",
    ])
    whatsapp = FuzzyChoice([True, False, True, True])
    health_insurance_company = FuzzyChoice(
        ["Health Inc", "Moderna", "BMI", "Google Health", "Apple Health"])
    email = factory.Faker("free_email")
    referral_source = FuzzyChoice(Patient.ReferralSourceChoices.values)

    class Meta:
        abstract = True
        model = Patient
Exemplo n.º 19
0
class BaseBookFactory(DjangoModelFactory):
    """Base book factory."""

    title = Faker('text', max_nb_chars=100)
    summary = Faker('text')
    publisher = SubFactory('factories.books_publisher.LimitedPublisherFactory')
    publication_date = Faker('date_between', start_date='-10y', end_date='now')
    price = Faker('pydecimal', left_digits=2, right_digits=2, positive=True)
    isbn = Faker('isbn13')
    state = FuzzyChoice(dict(BOOK_PUBLISHING_STATUS_CHOICES).keys())
    pages = LazyAttribute(lambda __x: random.randint(10, 200))
    created = Faker('date_time')

    class Meta(object):
        """Meta class."""

        model = Book
        abstract = True

    @post_generation
    def tags(obj, created, extracted, **kwargs):
        """Create Tag objects for the created Book instance."""
        if created:
            # Create from 1 to 7 ``Tag`` objects.
            amount = random.randint(1, 7)
            tags = TagGenreFactory.create_batch(amount, **kwargs)
            obj.tags.add(*tags)

    @post_generation
    def authors(obj, created, extracted, **kwargs):
        """Create `Author` objects for the created `Book` instance."""
        if created:
            # Create random amount of `Author` objects.
            amount = random.randint(3, 7)
            authors = LimitedAuthorFactory.create_batch(amount, **kwargs)
            obj.authors.add(*authors)

    @post_generation
    def orders(obj, created, extracted, **kwargs):
        """Create `Order` objects for the created `Book` instance."""
        if created:
            # Create 3 `Order` objects.
            amount = random.randint(2, 7)
            orders = OrderFactory.create_batch(amount, **kwargs)
            order_line_kwargs = dict(kwargs)
            order_line_kwargs['book'] = obj
            for order in orders:
                # Create 1 `OrderLine` object.
                amount = random.randint(1, 5)
                order_lines = OrderLineFactory.create_batch(
                    amount, **order_line_kwargs)
                order.lines.add(*order_lines)
Exemplo n.º 20
0
class ActivityFactory(DjangoModelFactory):
    event = SubFactory(EventFactory)
    zone = SubFactory(ZoneFactory)
    type = FuzzyChoice(choices=ActivityType.values)
    start_date = FuzzyDateTime(
        start_dt=datetime.datetime(2019, 1, 1, tzinfo=datetime.timezone.utc),
        end_dt=datetime.datetime(2019, 12, 31, tzinfo=datetime.timezone.utc))
    finish_date = FuzzyDateTime(
        start_dt=datetime.datetime(2019, 1, 1, tzinfo=datetime.timezone.utc),
        end_dt=datetime.datetime(2019, 12, 31, tzinfo=datetime.timezone.utc))

    class Meta:
        model = 'events.Activity'
Exemplo n.º 21
0
class AddressFactory(factory.Factory):
    """ Creates fake Addresses """

    class Meta:
        model = Address

    id = factory.Sequence(lambda n: n)
#    account_id = ???
    name = FuzzyChoice(choices=["home", "work", "other"])
    street = factory.Faker("street_address")
    city = factory.Faker("city")
    state = factory.Faker("state_abbr")
    postalcode = factory.Faker("postalcode")
Exemplo n.º 22
0
class ContentFileFactory(DjangoModelFactory):
    """Factory for ContentFiles"""

    run = factory.SubFactory(LearningResourceRunFactory)
    key = factory.Faker("file_path")
    title = factory.Faker("sentence")
    description = factory.Faker("sentence")
    uid = factory.Faker("text", max_nb_chars=32)
    url = factory.Faker("url")
    content_type = FuzzyChoice((CONTENT_TYPE_FILE, CONTENT_TYPE_PAGE))

    class Meta:
        model = ContentFile
Exemplo n.º 23
0
class HatFactory(DjangoModelFactory):
    """Factory for hats."""

    style = FuzzyChoice((hat_style[0] for hat_style in Hat.STYLES))
    brand = factory.SubFactory(BrandFactory)

    class Meta:
        model = Hat

    @factory.lazy_attribute
    def price(self):
        """Generate a random price between 0 and 400."""
        return Money(random.randint(0, 400), 'GBP')
class CustomerFactory(factory.Factory):
    """ Creates fake customers that you don't have to feed """
    class Meta:
        model = Customer
        exclude = ('number', 'street')

    firstname = factory.Faker('first_name')
    lastname = factory.Faker('last_name')
    email = FuzzyChoice(choices=[
        '*****@*****.**', '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**'
    ])
    subscribed = FuzzyChoice(choices=[True, False])
    number = factory.Faker('random_int')
    street = factory.Faker('street_name')
    address1 = factory.LazyAttribute(
        lambda p: '{} {}'.format(p.number, p.street))
    address2 = factory.Faker('secondary_address')
    city = factory.Faker('city')
    province = factory.Faker('state')
    country = factory.Faker('country')
    zip = factory.Faker('zipcode')
Exemplo n.º 25
0
class PotatoFactory(DjangoModelFactory):
    """ModelFactory for the Potato object."""

    class Meta:  # noqa
        model = Potato

    weight = FuzzyInteger(1, 1000)
    variety = FuzzyChoice(['Anya',
                           'Arran Victory',
                           'Blaue Viola',
                           'Doré',
                           'Duke of York',
                           ])
Exemplo n.º 26
0
class BaseProductFactory(DjangoModelFactory):
    """Base product factory."""

    name = Faker("text", max_nb_chars=100)
    price = Faker("pyint", min_value=100, max_value=1_000_000)
    price_with_tax = LazyAttribute(lambda __x: int(__x.price * 1.20))
    currency = FuzzyChoice([key for key, value in get_currency_choices()])

    class Meta:
        """Meta class."""

        model = Product
        abstract = True
Exemplo n.º 27
0
class PropositionFactory(SQLAFactory):
    class Meta:
        model = Proposition

    title = MimesisField('title')
    content = MimesisField('text', quantity=5)
    motivation = MimesisField('text', quantity=8)
    abstract = MimesisField('text', quantity=2)
    status = FuzzyChoice([
        PropositionStatus.DRAFT, PropositionStatus.SUBMITTED,
        PropositionStatus.QUALIFIED
    ])
    ballot = SubFactory(BallotFactory)
Exemplo n.º 28
0
class PromotionFactory(factory.Factory):
    """ Creates fake promotions that you don't have to feed """
    class Meta:
        """ Meta class for Promotion Factory """
        model = Promotion

    code = FuzzyChoice(choices=['SAVE15', 'SAVE20', 'SAVE30'])
    percentage = FuzzyChoice(choices=[10, 40, 30, 25, 5, 0, 15])
    start_date = int(
        (datetime.now() - timedelta(weeks=random.randint(1, 5))).timestamp())
    expiry_date = int(
        (datetime.now() + timedelta(weeks=random.randint(1, 5))).timestamp())
    products = FuzzyChoice(
        choices=[['5612234', '8516634'], ['847153', '645382']])

    @classmethod
    def batch_create(cls, count, **kwargs):
        """
        Factory method to create promotions in bulk.
        Ensure that promotions with the same code will not overlap with each others
        """
        promotions = cls.create_batch(count, **kwargs)
        promotions_dict = defaultdict(list)
        for promotion in promotions:
            promotions_dict[promotion.code].append(promotion)

        promotions = []
        for promos in promotions_dict.values():
            pre_expiry_date = promos[0].expiry_date
            promos[0].save()
            for promotion in promos[1:]:
                delta = promotion.expiry_date - promotion.start_date
                promotion.start_date = pre_expiry_date + random.randint(
                    100, 2000)
                promotion.expiry_date = promotion.start_date + delta
                pre_expiry_date = promotion.expiry_date
                promotion.save()
            promotions.extend(promos)
        return promotions
Exemplo n.º 29
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
Exemplo n.º 30
0
class DealFactory(DjangoModelFactory):
    tenant = SubFactory(TenantFactory)
    name = LazyAttribute(lambda o: faker.word())
    account = SubFactory(AccountFactory, tenant=SelfAttribute('..tenant'))
    amount_once = FuzzyDecimal(42.7)
    amount_recurring = FuzzyDecimal(42.7)
    expected_closing_date = FuzzyDate(datetime.date(2015, 1, 1),
                                      datetime.date(2016, 1, 1))
    assigned_to = SubFactory(LilyUserFactory, tenant=SelfAttribute('..tenant'))
    stage = FuzzyChoice(dict(Deal.STAGE_CHOICES).keys())

    class Meta:
        model = Deal
Exemplo n.º 31
0
class ReuseFactory(ModelFactory):
    class Meta:
        model = Reuse

    title = factory.Faker('sentence')
    description = factory.Faker('text')
    url = factory.LazyAttribute(
        lambda o: '/'.join([faker.url(), faker.unique_string()]))
    type = FuzzyChoice(REUSE_TYPES.keys())

    class Params:
        visible = factory.Trait(
            datasets=factory.LazyAttribute(lambda o: [DatasetFactory()]))
Exemplo n.º 32
0
class WellFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = db.models.Well

    plate_number = '{:0>5d}'.format(FuzzyInteger(0, 55000).fuzz())
    col = FuzzyInteger(0, 23).fuzz()
    row = FuzzyInteger(0, 16).fuzz()
    well_name = chr(ord('A') + row) + '{:0>2d}'.format(col)
    well_id = '%s:%s' % (plate_number, well_name)

    facility_id = 'HMSL{:0>5d}'.format(FuzzyInteger(0, 16).fuzz())
    library_well_type = FuzzyChoice(
        ['experimental', 'empty', 'dmso', 'library_control', 'rnai_buffer'])
Exemplo n.º 33
0
class WebsiteContentFactory(DjangoModelFactory):
    """Factory for WebsiteContent"""

    title = factory.Sequence(lambda n: "OCW Site Content %s" % n)
    type = FuzzyChoice([CONTENT_TYPE_PAGE, CONTENT_TYPE_RESOURCE])
    markdown = factory.Faker("text")
    metadata = factory.LazyAttribute(lambda _: {})
    filename = factory.Sequence(lambda n: "my-file-%s" % n)
    dirpath = factory.Faker("uri_path", deep=2)
    website = factory.SubFactory(WebsiteFactory)

    class Meta:
        model = WebsiteContent