예제 #1
0
class MainEntityVersionFactory(factory.DjangoModelFactory):
    class Meta:
        model = 'base.EntityVersion'

    entity = factory.SubFactory(EntityFactory,
                                organization__type=organization_type.MAIN)
    title = factory.Faker('text', max_nb_chars=255)
    acronym = factory.Faker('text', max_nb_chars=20)
    entity_type = factory.Iterator(entity_type.MAIN_ENTITY_TYPE)
    parent = factory.SubFactory(EntityFactory)
    start_date = datetime.date(2015, 1, 1).isoformat()
    end_date = None
예제 #2
0
class OrganizationFactory(factory.DjangoModelFactory):
    class Meta:
        model = 'base.Organization'

    external_id = factory.Faker('text', max_nb_chars=100)
    changed = factory.Faker('date_time_this_month', tzinfo=get_tzinfo())
    name = factory.Faker('text', max_nb_chars=255)
    acronym = factory.Faker('text', max_nb_chars=15)
    website = factory.Faker('url')
    prefix = factory.Faker('text', max_nb_chars=30)
    type = factory.Iterator(organization_type.ORGANIZATION_TYPE,
                            getter=lambda c: c[0])
예제 #3
0
class OrganisationFactory(Factory):

    class Meta:
        model = "organisations.Organisation"

    name = factory.Sequence(lambda n: "organisation{}".format(n))
    description = factory.Sequence(
        lambda n: "organisation_Description{}".format(n))
    organisation_role = factory.Sequence(
        lambda n: "organisation_role{}".format(n))
    organisation_type = factory.Iterator(dict(OrganisationType.CHOICES).keys())
    location = factory.SubFactory("tests.factories.LocationFactory")
예제 #4
0
class EntityVersionFactory(factory.DjangoModelFactory):
    class Meta:
        model = 'base.EntityVersion'

    entity = factory.SubFactory(EntityFactory)
    title = factory.Faker('text', max_nb_chars=255)
    acronym = factory.Faker('text', max_nb_chars=20)
    entity_type = factory.Iterator(entity_type.ENTITY_TYPES,
                                   getter=lambda c: c[0])
    parent = factory.SubFactory(EntityFactory)
    start_date = datetime.date(2015, 1, 1).isoformat()
    end_date = None
예제 #5
0
def create_applications(number_of_applications, target_date):
    """
    Creates applications equal to the `number_of_applications` with `submission_date` set to
    `target_date` sent as argument.

    Arguments:
        number_of_applications (int): Depicts the number of applications to be created
        target_date (datetime): Represents the date for application submission
    """
    user_applications = UserApplicationFactory.create_batch(number_of_applications)
    users = factory.Iterator([users_application.user for users_application in user_applications])
    ApplicationHubFactory.create_batch(number_of_applications, user=users, submission_date=target_date)
예제 #6
0
class ImageFactoryWithoutImageFile(ImageFactory):
    eye_choice = factory.Iterator([x[0] for x in Image.EYE_CHOICES])
    stereoscopic_choice = factory.Iterator(
        [x[0] for x in Image.STEREOSCOPIC_CHOICES]
    )
    field_of_view = factory.Iterator([x[0] for x in Image.FOV_CHOICES])
    name = factory.Sequence(lambda n: f"RetinaImage {n}")
    modality = factory.SubFactory(ImagingModalityFactory, modality="CF")
    color_space = factory.Iterator([x[0] for x in Image.COLOR_SPACES])
    patient_id = factory.Sequence(lambda n: f"Patient {n}")
    patient_name = fuzzy.FuzzyText(prefix="Patient")
    patient_birth_date = fuzzy.FuzzyDate(datetime.date(1970, 1, 1))
    patient_age = fuzzy.FuzzyText(length=4)
    patient_sex = factory.Iterator(
        [x[0] for x in Image.PATIENT_SEX_CHOICES] + [""]
    )
    study_date = fuzzy.FuzzyDate(datetime.date(1970, 1, 1))
    study_instance_uid = fuzzy.FuzzyText(length=64)
    series_instance_uid = fuzzy.FuzzyText(length=64)
    study_description = factory.Sequence(lambda n: f"Study {n}")
    series_description = factory.Sequence(lambda n: f"Series {n}")
예제 #7
0
파일: factories.py 프로젝트: tatubola/xpto
class BilateralFactory(CleanModelFactory):
    class Meta:
        model = 'core.Bilateral'

    label = factory.LazyAttribute(lambda a: 'AS{0}-AS{1}'.format(
        a.peer_a.asn.number, a.peer_b.asn.number))
    bilateral_type = factory.Iterator(['L2', 'VPWS', 'VXLAN'])
    peer_a = factory.SubFactory(BilateralPeerFactory)
    peer_b = factory.SubFactory(BilateralPeerFactory)
    last_ticket = factory.Faker('pyint')
    description = factory.Faker('bs')
    modified_by = factory.SubFactory(UserFactory)
예제 #8
0
 def test_multicall(self):
     objs = MultifieldModelFactory.create_batch(
         6,
         slug=factory.Iterator(['main', 'alt']),
     )
     self.assertEqual(6, len(objs))
     self.assertEqual(2, len(set(objs)))
     self.assertEqual(
         list(obj.slug
              for obj in models.session.query(models.MultiFieldModel.slug)),
         ["alt", "main"],
     )
예제 #9
0
class SmallVariantCommentFactory(factory.django.DjangoModelFactory):
    """Factory for ``SmallVariantComment`` model."""
    class Meta:
        model = SmallVariantComment

    release = "GRCh37"
    chromosome = factory.Iterator(list(CHROMOSOME_MAPPING.keys()))
    start = factory.Sequence(lambda n: (n + 1) * 100)
    end = factory.LazyAttribute(
        lambda o: o.start + len(o.reference) - len(o.alternative))
    bin = 0
    reference = factory.Iterator("ACGT")
    alternative = factory.Iterator("CGTA")
    user = None
    text = factory.Sequence(lambda n: "Comment %d" % n)
    case = factory.SubFactory(CaseFactory)

    @factory.post_generation
    def fix_bins(obj, *args, **kwargs):
        obj.bin = binning.assign_bin(obj.start - 1, obj.end)
        obj.save()
예제 #10
0
파일: factories.py 프로젝트: tatubola/xpto
class PhysicalInterfaceFactory(CleanModelFactory):
    class Meta:
        model = 'core.PhysicalInterface'

    serial_number = factory.Faker('pystr')
    connector_type = factory.Iterator(
        ['SFP', 'SFP+', 'XFP', 'CFP', 'CPAK', 'QSFP28'])
    port_type = factory.LazyAttribute(
        lambda o: PORT_TYPE_CONNECTOR_TYPE[o.connector_type][0])
    last_ticket = factory.Faker('pyint')
    description = factory.Faker('bs')
    modified_by = factory.SubFactory(UserFactory)
예제 #11
0
파일: tests.py 프로젝트: 3nprob/Inboxen
    def test_index(self):
        request = MockRequest(self.user, has_otp=True, has_sudo=True)
        BlogPostFactory.create_batch(2,
                                     draft=factory.Iterator([True, False]),
                                     author=self.user)

        response = views.blog_admin_index(request)
        self.assertEqual(response.status_code, 200)

        expected_posts = models.BlogPost.objects.all()
        self.assertEqual(list(response.context_data["posts"]),
                         list(expected_posts))
예제 #12
0
class PriceEstimateFactory(factory.DjangoModelFactory):
    class Meta(object):
        model = models.PriceEstimate

    scope = factory.SubFactory(structure_factories.ProjectFactory)
    total = factory.Iterator([10, 100, 1000, 10000, 980, 42])
    month = factory.Iterator(range(1, 13))
    year = factory.Iterator(range(2012, 2016))

    @classmethod
    def get_list_url(self, action=None):
        url = 'http://testserver' + reverse('priceestimate-list')
        return url if action is None else url + action + '/'

    @classmethod
    def get_url(cls, price_estimate, action=None):
        if price_estimate is None:
            price_estimate = PriceEstimateFactory()
        url = 'http://testserver' + reverse(
            'priceestimate-detail', kwargs={'uuid': price_estimate.uuid})
        return url if action is None else url + action + '/'
예제 #13
0
class GameFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.Game

    name = factory.Iterator(
        ['Quake', 'Unreal', 'Serious Sam', 'Duke 3D', 'Deus Ex'])
    year = 1999
    website = 'example.com'
    description = 'Description'
    platforms = factory.RelatedFactory(PlatformFactory, name='Amiga')
    genres = factory.RelatedFactory(GenreFactory, name='Arcade')
    is_public = True
예제 #14
0
class CarFactory(DjangoModelFactory):

    active = True
    year = 2000
    price = factory.Iterator(range(1000, 50000, 1000))
    mileage = factory.Iterator(range(0, 500000, 10000))

    make = factory.SubFactory(CarMakeFactory)
    model = factory.SubFactory(CarModelFactory)
    submodel = factory.SubFactory(CarSubmodelFactory)

    body_type = None
    transmission = None
    fuel_type = None
    exterior_color = None

    created_at = factory.LazyAttribute(lambda x: datetime.now())
    updated_at = factory.LazyAttribute(lambda x: datetime.now())

    class Meta:
        model = Car
예제 #15
0
class DisasterFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = 'dsnap_rules.Disaster'

    disaster_request_no = factory.Faker('pystr')
    title = factory.Faker('pystr')
    state = factory.Iterator(models.State.objects.all())
    benefit_begin_date = factory.Faker('date')
    benefit_end_date = factory.Faker('date')
    residency_required = factory.Faker('boolean')
    uses_DSED = factory.Faker('boolean')
    allows_food_loss_alone = factory.Faker('boolean')
예제 #16
0
class PointFactory(factory.DjangoModelFactory):
    class Meta:
        model = Point

    trip = factory.Iterator(Trip.objects.all())

    lat = factory.Sequence(lambda n: random.random() * 180 - 90)
    lon = factory.Sequence(lambda n: random.random() * 360 - 180)
    time = factory.Faker("date_time_between",
                         start_date="-2y",
                         end_date="now",
                         tzinfo=pytz.UTC)
예제 #17
0
class LearningUnitYearFactory(DjangoModelFactory):
    class Meta:
        model = "base.LearningUnitYear"

    external_id = factory.fuzzy.FuzzyText(length=10, chars=string.digits)
    academic_year = factory.SubFactory(AcademicYearFactory)
    learning_unit = factory.SubFactory(LearningUnitFactory)
    learning_container_year = factory.SubFactory(LearningContainerYearFactory)
    changed = factory.fuzzy.FuzzyDateTime(datetime.datetime(2016, 1, 1, tzinfo=get_tzinfo()),
                                          datetime.datetime(2017, 3, 1, tzinfo=get_tzinfo()))
    acronym = factory.Sequence(lambda n: 'LUY-%d' % n)
    specific_title = factory.Sequence(lambda n: 'Learning unit year - %d' % n)
    specific_title_english = factory.Sequence(lambda n: 'Learning unit year english - %d' % n)
    subtype = factory.Iterator(learning_unit_year_subtypes.LEARNING_UNIT_YEAR_SUBTYPES, getter=operator.itemgetter(0))
    credits = factory.fuzzy.FuzzyDecimal(MINIMUM_CREDITS, MAXIMUM_CREDITS)
    decimal_scores = False
    status = True
    session = factory.Iterator(learning_unit_year_session.LEARNING_UNIT_YEAR_SESSION, getter=operator.itemgetter(0))
    quadrimester = factory.Iterator(learning_unit_year_quadrimesters.LEARNING_UNIT_YEAR_QUADRIMESTERS,
                                    getter=operator.itemgetter(0))
    attribution_procedure = None
예제 #18
0
파일: person.py 프로젝트: austinsdoe/osis
class PersonFactory(factory.DjangoModelFactory):
    class Meta:
        model = 'base.Person'

    first_name = factory.LazyAttribute(
        lambda person: person.user.first_name
        if person.user else factory.Faker('first_name'))
    last_name = factory.LazyAttribute(
        lambda person: person.user.last_name
        if person.user else factory.Faker('last_name'))
    changed = factory.fuzzy.FuzzyDateTime(
        datetime.datetime(2016, 1, 1, tzinfo=get_tzinfo()))
    email = factory.LazyAttribute(lambda person: person.user.email
                                  if person.user else None)
    phone = factory.Faker('phone_number')
    language = factory.Iterator(settings.LANGUAGES,
                                getter=operator.itemgetter(0))
    gender = factory.Iterator(mdl.person.Person.GENDER_CHOICES,
                              getter=operator.itemgetter(0))
    user = factory.SubFactory(UserFactory)
    global_id = None
예제 #19
0
class MidpointMentorFeedbackFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.MidpointMentorFeedback
        django_get_or_create = ('intern_selection', )

    intern_selection = factory.SubFactory(
        InternSelectionFactory,
        active=True,
        round__start_from='midfeedback',
    )
    allow_edits = False
    ip_address = factory.Faker('ipv4_public')

    intern_help_requests_frequency = factory.Iterator(
        models.MidpointMentorFeedback.ASKING_FOR_HELP_FREQUENCY_CHOICES,
        getter=lambda c: c[0])
    mentor_help_response_time = factory.Iterator(
        models.MidpointMentorFeedback.RESPONSE_TIME_CHOICES,
        getter=lambda c: c[0])
    intern_contribution_frequency = factory.Iterator(
        models.MidpointMentorFeedback.CONTRIBUTION_FREQUENCY_CHOICES,
        getter=lambda c: c[0])
    mentor_review_response_time = factory.Iterator(
        models.MidpointMentorFeedback.RESPONSE_TIME_CHOICES,
        getter=lambda c: c[0])
    intern_contribution_revision_time = factory.Iterator(
        models.MidpointMentorFeedback.RESPONSE_TIME_CHOICES,
        getter=lambda c: c[0])

    last_contact = factory.Faker('past_date')

    progress_report = factory.Faker('paragraph')

    full_time_effort = True

    payment_approved = True

    request_extension = False

    request_termination = False
예제 #20
0
class BiogenEventFactory(factory.django.DjangoModelFactory):
    name = factory.Sequence(lambda n: f'dummy event name {n}')
    email = factory.Faker('company_email')
    phone = factory.Faker('phone_number')
    requestor_name = factory.Faker('name')
    date = '2018-01-01'
    time = factory.Faker('time', pattern='%H:%M')
    period = factory.Iterator(BiogenEvent.PERIOD, getter=lambda c: c[0])
    duration = factory.Iterator([60, 90, 120, 240, 480], getter=lambda c: c)
    timezone = factory.Iterator(BiogenEvent.TIMEZONE, getter=lambda c: c[0])
    participants_count = randint(1, 10)
    presenters_count = randint(1, 5)
    presenters = json.loads(
        json.dumps([{
            "name": fake.name(),
            "email": fake.email()
        } for i in range(randint(1, 5))]))
    eod_webcast = factory.Iterator(BiogenEvent.EOD_WEBCAST,
                                   getter=lambda c: c[0])
    ms_sma = factory.Iterator(BiogenEvent.MS_SMA, getter=lambda c: c[0])
    slide_deck_name = factory.Sequence(lambda n: f'slide deck name {n}')
    slide_deck_id = factory.Sequence(lambda n: f'slide deck id {n}')
    program_meeting_id = factory.Sequence(lambda n: f'program meeting id {n}')
    notes = factory.Faker('text')
    status = factory.Iterator(BiogenEvent.STATUS, getter=lambda c: c[0])
    project = factory.SubFactory(ProjectFactory)

    class Meta:
        model = BiogenEvent
        django_get_or_create = ('name', )
예제 #21
0
파일: factories.py 프로젝트: dougcole/sjfnw
class DraftGrantApplication(factory.django.DjangoModelFactory):

  class Meta:
    model = 'grants.DraftGrantApplication'

  organization = factory.SubFactory(Organization)
  grant_cycle = factory.SubFactory(GrantCycle)

  demographics = factory.Iterator(FILES)
  funding_sources = factory.Iterator(FILES)
  budget1 = factory.Iterator(FILES)
  budget2 = factory.Iterator(FILES)
  budget3 = factory.Iterator(FILES)
  project_budget_file = factory.Iterator(FILES)

  @factory.lazy_attribute
  def contents(self):
    app = GrantApplication.build() # pylint: disable=no-member
    fields_to_exclude = app.file_fields() + [
      'organization', 'grant_cycle', 'giving_projects', 'narratives', 'budget',
      'submission_time', 'pre_screening_status',
      'scoring_bonus_poc', 'scoring_bonus_geo'
    ]
    contents = model_to_dict(app, exclude=fields_to_exclude)
    qs = self.grant_cycle.narrative_questions.all() # pylint: disable=no-member
    for question in qs:
      result = generate_narrative_answer(question.name, for_draft=True)
      if isinstance(result, (unicode, str)):
        contents[question.name] = result
      else:
        contents.update(result)

    return json.dumps(contents)
예제 #22
0
class InitialMentorFeedbackFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.InitialMentorFeedback
        django_get_or_create = ('intern_selection', )

    intern_selection = factory.SubFactory(
        InternSelectionFactory,
        active=True,
        round__start_from='initialfeedback',
    )
    allow_edits = False
    ip_address = factory.Faker('ipv4_public')

    in_contact = True
    asking_questions = True
    active_in_public = True
    provided_onboarding = True

    checkin_frequency = factory.Iterator(
        models.InitialMentorFeedback.CHECKIN_FREQUENCY_CHOICES,
        getter=lambda c: c[0])

    last_contact = factory.Faker('past_date')

    intern_response_time = factory.Iterator(
        models.InitialMentorFeedback.RESPONSE_TIME_CHOICES,
        getter=lambda c: c[0])
    mentor_response_time = factory.Iterator(
        models.InitialMentorFeedback.RESPONSE_TIME_CHOICES,
        getter=lambda c: c[0])

    progress_report = factory.Faker('paragraph')

    full_time_effort = True

    payment_approved = True

    request_extension = False

    request_termination = False
예제 #23
0
class TaskFactory(factory.DjangoModelFactory):
    """ Фактори задач. """
    name = factory.Faker('text', max_nb_chars=50)
    notes = factory.Faker('text', max_nb_chars=250)
    assignee = factory.Iterator(AsanaUser.objects.all())
    workspace = factory.Iterator(Workspace.objects.all())
    gid = factory.Faker('pystr', max_chars=5)

    @factory.post_generation
    def projects(self, create, projects):
        """Создаём один или несколько проектов, если они переданы в параметрах.

        Пример использования TaskFactory(projects=['Проект 1', 'Проект 2'])
        Принимает либо название проекта, либо список, состоящий либо из
        названий проектов, либо из проектов, либо из словаря для передачи в 
        ProjectFactory.
        """
        if not create:
            return
        if projects:
            result = []
            # если передано просто название одной группы
            if isinstance(projects, str):
                result.append(ProjectFactory(name=projects))
            else:
                for g in projects:
                    if isinstance(g, Project):
                        result.append(g)
                    elif isinstance(g, str):
                        result.append(ProjectFactory(name=g))
                    else:
                        result.append(ProjectFactory(**g))
            self.projects.add(*result)

    # Костыль чтобы подсказать Pycharm-у тип создаваемого объекта.
    def __new__(cls, *args, **kwargs) -> Task:
        return super().__new__(*args, **kwargs)

    class Meta:
        model = Task
예제 #24
0
class FilmFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Film

    movie_title = factory.Faker('sentence', nb_words=2)
    production_year = factory.Faker('date')
    country = factory.Iterator(Country.objects.all())
    budget = factory.Iterator([float(randint(1000, 100000)) for x in range(100)])
    worldwide_gross = factory.Iterator([float(randint(1000, 100000)) for x in range(100)])
    duration = factory.Iterator([timedelta(minutes=randint(30, 180)) for x in range(100)])

    @factory.post_generation
    def genre(self, create, extracted, **kwargs):
        if extracted:
            for ge in extracted:
                self.genre.add(ge)

    @factory.post_generation
    def director(self, create, extracted, **kwargs):
        if extracted:
            for dir in extracted:
                self.director.add(dir)

    @factory.post_generation
    def producer(self, create, extracted, **kwargs):
        if extracted:
            for prod in extracted:
                self.producer.add(prod)

    @factory.post_generation
    def actor(self, create, extracted, **kwargs):
        if extracted:
            for act in extracted:
                self.actor.add(act)

    @factory.post_generation
    def tag(self, create, extracted, **kwargs):
        if extracted:
            for tg in extracted:
                self.tag.add(tg)
예제 #25
0
def test_run(s3_stubber, caplog):
    """Test that the command updates the specified records (ignoring ones with errors)."""
    caplog.set_level('ERROR')

    original_datetime = datetime(2017, 1, 1, tzinfo=timezone.utc)

    with freeze_time(original_datetime):
        accepts_dit_email_marketing_values = [True, False, True]
        contacts = ContactFactory.create_batch(
            3,
            accepts_dit_email_marketing=factory.Iterator(
                accepts_dit_email_marketing_values),
        )

    bucket = 'test_bucket'
    object_key = 'test_key'
    csv_content = f"""id,accepts_dit_email_marketing
00000000-0000-0000-0000-000000000000,true
{contacts[0].pk},false
{contacts[1].pk},false
{contacts[2].pk},blah
"""

    s3_stubber.add_response(
        'get_object',
        {
            'Body': BytesIO(csv_content.encode(encoding='utf-8')),
        },
        expected_params={
            'Bucket': bucket,
            'Key': object_key,
        },
    )

    with freeze_time('2018-11-11 00:00:00'):
        call_command('update_contact_accepts_dit_email_marketing', bucket,
                     object_key)

    for contact in contacts:
        contact.refresh_from_db()

    assert 'Contact matching query does not exist' in caplog.text
    assert 'Must be a valid boolean' in caplog.text
    assert len(caplog.records) == 2

    assert [contact.accepts_dit_email_marketing for contact in contacts] == [
        False,
        False,
        True,
    ]
    assert all(contact.modified_on == original_datetime
               for contact in contacts)
예제 #26
0
def test_happy_path(s3_stubber):
    """Test that the command creates the specified records."""
    sector_pks = [
        '00000000-0000-0000-0000-000000000001',
        '00000000-0000-0000-0000-000000000002',
        '00000000-0000-0000-0000-000000000003',
    ]
    segments = ['segment_1', 'segment_2', 'segment_3']
    clusters = SectorClusterFactory.create_batch(
        3,
        name=factory.Iterator(['cluster_1', 'cluster_2', 'cluster_3']),
    )
    parent_sector = SectorFactory()

    bucket = 'test_bucket'
    object_key = 'test_key'
    csv_content = f"""id,segment,sector_cluster_id,parent_id
{sector_pks[0]},{segments[0]},{clusters[0].pk},{parent_sector.pk}
{sector_pks[1]},{segments[1]},{clusters[1].pk},{parent_sector.pk}
{sector_pks[2]},{segments[2]},{clusters[2].pk},{parent_sector.pk}
"""

    s3_stubber.add_response(
        'get_object',
        {
            'Body': BytesIO(csv_content.encode(encoding='utf-8')),
        },
        expected_params={
            'Bucket': bucket,
            'Key': object_key,
        },
    )

    call_command('create_sector', bucket, object_key)

    sectors = Sector.objects.filter(pk__in=sector_pks).order_by('pk')
    assert len(sectors) == 3
    assert [str(sectors[0].pk),
            str(sectors[1].pk),
            str(sectors[2].pk)] == sector_pks
    assert [sectors[0].segment, sectors[1].segment,
            sectors[2].segment] == segments
    assert [
        sectors[0].sector_cluster,
        sectors[1].sector_cluster,
        sectors[2].sector_cluster,
    ] == clusters
    assert [
        sectors[0].parent,
        sectors[1].parent,
        sectors[2].parent,
    ] == [parent_sector, parent_sector, parent_sector]
예제 #27
0
class StudentPerformanceFactory(factory.DjangoModelFactory):
    class Meta:
        model = 'performance.StudentPerformance'

    registration_id = factory.fuzzy.FuzzyText(length=10, chars=string.digits)
    academic_year = datetime.datetime.today().year
    acronym = factory.fuzzy.FuzzyText(length=15, chars=string.ascii_letters)
    data = load_sample_student_performance()
    update_date = datetime.datetime.now(tz=pytz.utc) + datetime.timedelta(days=1)
    creation_date = datetime.datetime.now(tz=pytz.utc)
    authorized = True
    offer_registration_state = registration_state.CESSATION
    session_locked = factory.Iterator(session_month.SESSION_MONTHS, getter=operator.itemgetter(0))
예제 #28
0
class SessionExamCalendarFactory(factory.DjangoModelFactory):
    class Meta:
        model = "base.SessionExamCalendar"

    external_id = factory.fuzzy.FuzzyText(length=10, chars=string.digits)
    changed = factory.fuzzy.FuzzyDateTime(
        datetime.datetime(2016, 1, 1, tzinfo=get_tzinfo()),
        datetime.datetime(2017, 3, 1, tzinfo=get_tzinfo()))
    number_session = factory.Iterator(number_session.NUMBERS_SESSION,
                                      getter=operator.itemgetter(0))
    academic_calendar = factory.SubFactory(
        AcademicCalendarFactory,
        reference=academic_calendar_type.SCORES_EXAM_SUBMISSION)
예제 #29
0
파일: tests.py 프로젝트: LK4268/Inboxen
    def test_index(self):
        request = MockRequest(self.user, has_otp=True, has_sudo=True)
        QuestionFactory.create_batch(
            len(models.Question.STATUS_CHOICES),
            status=factory.Iterator(
                [i[0] for i in models.Question.STATUS_CHOICES]))

        response = views.question_admin_index(request)
        self.assertEqual(response.status_code, 200)

        expected_questions = models.Question.objects.all()
        self.assertEqual(list(response.context_data["questions"]),
                         list(expected_questions))
예제 #30
0
class EntityContainerYearFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = "base.EntityContainerYear"

    external_id = factory.Sequence(lambda n: '10000000%02d' % n)
    changed = factory.fuzzy.FuzzyDateTime(
        datetime.datetime(2016, 1, 1, tzinfo=get_tzinfo()),
        datetime.datetime(2017, 3, 1, tzinfo=get_tzinfo()))
    entity = factory.SubFactory(EntityFactory)
    learning_container_year = factory.SubFactory(LearningContainerYearFactory)
    type = factory.Iterator(
        entity_container_year_link_type.ENTITY_CONTAINER_YEAR_LINK_TYPES,
        getter=operator.itemgetter(0))