Exemplo n.º 1
0
class OrganizationFactory(SalesforceRecordFactory):
    uuid = factory.LazyFunction(uuid4)
    key = FuzzyText()
    name = FuzzyText()
    description = FuzzyText()
    homepage_url = FuzzyURL()
    logo_image = FuzzyText()
    banner_image = FuzzyText()
    certificate_logo_image = FuzzyText()
    partner = factory.SubFactory(PartnerFactory)

    class Meta:
        model = Organization
Exemplo n.º 2
0
class WorkflowInstanceFactory(BaseFactory):
    """WorkflowInstance Factory."""

    parameters = [{}]
    run_reason = FuzzyText()
    status = FuzzyChoice(["Submitted", "Created", "Running", "Completed", "Failed"])

    class Meta:
        """Factory Configuration."""

        model = WorkflowInstance

    @post_generation
    def artifacts(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            for artifact in extracted:
                self.artifacts.append(artifact)

    @post_generation
    def workflow(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            self.workflow_id = extracted.id

    @post_generation
    def incident(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            self.incident_id = extracted.id

    @post_generation
    def creator(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            self.creator_id = extracted.id
Exemplo n.º 3
0
class PluginFactory(BaseFactory):
    """Plugin Factory."""

    title = FuzzyText()
    slug = FuzzyText()
    description = FuzzyText()
    version = FuzzyText()
    author = FuzzyText()
    author_url = FuzzyText()
    type = FuzzyText()
    multiple = Faker().pybool()

    class Meta:
        """Factory Configuration."""

        model = Plugin
        sqlalchemy_get_or_create = ("slug",)
Exemplo n.º 4
0
class ServerFactory(DjangoModelFactory):
    class Meta:
        model = Server

    name = LazyAttribute(lambda x: faker.text(max_nb_chars=20))
    notes = LazyAttribute(
        lambda x: faker.paragraph(nb_sentences=3, variable_nb_sentences=True))
    virtual = Iterator([True, False])
    ip_address = LazyAttribute(lambda o: faker.ipv4(network=False))
    created = LazyAttribute(lambda x: faker.date_time_between(
        start_date="-1y", end_date="now", tzinfo=timezone(settings.TIME_ZONE)))
    online_date = LazyAttribute(lambda x: faker.date_time_between(
        start_date="-1y", end_date="now", tzinfo=timezone(settings.TIME_ZONE)))
    operating_system = SubFactory(OperatingSystemFactory)
    server_id = LazyAttribute(
        lambda x: FuzzyText(length=6, chars=string.digits).fuzz())
    use = Iterator(Server.USE_CHOICES, getter=lambda x: x[0])
    comments = LazyAttribute(
        lambda x: faker.paragraph(nb_sentences=3, variable_nb_sentences=True))
Exemplo n.º 5
0
class TriggerRuleFactory(factory.DjangoModelFactory):
    class Meta:
        model = TriggerRule

    slug = FuzzyText()
    title = 'OU812'
    description = 'Oh, you ate one, too?'
    url = 'https://wiki.mozilla.org/Firefox/Input'

    is_enabled = True

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

        if extracted:
            for product in extracted:
                self.products.add(product)
Exemplo n.º 6
0
    def test_vendor_number_list_view(self):
        for i in range(3):
            user = UserFactory(is_staff=True)
            user.first_name = 'Test'
            user.save()

            profile = user.profile
            profile.vendor_number = FuzzyText().fuzz()
            profile.save()

        for i in range(3):
            TravelAgentFactory()

        with self.assertNumQueries(2):
            response = self.forced_auth_req('get',
                                            reverse('t2f:vendor_numbers'),
                                            user=self.unicef_staff)
        response_json = json.loads(response.rendered_content)
        self.assertEqual(len(response_json), 6)
Exemplo n.º 7
0
class SimulationFactory(BaseFactory):
    """Factory for creating mock users"""
    class Meta:  # pylint: disable=missing-docstring
        model = Simulation

    name = factory.Sequence(lambda n: 'sim%d' % n)
    description = FuzzyText()
    tsum1 = random.randint(700, 999)
    tsum2 = random.randint(700, 999)

    location_lat = random.randint(35, 37)
    location_lon = random.randint(-4, 1)
    location = "37.7, -4.88"

    @classmethod
    def create_batch(cls, size, **kwargs):
        """When creating batch, we create one less than requested size and then add admin user
        at the end"""
        super(SimulationFactory, cls).create_batch(size - 1, **kwargs)
Exemplo n.º 8
0
class CourseRunFactory(factory.DjangoModelFactory):
    status = CourseRunStatus.Published
    uuid = factory.LazyFunction(uuid4)
    key = FuzzyText(prefix='course-run-id/', suffix='/fake')
    course = factory.SubFactory(CourseFactory)
    title_override = None
    short_description_override = None
    full_description_override = None
    language = factory.Iterator(LanguageTag.objects.all())
    start = FuzzyDateTime(datetime.datetime(2014, 1, 1, tzinfo=UTC))
    end = FuzzyDateTime(datetime.datetime(2014, 1, 1, tzinfo=UTC)).end_dt
    enrollment_start = FuzzyDateTime(datetime.datetime(2014, 1, 1, tzinfo=UTC))
    enrollment_end = FuzzyDateTime(datetime.datetime(2014, 1, 1,
                                                     tzinfo=UTC)).end_dt
    announcement = FuzzyDateTime(datetime.datetime(2014, 1, 1, tzinfo=UTC))
    card_image_url = FuzzyURL()
    video = factory.SubFactory(VideoFactory)
    min_effort = FuzzyInteger(1, 10)
    max_effort = FuzzyInteger(10, 20)
    pacing_type = FuzzyChoice([name for name, __ in CourseRunPacing.choices])
    reporting_type = FuzzyChoice([name for name, __ in ReportingType.choices])
    hidden = False
    weeks_to_complete = FuzzyInteger(1)
    license = 'all-rights-reserved'
    has_ofac_restrictions = True

    @factory.post_generation
    def staff(self, create, extracted, **kwargs):
        if create:
            add_m2m_data(self.staff, extracted)

    class Meta:
        model = CourseRun

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

    @factory.post_generation
    def authoring_organizations(self, create, extracted, **kwargs):
        if create:  # pragma: no cover
            add_m2m_data(self.authoring_organizations, extracted)
Exemplo n.º 9
0
class PageContentFactory(factory.django.DjangoModelFactory):
    page = factory.SubFactory(PageFactory)
    language = FuzzyChoice(["en", "fr", "it"])
    title = FuzzyText(length=12)
    page_title = FuzzyText(length=12)
    menu_title = FuzzyText(length=12)
    meta_description = FuzzyText(length=12)
    redirect = FuzzyText(length=12)
    created_by = FuzzyText(length=12)
    changed_by = FuzzyText(length=12)
    in_navigation = FuzzyChoice([True, False])
    soft_root = FuzzyChoice([True, False])
    limit_visibility_in_menu = constants.VISIBILITY_USERS
    template = 'page.html'
    xframe_options = FuzzyInteger(0, 25)

    class Meta:
        model = PageContent
Exemplo n.º 10
0
class VulnerabilityFactory(VulnerabilityGenericFactory,
                           HasParentHostOrService):

    host = factory.SubFactory(HostFactory,
                              workspace=factory.SelfAttribute('..workspace'))
    service = factory.SubFactory(
        ServiceFactory, workspace=factory.SelfAttribute('..workspace'))
    description = FuzzyText()
    type = "vulnerability"

    @classmethod
    def build_dict(cls, **kwargs):
        ret = super().build_dict(**kwargs)
        assert ret['type'] == 'vulnerability'
        ret['type'] = 'Vulnerability'
        return ret

    class Meta:
        model = Vulnerability
        sqlalchemy_session = db.session
Exemplo n.º 11
0
    def test_save_form_data(self, mock_optimize_from_buffer):
        """Calling save_form_data() on an OptimizedImageField calls optimize_from_buffer()."""
        generic_model = factories.GenericModelFactory(title='Generic Model',
                                                      image=None)
        # So far there is no optimized image, and mock_optimize_from_buffer has not been called
        self.assertEqual(generic_model.image.name, None)
        self.assertEqual(mock_optimize_from_buffer.call_count, 0)

        new_io = io.StringIO()
        new_io.write('something')
        new_file = InMemoryUploadedFile(
            new_io, 'image', 'static/images/{}.png'.format(FuzzyText().fuzz()),
            'image/jpeg', len(new_io.getvalue()), 'utf-8')

        # Call save_form_data on the OptimizedImageField
        generic_model.image.field.save_form_data(generic_model, new_file)

        # Now the mock_optimize_from_buffer has been called once
        self.assertEqual(mock_optimize_from_buffer.call_count, 1)
        self.assertEqual(mock_optimize_from_buffer.call_args[0][0], new_file)
Exemplo n.º 12
0
    def test_save_does_not_create_optimized_image(self,
                                                  mock_optimize_from_buffer):
        """Saving an image to an OptimizedImageField does not call optimize_from_buffer()."""
        generic_model = factories.GenericModelFactory(title='Generic Model',
                                                      image=None)
        # So far there is no optimized image, and mock_optimize_from_buffer has not been called
        self.assertEqual(generic_model.image.name, None)
        self.assertEqual(mock_optimize_from_buffer.call_count, 0)

        new_io = io.StringIO()
        new_io.write('something')
        new_file = InMemoryUploadedFile(
            new_io, 'image', 'static/images/{}.png'.format(FuzzyText().fuzz()),
            'image/jpeg', len(new_io.getvalue()), 'utf-8')
        generic_model.image = new_file
        generic_model.save()

        self.assertNotEqual(generic_model.image.name, None)
        # The mock_optimize_from_buffer still has not been called
        self.assertEqual(mock_optimize_from_buffer.call_count, 0)
Exemplo n.º 13
0
    def test_send_email(self):
        self.assertEqual(len(mail.outbox), 0)

        status_text = FuzzyText(length=400)
        signal = SignalFactory.create(status__state=self.state,
                                      status__text=status_text,
                                      status__send_email=self.send_email,
                                      reporter__email='*****@*****.**')
        self.assertTrue(self.action(signal, dry_run=False))
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(
            mail.outbox[0].subject,
            f'Uw melding {signal.get_id_display()} {self.action.key}')
        self.assertEqual(mail.outbox[0].to, [
            signal.reporter.email,
        ])
        self.assertEqual(mail.outbox[0].from_email,
                         settings.DEFAULT_FROM_EMAIL)
        self.assertEqual(Note.objects.count(), 1)
        self.assertTrue(Note.objects.filter(text=self.action.note).exists())
Exemplo n.º 14
0
class ProjectFactory(BaseFactory):
    """Project Factory."""

    name = Sequence(lambda n: f"project{n}")
    description = FuzzyText()
    default = Faker().pybool()
    color = Faker().color()

    class Meta:
        """Factory Configuration."""

        model = Project

    @post_generation
    def organization(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            self.organization_id = extracted.id
Exemplo n.º 15
0
    def test_happy_flow(self):
        status_text = FuzzyText(length=400)

        # create signal in prev status
        signal = SignalFactory.create(status__state=self.prev_state,
                                      status__text=status_text,
                                      status__send_email=self.send_email,
                                      reporter__email='*****@*****.**')

        # create the new current state
        status = StatusFactory.create(_signal=signal, state=self.state)
        signal.status = status
        signal.save()

        feedback = FeedbackFactory.create(
            allows_contact=True,
            _signal=signal,
        )
        feedback.save()
        self.assertTrue(self.rule(signal))
Exemplo n.º 16
0
class LicenceFactory(DjangoModelFactory):

    licence_type = factory.SubFactory(LicenceTypeFactory)
    software = factory.SubFactory(SoftwareFactory)
    region = factory.SubFactory(RegionFactory)
    manufacturer = factory.SubFactory(ManufacturerFactory)
    niw = FuzzyText()
    number_bought = 10
    invoice_date = date_now - timedelta(days=15)
    valid_thru = date_now + timedelta(days=365)
    invoice_no = factory.Sequence(lambda n: 'Invoice number ' + str(n))
    budget_info = factory.SubFactory(BudgetInfoFactory)
    sn = factory.Faker('ssn')
    order_no = factory.Sequence(lambda n: 'Order number ' + str(n))
    property_of = factory.SubFactory(AssetHolderFactory)
    office_infrastructure = factory.SubFactory(OfficeInfrastructureFactory)
    depreciation_rate = '100.00'

    class Meta:
        model = Licence
Exemplo n.º 17
0
class AuthorityFactory(BaseFactory):
    """Authority factory."""
    name = Sequence(lambda n: 'authority{0}'.format(n))
    owner = '*****@*****.**'
    plugin = {'slug': 'test-issuer'}
    description = FuzzyText(length=128)
    authority_certificate = SubFactory(CertificateFactory)

    class Meta:
        """Factory configuration."""
        model = Authority

    @post_generation
    def roles(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            for role in extracted:
                self.roles.append(role)
Exemplo n.º 18
0
class PostFactory(factory.DjangoModelFactory):
    FACTORY_FOR = Post

    title = factory.Sequence(lambda n: u'Post Title #{}'.format(n))
    feed = factory.SubFactory(FeedFactory)
    url = factory.LazyAttribute(
        lambda obj: u'post-{}.html'.format(obj.feed.blog.url))
    guid = factory.Sequence(lambda n: u'GUID-{}'.format(n))
    content = FuzzyText(length=200)

    @factory.post_generation
    def authors(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of groups were passed in, use them
            for author in extracted:
                PostAuthorDataFactory.create(post=self, author=author)
Exemplo n.º 19
0
class FlightFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = 'app.Flight'
        django_get_or_create = ('ident', )

    ident = FuzzyText(prefix='C', chars=string.ascii_uppercase, length=4)
    flight_path = factory.LazyAttribute(lambda obj: LineString(
        obj.departure_facility.location, obj.arrival_facility.location))
    departure_facility = factory.Iterator(Facility.objects.all())
    departure_time = FuzzyDateTime(utc_now_offset(hours=3))
    arrival_facility = factory.Iterator(Facility.objects.reverse(
    ))  # Get a different iterator than departure_facility
    arrival_time = factory.LazyAttribute(
        lambda obj: obj.departure_time + datetime.timedelta(minutes=random.
                                                            randint(30, 90)))

    status = FlightStatus.FILED.value
    time = FuzzyDateTime(utc_now_offset())
    location = FuzzyPoint()
    heading = FuzzyInteger(0, 359)
Exemplo n.º 20
0
class Comment(factory.Factory):
    """A factory class for creating CKAN datasets."""
    class Meta:
        model = model.Comment

    thread = factory.LazyAttribute(lambda _: Thread())
    content = FuzzyText("content:", 140)

    @classmethod
    def _create(cls, target_class, *args, **kwargs):
        context = {"user": factories._get_action_user_name(kwargs)}

        thread = kwargs.pop("thread")
        kwargs["subject_id"] = thread["subject_id"]
        kwargs["subject_type"] = thread["subject_type"]

        comment_dict = helpers.call_action("comments_comment_create",
                                           context=context,
                                           **kwargs)
        return comment_dict
Exemplo n.º 21
0
class LocationFactory(DjangoModelFactory):
    class Meta:
        model = Location

    _signal = SubFactory(
        'signals.apps.signals.factories.signal.signal.SignalFactory',
        location=None)

    buurt_code = FuzzyText(length=4)
    stadsdeel = FuzzyChoice(choices=(s[0] for s in STADSDELEN))
    geometrie = get_puntje()
    address = {
        'straat': 'Sesamstraat',
        'huisnummer': 666,
        'postcode': '1011AA',
        'openbare_ruimte': 'Ergens'
    }

    @post_generation
    def set_one_to_one_relation(self, create, extracted, **kwargs):
        self.signal = self._signal
Exemplo n.º 22
0
class TaskFactory(ResourceBaseFactory):
    """Task Factory."""

    resolved_at = FuzzyDateTime(datetime(2020, 1, 1, tzinfo=UTC))
    last_reminder_at = FuzzyDateTime(datetime(2020, 1, 1, tzinfo=UTC))
    creator = "*****@*****.**"
    assignees = "*****@*****.**"
    description = FuzzyText()

    class Meta:
        """Factory Configuration."""

        model = Task

    @post_generation
    def incident(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            self.incident_id = extracted.id
Exemplo n.º 23
0
    def test_send_email_anonymous(self):
        self.assertEqual(len(mail.outbox), 0)

        status_text = FuzzyText(length=400)
        signal = SignalFactory.create(status__state=self.state,
                                      status__text=status_text,
                                      status__send_email=self.send_email,
                                      reporter__email='')
        self.assertFalse(self.action(signal, dry_run=False))
        self.assertEqual(len(mail.outbox), 0)
        self.assertEqual(Note.objects.count(), 0)
        self.assertFalse(Note.objects.filter(text=self.action.note).exists())

        signal = SignalFactory.create(status__state=self.state,
                                      status__text=status_text,
                                      status__send_email=self.send_email,
                                      reporter__email=None)
        self.assertFalse(self.action(signal, dry_run=False))
        self.assertEqual(len(mail.outbox), 0)
        self.assertEqual(Note.objects.count(), 0)
        self.assertFalse(Note.objects.filter(text=self.action.note).exists())
Exemplo n.º 24
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.º 25
0
class EmploymentFactory(DjangoModelFactory):
    """
    A factory for work history
    """
    profile = SubFactory(ProfileFactory)
    city = FuzzyText(suffix=" city")
    country = FuzzyText(suffix=" land")
    state_or_territory = FuzzyText(suffix=" state")
    company_name = FuzzyText(suffix=" XYZ-ABC")
    industry = FuzzyText(suffix=" IT")
    position = FuzzyText(suffix=" developer")
    end_date = FuzzyDate(date(1850, 1, 1))
    start_date = FuzzyDate(date(1850, 1, 1))

    class Meta:  # pylint: disable=missing-docstring
        model = Employment
Exemplo n.º 26
0
class UserFactory(BaseFactory):
    """User Factory."""

    username = Sequence(lambda n: "user{0}".format(n))
    email = Sequence(lambda n: "user{0}@example.com".format(n))
    active = True
    password = FuzzyText(length=24)
    certificates = []

    class Meta:
        """Factory Configuration."""

        model = User

    @post_generation
    def roles(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            for role in extracted:
                self.roles.append(role)

    @post_generation
    def certificates(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            for cert in extracted:
                self.certificates.append(cert)

    @post_generation
    def authorities(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            for authority in extracted:
                self.authorities.append(authority)
Exemplo n.º 27
0
class AgentFactory(FaradayFactory):
    name = FuzzyText()
    active = True

    @factory.post_generation
    def workspaces(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of groups were passed in, use them
            for workspace in extracted:
                self.workspaces.append(workspace)
        else:
            self.workspaces.append(WorkspaceFactory())
            self.workspaces.append(WorkspaceFactory())


    class Meta:
        model = Agent
        sqlalchemy_session = db.session
Exemplo n.º 28
0
    def test_context(self):
        """
        Assert context values for logged in user
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create()
        self.client.force_login(profile.user)

        # ProgramFaculty and ProgramCourse are asserted via ProgramPageSerializer below
        FacultyFactory.create_batch(3, program_page=self.program_page)
        courses = self.program_page.program.course_set.all()
        ProgramCourseFactory.create_batch(len(courses),
                                          program_page=self.program_page,
                                          course=Iterator(courses))

        ga_tracking_id = FuzzyText().fuzz()
        with self.settings(
                GA_TRACKING_ID=ga_tracking_id,
                ENVIRONMENT='environment',
                VERSION='version',
        ):
            response = self.client.get(self.program_page.url)
            assert response.context['authenticated'] is True
            assert response.context['username'] is None
            assert response.context['title'] == self.program_page.title
            assert response.context['is_public'] is True
            assert response.context['has_zendesk_widget'] is True
            assert response.context['is_staff'] is False
            self.assertContains(response, 'Share this page')
            js_settings = json.loads(response.context['js_settings_json'])
            assert js_settings == {
                'gaTrackingID': ga_tracking_id,
                'environment': 'environment',
                'sentry_dsn': None,
                'host': 'testserver',
                'release_version': 'version',
                'user': serialize_maybe_user(profile.user),
                'program': ProgramPageSerializer(self.program_page).data,
            }
Exemplo n.º 29
0
class RoomV4Factory(DjangoModelFactory):
    class Meta:
        model = RoomV4

    id = factory.LazyFunction(uuid.uuid4)
    name = FuzzyText(length=60)
    image = factory.django.ImageField()
    default_image = factory.SubFactory(DefaultRoomImageFactory)
    owner = factory.SubFactory(AccountFactory)

    @factory.post_generation
    def participants(self, create, extracted, **kwargs):
        if not create:
            return
        if extracted:
            for _participant in extracted:
                self.participants.add(_participant)

    @factory.post_generation
    def left_members(self, create, extracted, **kwargs):
        if not create:
            return
        if extracted:
            for _left_member in extracted:
                self.left_members.add(_left_member)

    @factory.post_generation
    def closed_members(self, create, extracted, **kwargs):
        if not create:
            return
        if extracted:
            for _closed_member in extracted:
                self.closed_members.add(_closed_member)

    max_num_participants = 1
    is_exclude_different_gender = False
    created_at = timezone.now()
    is_end = False
    is_active = False
Exemplo n.º 30
0
class UserFactory(factory.django.DjangoModelFactory):
    username = FuzzyText(length=12)
    first_name = factory.Faker("first_name")
    last_name = factory.Faker("last_name")
    email = factory.LazyAttribute(lambda u: "*****@*****.**" %
                                  (u.first_name.lower(), u.last_name.lower()))

    class Meta:
        model = get_user_model()

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        """Return existing user instance if found.
        Otherwise create a new user."""
        manager = cls._get_manager(model_class)
        username = kwargs.get("username")
        if username is not None:
            try:
                return manager.get(username=username)
            except model_class.DoesNotExist:
                pass
        return manager.create_user(*args, **kwargs)