Exemplo n.º 1
0
def test_data():
    mixer.cycle(30).blend(User, password='******')
    mixer.cycle(50).blend(ReviewGroup)
    mixer.cycle(100).blend(Proposal, review_group=mixer.SELECT)
    mixer.cycle(200).blend(ReviewVote,
                           review_group=mixer.SELECT,
                           user=mixer.SELECT)
    mixer.cycle(30).blend(Vote, user=mixer.SELECT, proposal=mixer.SELECT)
Exemplo n.º 2
0
def test_converse_responds_with_two_quotes_per_person(client, session, mock_bot):
    mock_person1 = mixer.blend(Person, first_name="Beth")
    mock_person2 = mixer.blend(Person, first_name="Valisy")
    mock_quotes1 = mixer.cycle().blend(Quote, person=mock_person1)
    mock_quotes2 = mixer.cycle().blend(Quote, person=mock_person2)

    session.bulk_save_objects([mock_person1, mock_person2, *mock_quotes1, *mock_quotes2])
    session.commit()

    result = mock_bot.converse([mock_person1.slack_user_id, mock_person2.slack_user_id])
    message = result.message

    assert message.count("Beth:") == 2
    assert message.count("Valisy:") == 2
Exemplo n.º 3
0
def test_get_all_quotes_from_person(num_quotes, client, session):
    person = mixer.blend(Person)
    expected_quotes = mixer.cycle(num_quotes).blend(Quote, person=person)

    actual_quotes = get_all_quotes_from_person(person.slack_user_id)

    assert actual_quotes == expected_quotes
Exemplo n.º 4
0
 def blend_geokret(self, *args, **kwargs):
     with mixer.ctx():
         if 'created_on_datetime' not in kwargs:
             kwargs['created_on_datetime'] = "2019-01-12T16:33:46"
         if kwargs.get('count'):
             return mixer.cycle(kwargs.get('count')).blend(Geokret, **kwargs)
         return mixer.blend(Geokret, **kwargs)
Exemplo n.º 5
0
    def setUp(self):
        app.config['TESTING'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
            os.path.join(basedir, 'test.db')
        self.__app__ = app.test_client()            
        db.create_all()

        titles = ['Title1', 'Title2', 'Title3']
        authors = ['Author1', 'Author2', 'Author3']
        user_emails = ['*****@*****.**', '*****@*****.**', '*****@*****.**']
        mixer.init_app(app)
        users = mixer.cycle(2).blend(User, email=(email for email in user_emails))
        books = mixer.cycle(2).blend(Book, title=(title for title in titles),
                                    author=(author for author in authors))
        user_book = mixer.cycle(2).blend(UserBooks,
                                         user_id=(user.id for user in users),
                                         book_id=(book.id for book in books))
Exemplo n.º 6
0
def test_get_random_quotes_from_person_defaults_to_one(client, session):
    person = mixer.blend(Person)
    expected_quotes = mixer.cycle().blend(Quote, person=person)

    random_quotes = get_random_quotes_from_person(person.slack_user_id)

    assert set(random_quotes).issubset(expected_quotes)
    assert len(random_quotes) == 1
Exemplo n.º 7
0
Arquivo: base.py Projeto: ricekab/zou
 def generate_data(self, cls, number, **kwargs):
     """
     Generate random data for a given data model.
     """
     mixer.init_app(self.flask_app)
     return mixer.cycle(number).blend(
         cls,
         id=fields.gen_uuid,
         **kwargs
     )
Exemplo n.º 8
0
 def blend_move_comment(self, *args, **kwargs):
     with mixer.ctx():
         if kwargs.get('count'):
             move_comments = mixer.cycle(kwargs.get('count')).blend(MoveComment, **kwargs)
             for move_comment in move_comments:
                 update_geokret_and_moves(db.session, move_comment.move.geokret_id, move_comment.move.id)
             return move_comments
         move_comment = mixer.blend(MoveComment, **kwargs)
         update_geokret_and_moves(db.session, move_comment.move.geokret_id, move_comment.move.id)
         return move_comment
Exemplo n.º 9
0
def test_converse_notifies_users_if_person_does_not_exist(client, session, mock_bot):
    mock_person = mixer.blend(Person, first_name="Beth")
    mock_quotes = mixer.cycle().blend(Quote, person=mock_person)
    non_existent_id1 = "foo"
    non_existent_id2 = "bar"

    session.bulk_save_objects([mock_person, *mock_quotes])
    session.commit()

    result = mock_bot.converse([mock_person.slack_user_id, non_existent_id1, non_existent_id2])
    message = result.message

    assert message == f"I don't recognize {non_existent_id1}, {non_existent_id2}"
Exemplo n.º 10
0
def test_random_responds_with_random_quote(client, session, mock_bot):
    mock_person = mixer.blend(Person)
    mock_quotes = mixer.cycle().blend(Quote, person=mock_person)
    quote_contents = [quote.content for quote in mock_quotes]

    session.bulk_save_objects([mock_person, *mock_quotes])
    session.commit()

    result = mock_bot.random()

    result_quote, result_user = result.message.replace('"', "").split(" - ")
    assert result_quote in quote_contents
    assert result_user == mock_person.first_name
Exemplo n.º 11
0
def test_converse_repeats_quote_if_person_has_fewer_than_two_quotes(client, session, mock_bot):
    mock_person1 = mixer.blend(Person, first_name="Beth")
    mock_person2 = mixer.blend(Person, first_name="Vasily")
    mock_quotes1 = mixer.cycle().blend(Quote, person=mock_person1)
    mock_quotes2 = [Quote(content="I only have one quote", person_id=mock_person2.id)]

    session.bulk_save_objects([mock_person1, mock_person2, *mock_quotes1, *mock_quotes2])
    session.commit()

    result = mock_bot.converse([mock_person1.slack_user_id, mock_person2.slack_user_id])
    message = result.message

    assert message.count("Beth:") == 2
    assert message.count("Vasily:") == 2
Exemplo n.º 12
0
def generate_data(people: int, quotes: int):
    """
    Create people amount of Person objects in the database each
    with quotes amount of Quotes.
    """
    current_app.logger.info(
        f"Generating {people} People objects with {quotes} Quotes each..."
    )

    # May need to modify this when this command is unit tested
    mixer.init_app(current_app)

    people = mixer.cycle(people).blend(Person,
                                       slack_user_id=mixer.faker.isbn10,
                                       last_name=mixer.faker.last_name)
    quotes = mixer.cycle(quotes).blend(Quote,
                                       person=mixer.SELECT)

    current_app.logger.info("Generated the following people:")
    for person in people:
        current_app.logger.info(
            f"{person.slack_user_id} - {person.first_name} {person.last_name}"
        )
Exemplo n.º 13
0
def test_get_all_quotes_from_person(num_quotes, client, session,
                                    prepared_user):
    quotes = mixer.cycle(num_quotes).blend(Quote, person=prepared_user)
    expected_data = [get_serialized_quote(quote) for quote in quotes]

    response = client.get(
        url_for(
            "api.personquotelistresource",
            slack_user_id=prepared_user.slack_user_id,
        ))

    response_json = response.json
    assert response.status_code == 200
    assert len(response_json) == num_quotes
    assert response_json == expected_data
Exemplo n.º 14
0
def test_remind_pings_multiple_targes(client, session, mock_bot):
    mock_nostalgia_person = mixer.blend(Person)
    mock_target_persons = mixer.cycle(3).blend(Person)
    mock_quote = mixer.blend(Quote, person=mock_nostalgia_person)
    target_user_ids = [target.slack_user_id for target in mock_target_persons]
    expected_message = (
        f"{' '.join(f'<@{user_id}>' for user_id in target_user_ids)} Do you remember this?"
        f'\n\n"{mock_quote.content}" - {mock_nostalgia_person.first_name}'
    )

    session.bulk_save_objects([mock_nostalgia_person, *mock_target_persons, mock_quote])
    session.commit()

    result = mock_bot.remind(mock_nostalgia_person.slack_user_id, target_user_ids)

    assert expected_message == result.message
Exemplo n.º 15
0
def test_get_random_person(client, session):
    people = mixer.cycle().blend(Person)
    slack_user_ids = [person.slack_user_id for person in people]
    different_user_returned = False

    random_person = get_random_person()

    assert random_person in slack_user_ids

    # Note because this part of the test tests randomness it could be flaky,
    # but the probability of returning the same user 6 times is quite low.
    for _ in range(5):
        new_random_person = get_random_person()
        if new_random_person != random_person:
            different_user_returned = True
            break

    assert different_user_returned
Exemplo n.º 16
0
 def create_persons(self, number=3):
     persons = mixer.cycle(number).blend(Person)
     map(db.session.add, persons)
     db.session.flush()
     return persons
Exemplo n.º 17
0
 def blend_news_comment(self, *args, **kwargs):
     with mixer.ctx():
         if kwargs.get('count'):
             return mixer.cycle(kwargs.get('count')).blend(NewsComment, **kwargs)
         return mixer.blend(NewsComment, **kwargs)
Exemplo n.º 18
0
def fake_data():
    mixer.init_app(app)

    mixer.cycle(50).blend(User, password=hashing.hash_value("123456"))
    mixer.cycle(10).blend(Cinema, info=mixer.sequence("info_{0}"))
    mixer.cycle(10).blend(Movie, length=(a for a in range(95, 126)))
Exemplo n.º 19
0
def resetdb():
    "Create a test database"
    names = ['Jim', 'Bob', 'Sarah', 'Sue']
    wards = ['Easton', 'AWL', 'BCR', 'WOT']
    lead_statuses = ['Successful', 'Possible', 'Dead']
    db.drop_all()
    db.create_all()
    admin_role = Role(name='admin')
    db.session.add(admin_role)
    db.session.add(Role(name='manager'))
    db.session.add(Role(name='surveyor'))
    admin_user = User(email='*****@*****.**',
                      active=True,
                      password=user_manager.hash_password('admin'))
    admin_user.roles.append(admin_role)
    db.session.add(admin_user)
    for x in lead_statuses:
        lead_status = SurveyLeadStatuses()
        lead_status.name = x
        db.session.add(lead_status)
    db.session.commit()
    # Generate some random entries.
    def get_random_name():
        return random.choice(names)
    def get_random_ward():
        return random.choice(wards)
    def get_random_box_number():
        return random.randrange(100)
    def get_random_date():
        start = PHASE_START_DATES[0]
        end = PHASE_START_DATES[-1]
        delta = end - start
        return start + datetime.timedelta(random.randrange(delta.days))
    def get_random_phase():
        return random.randint(1, NUM_PHASES)
    mixer.cycle(10).blend(User)
    mixer.cycle(50).blend(Surveys,
                          name=mixer.RANDOM,
                          ward=mixer.RANDOM,
                          free_survey_consideration=mixer.RANDOM,
                          lead_status=mixer.SELECT,
                          survey_request_date=get_random_date,
                          phase=get_random_phase,
                          survey_date=get_random_date,
                          address_line=mixer.RANDOM,
                          availability=mixer.RANDOM,
                          expected_benefit=mixer.RANDOM,
                          box_collected=mixer.RANDOM,
                          notes=mixer.RANDOM)
    mixer.cycle(50).blend(Results,
                          survey=mixer.SELECT,
                          survey_date=get_random_date,
                          lead_surveyor=get_random_name,
                          assistant_surveyor=get_random_name,
                          cheese_box_number=get_random_box_number,
                          faults_identified=mixer.RANDOM,
                          recommendations=mixer.RANDOM,
                          notes=mixer.RANDOM)
    mixer.cycle(50).blend(MonthFeedback,
                          survey=mixer.SELECT,
                          completed_actions=mixer.RANDOM,
                          planned_actions=mixer.RANDOM,
                          cheese_box=mixer.RANDOM,
                          feedback=mixer.RANDOM,
                          notes=mixer.RANDOM)
    mixer.cycle(20).blend(YearFeedback,
                          householders_name=mixer.RANDOM,
                          survey=mixer.SELECT,
                          diy_work=mixer.RANDOM,
                          prof_work=mixer.RANDOM,
                          contractors_used=mixer.RANDOM,
                          planned_work=mixer.RANDOM,
                          wellbeing_improvement=mixer.RANDOM,
                          behaviour_changes=mixer.RANDOM,
                          feedback=mixer.RANDOM,
                          notes=mixer.RANDOM)
    mixer.cycle(10).blend(Wards)
    mixer.cycle(10).blend(BuildingTypes)
    mixer.cycle(10).blend(WallConstructionTypes)
    mixer.cycle(10).blend(OccupationTypes)
    mixer.cycle(10).blend(SpaceHeatingTypes)
    mixer.cycle(10).blend(WaterHeatingTypes)
    mixer.cycle(10).blend(CookingTypes)
    # Remove duplicate references (where there should only be one).
    for s in Surveys.query.all():
      if len(s.result) > 1:
        for x in s.result[1:]:
          db.session.delete(x)
      if len(s.month_feedback) > 1:
        for x in s.month_feedback[1:]:
          db.session.delete(x)
      if len(s.year_feedback) > 1:
        for x in s.year_feedback[1:]:
          db.session.delete(x)
    db.session.commit()
Exemplo n.º 20
0
 def blend_badge(self, *args, **kwargs):
     with mixer.ctx():
         if kwargs.get('count'):
             return mixer.cycle(kwargs.get('count')).blend(Badge, **kwargs)
         return mixer.blend(Badge, **kwargs)
Exemplo n.º 21
0
 def blend_news_subscription(self, *args, **kwargs):
     with mixer.ctx():
         if kwargs.get('count'):
             return mixer.cycle(kwargs.get('count')).blend(NewsSubscription, **kwargs)
         return mixer.blend(NewsSubscription, **kwargs)
Exemplo n.º 22
0
from mixer.main import TypeMixer

@mixer.middleware(models.Task)
def encrypt_password(task):
    task.due_date = datetime.datetime.utcnow() + datetime.timedelta(days=randint(5, 10))
    return task


with app.app_context():
    db.drop_all()
    db.create_all()
    mixer.init_app(app)
    mixer.register(models.Task, description=lambda: 'LALAAL')

    for task in mixer.cycle(10).blend(models.Task,
                                      name=mixer.faker.name,
                                      description=mixer.FAKE):
        print(task.due_date)

    db.session.flush()

    for item in mixer.cycle(100).blend(models.Item,
                                       name=mixer.faker.name,
                                       description=mixer.faker.text,
                                       task=mixer.SELECT):
        item.handled = True if randint(0, 1) == 1 else False
        item.due_date = datetime.datetime.utcnow() + datetime.timedelta(days=randint(0, 5) + (365 * 30))
        if item.handled is True:
            item.handled_date = datetime.datetime.utcnow() - datetime.timedelta(days=randint(0, 3))
        db.session.add(item)
Exemplo n.º 23
0
def test_data():
    mixer.cycle(30).blend(User, password='******')
    mixer.cycle(50).blend(ReviewGroup)
    mixer.cycle(100).blend(Proposal, review_group=mixer.SELECT)
    mixer.cycle(200).blend(ReviewVote, review_group=mixer.SELECT, user=mixer.SELECT)
    mixer.cycle(30).blend(Vote, user=mixer.SELECT, proposal=mixer.SELECT)
Exemplo n.º 24
0
def test_get_all_people_returns_all_people(client, session, num_people):
    mixer.cycle(num_people).blend(Person)

    assert len(get_all_people()) == num_people
Exemplo n.º 25
0
 def create_fixtures(cls):
     # Create some random links
     link_fixtures = mixer.cycle(5).blend(Link, geom='SRID=4326; LINESTRING EMPTY')
     db.session.add_all(link_fixtures)
Exemplo n.º 26
0
def resetdb():
    "Create a test database"
    names = ['Sue', 'Dave', 'Mike', 'Brian', 'Roz', 'Jeremy', 'Jamie', 'Maddy']
    wards = ['Easton', 'Lawrence Hill', 'Clifton', 'Kingsdown']
    lead_statuses = ['Successful', 'Possible', 'Dead']
    building_types = ['Flat', 'Terrace', 'Detached', 'Unknown']
    wall_construction_types = ['Brick', 'Stone', 'Timber', 'Unknown']
    occupation_types = ['Rented', 'Owner', 'Unknown']
    space_heating_types = [
        'Central heating', 'Gas fire', 'Electric heaters', 'Unknown'
    ]
    water_heating_types = ['Electricity', 'Gas', 'Solar', 'Unknown']
    cooking_types = ['Electricity', 'Gas', 'Other', 'Unknown']
    db.drop_all()
    db.create_all()
    admin_role = Role(name='admin')
    db.session.add(admin_role)
    db.session.add(Role(name='manager'))
    db.session.add(Role(name='surveyor'))
    admin_user = User(email='*****@*****.**',
                      active=True,
                      password=user_manager.hash_password('admin'))
    admin_user.roles.append(admin_role)
    db.session.add(admin_user)
    # Create enum tables.
    create_enum_values(db, Wards, wards)
    create_enum_values(db, SurveyLeadStatuses, lead_statuses)
    create_enum_values(db, BuildingTypes, building_types)
    create_enum_values(db, WallConstructionTypes, wall_construction_types)
    create_enum_values(db, OccupationTypes, occupation_types)
    create_enum_values(db, SpaceHeatingTypes, space_heating_types)
    create_enum_values(db, WaterHeatingTypes, water_heating_types)
    create_enum_values(db, CookingTypes, cooking_types)
    db.session.commit()

    # Generate some random entries.
    def get_random_name():
        return random.choice(names)

    def get_random_ward():
        return random.choice(wards)

    def get_random_box_number():
        return random.randrange(100)

    def get_random_date():
        start = PHASE_START_DATES[0]
        end = PHASE_START_DATES[-1]
        delta = end - start
        return start + datetime.timedelta(random.randrange(delta.days))

    def get_random_phase():
        return random.randint(1, NUM_PHASES)

    mixer.cycle(10).blend(User)
    mixer.cycle(50).blend(Surveys,
                          name=mixer.RANDOM,
                          ward=mixer.RANDOM,
                          free_survey_consideration=mixer.RANDOM,
                          lead_status=mixer.SELECT,
                          survey_request_date=get_random_date,
                          phase=get_random_phase,
                          survey_date=get_random_date,
                          address_line=mixer.RANDOM,
                          availability=mixer.RANDOM,
                          expected_benefit=mixer.RANDOM,
                          box_collected=mixer.RANDOM,
                          notes=mixer.RANDOM)
    # This table is now deprecated for phase 5 and onwards.
    mixer.cycle(50).blend(Results,
                          survey=mixer.SELECT,
                          survey_date=get_random_date,
                          lead_surveyor=get_random_name,
                          assistant_surveyor=get_random_name,
                          cheese_box_number=get_random_box_number,
                          faults_identified=mixer.RANDOM,
                          recommendations=mixer.RANDOM,
                          notes=mixer.RANDOM)
    mixer.cycle(50).blend(PreSurveyDetails,
                          survey=mixer.SELECT,
                          householder_name=get_random_name,
                          postcode=mixer.RANDOM,
                          building_type=mixer.SELECT,
                          year_of_construction=mixer.RANDOM,
                          wall_construction_type=mixer.SELECT,
                          occupation_type=mixer.SELECT,
                          primary_heating_type=mixer.SELECT,
                          secondary_heating_type=mixer.SELECT,
                          water_heating_type=mixer.SELECT,
                          cooking_type=mixer.SELECT,
                          depth_loft_insulation=mixer.RANDOM,
                          number_open_fireplaces=mixer.RANDOM,
                          double_glazing=mixer.RANDOM,
                          has_asbestos=mixer.RANDOM,
                          asbestos_details=mixer.RANDOM,
                          num_occupants=mixer.RANDOM,
                          notes=mixer.RANDOM)
    mixer.cycle(50).blend(PostSurveyDetails,
                          survey=mixer.SELECT,
                          lead_surveyor=get_random_name,
                          assistant_surveyor=get_random_name,
                          survey_date=get_random_date,
                          camera_kit_number=mixer.RANDOM,
                          external_temperature=mixer.RANDOM,
                          faults_identified=mixer.RANDOM,
                          recommendations=mixer.RANDOM,
                          notes=mixer.RANDOM)
    mixer.cycle(50).blend(MonthFeedback,
                          survey=mixer.SELECT,
                          completed_actions=mixer.RANDOM,
                          planned_actions=mixer.RANDOM,
                          cheese_box=mixer.RANDOM,
                          feedback=mixer.RANDOM,
                          notes=mixer.RANDOM)
    mixer.cycle(20).blend(YearFeedback,
                          householders_name=mixer.RANDOM,
                          survey=mixer.SELECT,
                          diy_work=mixer.RANDOM,
                          prof_work=mixer.RANDOM,
                          contractors_used=mixer.RANDOM,
                          planned_work=mixer.RANDOM,
                          wellbeing_improvement=mixer.RANDOM,
                          behaviour_changes=mixer.RANDOM,
                          feedback=mixer.RANDOM,
                          notes=mixer.RANDOM)
    # Remove duplicate references (where there should only be one).
    for s in Surveys.query.all():
        if len(s.result) > 1:
            for x in s.result[1:]:
                db.session.delete(x)
        if len(s.pre_details) > 1:
            for x in s.pre_details[1:]:
                db.session.delete(x)
        if len(s.post_details) > 1:
            for x in s.post_details[1:]:
                db.session.delete(x)
        if len(s.month_feedback) > 1:
            for x in s.month_feedback[1:]:
                db.session.delete(x)
        if len(s.year_feedback) > 1:
            for x in s.year_feedback[1:]:
                db.session.delete(x)
    db.session.commit()