示例#1
0
async def test_handle_action_GameMods_post_launch_updates_played_cache(
        game: Game, game_connection: GameConnection, db_engine):
    game.launch = CoroMock()
    game.remove_game_connection = CoroMock()

    await game_connection.handle_action(
        'GameMods', ['uids', 'foo bar EA040F8E-857A-4566-9879-0D37420A5B9D'])
    await game_connection.handle_action('GameState', ['Launching'])

    async with db_engine.acquire() as conn:
        result = await conn.execute(
            "select `played` from table_mod where uid=%s",
            ('EA040F8E-857A-4566-9879-0D37420A5B9D', ))
        row = await result.fetchone()
        assert 2 == row[0]
示例#2
0
async def test_handle_action_GameMods_post_launch_updates_played_cache(
        game, game_connection):
    game.launch = CoroMock()
    game.remove_game_connection = CoroMock()

    await game_connection.handle_action(
        'GameMods', ['uids', 'foo bar EA040F8E-857A-4566-9879-0D37420A5B9D'])
    await game_connection.handle_action('GameState', ['Launching'])

    import server.db as db
    async with db.db_pool.get() as conn:
        cursor = await conn.cursor()
        await cursor.execute("select `played` from table_mod where uid=%s",
                             ('EA040F8E-857A-4566-9879-0D37420A5B9D', ))
        assert (2, ) == await cursor.fetchone()
示例#3
0
文件: test_game.py 项目: b2ag/server
async def test_on_game_end_calls_rate_game(game):
    game.rate_game = CoroMock()
    game.state = GameState.LIVE
    game.launched_at = time.time()
    await game.on_game_end()
    assert game.state == GameState.ENDED
    game.rate_game.assert_any_call()
示例#4
0
async def test_test_stun(loop, player, connectivity):
    natserver = mock.create_autospec(
        NatPacketServer(addresses=[('0.0.0.0', 6112), ('0.0.0.0', 30351)]))
    natserver.ports = [6112, 30351]

    future = asyncio.Future()
    natserver.await_packet.return_value = future

    def send(command_id, args):
        addr, msg = args
        host, port = addr.split(':')
        if int(port) in natserver.ports:
            if not future.done():
                future.set_result((msg, (host, int(port))))

    connectivity.send = send
    connectivity.drain = CoroMock()

    connectivity_test = ConnectivityTest(connectivity, '', 0, player)
    connectivity_test._natserver = natserver

    await connectivity_test.test_stun()

    msg, (host, port) = future.result()
    assert port in natserver.ports
示例#5
0
async def test_record_multiple(service: EventService):

    content = {
        "data": [
            {"attributes": {"eventId": "1-2-3", "currentCount": 1}},
            {"attributes": {"eventId": "2-3-4", "currentCount": 4}}
        ]
    }

    queue = create_queue()

    service.api_accessor.update_events = CoroMock(return_value=(200, content))
    result = await service.execute_batch_update(42, queue)

    events_data = []
    for event in content['data']:
        converted_event = dict(
            event_id=event['attributes']['eventId'],
            count=event['attributes']['currentCount']
        )
        events_data.append(converted_event)

    assert result == events_data

    service.api_accessor.update_events.assert_called_once_with(queue, 42)
示例#6
0
async def test_handle_action_GameResult_draw_ends_sim(
        game: Game, game_connection: GameConnection):
    game_connection.connect_to_host = CoroMock()
    await game_connection.handle_action('GameResult', [0, 'draw'])

    assert game_connection.finished_sim
    assert game.check_sim_end.called
示例#7
0
async def test_handle_action_GameResult_calls_add_result(
        game, game_connection):
    game_connection.ConnectToHost = CoroMock()

    await game_connection.handle_action('GameResult', [0, 'score -5'])
    game.add_result.assert_called_once_with(game_connection.player, 0, 'score',
                                            -5)
示例#8
0
async def test_handle_action_GameResult_victory_ends_sim(
        game, game_connection):
    game_connection.ConnectToHost = CoroMock()
    await game_connection.handle_action('GameResult', [0, 'victory'])

    assert game_connection.finished_sim
    assert game.check_sim_end.called
示例#9
0
async def test_on_game_end_does_not_call_rate_game_for_single_player(game):
    game.rate_game = CoroMock()
    game.state = GameState.LIVE
    game.launched_at = time.time()

    await game.on_game_end()
    assert game.state == GameState.ENDED
    game.rate_game.assert_not_called()
示例#10
0
async def test_game_end_when_no_more_connections(game: Game, mock_game_connection):
    game.state = GameState.LOBBY

    game.on_game_end = CoroMock()
    mock_game_connection.state = GameConnectionState.CONNECTED_TO_HOST
    game.add_game_connection(mock_game_connection)
    await game.remove_game_connection(mock_game_connection)

    game.on_game_end.assert_any_call()
示例#11
0
async def test_handle_action_GameState_launching_calls_launch(
        game_connection: GameConnection, players, game):
    game_connection.player = players.hosting
    game_connection.game = game
    game.launch = CoroMock()

    await game_connection.handle_action('GameState', ['Launching'])

    game.launch.assert_any_call()
示例#12
0
async def test_start_game(ladder_service: LadderService,
                          game_service: GameService):
    p1 = mock.create_autospec(Player('Dostya', id=1))
    p2 = mock.create_autospec(Player('Rhiza', id=2))
    game_service.ladder_maps = [(1, 'scmp_007', 'maps/scmp_007.zip')]

    with mock.patch('asyncio.sleep', CoroMock()):
        await ladder_service.start_game(p1, p2)

    assert p1.lobby_connection.launch_game.called
    assert p2.lobby_connection.launch_game.called
示例#13
0
async def test_handle_action_GameState_lobby_calls_ConnectToPeer(
        game: Game, game_connection: GameConnection, players):
    game_connection.send_message = mock.MagicMock()
    game_connection.connect_to_host = CoroMock()
    game_connection.connect_to_peer = CoroMock()
    game_connection.player = players.joining

    players.joining.game = game

    game.host = players.hosting
    game.map_file_path = 'maps/some_map.zip'
    game.map_folder_name = 'some_map'
    game.connections = [players.peer.game_connection]

    await game_connection.handle_action('GameState', ['Lobby'])
    # Give the connection coro time to run
    await asyncio.sleep(0.1)

    game_connection.connect_to_peer.assert_called_with(
        players.peer.game_connection)
示例#14
0
async def test_game_subscription(lobbyconnection: LobbyConnection):
    game = Mock()
    game.handle_action = CoroMock()
    lobbyconnection.game_connection = game
    lobbyconnection.ensure_authenticated = lambda _: True

    await lobbyconnection.on_message_received({'command': 'test',
                                               'args': ['foo', 42],
                                               'target': 'game'})

    game.handle_action.assert_called_with('test', ['foo', 42])
示例#15
0
async def test_handle_action_TeamkillReport_invalid_offender_id_and_name(
        game: Game, game_connection: GameConnection, db_engine):
    game.launch = CoroMock()
    await game_connection.handle_action('TeamkillReport',
                                        ['270', 0, 'Dostya', 0, 'Geosearchef'])

    async with db_engine.acquire() as conn:
        result = await conn.execute(
            "select game_id,id from moderation_report where reporter_id=2 and game_id=%s and game_incident_timecode=270",
            game.id)
        report = await result.fetchone()
        assert report is None
示例#16
0
async def test_choose_map_all_maps_played(ladder_service: LadderService):
    ladder_service.get_ladder_history = CoroMock(return_value=[1, 2, 3])

    ladder_service.game_service.ladder_maps = [
        (1, "some_map", "maps/some_map.v001.zip"),
        (2, "some_map", "maps/some_map.v001.zip"),
        (3, "some_map", "maps/some_map.v001.zip"),
    ]

    chosen_map = await ladder_service.choose_map([None])

    assert chosen_map is not None
示例#17
0
async def test_persist_results_not_called_with_no_results(game):
    game.state = GameState.LOBBY
    add_players(game, 5)
    game.persist_results = CoroMock()
    game.launched_at = time.time() - 60 * 20

    await game.launch()
    await game.on_game_end()

    assert len(game.players) == 5
    assert len(game._results) == 0
    assert game.validity is ValidityState.UNKNOWN_RESULT
    game.persist_results.assert_not_called()
示例#18
0
async def test_handle_action_TeamkillHappened(game: Game,
                                              game_connection: GameConnection,
                                              db_engine):
    game.launch = CoroMock()
    await game_connection.handle_action('TeamkillHappened',
                                        ['200', '2', 'Dostya', '3', 'Rhiza'])

    async with db_engine.acquire() as conn:
        result = await conn.execute(
            "select game_id from teamkills where victim=2 and teamkiller=3 and game_id=%s and gametime=200",
            (game.id))
        row = await result.fetchone()
        assert game.id == row[0]
示例#19
0
async def test_persist_results_not_called_with_one_player(game):
    await game.clear_data()
    game.persist_results = CoroMock()

    game.state = GameState.LOBBY
    players = [Player(id=1, login='******', global_rating=(1500, 500))]
    add_connected_players(game, players)
    await game.launch()
    assert len(game.players) == 1
    await game.add_result(0, 1, 'VICTORY', 5)
    await game.on_game_end()

    game.persist_results.assert_not_called()
示例#20
0
async def test_handle_action_TeamkillReport(game, game_connection):
    game.launch = CoroMock()
    await game_connection.handle_action('TeamkillReport',
                                        ['200', '2', 'Dostya', '3', 'Rhiza'])

    import server.db as db
    async with db.db_pool.get() as conn:
        cursor = await conn.cursor()
        await cursor.execute(
            "select game_id from teamkills where victim=2 and teamkiller=3 and game_id=%s and gametime=200",
            (game.id))

        assert (game.id, ) == await cursor.fetchone()
示例#21
0
def lobbyconnection(loop, mock_protocol, mock_games, mock_players, mock_player,
                    mock_geoip):
    lc = LobbyConnection(geoip=mock_geoip,
                         games=mock_games,
                         players=mock_players,
                         nts_client=mock_nts_client,
                         ladder_service=mock.create_autospec(LadderService))

    lc.player = mock_player
    lc.protocol = mock_protocol
    lc.player_service.get_permission_group.return_value = 0
    lc.player_service.fetch_player_data = CoroMock()
    lc.peer_address = Address('127.0.0.1', 1234)
    return lc
示例#22
0
def make_game(uid, players):
    from server.games import Game
    from server.abc.base_game import InitMode
    mock_parent = mock.Mock()
    game = mock.create_autospec(spec=Game(uid, mock_parent, mock.Mock()))
    game.remove_game_connection = CoroMock()
    players.hosting.getGame = mock.Mock(return_value=game)
    players.joining.getGame = mock.Mock(return_value=game)
    players.peer.getGame = mock.Mock(return_value=game)
    game.hostPlayer = players.hosting
    game.init_mode = InitMode.NORMAL_LOBBY
    game.name = "Some game name"
    game.id = uid
    return game
示例#23
0
async def test_handle_action_GameState_lobby_calls_ConnectToHost(
        game_connection: GameConnection, players, game):
    game_connection.send_message = mock.MagicMock()
    game_connection.ConnectToHost = CoroMock()
    game_connection.player = players.joining
    players.joining.game = game
    game.host = players.hosting
    game.map_file_path = 'some_map'

    await game_connection.handle_action('GameState', ['Lobby'])
    # Give the connection coro time to run
    await asyncio.sleep(0.1)

    game_connection.ConnectToHost.assert_called_with(
        players.hosting.game_connection)
示例#24
0
async def test_choose_map(ladder_service: LadderService):
    ladder_service.get_ladder_history = CoroMock(return_value=[1, 2, 3])

    ladder_service.game_service.ladder_maps = [
        (1, "some_map", "maps/some_map.v001.zip"),
        (2, "some_map", "maps/some_map.v001.zip"),
        (3, "some_map", "maps/some_map.v001.zip"),
        (4, "CHOOSE_ME", "maps/choose_me.v001.zip"),
    ]

    chosen_map = await ladder_service.choose_map([None])

    # Make the probability very low that the test passes because we got lucky
    for _ in range(20):
        assert chosen_map == (4, "CHOOSE_ME", "maps/choose_me.v001.zip")
示例#25
0
async def test_on_game_end_calls_rate_game_with_two_players(game):
    await game.clear_data()
    game.rate_game = CoroMock()
    game.state = GameState.LOBBY
    add_players(game, 2)

    await game.launch()

    assert len(game.players) == 2
    await game.add_result(0, 1, 'victory', 10)
    await game.add_result(1, 2, 'defeat', -10)

    await game.on_game_end()
    assert game.state == GameState.ENDED
    game.rate_game.assert_any_call()

    assert game.validity is ValidityState.VALID
示例#26
0
async def test_handle_action_TeamkillReport_invalid_ids(
        game: Game, game_connection: GameConnection, db_engine):
    game.launch = CoroMock()
    await game_connection.handle_action('TeamkillReport',
                                        ['230', 0, 'Dostya', 0, 'Rhiza'])

    async with db_engine.acquire() as conn:
        result = await conn.execute(
            "select game_id,id from moderation_report where reporter_id=2 and game_id=%s and game_incident_timecode=230",
            (game.id))
        report = await result.fetchone()
        assert game.id == report["game_id"]

        reported_user_query = await conn.execute(
            "select player_id from reported_user where report_id=%s",
            (report["id"]))
        data = await reported_user_query.fetchone()
        assert data["player_id"] == 3
示例#27
0
def test_queue_race(mocker, player_service, matchmaker_queue):
    p1, p2, p3 = Player('Dostya', id=1, ladder_rating=(2300, 150)), \
                 Player('Brackman', id=2, ladder_rating=(2200, 150)), \
                 Player('Zoidberg', id=3, ladder_rating=(2300, 125))

    player_service.players = {p1.id: p1, p2.id: p2, p3.id: p3}

    matchmaker_queue.game_service.ladder_service.start_game = CoroMock()

    try:
        yield from asyncio.gather(
            asyncio.wait_for(matchmaker_queue.search(p1), 0.1),
            asyncio.wait_for(matchmaker_queue.search(p2), 0.1),
            asyncio.wait_for(matchmaker_queue.search(p3), 0.1))
    except (TimeoutError, CancelledError):
        pass

    assert len(matchmaker_queue) == 0
示例#28
0
async def test_start_game_called_on_match(ladder_service: LadderService):
    p1 = mock.create_autospec(Player('Dostya', id=1))
    p1.ladder_rating = (2300, 64)
    p1.numGames = 0

    p2 = mock.create_autospec(Player('QAI', id=4))
    p2.ladder_rating = (2350, 125)
    p2.numGames = 0

    ladder_service.start_game = CoroMock()
    ladder_service.inform_player = mock.Mock()

    ladder_service.start_search(p1, Search([p1]), 'ladder1v1')
    ladder_service.start_search(p2, Search([p2]), 'ladder1v1')

    await asyncio.sleep(1)

    ladder_service.inform_player.assert_called()
    ladder_service.start_game.assert_called_once()
示例#29
0
async def test_start_game_timeout(ladder_service: LadderService,
                                  game_service: GameService):
    p1 = mock.create_autospec(Player('Dostya', id=1))
    p2 = mock.create_autospec(Player('Rhiza', id=2))

    p1.id = 1
    p2.id = 2
    game_service.ladder_maps = [(1, 'scmp_007', 'maps/scmp_007.zip')]

    with mock.patch('server.games.game.Game.sleep', CoroMock()):
        await ladder_service.start_game(p1, p2)

    p1.lobby_connection.send.assert_called_once_with(
        {"command": "game_launch_timeout"})
    p2.lobby_connection.send.assert_called_once_with(
        {"command": "game_launch_timeout"})
    assert p1.lobby_connection.launch_game.called
    # TODO: Once client supports `game_launch_timeout` change this to `assert not ...`
    assert p2.lobby_connection.launch_game.called
示例#30
0
async def test_record_multiple(service: EventService):
    content = '''{"updated_events": [
        { "event_id": "1-2-3", "count": 1},
        { "event_id": "2-3-4", "count": 4}
    ]}'''.encode('utf-8')
    service.api_accessor.api_post = CoroMock(return_value=(None, content))

    queue = []
    service.record_event('1-2-3', 1, queue)
    service.record_event('2-3-4', 4, queue)

    assert queue == [
        dict(event_id='1-2-3', count=1),
        dict(event_id='2-3-4', count=4),
    ]

    result = await service.execute_batch_update(42, queue)
    assert result == json.loads(content.decode('utf-8'))['updated_events']

    service.api_accessor.api_post.assert_called_once_with("/events/recordMultiple", 42, data=dict(updates=queue))