示例#1
0
def test_doesnt_create_directory_if_clips_error(mocker: MockFixture,
                                                fs: FakeFilesystem) -> None:
    mocker.patch("abridge.processor.abridge_clip")

    mocker.spy(abridge.cli, "sys")

    sys.argv = ["", "-o", "outputdir", "noexist.mp4"]

    main()

    os.path.isdir("outputdir")
示例#2
0
    async def test_transaction_cm(self, async_context_manager, mocker: MockFixture):
        exc_type, exc_val, exc_tb = None, None, None
        fake_transaction_cm = async_context_manager(mocker.Mock())
        fake_connection = mocker.Mock(begin=mocker.Mock(return_value=fake_transaction_cm))
        fake_conn_cm = async_context_manager(fake_connection)
        fake_model_mgr = mocker.Mock(
            transaction_connection=None,
            engine=mocker.Mock(acquire=mocker.Mock(return_value=fake_conn_cm))
        )
        mocker.spy(fake_conn_cm, '__aenter__')
        mocker.spy(fake_conn_cm, '__aexit__')

        mocker.spy(fake_transaction_cm, '__aenter__')
        mocker.spy(fake_transaction_cm, '__aexit__')

        transaction = _TransactionContextManager(fake_model_mgr)

        async with transaction as model_objects:
            assert model_objects == fake_model_mgr
            fake_model_mgr.engine.acquire.assert_called_once_with()
            fake_conn_cm.__aenter__.assert_called_once_with()
            fake_transaction_cm.__aenter__.assert_called_once_with()
            fake_connection.begin.assert_called_once_with()
            assert fake_model_mgr.transaction_connection == fake_connection

        fake_transaction_cm.__aexit__.assert_called_once_with(exc_type, exc_val, exc_tb)
        fake_conn_cm.__aexit__.assert_called_once_with(exc_type, exc_val, exc_tb)
        assert fake_model_mgr.transaction_connection is None
示例#3
0
def test_db_verbosity(
    cli_runner: testing.CliRunner,
    mocker: ptm.MockFixture,
    invoke_arg: t.List[str],
) -> None:
    from loguru import logger
    enable_spy = mocker.spy(logger, name='enable')
    disable_spy = mocker.spy(logger, name='disable')
    add_spy = mocker.spy(logger, name='add')
    _ = mocker.patch('asyncpg_migrate.loader.load_configuration')

    from asyncpg_migrate import main

    @main.db.command(name='test', short_help='test command')
    def test() -> None:
        click.echo(1)

    result = cli_runner.invoke(main.db, invoke_arg)
    assert result.exit_code == 0

    if invoke_arg[0] == '-v' or invoke_arg[0] == '--verbose':
        assert enable_spy.called
        assert not disable_spy.called
        assert add_spy.mock_calls[0].kwargs == {
            'format': '{time} {message}',
            'filter': 'asyncpg-migrate',
            'level': 'INFO',
        }
    elif invoke_arg[0] == '-vv':
        assert enable_spy.called
        assert not disable_spy.called
        assert add_spy.mock_calls[0].kwargs == {
            'format': '{time} {message}',
            'filter': 'asyncpg-migrate',
            'level': 'DEBUG',
        }
    elif invoke_arg[0] == '-vvv':
        assert enable_spy.called
        assert not disable_spy.called
        assert add_spy.mock_calls[0].kwargs == {
            'format': '{time} {message}',
            'filter': 'asyncpg-migrate',
            'level': 'TRACE',
        }
    else:
        assert not enable_spy.called
        assert disable_spy.called
        assert not add_spy.called
示例#4
0
def test_run_configuration_should_filter_message_where_receiver_is_not_working(
    db: MockFixture,
    mocker: MockFixture,
    setup: tuple[User, User, list[ExternalMessage]],
) -> None:
    user1, user2, messages_should_be_consumed = setup
    user_not_working = UserFactory(
        on_leave=True,
        working_time_start=datetime.time(8, 0, 0),
        working_time_end=datetime.time(17, 0, 0),
    )

    fake_messages = messages_should_be_consumed + [
        ExternalMessage(user2.username, user_not_working.username,
                        'message to not working user'),
    ]

    mocker.patch.object(SampleProducer,
                        'produce_external_messages',
                        return_value=fake_messages)

    consume_messages_spy = mocker.spy(SampleConsumer, 'consume_messages')

    configuration = ConfigurationFactory(
        consumers=(ConsumerModelFactory(), ),
        producers=(ProducerModelFactory(), ),
        users=(user1, user2, user_not_working),
        message_filters=(MessageFilterModelFactory(
            object_type=ReceiverWorkingMessageFilter.__name__), ),
    )

    configuration.run()

    assert consume_messages_spy.call_args.args[
        1] == messages_should_be_consumed
示例#5
0
def test_extend_by_cancellation_with_future_date(client_subscription_factory,
                                                 event_factory,
                                                 mocker: MockFixture):
    start_date = date(2019, 2, 25)
    event = event_factory(event_class__date_from=start_date,
                          canceled_at=date(2019, 2, 26))
    cs: models.ClientSubscriptions = client_subscription_factory(
        subscription__event_class__events=event.event_class,
        subscription__rounding=False,
        subscription__duration=7,
        subscription__duration_type=GRANULARITY.DAY,
        start_date=start_date)
    new_end_date = date(2019, 2, 27)

    mocker.patch('crm.models.ClientSubscriptions.nearest_extended_end_date',
                 return_value=new_end_date)

    spy = mocker.spy(models.ExtensionHistory.objects, 'create')
    old_end_date = cs.end_date

    cs.extend_by_cancellation(event)

    cs.refresh_from_db()

    assert_that(cs, has_properties(end_date=new_end_date))
    spy.assert_called_once_with(
        client_subscription=cs,
        reason=f'В связи с отменой тренировки {event}',
        added_visits=0,
        related_event=event,
        extended_to=new_end_date,
        extended_from=old_end_date,
    )
示例#6
0
def test_extend_duration_without_new_end_date_and_zero(
        client_subscription_factory, mocker: MockFixture):
    start_date = date(2019, 2, 25)
    cs: models.ClientSubscriptions = client_subscription_factory(
        subscription__event_class__events=[],
        subscription__rounding=False,
        subscription__duration=7,
        subscription__duration_type=GRANULARITY.DAY,
        start_date=start_date)
    old_end_date = cs.end_date

    mocker.patch('crm.models.ClientSubscriptions.nearest_extended_end_date',
                 return_value=cs.end_date)

    old_visits = cs.visits_left

    spy = mocker.spy(models.ExtensionHistory.objects, 'create')

    cs.extend_duration(0, reason='TEST')

    cs.refresh_from_db()

    assert_that(cs,
                has_properties(visits_left=old_visits, end_date=old_end_date))
    spy.assert_not_called()
示例#7
0
def test_extend_by_cancellation_no_future_date(client_subscription_factory,
                                               event_factory,
                                               mocker: MockFixture):
    start_date = date(2019, 2, 25)
    event = event_factory(event_class__date_from=start_date,
                          canceled_at=date(2019, 2, 26))
    cs: models.ClientSubscriptions = client_subscription_factory(
        subscription__event_class__events=event.event_class,
        subscription__rounding=False,
        subscription__duration=7,
        subscription__duration_type=GRANULARITY.DAY,
        start_date=start_date)
    old_end_date = cs.end_date

    mocker.patch('crm.models.ClientSubscriptions.nearest_extended_end_date',
                 return_value=cs.end_date)

    spy = mocker.spy(models.ExtensionHistory.objects, 'create')

    cs.extend_by_cancellation(event)

    cs.refresh_from_db()

    assert_that(cs, has_properties(end_date=old_end_date))
    spy.assert_not_called()
示例#8
0
def test_spec_load_from_path(
    spec_path: Path,
    mocker: ptm.MockFixture,
) -> None:
    parse_spec = mocker.spy(parser, 'parse_spec')
    assert loader.load_spec(spec_path) is not None
    parse_spec.assert_called_once()
示例#9
0
def test_run_configuration_should_filter_message_with_skip_keywords(
    db: MockFixture,
    mocker: MockFixture,
    setup: tuple[User, User, list[ExternalMessage]],
) -> None:
    user1, user2, messages_should_be_consumed = setup

    fake_messages = messages_should_be_consumed + [
        ExternalMessage(user2.username, user1.username,
                        'message with skip_keyword1'),
    ]

    mocker.patch.object(SampleProducer,
                        'produce_external_messages',
                        return_value=fake_messages)

    consume_messages_spy = mocker.spy(SampleConsumer, 'consume_messages')

    configuration = ConfigurationFactory(
        consumers=(ConsumerModelFactory(), ),
        producers=(ProducerModelFactory(), ),
        users=(user1, user2),
        message_filters=(MessageFilterModelFactory(
            object_type=SkipKeywordsMessageFilter.__name__,
            parameters={'skip_keywords': ['skip_keyword1']},
        ), ),
    )

    configuration.run()

    assert consume_messages_spy.call_args.args[
        1] == messages_should_be_consumed
示例#10
0
def test_preview_pipeline(mocker: MockFixture, pipeline_executor):
    df_to_json_spy = mocker.spy(pd.DataFrame, 'to_json')
    result = json.loads(
        pipeline_executor.preview_pipeline(
            Pipeline(steps=[
                {
                    'name': 'domain',
                    'domain': 'domain_a'
                },
            ])))
    assert 'data' in result
    assert len(result['data']) == 3  # rows
    assert len(result['data'][0]) == 3  # columns
    assert result['schema']['fields'] == [
        {
            'name': 'colA',
            'type': 'string'
        },
        {
            'name': 'colB',
            'type': 'integer'
        },
        {
            'name': 'colC',
            'type': 'integer'
        },
    ]
    assert result['offset'] == 0
    assert result['limit'] == 50
    assert result['total'] == 3

    # DataFrames must be exported with pandas' method to ensure NaN and dates are correctly converted
    df_to_json_spy.assert_called_once()
示例#11
0
def test_configuration_with_multiplie_producers_and_consumers(
    db: MockFixture,
    mocker: MockFixture,
    setup: tuple[User, User, list[ExternalMessage]],
) -> None:
    user1, user2, messages_should_be_consumed = setup

    fake_messages = messages_should_be_consumed + [
        ExternalMessage('unknown_user', user1.username,
                        'message from unknown user'),
    ]

    mocker.patch.object(SampleProducer,
                        'produce_external_messages',
                        return_value=fake_messages)
    consume_messages_spy = mocker.spy(SampleConsumer, 'consume_messages')

    configuration = ConfigurationFactory(
        consumers=(ConsumerModelFactory(), ConsumerModelFactory()),
        producers=(ProducerModelFactory(), ProducerModelFactory()),
        users=(user1, user2),
    )
    configuration.run()

    assert consume_messages_spy.call_count == 2
    assert consume_messages_spy.call_args.args[
        1] == messages_should_be_consumed * 2
示例#12
0
def test_extend_duration_with_new_end_date(client_subscription_factory,
                                           mocker: MockFixture):
    start_date = date(2019, 2, 25)
    new_end_date = start_date + timedelta(days=14)

    mocker.patch('crm.models.ClientSubscriptions.nearest_extended_end_date',
                 return_value=new_end_date)

    cs: models.ClientSubscriptions = client_subscription_factory(
        subscription__event_class__events=[],
        subscription__rounding=False,
        subscription__duration=7,
        subscription__duration_type=GRANULARITY.DAY,
        start_date=start_date)
    old_visits = cs.visits_left

    spy = mocker.spy(models.ExtensionHistory.objects, 'create')
    old_end_date = cs.end_date

    cs.extend_duration(10, reason='TEST')

    cs.refresh_from_db()

    assert_that(
        cs, has_properties(visits_left=old_visits + 10, end_date=new_end_date))
    spy.assert_called_once_with(
        client_subscription=cs,
        reason='TEST',
        added_visits=10,
        extended_to=new_end_date,
        extended_from=old_end_date,
    )
示例#13
0
async def test_control_sent_on_adjust(
    servo_runner: servo.runner.ServoRunner,
    fakeapi_url: str,
    fastapi_app: "tests.OpsaniAPI",
    mocker: pytest_mock.MockFixture,
) -> None:
    sequenced_optimizer = tests.fake.SequencedOptimizer(
        id="dev.opsani.com/big-in-japan", token="31337"
    )
    control = servo.Control(settlement="10s")
    await sequenced_optimizer.recommend_adjustments(adjustments=[], control=control),
    sequenced_optimizer.sequence(sequenced_optimizer.done())
    fastapi_app.optimizer = sequenced_optimizer
    servo_runner.servo.optimizer.base_url = fakeapi_url

    adjust_connector = servo_runner.servo.get_connector("adjust")
    event_handler = adjust_connector.get_event_handlers(
        "adjust", servo.events.Preposition.on
    )[0]
    spy = mocker.spy(event_handler, "handler")

    async def wait_for_optimizer_done():
        while fastapi_app.optimizer.state.name != "done":
            await asyncio.sleep(0.01)

    await servo_runner.run()
    await asyncio.wait_for(wait_for_optimizer_done(), timeout=2)
    await servo_runner.shutdown()

    spy.assert_called_once_with(adjust_connector, [], control)
示例#14
0
async def test_on_authenticate(com: WebsocketCommunicator,
                               consumer: AsyncConsumer, mocker: MockFixture,
                               auth_request, access_token, user: User):
    on_auth = mocker.spy(consumer, 'on_authenticate_success')

    await com.send_json_to(auth_request(access_token(user)))
    await com.receive_json_from()

    on_auth.assert_called_once()
示例#15
0
def test_exits_when_one_clip_doesnt_exist(mocker: MockFixture,
                                          fs: FakeFilesystem) -> None:
    fs.create_file("exists.mp4")
    mocker.patch("abridge.processor.abridge_clip")

    sys_spy = mocker.spy(abridge.cli, "sys")

    sys.argv = ["", "exists.mp4", "something.mp4"]

    main()

    sys_spy.exit.assert_called_with("something.mp4: No such file or directory")
示例#16
0
def test_get_calendar_all_absent(
    event_class_factory,
    mocker: MockFixture
):
    start = date(2019, 1, 1)
    ec = event_class_factory(date_from=start)
    spy = mocker.spy(models, 'Event')

    ec.get_calendar(start, date(2019, 1, 31))
    assert_that(
        spy.call_count, is_(31)
    )
示例#17
0
def test_game_correctly_ends(mocker: MockFixture):
    mock_socket_cls = mocker.patch("socket.socket")
    sock = get_socket_with_mocked_recv(mock_socket_cls,
                                       "HELO boring Hawking".encode("utf-8"))
    game = init_game(sock, 1, "happy Pascal")

    sendall_spy = mocker.spy(sock, "sendall")
    set_stdin_value(mocker, "A 1")
    make_step(sock, game)
    sock.close()

    assert game.check_winner() == "X"
    sendall_spy.assert_called_once_with("MOVE A 1 STOP X".encode("utf-8"))
示例#18
0
def test_send_personalized_multiple(client_factory, mocker: MockFixture):
    client = client_factory.create_batch(3, vk_user_id=1)
    mocker.patch('bot.api.messages.base.Message.prepare_generalized_message',
                 return_value='Test')

    msg_sender = Message(client, personalized=True)

    spy = mocker.spy(msg_sender, 'personalize')
    sm = mocker.patch('bot.api.messages.base.send_message')

    msg_sender.send_message()

    assert_that(spy.call_count, is_(3))
    assert_that(sm.call_count, is_(3))
示例#19
0
def test_send_personalized(client_factory, mocker: MockFixture):
    client = client_factory(vk_user_id=1)
    mocker.patch('bot.api.messages.base.Message.prepare_generalized_message',
                 return_value='Test')

    msg_sender = Message(client, personalized=True)

    spy = mocker.spy(msg_sender, 'personalize')
    sm = mocker.patch('bot.api.messages.base.send_message')

    msg_sender.send_message()

    spy.assert_called_once_with('Test', client)
    sm.assert_called_once_with(1, mocker.ANY, mocker.ANY)
示例#20
0
def test_apply_specification_subapp(
    spec_path: Path,
    mocker: ptm.MockFixture,
) -> None:
    the_spec = loader.load_spec(spec_path)
    the_app = app.AioHttpPlugin(configuration=mocker.ANY)

    add_route_spy = mocker.spy(the_app.root_app.router, 'add_route')
    add_subapp_spy = mocker.spy(the_app.root_app, 'add_subapp')
    resolve_handler = mocker.patch('axion.handler.resolve')

    the_app.add_api(
        spec=the_spec,
        base_path='/api',
    )

    assert resolve_handler.call_count == len(the_spec.operations)

    assert add_route_spy.call_count == 0
    assert add_subapp_spy.call_count == 1
    assert len(the_app.root_app.router.resources()) == 1

    subapp = the_app.root_app._subapps[0]
    assert len(subapp.router.resources()) == len(the_spec.operations)
示例#21
0
def test_get_calendar_partial_events_exists(
    event_class_factory,
    event_factory,
    mocker: MockFixture
):
    start = date(2019, 1, 1)
    ec = event_class_factory(date_from=start)
    for day in range_days(start, date(2019, 1, 4)):
        event_factory(
            company=ec.company,
            event_class=ec,
            date=day
        )

    spy = mocker.spy(models, 'Event')

    ec.get_calendar(start, date(2019, 1, 10))
    assert_that(spy.call_count, is_(7))
示例#22
0
def test_run_configuration_should_filter_message_where_receiver_doesnt_have_consumer_username(
    db: MockFixture,
    mocker: MockFixture,
    setup: tuple[User, User, list[ExternalMessage]],
) -> None:
    user1, user2, messages_should_be_consumed = setup
    user_without_consumer_username = UserFactory(
        on_leave=False,
        working_time_start=datetime.time(8, 0, 0),
        working_time_end=datetime.time(17, 0, 0),
    )
    user_without_consumer_username.additional_info.pop(
        SampleConsumer.USERNAME_KEY)
    user_without_consumer_username.save()

    messages_should_be_consumed = [
        ExternalMessage(user1.username, user2.username, 'message1'),
        ExternalMessage(user2.username, user1.username, 'message2'),
    ]

    fake_messages = messages_should_be_consumed + [
        ExternalMessage(
            user1.username,
            user_without_consumer_username.username,
            'message to user without consumer username',
        ),
    ]

    mocker.patch.object(SampleProducer,
                        'produce_external_messages',
                        return_value=fake_messages)

    consume_messages_spy = mocker.spy(SampleConsumer, 'consume_messages')

    configuration = ConfigurationFactory(
        consumers=(ConsumerModelFactory(), ),
        producers=(ProducerModelFactory(), ),
        users=(user1, user2, user_without_consumer_username),
    )

    configuration.run()

    assert consume_messages_spy.call_args.args[
        1] == messages_should_be_consumed
示例#23
0
def test_mod_with_pgd_tester(loader: AssetLoader, testmod_assetpath: str,
                             mocker: MockFixture):
    d = Discoverer(loader)

    tester = PGDTester()
    d.register_asset_tester(tester)

    fast_spy = mocker.spy(tester, 'is_a_fast_match')
    full_spy = mocker.spy(tester, 'is_a_full_match')

    results = d.run(testmod_assetpath)

    assert results and 'pgd' in results
    assert results['pgd'] == [
        '/Game/Mods/PurloviaTEST/PrimalGameData_BP_PurloviaTEST'
    ]

    assert fast_spy.call_count > 1
    assert full_spy.call_count == 1
示例#24
0
def given_request_none_stored(monkeypatch: pytest.MonkeyPatch, mocker: MockFixture, request_json: Tuple[dict, str]):
    """ Handle request
    """
    # mock anything that uses aiohttp.ClientSession::get
    monkeypatch.setattr(ClientSession, 'get', default_mock_client_get)

    # mock out database calls:
    mock_station_crud(monkeypatch)

    store_spy = mocker.spy(app.routers.hfi_calc, 'store_hfi_request')

    client = TestClient(app.main.app)
    headers = {'Content-Type': 'application/json',
               'Authorization': 'Bearer token'}
    return {
        'response': client.post('/api/hfi-calc/', headers=headers, json=request_json[0]),
        'filename': request_json[1],
        'saved': store_spy.call_count == 1
    }
示例#25
0
def test_revoke_extending_no_chain(subscriptions_type_factory, event_factory,
                                   extension_history_factory,
                                   client_subscription_factory,
                                   mocker: MockFixture):
    event = event_factory(date=date(2019, 2, 25),
                          event_class__date_from=date(2019, 1, 1),
                          canceled_at=date(2019, 2, 24),
                          canceled_with_extending=False)
    subs = subscriptions_type_factory(company=event.company,
                                      duration=1,
                                      duration_type=GRANULARITY.DAY,
                                      rounding=False,
                                      event_class__events=event.event_class)
    cs = client_subscription_factory(company=event.company,
                                     subscription=subs,
                                     purchase_date=date(2019, 2, 24),
                                     start_date=date(2019, 2, 25))
    ex_his = extension_history_factory(company=event.company,
                                       client_subscription=cs,
                                       added_visits=0,
                                       date_extended=datetime(2019,
                                                              2,
                                                              25,
                                                              tzinfo=pytz.utc),
                                       extended_from=date(2019, 2, 25),
                                       extended_to=date(2019, 2, 26),
                                       related_event=event)
    # Update client subscription end date, as it was changed by extension
    cs.end_date = date(2019, 2, 26)
    cs.save()
    spy = mocker.spy(models.ExtensionHistory, 'delete')

    cs.revoke_extending(event)
    cs.refresh_from_db()

    assert_that(cs.end_date, is_(date(2019, 2, 25)))
    assert_that(calling(ex_his.refresh_from_db),
                raises(models.ExtensionHistory.DoesNotExist))
    spy.assert_called_once()
示例#26
0
def test_game_continues_after_step(mocker: MockFixture):
    mock_socket_cls = mocker.patch("socket.socket")
    sock = get_socket_with_mocked_recv(mock_socket_cls,
                                       "HELO boring Hawking".encode("utf-8"))
    game = init_game(sock, 2, "happy Pascal")
    sock.close()

    set_stdin_value(mocker, "A 1")
    sock = get_socket_with_mocked_recv(mock_socket_cls,
                                       "MOVE B 1".encode("utf-8"))
    game_over = make_step(sock, game)
    sock.close()

    assert not game_over

    set_stdin_value(mocker, "A 2")
    sock = mock_socket_cls()
    sendall_spy = mocker.spy(sock, "sendall")
    game_over = make_step(sock, game)
    sock.close()

    assert game_over
    sendall_spy.assert_called_once_with("MOVE A 2 STOP X".encode("utf-8"))
示例#27
0
def test_revoke_extending_no_extension_history(subscriptions_type_factory,
                                               event_factory,
                                               client_subscription_factory,
                                               mocker: MockFixture):
    event = event_factory(date=date(2019, 2, 25),
                          event_class__date_from=date(2019, 1, 1),
                          canceled_at=date(2019, 2, 24),
                          canceled_with_extending=False)
    subs = subscriptions_type_factory(company=event.company,
                                      duration=1,
                                      duration_type=GRANULARITY.DAY,
                                      rounding=False,
                                      event_class__events=event.event_class)
    cs = client_subscription_factory(company=event.company,
                                     subscription=subs,
                                     purchase_date=date(2019, 2, 24),
                                     start_date=date(2019, 2, 25))
    spy = mocker.spy(models.ExtensionHistory, 'delete')
    # Update client subscription end date, as it was changed by extension

    cs.revoke_extending(event)

    spy.assert_not_called()
示例#28
0
def test_enemy_wins(mocker: MockFixture):
    mock_socket_cls = mocker.patch("socket.socket")
    sock = get_socket_with_mocked_recv(mock_socket_cls,
                                       "HELO boring Hawking".encode("utf-8"))
    game = init_game(sock, 3, "happy Pascal")

    set_stdin_value(mocker, "A 2")
    sock = get_socket_with_mocked_recv(mock_socket_cls,
                                       "MOVE A 1".encode("utf-8"))
    make_step(sock, game)

    set_stdin_value(mocker, "B 1")
    sock = get_socket_with_mocked_recv(mock_socket_cls,
                                       "MOVE B 2".encode("utf-8"))
    make_step(sock, game)

    set_stdin_value(mocker, "C 2")
    sock = get_socket_with_mocked_recv(mock_socket_cls,
                                       "MOVE C 3".encode("utf-8"))
    sendall_spy = mocker.spy(sock, "sendall")
    make_step(sock, game)

    sendall_spy.assert_called_with("STOP O".encode("utf-8"))
示例#29
0
def test_spec_load_from_unsupported_type(mocker: ptm.MockFixture) -> None:
    parse_spec = mocker.spy(parser, 'parse_spec')
    with pytest.raises(ValueError):
        loader.load_spec(1)  # type: ignore
    assert not parse_spec.called