Пример #1
0
    def testEnsureToResolveMethodOnClass(self):
        class A(object):
            class B(object):
                def c(self):
                    pass

        when2(A.B.c)
Пример #2
0
    def testEnsureToResolveMethodOnClass(self):
        class A(object):
            class B(object):
                def c(self):
                    pass

        when2(A.B.c)
Пример #3
0
def setup_game_in_progress(game_type: str = "ca",
                           mapname: str = "campgrounds",
                           map_title: Optional[str] = None,
                           roundlimit: int = 8,
                           red_score: int = 0,
                           blue_score: int = 0,
                           maxclients: int = 16) -> None:
    """Set up the server with a game currently in progress. You may specify the game_type, roundlimit, and score for
    the red and blue teams with the optional parameters.

    **Make sure to use :func:`mockito.unstub()` after calling this assertion to avoid side effects spilling into the
    next test.**

    :param game_type: the game_type currently being played (default: "ca")
    :param mapname: the map the game is currently running on (default: "campgrounds")
    :param map_title: the long title of the map (default: None)
    :param roundlimit: the current setup roundlimit for the game (default: 8)
    :param red_score: the current score of the red team (default: 0)
    :param blue_score: the current score of the blue team (default: 0)
    :param maxclients: (default: 16)
    """
    mock_game = mock(spec=Game, strict=False)
    when2(minqlx.Game).thenReturn(mock_game)
    mock_game.state = "in_progress"
    mock_game.type_short = game_type
    mock_game.map = mapname
    mock_game.map_title = map_title
    mock_game.roundlimit = roundlimit
    mock_game.red_score = red_score
    mock_game.blue_score = blue_score
    mock_game.maxclients = maxclients
Пример #4
0
    def testEnsureToResolveClass(self):
        class A(object):
            class B(object):
                pass

        when2(A.B, 'Hi').thenReturn('Ho')
        assert A.B('Hi') == 'Ho'
Пример #5
0
    def testEnsureToResolveClass(self):
        class A(object):
            class B(object):
                pass

        when2(A.B, 'Hi').thenReturn('Ho')
        assert A.B('Hi') == 'Ho'
    async def test_on_message_without_message(self):
        patch(minqlx.CHAT_CHANNEL, "reply", lambda msg: None)
        when2(minqlx.CHAT_CHANNEL.reply, any).thenReturn(None)

        await self.discord.on_message(None)

        verify(minqlx.CHAT_CHANNEL, times=0).reply(any)
    def test_shuffle_double_blink_when_diff_one_player(self):
        spy2(time.sleep)
        when2(time.sleep, any_(float)).thenReturn(None)
        spy2(Plugin.shuffle)
        when2(Plugin.shuffle).thenReturn(None)

        connected_players(fake_player(1, "Red Player1", team="red"),
                          fake_player(2, "Red Player2", team="red"),
                          fake_player(3, "Red Player3", team="red"),
                          fake_player(4, "Red Player4", team="red"),
                          fake_player(5, "Blue Player1", team="blue"),
                          fake_player(6, "Blue Player2", team="blue"),
                          fake_player(7, "Blue Player3", team="blue"),
                          fake_player(8, "Blue Player4", team="blue"),
                          fake_player(9, "Blue Player5", team="blue"))

        autoready.shuffle_double_blink(10)

        verify(time, times=2).sleep(0.2)
        verify(time).sleep(0.3)
        verify(Plugin, times=0).shuffle()
        assert_plugin_center_printed(
            "Match will ^2auto-start^7 in\n^1 ^7:^1  ", times=2)
        assert_plugin_center_printed(
            "Match will ^2auto-start^7 in\n^10^7:^110", times=2)
    def test_stop_when_target_time_is_unset(self):
        spy2(self.countdown_thread.is_alive)
        when2(self.countdown_thread.is_alive).thenReturn(True)

        self.countdown_thread.stop()

        assert_that(self.countdown_thread.seconds_left,
                    is_(self.countdown_thread.duration))
Пример #9
0
    def test_process_vote_with_no_active_vote_running(self):
        when2(Plugin.is_vote_active).thenReturn(False)
        self.plugin.track_vote = True

        self.plugin.process_vote(fake_player(123, "Any Player"), True)

        assert_that(self.plugin.track_vote, is_(False))
        verify(Plugin, times=0).force_vote(any_)
Пример #10
0
    def test_process_vote_current_vote_count_not_available(self):
        self.setup_vote_in_progress()
        self.plugin.track_vote = True
        when2(Plugin.current_vote_count).thenReturn(None)

        self.plugin.process_vote(fake_player(123, "Any Player"), False)

        assert_that(self.plugin.track_vote, is_(True))
        verify(Plugin, times=0).force_vote(any_)
Пример #11
0
def setup_no_game():
    """Set up the server with no game running currently.

    **Make sure to use :func:`mockito.unstub()` after calling this assertion to avoid side effects spilling into the
    next test.**
    """
    when2(minqlx.Game).thenRaise(
        NonexistentGameError(
            "Tried to instantiate a game while no game is active."))
    def test_allready(self):
        spy2(Plugin.allready)
        when2(Plugin.allready).thenReturn(None)

        autoready.allready(0)

        verify(Plugin).allready()
        assert_plugin_center_printed(
            "Match will ^2auto-start^7 in\n^20^7:^200")
Пример #13
0
def setup_cvar(cvar_name: str, cvar_value: str) -> None:
    """Set up a minqlx.Plugin with the provided cvar and value.

    **Make sure to use :func:`mockito.unstub()` after calling this function to avoid side effects spilling into the
    next test.**

    :param cvar_name: the name of the cvar
    :param cvar_value: the value the plugin should return for the cvar
    """
    when2(minqlx.get_cvar, cvar_name).thenReturn(cvar_value)
    def test_stop_when_thread_is_running(self):
        spy2(self.countdown_thread.is_alive)
        when2(self.countdown_thread.is_alive).thenReturn(True)
        test_target_time = self.fake_thread_runtime + timedelta(
            seconds=11, milliseconds=999, microseconds=999)
        self.countdown_thread._target_time = test_target_time  # pylint: disable=W0212

        self.countdown_thread.stop()

        assert_that(self.countdown_thread.seconds_left, is_(11))
Пример #15
0
def setup_cvars(cvars: Dict[str, str]) -> None:
    """Set up a minqlx.Plugin with the provided cvars and values.

    **Make sure to use :func:`mockito.unstub()` after calling this function to avoid side effects spilling into the
    next test.**

    :param cvars: a dictionary containing the cvar names as keys, and their values
    """
    for cvar, value in cvars.items():
        when2(minqlx.get_cvar, cvar).thenReturn(value)
    async def test_on_message_too_short_message(self):
        message = mocked_message(content="",
                                 channel=self.relay_channel())

        patch(minqlx.CHAT_CHANNEL, "reply", lambda msg: None)
        when2(minqlx.CHAT_CHANNEL.reply, any).thenReturn(None)

        await self.discord.on_message(message)

        verify(minqlx.CHAT_CHANNEL, times=0).reply(any)
    async def test_on_message_in_wrong_channel(self):
        message = mocked_message(content="some chat message",
                                 channel=self.triggered_channel())

        patch(minqlx.CHAT_CHANNEL, "reply", lambda msg: None)
        when2(minqlx.CHAT_CHANNEL.reply, any).thenReturn(None)

        await self.discord.on_message(message)

        verify(minqlx.CHAT_CHANNEL, times=0).reply(any)
    def test_blink(self):
        spy2(time.sleep)
        when2(time.sleep, any_(float)).thenReturn(None)

        autoready.blink(8)

        verify(time).sleep(0.4)
        assert_plugin_center_printed(
            "Match will ^2auto-start^7 in\n^1 ^7:^1  ")
        assert_plugin_center_printed(
            "Match will ^2auto-start^7 in\n^10^7:^108")
    async def test_on_message_by_user_with_nickname(self):
        message = mocked_message(content="some chat message",
                                 user=mocked_user(name="Sender", nick="SenderNick"),
                                 channel=self.relay_channel())

        patch(minqlx.CHAT_CHANNEL, "reply", lambda msg: None)
        when2(minqlx.CHAT_CHANNEL.reply, any).thenReturn(None)

        await self.discord.on_message(message)

        verify(minqlx.CHAT_CHANNEL).reply("[DISCORD] ^6SenderNick^7:^2 some chat message")
    def test_warning_blink(self):
        spy2(time.sleep)
        when2(time.sleep, any_(float)).thenReturn(None)

        autoready.warning_blink(30, "thirty_second_warning")

        verify(time).sleep(0.4)
        assert_plugin_played_sound("thirty_second_warning")
        assert_plugin_center_printed(
            "Match will ^2auto-start^7 in\n^1 ^7:^1  ")
        assert_plugin_center_printed(
            "Match will ^2auto-start^7 in\n^10^7:^130")
    def test_wear_off_double_blink(self):
        spy2(time.sleep)
        when2(time.sleep, any_(float)).thenReturn(None)

        autoready.wear_off_double_blink(8)

        verify(time, times=2).sleep(0.2)
        verify(time).sleep(0.3)
        assert_plugin_played_sound("sound/items/wearoff.ogg")
        assert_plugin_center_printed(
            "Match will ^2auto-start^7 in\n^1 ^7:^1  ", times=2)
        assert_plugin_center_printed(
            "Match will ^2auto-start^7 in\n^10^7:^108", times=2)
Пример #22
0
        def testA(self):
            with pytest.raises(TypeError) as exc:
                when2(os)
            assert str(exc.value) == "can't guess origin of 'os'"

            cp = os.path.commonprefix
            with pytest.raises(TypeError) as exc:
                spy2(cp)
            assert str(exc.value) == "can't guess origin of 'cp'"

            ptch = patch
            with pytest.raises(TypeError) as exc:
                ptch(os.path.exists, lambda: 'boo')
            assert str(exc.value) == "could not destructure first argument"
Пример #23
0
        def testA(self):
            with pytest.raises(TypeError) as exc:
                when2(os)
            assert str(exc.value) == "can't guess origin of 'os'"

            cp = os.path.commonprefix
            with pytest.raises(TypeError) as exc:
                spy2(cp)
            assert str(exc.value) == "can't guess origin of 'cp'"

            ptch = patch
            with pytest.raises(TypeError) as exc:
                ptch(os.path.exists, lambda: 'boo')
            assert str(exc.value) == "could not destructure first argument"
    def setUp(self):
        spy2(time.sleep)
        when2(time.sleep, any_(float)).thenReturn(None)

        self.mocked_function42 = mock()
        self.mocked_function21 = mock()
        timed_test_actions = {
            42: self.mocked_function42,
            21: self.mocked_function21
        }
        self.countdown_thread = CountdownThread(
            125, timed_actions=timed_test_actions)
        self.fake_thread_runtime = datetime(year=2022,
                                            month=4,
                                            day=4,
                                            hour=11,
                                            minute=11,
                                            second=11)
        self.countdown_thread._now = self.fake_thread_runtime  # pylint: disable=W0212
Пример #25
0
    def testWhen2WithArguments(self):
        # This test is a bit flaky bc pytest does not like a patched
        # `os.path.exists` module.
        when2(os.path.commonprefix, '/Foo').thenReturn(False)
        when2(os.path.commonprefix, '/Foo').thenReturn(True)
        when2(os.path.exists, '/Foo').thenReturn(True)

        assert os.path.commonprefix('/Foo')
        assert os.path.exists('/Foo')
Пример #26
0
    def testWhen2WithArguments(self):
        # This test is a bit flaky bc pytest does not like a patched
        # `os.path.exists` module.
        when2(os.path.commonprefix, '/Foo').thenReturn(False)
        when2(os.path.commonprefix, '/Foo').thenReturn(True)
        when2(os.path.exists, '/Foo').thenReturn(True)

        assert os.path.commonprefix('/Foo')
        assert os.path.exists('/Foo')
Пример #27
0
def spy2(fn):  # type: (...) -> None
    """Spy usage of given `fn`.

    Patches the module, class or object `fn` lives in, so that all
    interactions can be recorded; otherwise executes `fn` as before, so
    that all side effects happen as before.

    E.g.::

        import time
        spy(time.time)
        do_work(...)  # nothing injected, uses global patched `time` module
        verify(time).time()

    Note that builtins often cannot be patched because they're read-only.


    """
    if isinstance(fn, str):
        answer = get_obj(fn)
    else:
        answer = fn

    when2(fn, Ellipsis).thenAnswer(answer)
Пример #28
0
def setup_game_in_warmup(game_type: str = "ca",
                         mapname: str = "campgrounds",
                         map_title: Optional[str] = None,
                         roundlimit: int = 8,
                         maxclients: int = 16) -> None:
    """Set up the server with a game currently in warmup mode.

    **Make sure to use :func:`mockito.unstub()` after calling this assertion to avoid side effects spilling into the
    next test.**

    :param: game_type: the game_type currently being played (default: "ca")
    :param: mapname: the map the game is currently running on (default: "campgrounds")
    :param: map_title: the long title of the map (default: None)
    :param: roundlimit: (default: 8)
    :param: maxclients: (default: 16)
    """
    mock_game = mock(spec=Game, strict=False)
    when2(minqlx.Game).thenReturn(mock_game)
    mock_game.state = "warmup"
    mock_game.type_short = game_type
    mock_game.map = mapname
    mock_game.map_title = map_title
    mock_game.roundlimit = roundlimit
    mock_game.maxclients = maxclients
Пример #29
0
def connected_players(*players: Player) -> None:
    """Sets up a plugin with the provided players being connected to the server.

    **Make sure to use :func:`mockito.unstub()` after calling this function to avoid side effects spilling into the
    next test.**

    :param players: the players that are currently on the server, in all possible teams: "red", "blue", "spectator",
    and "free"
    """
    when2(Plugin.players).thenReturn(players)
    for player in players:
        when2(Plugin.player, player.steam_id).thenReturn(player)
        when2(Plugin.player, player).thenReturn(player)
Пример #30
0
    def testWhen2(self):
        when2('os.path.exists', '/Foo').thenReturn(True)

        import os.path
        assert os.path.exists('/Foo')
Пример #31
0
 def testWhen2(self):
     rex = Dog()
     when2(rex.bark, 'Miau').thenReturn('Wuff')
     when2(rex.bark, 'Miau').thenReturn('Grrr')
     assert rex.bark('Miau') == 'Grrr'
Пример #32
0
 def testWhen2WithoutArguments(self):
     import time
     when2(time.time).thenReturn('None')
     assert time.time() == 'None'
Пример #33
0
    def testWhen2(self):
        when2('os.path.exists', '/Foo').thenReturn(True)

        import os.path
        assert os.path.exists('/Foo')
Пример #34
0
 def testWhenSplitOnNextLine(self):
     # fmt: off
     when2(
         os.path.commonprefix, '/Foo').thenReturn(True)
     # fmt: on
     assert os.path.commonprefix('/Foo')
Пример #35
0
 def testEnsureWithWhen2SameLine(self):
     with when2(os.path.commonprefix, '/Foo'):
         pass
Пример #36
0
 def testEnsureWithWhen2SplitLine(self):
     # fmt: off
     with when2(os.path.commonprefix, '/Foo'):
         pass
Пример #37
0
 def testEnsureWithWhen2SameLine(self):
     with when2(os.path.commonprefix, '/Foo'):
         pass
Пример #38
0
 def testWhenSplitOnNextLine(self):
     # fmt: off
     when2(os.path.commonprefix, '/Foo').thenReturn(True)
     # fmt: on
     assert os.path.commonprefix('/Foo')
Пример #39
0
 def testWhen2WithoutArguments(self):
     import time
     when2(time.time).thenReturn('None')
     assert time.time() == 'None'
Пример #40
0
 def testEnsureWithWhen2SplitLine(self):
     # fmt: off
     with when2(
             os.path.commonprefix, '/Foo'):
         pass