Exemple #1
0
class Test_bf3_events(BF3TestCase):

    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = Bf3Parser(self.conf)
        self.parser.startup()

    def test_cmd_rotateMap_generates_EVT_GAME_ROUND_END(self):
        # prepare fake BF3 server responses
        def fake_write(data):
            if data ==  ('mapList.getMapIndices', ):
                return [0, 1]
            else:
                return []
        self.parser.write = Mock(side_effect=fake_write)
        self.parser.getFullMapRotationList = Mock(return_value=MapListBlock(['4', '3', 'MP_007', 'RushLarge0', '4', 'MP_011', 'RushLarge0', '4', 'MP_012',
                                                                             'SquadRush0', '4', 'MP_013', 'SquadRush0', '4']))

        # mock parser queueEvent method so we can make assertions on it later on
        self.parser.queueEvent = Mock(name="queueEvent method")

        self.parser.rotateMap()
        self.assertEqual(1, self.parser.queueEvent.call_count)
        self.assertEqual(self.parser.getEventID("EVT_GAME_ROUND_END"), self.parser.queueEvent.call_args[0][0].type)
        self.assertIsNone(self.parser.queueEvent.call_args[0][0].data)
class test_others(Arma2TestCase):

    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""<configuration></configuration>""")
        self.parser = Arma2Parser(self.conf)
        self.parser.output = Mock()
        self.parser.startup()
        self.player = self.parser.clients.newClient(cid="4", guid="theGuid", name="theName", ip="11.22.33.44")


    def test_getBanlist(self):
        # GIVEN
        self.maxDiff = 1024
        when(self.parser.output).write("bans").thenReturn("""\
GUID Bans:
[#] [GUID] [Minutes left] [Reason]
----------------------------------------
0  b57c222222a76f458893641000000005 perm Script Detection: Gerk
1  8ac61111111cd2ff4235140000000026 perm Script Detection: setVehicleInit DoThis;""")
        # WHEN
        rv = self.parser.getBanlist()
        # THEN
        self.assertDictEqual({
            'b57c222222a76f458893641000000005': {'ban_index': '0', 'guid': 'b57c222222a76f458893641000000005', 'reason': 'Script Detection: Gerk', 'min_left': 'perm'},
            '8ac61111111cd2ff4235140000000026': {'ban_index': '1', 'guid': '8ac61111111cd2ff4235140000000026', 'reason': 'Script Detection: setVehicleInit DoThis;', 'min_left': 'perm'},
        }, rv)
Exemple #3
0
class Test_patch_b3_client_yell(AbstractParser_TestCase):
    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = ConcretegameParser(self.conf)
        self.parser._settings['big_msg_duration'] = '3.1'
        # setup context
        self.joe = self.parser.clients.newClient(cid='joe', name='joe', guid="bbbbbbbb5555555")


    def test_client_yell(self):
        with patch.object(time, 'sleep'):
            with patch.object(AbstractParser, 'write') as write_mock:

                self.joe.yell('test')
                self.joe.yell('test2')
                self.joe.yell('test3')

                self.assertTrue(write_mock.called)
                write_mock.assert_any_call(('admin.yell', '[pm] test', '3', 'player', 'joe'))
                write_mock.assert_any_call(('admin.yell', '[pm] test2', '3', 'player', 'joe'))
                write_mock.assert_any_call(('admin.yell', '[pm] test3', '3', 'player', 'joe'))
class Test_cmd_serverreboot(Bf3TestCase):
    def setUp(self):
        super(Test_cmd_serverreboot, self).setUp()
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
        <configuration plugin="poweradminbf3">
            <settings name="commands">
                <set name="serverreboot">100</set>
            </settings>
        </configuration>
        """)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()


    def test_nominal(self, sleep_mock):
        self.console.write.expect(('admin.shutDown',))
        self.superadmin.connects("god")
        self.superadmin.says("!serverreboot")
        self.console.write.verify_expected_calls()

    def test_frostbite_error(self, sleep_mock):
        self.console.write.expect(('admin.shutDown',)).thenRaise(CommandFailedError(['fOO']))
        self.superadmin.connects("god")
        self.superadmin.message_history = []
        self.superadmin.says("!serverreboot")
        self.console.write.verify_expected_calls()
        self.assertEqual(['Error: fOO'], self.superadmin.message_history)
class AdminTestCase(unittest.TestCase):
    """
    Test case that is suitable for testing EtPro parser specific features with the B3 admin plugin available
    """

    @classmethod
    def setUpClass(cls):
        from b3.fake import FakeConsole
        AbstractParser.__bases__ = (FakeConsole,)
        # Now parser inheritance hierarchy is :
        # EtproParser -> AbstractParser -> FakeConsole -> Parser

    def setUp(self):
        self.status_response = None  # defaults to STATUS_RESPONSE module attribute
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""<configuration></configuration>""")
        self.parser = EtproParser(self.conf)
        self.parser.output = Mock()
        self.parser.output.write = Mock(wraps=sys.stdout.write)
        adminPlugin_conf = CfgConfigParser()
        adminPlugin_conf.load(ADMIN_CONFIG_FILE)
        adminPlugin = AdminPlugin(self.parser, adminPlugin_conf)
        adminPlugin.onLoadConfig()
        adminPlugin.onStartup()
        when(self.parser).getPlugin('admin').thenReturn(adminPlugin)
        when(self.parser).getCvar('b_privatemessages').thenReturn(Cvar('b_privatemessages', value='1'))
        self.parser.startup()

    def tearDown(self):
        if hasattr(self, "parser"):
            del self.parser.clients
            self.parser.working = False
class Test_patch_b3_Client_isAlive(BF3TestCase):
    def setUp(self):
        BF3TestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = Bf3Parser(self.conf)
        self.foobar = self.parser.clients.newClient(cid='Foobar', name='Foobar', guid="FoobarGuid")

    def test_unknown(self):
        # GIVEN
        when(self.parser).write(('player.isAlive', 'Foobar')).thenReturn()
        # THEN
        self.assertEqual(b3.STATE_UNKNOWN, self.foobar.state)

    def test_alive(self):
        # GIVEN
        when(self.parser).write(('player.isAlive', 'Foobar')).thenReturn(['true'])
        # THEN
        self.assertEqual(b3.STATE_ALIVE, self.foobar.state)

    def test_dead(self):
        # GIVEN
        when(self.parser).write(('player.isAlive', 'Foobar')).thenReturn(['false'])
        # THEN
        self.assertEqual(b3.STATE_DEAD, self.foobar.state)

    def test_exception_InvalidPlayerName(self):
        when(self.parser).write(('player.isAlive', 'Foobar')).thenRaise(CommandFailedError(['InvalidPlayerName']))
        self.assertEqual(b3.STATE_UNKNOWN, self.foobar.state)
class Iourt41TestCase(Iourt41_TestCase_mixin):
    """
    Test case that is suitable for testing Iourt41 parser specific features
    """

    def setUp(self):
        # create a Iourt41 parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString("""<configuration><settings name="server"><set name="game_log"></set></settings></configuration>""")
        self.console = Iourt41Parser(self.parser_conf)

        self.console.write = Mock(name="write", side_effect=write)
        self.console.startup()


        # load the admin plugin
        if B3version(b3_version) >= B3version("1.10dev"):
            admin_plugin_conf_file = '@b3/conf/plugin_admin.ini'
        else:
            admin_plugin_conf_file = '@b3/conf/plugin_admin.xml'
        self.adminPlugin = AdminPlugin(self.console, admin_plugin_conf_file)
    	self.adminPlugin.onLoadConfig()
    	self.adminPlugin.onStartup()

        # make sure the admin plugin obtained by other plugins is our admin plugin
        when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)


    def tearDown(self):
        self.console.working = False
class Admin_functional_test(B3TestCase):
    """ tests from a class inherithing from Admin_functional_test must call self.init() """

    def setUp(self):
        B3TestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.p = AdminPlugin(self.console, self.conf)

    def init(self, config_content=None):
        """ optionally specify a config for the plugin. If called with no parameter, then the default config is loaded """
        if config_content is None:
            if not os.path.isfile(ADMIN_CONFIG_FILE):
                B3TestCase.tearDown(self)  # we are skipping the test at a late stage after setUp was called
                raise unittest.SkipTest("%s is not a file" % ADMIN_CONFIG_FILE)
            else:
                self.conf.load(ADMIN_CONFIG_FILE)
        else:
            self.conf.loadFromString(config_content)
        self.p.onLoadConfig()
        self.p.onStartup()

        self.joe = FakeClient(self.console, name="Joe", exactName="Joe", guid="joeguid", groupBits=128, team=TEAM_RED)
        self.mike = FakeClient(
            self.console, name="Mike", exactName="Mike", guid="mikeguid", groupBits=1, team=TEAM_BLUE
        )
class Test_cmd_yell(Bf3TestCase):

    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
        <configuration plugin="poweradminbf3">
            <settings name="commands">
                <set name="yell">20</set>
            </settings>
            <settings name="preferences">
                <set name="yell_duration">2</set>
            </settings>
        </configuration>
        """)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()


    def test_no_argument(self):
        self.moderator.connects("moderator")
        self.moderator.message_history = []
        self.moderator.says("!yell")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('missing parameter, try !help yell', self.moderator.message_history[0])

    def test_nominal(self):
        self.moderator.connects("moderator")
        self.moderator.says("!yell changing map soon !")
        self.console.write.assert_called_once_with(('admin.yell', 'changing map soon !', '2'))
class EtTestCase(unittest.TestCase):
    """
    Test case that is suitable for testing et parser specific features
    """

    @classmethod
    def setUpClass(cls):
        from b3.parsers.q3a.abstractParser import AbstractParser
        from b3.fake import FakeConsole

        AbstractParser.__bases__ = (FakeConsole,)
        # Now parser inheritance hierarchy is :
        # EtParser -> AbstractParser -> FakeConsole -> Parser

        logging.getLogger('output').setLevel(logging.ERROR)

    def setUp(self):
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString("""<configuration>
                <settings name="server">
                    <set name="game_log"/>
                </settings>
            </configuration>""")
        self.console = EtParser(self.parser_conf)
        self.console.write = Mock()
        self.console.PunkBuster = None  # no Punkbuster support in that game

    def tearDown(self):
        if hasattr(self, "parser"):
            del self.parser.clients
            self.parser.working = False
Exemple #11
0
class Test_getPlayerPings(BF3TestCase):

    def setUp(self):
        BF3TestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = Bf3Parser(self.conf)
        self.p1 = FakeClient(self.parser, name="Player1")
        self.p2 = FakeClient(self.parser, name="Player2")

    def test_no_player(self):
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({}, actual_result)

    def test_one_player(self):
        # GIVEN
        self.p1.connects("Player1")
        when(self.parser).write(('player.ping', self.p1.cid)).thenReturn(['140'])
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)

    def test_two_player(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('player.ping', self.p1.cid)).thenReturn(['140'])
        when(self.parser).write(('player.ping', self.p2.cid)).thenReturn(['450'])
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({self.p1.cid: 140, self.p2.cid: 450}, actual_result)

    def test_bad_data(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('player.ping', self.p1.cid)).thenReturn(['140'])
        when(self.parser).write(('player.ping', self.p2.cid)).thenReturn(['f00'])
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)

    def test_exception(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('player.ping', self.p1.cid)).thenReturn(['140'])
        when(self.parser).write(('player.ping', self.p2.cid)).thenRaise(Exception)
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)
class AdminTestCase(unittest.TestCase):
    """
    Test case that is suitable for testing Insurgency parser specific features with the B3 admin plugin available
    """

    @classmethod
    def setUpClass(cls):
        from b3.fake import FakeConsole
        InsurgencyParser.__bases__ = (FakeConsole,)
        # Now parser inheritance hierarchy is :
        # InsurgencyParser -> FakeConsole -> Parser

    def setUp(self):
        self.status_response = None  # defaults to STATUS_RESPONSE module attribute
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""<configuration></configuration>""")
        self.parser = InsurgencyParser(self.conf)
        self.parser.output = Mock()
        self.parser.output.write = Mock(wraps=sys.stdout.write)
        when(self.parser).is_sourcemod_installed().thenReturn(True)
        adminPlugin_conf = CfgConfigParser()
        adminPlugin_conf.load(ADMIN_CONFIG_FILE)
        adminPlugin = AdminPlugin(self.parser, adminPlugin_conf)
        adminPlugin.onLoadConfig()
        adminPlugin.onStartup()
        when(self.parser).getPlugin('admin').thenReturn(adminPlugin)
        when(self.parser).getAllAvailableMaps().thenReturn (['buhriz', 'district', 'sinjar', 'siege', 'uprising', 'ministry', 'revolt', 'heights', 'contact', 'peak', 'panj', 'market'])
        when(self.parser).getMap().thenReturn('buhriz')
        self.parser.startup()
        self.parser.patch_b3_admin_plugin() # seems that without this the test module doesn't patch the admin plugin

    def tearDown(self):
        if hasattr(self, "parser"):
            del self.parser.clients
            self.parser.working = False
class B3TestCase(unittest.TestCase):

    def setUp(self):
        testcase_lock.acquire()
        flush_console_streams()

        # create a FakeConsole parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString(r"""<configuration/>""")
        with logging_disabled():
            from b3.fake import FakeConsole
            self.console = FakeConsole(self.parser_conf)

        self.console.screen = Mock()
        self.console.time = time.time
        self.console.upTime = Mock(return_value=3)

        self.console.cron.stop()

        def myError(msg, *args, **kwargs):
            print(("ERROR: %s" % msg) % args)
        self.console.error = myError

    def tearDown(self):
        flush_console_streams()
        testcase_lock.release()
class ChatloggerTestCase(unittest.TestCase):

    def setUp(self):
        testcase_lock.acquire()
        self.addCleanup(cleanUp)
        flush_console_streams()
        # create a FakeConsole parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString(r"""<configuration/>""")
        with logging_disabled():
            from b3.fake import FakeConsole
            self.console = FakeConsole(self.parser_conf)

        with logging_disabled():
            self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.ini')
            self.adminPlugin.onStartup()

        # make sure the admin plugin obtained by other plugins is our admin plugin
        when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)

        self.console.screen = Mock()
        self.console.time = time.time
        self.console.upTime = Mock(return_value=3)

    def tearDown(self):
        try:
            self.console.storage.shutdown()
        except:
            pass
Exemple #15
0
class Test_patch_b3_clients_getByMagic(AbstractParser_TestCase):
    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = ConcretegameParser(self.conf)
        # setup context
        self.foobar = self.parser.clients.newClient(cid='Foobar', name='Foobar', guid="aaaaaaa5555555")
        self.joe = self.parser.clients.newClient(cid='joe', name='joe', guid="bbbbbbbb5555555")
        self.jack = self.parser.clients.newClient(cid='jack', name='jack', guid="ccccccccc5555555")
        self.jacky = self.parser.clients.newClient(cid='jacky', name='jacky', guid="ddddddddd5555555")
        self.p123456 = self.parser.clients.newClient(cid='123456', name='123456', guid="eeeeeee5555555")


    def test_exact_name(self):
        self.assertEqual([self.foobar], self.parser.clients.getByMagic('Foobar'))
        self.assertEqual([self.foobar], self.parser.clients.getByMagic('fOObAr'))

    def test_partial_name(self):
        self.assertEqual([self.foobar], self.parser.clients.getByMagic('foo'))
        self.assertEqual([self.foobar], self.parser.clients.getByMagic('oba'))
        self.assertSetEqual(set([self.jacky, self.jack]), set(self.parser.clients.getByMagic('jac')))
        self.assertSetEqual(set([self.jacky, self.jack]), set(self.parser.clients.getByMagic('jack')))

    def test_player_123456_with_exact_name(self):
        self.assertEqual([self.p123456], self.parser.clients.getByMagic('123456'))

    def test_player_123456_with_partial_name(self):
        """
        This test will fail if the b3.clients.Clients.getByMagic method was not patched
        """
        self.assertEqual([self.p123456], self.parser.clients.getByMagic('345'))
class PluginTestCase(unittest.TestCase):

    def setUp(self):
        # less logging
        logging.getLogger('output').setLevel(logging.ERROR)

        # create a parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString("""<configuration></configuration>""")
        self.console = DummyParser(self.parser_conf)
        self.console.startup()

        # load the admin plugin
        if B3version(b3_version) >= B3version("1.10dev"):
            admin_plugin_conf_file = '@b3/conf/plugin_admin.ini'
        else:
            admin_plugin_conf_file = '@b3/conf/plugin_admin.xml'
        with logging_disabled():
            self.adminPlugin = AdminPlugin(self.console, admin_plugin_conf_file)
            self.adminPlugin.onStartup()

        # make sure the admin plugin obtained by other plugins is our admin plugin
        when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)


        # prepare a few players
        self.joe = FakeClient(self.console, name="Joe", guid="joe_guid", groupBits=1)
        self.simon = FakeClient(self.console, name="Simon", guid="simon_guid", groupBits=0)
        self.moderator = FakeClient(self.console, name="Moderator", guid="moderator_guid", groupBits=8)

        logging.getLogger('output').setLevel(logging.DEBUG)


    def tearDown(self):
        self.console.working = False
class Test_getGamemodeSoundingLike(MohwTestCase):
    """
    make sure that getGamemodeSoundingLike returns expected results
    """

    def setUp(self):
        MohwTestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = MohwParser(self.conf)

    def test_CombatMission(self):
        self.assertEqual('CombatMission', self.parser.getGamemodeSoundingLike('MP_03', 'CombatMission'))
        self.assertEqual('CombatMission', self.parser.getGamemodeSoundingLike('MP_03', 'Combat Mission'))
        self.assertEqual('CombatMission', self.parser.getGamemodeSoundingLike('MP_03', 'Combt Mission'))
        self.assertEqual('CombatMission', self.parser.getGamemodeSoundingLike('MP_03', 'Mission'))
        self.assertEqual('CombatMission', self.parser.getGamemodeSoundingLike('MP_03', 'combat'))
        self.assertEqual('CombatMission', self.parser.getGamemodeSoundingLike('MP_03', 'cm'))

    def test_Sport(self):
        self.assertEqual('Sport', self.parser.getGamemodeSoundingLike('MP_03', 'Sport'))
        self.assertEqual('Sport', self.parser.getGamemodeSoundingLike('MP_03', 'Home Run'))
        self.assertEqual('Sport', self.parser.getGamemodeSoundingLike('MP_03', 'Home'))
        self.assertEqual('Sport', self.parser.getGamemodeSoundingLike('MP_03', 'run'))
        self.assertEqual('Sport', self.parser.getGamemodeSoundingLike('MP_03', 'homerun'))
        self.assertEqual('Sport', self.parser.getGamemodeSoundingLike('MP_03', 'hr'))

    def test_SectorControl(self):
        self.assertEqual('SectorControl', self.parser.getGamemodeSoundingLike('MP_03', 'SectorControl'))
        self.assertEqual('SectorControl', self.parser.getGamemodeSoundingLike('MP_03', 'Sector Control'))
        self.assertEqual('SectorControl', self.parser.getGamemodeSoundingLike('MP_03', 'Sector'))
        self.assertEqual('SectorControl', self.parser.getGamemodeSoundingLike('MP_03', 'control'))
        self.assertEqual('SectorControl', self.parser.getGamemodeSoundingLike('MP_03', 'sc'))

    def test_TeamDeathMatch(self):
        self.assertEqual('TeamDeathMatch', self.parser.getGamemodeSoundingLike('MP_03', 'TeamDeathMatch'))
        self.assertEqual('TeamDeathMatch', self.parser.getGamemodeSoundingLike('MP_03', 'Team DeathMatch'))
        self.assertEqual('TeamDeathMatch', self.parser.getGamemodeSoundingLike('MP_03', 'Team Death Match'))
        self.assertEqual('TeamDeathMatch', self.parser.getGamemodeSoundingLike('MP_03', 'Death Match'))
        self.assertEqual('TeamDeathMatch', self.parser.getGamemodeSoundingLike('MP_03', 'team'))
        self.assertEqual('TeamDeathMatch', self.parser.getGamemodeSoundingLike('MP_03', 'death'))
        self.assertEqual('TeamDeathMatch', self.parser.getGamemodeSoundingLike('MP_03', 'Match'))
        self.assertEqual('TeamDeathMatch', self.parser.getGamemodeSoundingLike('MP_03', 'tdm'))

    def test_BombSquad(self):
        self.assertEqual('BombSquad', self.parser.getGamemodeSoundingLike('MP_03', 'BombSquad'))
        self.assertEqual('BombSquad', self.parser.getGamemodeSoundingLike('MP_03', 'Hot Spot'))
        self.assertEqual('BombSquad', self.parser.getGamemodeSoundingLike('MP_03', 'Hotspot'))
        self.assertEqual('BombSquad', self.parser.getGamemodeSoundingLike('MP_03', 'hot'))
        self.assertEqual('BombSquad', self.parser.getGamemodeSoundingLike('MP_03', 'spot'))
        self.assertEqual('BombSquad', self.parser.getGamemodeSoundingLike('MP_03', 'Bomb'))
        self.assertEqual('BombSquad', self.parser.getGamemodeSoundingLike('MP_03', 'hs'))

    def test_suggestions(self):
        # unrecognizable input, falling back on available gamemodes for current map
        self.assertEqual(['Team Death Match', 'Combat Mission', 'Home Run'],
                         self.parser.getGamemodeSoundingLike('MP_12', ''))
Exemple #18
0
class CustomcommandsTestCase(unittest2.TestCase):

    def setUp(self):
        self.sleep_patcher = patch("time.sleep")
        self.sleep_mock = self.sleep_patcher.start()

        # create a FakeConsole parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString(r"""<configuration/>""")
        with logging_disabled():
            from b3.fake import FakeConsole
            self.console = FakeConsole(self.parser_conf)

        with logging_disabled():
            self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.ini')
            self.adminPlugin._commands = {}  # work around known bug in the Admin plugin which makes the _command property shared between all instances
            self.adminPlugin.onStartup()

        # make sure the admin plugin obtained by other plugins is our admin plugin
        when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)

        self.console.screen = Mock()
        self.console.time = time.time
        self.console.upTime = Mock(return_value=3)

        self.console.cron.stop()

    def tearDown(self):
        self.sleep_patcher.stop()
Exemple #19
0
class Iourt41TestCase(unittest.TestCase):
    """
    Test case that is suitable for testing iourt41 parser specific features
    """

    @classmethod
    def setUpClass(cls):
        from b3.parsers.q3a.abstractParser import AbstractParser
        from b3.fake import FakeConsole
        AbstractParser.__bases__ = (FakeConsole,)
        # Now parser inheritance hierarchy is :
        # Iourt41Parser -> AbstractParser -> FakeConsole -> Parser

        logging.getLogger('output').setLevel(logging.ERROR)

    def setUp(self):
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString("""
                    <configuration>
                    </configuration>
                """)
        self.console = Iourt41Parser(self.parser_conf)
        self.console.PunkBuster = None # no Punkbuster support in that game

        self.output_mock = mock()
        # simulate game server actions
        def write(*args, **kwargs):
            pretty_args = map(repr, args) + ["%s=%s" % (k, v) for k, v in kwargs.iteritems()]
            log.info("write(%s)" % ', '.join(pretty_args))
            return self.output_mock.write(*args, **kwargs)
        self.console.write = write
Exemple #20
0
class Test_say(AbstractParser_TestCase):
    def setUp(self):
        log = logging.getLogger('output')
        log.setLevel(logging.NOTSET)

        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = ConcretegameParser(self.conf)


    def test_say(self):
        with patch.object(time, 'sleep'):
            with patch.object(AbstractParser, 'write') as write_mock:
                self.parser._settings['big_b3_private_responses'] = False

                self.parser.say('test')
                self.parser.say('test2')

                self.parser.start_sayqueue_worker()
                self.parser.sayqueuelistener.join(.1)

                self.assertTrue(write_mock.called)
                write_mock.assert_any_call(('admin.say', 'test', 'all'))
                write_mock.assert_any_call(('admin.say', 'test2', 'all'))
Exemple #21
0
class Test_patch_b3_clients_getByMagic(AbstractParser_TestCase):
    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString(
            """
                <configuration>
                </configuration>
            """
        )
        self.parser = AbstractParser(self.conf)
        # setup context
        self.foobar = self.parser.clients.newClient(cid="Foobar", name="Foobar", guid="aaaaaaa5555555")
        self.joe = self.parser.clients.newClient(cid="joe", name="joe", guid="bbbbbbbb5555555")
        self.jack = self.parser.clients.newClient(cid="jack", name="jack", guid="ccccccccc5555555")
        self.jacky = self.parser.clients.newClient(cid="jacky", name="jacky", guid="ddddddddd5555555")
        self.p123456 = self.parser.clients.newClient(cid="123456", name="123456", guid="eeeeeee5555555")

    def test_exact_name(self):
        self.assertEqual([self.foobar], self.parser.clients.getByMagic("Foobar"))
        self.assertEqual([self.foobar], self.parser.clients.getByMagic("fOObAr"))

    def test_partial_name(self):
        self.assertEqual([self.foobar], self.parser.clients.getByMagic("foo"))
        self.assertEqual([self.foobar], self.parser.clients.getByMagic("oba"))
        self.assertSetEqual(set([self.jacky, self.jack]), set(self.parser.clients.getByMagic("jac")))
        self.assertSetEqual(set([self.jacky, self.jack]), set(self.parser.clients.getByMagic("jack")))

    def test_player_123456_with_exact_name(self):
        self.assertEqual([self.p123456], self.parser.clients.getByMagic("123456"))

    def test_player_123456_with_partial_name(self):
        """
        This test will fail if the b3.clients.Clients.getByMagic method was not patched
        """
        self.assertEqual([self.p123456], self.parser.clients.getByMagic("345"))
class CalladminTestCase(unittest2.TestCase):

    def setUp(self):
        self.sleep_patcher = patch("time.sleep")
        self.sleep_mock = self.sleep_patcher.start()

        # create a FakeConsole parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString(r"""<configuration/>""")
        with logging_disabled():
            from b3.fake import FakeConsole
            self.console = FakeConsole(self.parser_conf)

        with logging_disabled():
            self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.ini')
            self.adminPlugin._commands = {}
            self.adminPlugin.onStartup()

        # make sure the admin plugin obtained by other plugins is our admin plugin
        when(self.console).getCvar('sv_hostname').thenReturn(Cvar(name='sv_hostname', value='Test Server'))
        when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)
        when(time).time().thenReturn(60)

    def tearDown(self):
        self.sleep_patcher.stop()
class Test_Client_player_type(BFHTestCase):
    def setUp(self):
        BFHTestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = BfhParser(self.conf)
        self.foobar = self.parser.clients.newClient(cid='Foobar', name='Foobar', guid="FoobarGuid")

    def test_player_type_player(self):
        # GIVEN
        when(self.parser).write(('admin.listPlayers', 'player', 'Foobar')).thenReturn(
            ['10', 'name', 'guid', 'teamId', 'squadId', 'kills', 'deaths', 'score', 'rank', 'ping', 'type', '1',
             'Foobar', 'xxxxy', '1', '0', '0', '0', '0', '71', '65535', '0'])
        # THEN
        self.assertEqual(BFH_PLAYER, self.foobar.player_type)

    def test_player_type_spectator(self):
        # GIVEN
        when(self.parser).write(('admin.listPlayers', 'player', 'Foobar')).thenReturn(
            ['10', 'name', 'guid', 'teamId', 'squadId', 'kills', 'deaths', 'score', 'rank', 'ping', 'type', '1',
             'Foobar', 'xxxxy', '0', '0', '0', '0', '0', '71', '65535', '1'])
        # THEN
        self.assertEqual(BFH_SPECTATOR, self.foobar.player_type)
class Iourt41TestCase(unittest.TestCase):
    """
    Test case that is suitable for testing iourt41 parser specific features
    """

    @classmethod
    def setUpClass(cls):
        # less logging
        logging.getLogger('output').setLevel(logging.CRITICAL)

        from b3.parsers.q3a.abstractParser import AbstractParser
        from b3.fake import FakeConsole
        AbstractParser.__bases__ = (FakeConsole,)
        # Now parser inheritance hierarchy is :
        # Iourt41Parser -> AbstractParser -> FakeConsole -> Parser


    def setUp(self):
        # create a BF3 parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString("""
            <configuration>
                <settings name="messages">
                <set name="kicked_by">$clientname was kicked by $adminname $reason</set>
                <set name="kicked">$clientname was kicked $reason</set>
                <set name="banned_by">$clientname was banned by $adminname $reason</set>
                <set name="banned">$clientname was banned $reason</set>
                <set name="temp_banned_by">$clientname was temp banned by $adminname for $banduration $reason</set>
                <set name="temp_banned">$clientname was temp banned for $banduration $reason</set>
                <set name="unbanned_by">$clientname was un-banned by $adminname $reason</set>
                <set name="unbanned">$clientname was un-banned $reason</set>
            </settings>
            </configuration>
        """)
        self.console = Iourt41Parser(self.parser_conf)
        self.console.startup()

        # load the admin plugin
        self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.xml')
        self.adminPlugin.onStartup()

        # make sure the admin plugin obtained by other plugins is our admin plugin
        def getPlugin(name):
            if name == 'admin':
                return self.adminPlugin
            else:
                return self.console.getPlugin(name)
        self.console.getPlugin = getPlugin

        # prepare a few players
        self.joe = FakeClient(self.console, name="Joe", guid="00000000000000000000000000000001", groupBits=1, team=TEAM_UNKNOWN)
        self.simon = FakeClient(self.console, name="Simon", guid="00000000000000000000000000000002", groupBits=0, team=TEAM_UNKNOWN)
        self.reg = FakeClient(self.console, name="Reg", guid="00000000000000000000000000000003", groupBits=4, team=TEAM_UNKNOWN)
        self.moderator = FakeClient(self.console, name="Moderator", guid="00000000000000000000000000000004", groupBits=8, team=TEAM_UNKNOWN)
        self.admin = FakeClient(self.console, name="Level-40-Admin", guid="00000000000000000000000000000005", groupBits=16, team=TEAM_UNKNOWN)
        self.superadmin = FakeClient(self.console, name="God", guid="00000000000000000000000000000000", groupBits=128, team=TEAM_UNKNOWN)

        # more logging
        logging.getLogger('output').setLevel(logging.DEBUG)
class Write_controlled_TestCase(AbstractParser_TestCase):
    """
    Test case that controls replies given by the parser write method as follow :

    ## mapList.list
    Responds with the maps found on class properties 'maps'.
    Response contains 5 maps at most ; to get other maps, you have to use the 'StartOffset' command parameter that appears
    from BF3 R12 release.

    ## mapList.getMapIndices
    Responds with the value of the class property 'map_indices'.

    ## getEasyName
    Responds with whatever argument was passed to it.

    ## getGameMode
    Responds with whatever argument was passed to it.
    """

    maps = (
        ('MP_001 ', 'ConquestLarge0', '2'),
        ('MP_002 ', 'Rush0', '2'),
        ('MP_003 ', 'ConquestLarge0', '2'),
        )
    map_indices = [1, 2]

    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = ConcretegameParser(self.conf)
        self.parser.startup()

        # simulate responses we can expect from the rcon command mapList.list
        def write(data):
            if type(data) in (tuple, list):
                if data[0].lower() == 'maplist.list':
                    offset = 0
                    if len(data) > 1:
                        try:
                            offset = int(data[1])
                        except ValueError:
                            raise CommandFailedError(['InvalidArguments'])
                            # simulate that the Frostbite2 server responds with 5 maps at most for the mapList.list command
                    maps_to_send = self.__class__.maps[offset:offset + 5]
                    return [len(maps_to_send), 3] + list(reduce(tuple.__add__, maps_to_send, tuple()))
                elif data[0].lower() == 'maplist.getmapindices':
                    return self.__class__.map_indices
            return []

        self.parser.write = Mock(side_effect=write)

        self.parser.getEasyName = Mock(side_effect=lambda x: x)
        self.parser.getGameMode = Mock(side_effect=lambda x: x)

    def tearDown(self):
        self.parser.working = False
class Iourt41TestCase(unittest.TestCase):
    """
    Test case that is suitable for testing Iourt41 parser specific features
    """

    @classmethod
    def setUpClass(cls):

        with logging_disabled():
            from b3.parsers.q3a.abstractParser import AbstractParser
            from b3.fake import FakeConsole
            AbstractParser.__bases__ = (FakeConsole,)
            # Now parser inheritance hierarchy is :
            # Iourt41Parser -> abstractParser -> FakeConsole -> Parser

    def setUp(self):

        with logging_disabled():
            # create a Iourt41 parser
            self.parser_conf = XmlConfigParser()
            self.parser_conf.loadFromString("""<configuration><settings name="server"><set name="game_log"></set></settings></configuration>""")
            self.console = Iourt41Parser(self.parser_conf)
            self.console.startup()

            # load the admin plugin
            if B3version(b3_version) >= B3version("1.10dev"):
                admin_plugin_conf_file = '@b3/conf/plugin_admin.ini'
            else:
                admin_plugin_conf_file = '@b3/conf/plugin_admin.xml'
            with logging_disabled():
                self.adminPlugin = AdminPlugin(self.console, admin_plugin_conf_file)
                self.adminPlugin.onLoadConfig()
                self.adminPlugin.onStartup()

            # make sure the admin plugin obtained by other plugins is our admin plugin
            when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)

            # prepare a few players
            from b3.fake import FakeClient
            self.joe = FakeClient(self.console, name="Joe", exactName="Joe", guid="zaerezarezar", groupBits=1, team=TEAM_UNKNOWN, teamId=0, squad=0)
            self.simon = FakeClient(self.console, name="Simon", exactName="Simon", guid="qsdfdsqfdsqf", groupBits=0, team=TEAM_UNKNOWN, teamId=0, squad=0)
            self.reg = FakeClient(self.console, name="Reg", exactName="Reg", guid="qsdfdsqfdsqf33", groupBits=4, team=TEAM_UNKNOWN, teamId=0, squad=0)
            self.moderator = FakeClient(self.console, name="Moderator", exactName="Moderator", guid="sdf455ezr", groupBits=8, team=TEAM_UNKNOWN, teamId=0, squad=0)
            self.admin = FakeClient(self.console, name="Level-40-Admin", exactName="Level-40-Admin", guid="875sasda", groupBits=16, team=TEAM_UNKNOWN, teamId=0, squad=0)
            self.superadmin = FakeClient(self.console, name="God", exactName="God", guid="f4qfer654r", groupBits=128, team=TEAM_UNKNOWN, teamId=0, squad=0)

    def tearDown(self):
        self.console.working = False
#        sys.stdout.write("\tactive threads count : %s " % threading.activeCount())
#        sys.stderr.write("%s\n" % threading.enumerate())

    def init_default_cvar(self):
        when(self.console).getCvar('timelimit').thenReturn(Cvar('timelimit', value=20))
        when(self.console).getCvar('g_maxGameClients').thenReturn(Cvar('g_maxGameClients', value=16))
        when(self.console).getCvar('sv_maxclients').thenReturn(Cvar('sv_maxclients', value=16))
        when(self.console).getCvar('sv_privateClients').thenReturn(Cvar('sv_privateClients', value=0))
        when(self.console).getCvar('g_allowvote').thenReturn(Cvar('g_allowvote', value=0))
        when(self.console).getCvar('g_gear').thenReturn(Cvar('g_gear', value=''))
class MapcycleTestCase(unittest2.TestCase):

    @classmethod
    def setUpClass(cls):
        with logging_disabled():
            from b3.parsers.q3a.abstractParser import AbstractParser
            from b3.fake import FakeConsole
            AbstractParser.__bases__ = (FakeConsole,)
            # Now parser inheritance hierarchy is :
            # Iourt41Parser -> abstractParser -> FakeConsole -> Parser

    def setUp(self):
        # create a Iourt42 parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString(dedent(r"""
            <configuration>
                <settings name="server">
                    <set name="game_log"></set>
                </settings>
            </configuration>
            """))

        self.console = Iourt42Parser(self.parser_conf)

        # initialize some fixed cvars which will be used by both the plugin and the iourt42 parser
        when(self.console).getCvar('auth').thenReturn(Cvar('auth', value='0'))
        when(self.console).getCvar('fs_basepath').thenReturn(Cvar('g_maxGameClients', value='/fake/basepath'))
        when(self.console).getCvar('fs_homepath').thenReturn(Cvar('sv_maxclients', value='/fake/homepath'))
        when(self.console).getCvar('fs_game').thenReturn(Cvar('fs_game', value='q3ut4'))
        when(self.console).getCvar('gamename').thenReturn(Cvar('gamename', value='q3urt42'))

        # start the parser
        self.console.startup()

        with logging_disabled():
            self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.ini')
            self.adminPlugin.onLoadConfig()
            self.adminPlugin.onStartup()

        # make sure the admin plugin obtained by other plugins is our admin plugin
        when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)

        # force fake mapname here so Mapcycle Plugin will
        # not catch useless EVT_GAME_MAP_CHANGE
        self.console.game.mapName = 'ut4_casa'

        self.conf = XmlConfigParser()
        self.conf.loadFromString(dedent(MAPCYCLE_PLUGIN_CONFIG))

        # patch the mapcycle plugin for testing purpose
        patch_mapcycle_plugin()

        self.p = MapcyclePlugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

    def tearDown(self):
        self.console.working = False
class test_functional(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        from b3.fake import FakeConsole
        RavagedParser.__bases__ = (FakeConsole,)
        # Now parser inheritance hierarchy is :
        # RavagedParser -> FakeConsole -> Parser


    def setUp(self):
        self.status_response = None # defaults to STATUS_RESPONSE module attribute
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""<configuration></configuration>""")
        self.parser = RavagedParser(self.conf)
        self.parser.output = Mock()
        self.parser.output.write = Mock()

        ADMIN_CONFIG = XmlConfigParser()
        ADMIN_CONFIG.load(ADMIN_CONFIG_FILE)
        self.adminPlugin = AdminPlugin(self.parser, ADMIN_CONFIG)
        when(self.parser).getPlugin("admin").thenReturn(self.adminPlugin)
        self.adminPlugin.onLoadConfig()
        self.adminPlugin.onStartup()

        self.parser.startup()

    def tearDown(self):
        if hasattr(self, "parser"):
            del self.parser.clients
            self.parser.working = False



    def test_map(self):
        # GIVEN
        when(self.parser.output).write("getmaplist false").thenReturn(u"""0 CTR_Bridge
1 CTR_Canyon
2 CTR_Derelict
3 CTR_IceBreaker
4 CTR_Liberty
5 CTR_Rooftop
6 Thrust_Bridge
7 Thrust_Canyon
8 Thrust_Chasm
9 Thrust_IceBreaker
10 Thrust_Liberty
11 Thrust_Oilrig
12 Thrust_Rooftop
""".encode('UTF-8'))
        admin = FakeClient(console=self.parser, name="admin", guid="guid_admin", groupBits=128)
        admin.connects("guid_admin")
        # WHEN
        with patch.object(self.parser.output, 'write', wraps=self.parser.output.write) as write_mock:
            admin.says("!map chasm")
        # THEN
        write_mock.assert_has_calls([call("addmap Thrust_Chasm 1"), call("nextmap")])
Exemple #29
0
    def setUp(self):
        # create a Iourt42 parser
        parser_conf = XmlConfigParser()
        parser_conf.loadFromString(dedent(r"""
            <configuration>
                <settings name="server">
                    <set name="game_log"></set>
                </settings>
            </configuration>
        """))

        self.parser_conf = MainConfig(parser_conf)
        self.console = Iourt42Parser(self.parser_conf)

        # initialize some fixed cvars which will be used by both the plugin and the iourt42 parser
        when(self.console).getCvar('auth').thenReturn(Cvar('auth', value='0'))
        when(self.console).getCvar('fs_basepath').thenReturn(Cvar('fs_basepath', value='/fake/basepath'))
        when(self.console).getCvar('fs_homepath').thenReturn(Cvar('fs_homepath', value='/fake/homepath'))
        when(self.console).getCvar('fs_game').thenReturn(Cvar('fs_game', value='q3ut4'))
        when(self.console).getCvar('gamename').thenReturn(Cvar('gamename', value='q3urt42'))

        # start the parser
        self.console.startup()

        with logging_disabled():
            self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.ini')
            self.adminPlugin.onLoadConfig()
            self.adminPlugin.onStartup()

        # make sure the admin plugin obtained by other plugins is our admin plugin
        when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)

        self.conf = CfgConfigParser()
        self.conf.loadFromString(dedent(r"""
            [settings]
            demorecord: no
            skipstandardmaps: yes
            minleveldelete: senioradmin

            [commands]
            delrecord: guest
            maprecord: guest
            mapinfo: guest
            record: guest
            setway: senioradmin
            topruns: guest
            map: fulladmin
            maps: user
            setnextmap: admin
        """))

        self.p = JumperPlugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        # load fixed json data (do not contact urtjumpers api for testing)
        when(self.p).getMapsDataFromApi().thenReturn(json.loads(MAPDATA_JSON))
    def init(self, xml_content, cfg_content):
        xml_parser = XmlConfigParser()
        xml_parser.loadFromString(xml_content)
        conf_xml = MainConfig(xml_parser)
        cfg_parser = CfgConfigParser(allow_no_value=True)
        cfg_parser.loadFromString(cfg_content)
        conf_cfg = MainConfig(cfg_parser)

        return conf_xml, conf_cfg
Exemple #31
0
    def setUp(self):
        # create a Iourt42 parser
        parser_conf = XmlConfigParser()
        parser_conf.loadFromString(
            dedent(r"""
            <configuration>
                <settings name="server">
                    <set name="game_log"></set>
                </settings>
            </configuration>
        """))

        self.parser_conf = MainConfig(parser_conf)
        self.console = Iourt42Parser(self.parser_conf)

        # initialize some fixed cvars which will be used by both the plugin and the iourt42 parser
        when(self.console).getCvar('auth').thenReturn(Cvar('auth', value='0'))
        when(self.console).getCvar('fs_basepath').thenReturn(
            Cvar('fs_basepath', value='/fake/basepath'))
        when(self.console).getCvar('fs_homepath').thenReturn(
            Cvar('fs_homepath', value='/fake/homepath'))
        when(self.console).getCvar('fs_game').thenReturn(
            Cvar('fs_game', value='q3ut4'))
        when(self.console).getCvar('gamename').thenReturn(
            Cvar('gamename', value='q3urt42'))

        # start the parser
        self.console.startup()

        with logging_disabled():
            self.adminPlugin = AdminPlugin(self.console,
                                           '@b3/conf/plugin_admin.ini')
            self.adminPlugin.onLoadConfig()
            self.adminPlugin.onStartup()

        # make sure the admin plugin obtained by other plugins is our admin plugin
        when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)

        self.conf = CfgConfigParser()
        self.conf.loadFromString(
            dedent(r"""
            [settings]
            firstkill: on
            firsttk: on
            firsths: on

            [commands]
            firstkill: superadmin
            firsttk: superadmin
            firsths: superadmin

            [messages]
            ## $client = the client who made the kill
            ## $target = the client who suffered the kill
            first_kill: ^2First Kill^3: $client killed $target
            first_kill_by_headshot: ^2First Kill ^5by Headshot^3: $client killed $target
            first_teamkill: ^1First TeamKill^3: $client teamkilled $target
        """))

        self.p = FirstkillPlugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        with logging_disabled():
            from b3.fake import FakeClient

        # create some clients
        self.mike = FakeClient(console=self.console,
                               name="Mike",
                               guid="mikeguid",
                               team=TEAM_BLUE,
                               groupBits=1)
        self.mark = FakeClient(console=self.console,
                               name="Mark",
                               guid="markguid",
                               team=TEAM_BLUE,
                               groupBits=1)
        self.bill = FakeClient(console=self.console,
                               name="Bill",
                               guid="billguid",
                               team=TEAM_RED,
                               groupBits=1)
        self.mike.connects("1")
        self.bill.connects("2")
        self.mark.connects("3")
class EventParsingTestCase(Arma3TestCase):

    def setUp(self):
        """ran before each test"""
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        with logging_disabled():
            self.parser = Arma3Parser(self.conf)
        self.parser.output = Mock()  # mock Rcon

        self.evt_queue = []

        def queue_event(evt):
            self.evt_queue.append(evt)

        self.queueEvent_patcher = patch.object(self.parser, "queueEvent", wraps=queue_event)
        self.queueEvent_mock = self.queueEvent_patcher.start()

        self.write_patcher = patch.object(self.parser, "write")
        self.write_mock = self.write_patcher.start()

        with logging_disabled():
            self.parser.startup()

    def tearDown(self):
        """ran after each test to clean up"""
        Arma3TestCase.tearDown(self)
        self.queueEvent_patcher.stop()
        self.write_patcher.stop()
        if hasattr(self, "parser"):
            self.parser.working = False

    def clear_events(self):
        """
        clear the event queue, so when assert_has_event is called, it will look only at the newly caught events.
        """
        self.evt_queue = []

    def assert_has_event(self, event_type, data=ANY, client=ANY, target=ANY):
        """
        assert that self.evt_queue contains at least one event for the given type that has the given characteristics.
        """
        assert isinstance(event_type, basestring)

        def assert_event_equals(expected_event, actual_event):
            if expected_event is None:
                self.assertIsNone(actual_event)
            self.assertEqual(expected_event.type, actual_event.type, "expecting type %s, but got %s" %
                                                                     (self.parser.getEventKey(expected_event.type), self.parser.getEventKey(actual_event.type)))
            if client is not ANY:
                self.assertEqual(expected_event.client, actual_event.client, "expecting client %s, but got %s" % (expected_event.client, actual_event.client))
            if target is not ANY:
                self.assertEqual(expected_event.target, actual_event.target, "expecting target %s, but got %s" % (expected_event.target, actual_event.target))
            if data is not ANY:
                self.assertEqual(expected_event.data, actual_event.data, "expecting data %s, but got %s" % (expected_event.data, actual_event.data))

        expected_event = self.parser.getEvent(event_type, data, client, target)
        if not len(self.evt_queue):
            self.fail("expecting %s. Got no event instead" % expected_event)
        elif len(self.evt_queue) == 1:
            assert_event_equals(expected_event, self.evt_queue[0])
        else:
            for evt in self.evt_queue:
                try:
                    assert_event_equals(expected_event, evt)
                    return
                except AssertionError:
                    pass
            self.fail("expecting event %s. Got instead: %s" % (expected_event, map(str, self.evt_queue)))
Exemple #33
0
# -*- encoding: utf-8 -*-
from tests import prepare_fakeparser_for_tests
prepare_fakeparser_for_tests()

from b3.fake import fakeConsole, joe, simon, superadmin, moderator
from poweradminbf3 import Poweradminbf3Plugin
from b3.config import XmlConfigParser

conf = XmlConfigParser()
conf.loadFromString("""
<configuration plugin="poweradminbf3">
    <settings name="commands">
        <set name="changeteam">0</set>
    </settings>
    <settings name="preferences">
        <set name="no_level_check_level">20</set>
    </settings>
</configuration>
""")

p = Poweradminbf3Plugin(fakeConsole, conf)
p.onLoadConfig()
p.onStartup()

simon.connects("simon")
simon.teamId = 1
moderator.connects('moderator')
moderator.teamId = 2
superadmin.connects('superadmin')
superadmin.teamId = 2
print "Simon's group is " + simon.maxGroup.name
class Test_getClient(BFHTestCase):
    def setUp(self):
        BFHTestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""<configuration/>""")
        self.parser = BfhParser(self.conf)

    @staticmethod
    def build_listPlayer_response(cid, team_id, type_id):
        """
        :param type_id: {0: player, 1: spectator, 2: commander}
        :type cid: str
        :type team_id: str
        :type type_id: str
        :rtype : list of str
        """
        return [
            '10', 'name', 'guid', 'teamId', 'squadId', 'kills', 'deaths',
            'score', 'rank', 'ping', 'type', '1', cid, 'xxxxy', team_id, '0',
            '0', '0', '0', '71', '65535', type_id
        ]

    def test_team_red_player(self):
        # GIVEN
        when(self.parser).write(
            ('admin.listPlayers', 'player', 'Foobar')).thenReturn(
                self.build_listPlayer_response('Foobar', '1', '0'))
        # WHEN
        player = self.parser.getClient('Foobar')
        # THEN
        self.assertEqual(b3.TEAM_RED, player.team)

    def test_team_blue_player(self):
        # GIVEN
        when(self.parser).write(
            ('admin.listPlayers', 'player', 'Foobar')).thenReturn(
                self.build_listPlayer_response('Foobar', '2', '0'))
        # WHEN
        player = self.parser.getClient('Foobar')
        # THEN
        self.assertEqual(b3.TEAM_BLUE, player.team)

    def test_team_red_commander(self):
        # GIVEN
        when(self.parser).write(
            ('admin.listPlayers', 'player', 'Foobar')).thenReturn(
                self.build_listPlayer_response('Foobar', '1', '2'))
        # WHEN
        player = self.parser.getClient('Foobar')
        # THEN
        self.assertEqual(b3.TEAM_RED, player.team)

    def test_team_blue_commander(self):
        # GIVEN
        when(self.parser).write(
            ('admin.listPlayers', 'player', 'Foobar')).thenReturn(
                self.build_listPlayer_response('Foobar', '2', '2'))
        # WHEN
        player = self.parser.getClient('Foobar')
        # THEN
        self.assertEqual(b3.TEAM_BLUE, player.team)

    def test_team_spectator(self):
        # GIVEN
        when(self.parser).write(
            ('admin.listPlayers', 'player', 'Foobar')).thenReturn(
                self.build_listPlayer_response('Foobar', '0', '1'))
        # WHEN
        player = self.parser.getClient('Foobar')
        # THEN
        self.assertEqual(b3.TEAM_SPEC, player.team)
Exemple #35
0
class Test_getMapsSoundingLike(MohwTestCase):
    """
    make sure that getMapsSoundingLike returns expected results
    """
    def setUp(self):
        MohwTestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = MohwParser(self.conf)

    def test_MP_03(self):
        self.assertEqual('MP_03',
                         self.parser.getMapsSoundingLike('somalia stronghold'))
        self.assertEqual('MP_03',
                         self.parser.getMapsSoundingLike('somaliastronghold'))
        self.assertEqual('MP_03', self.parser.getMapsSoundingLike('somalia'))
        self.assertEqual('MP_03',
                         self.parser.getMapsSoundingLike('stronghold'))

    def test_MP_05(self):
        self.assertEqual('MP_05',
                         self.parser.getMapsSoundingLike('novi grad warzone'))
        self.assertEqual('MP_05',
                         self.parser.getMapsSoundingLike('novigradwarzone'))
        self.assertEqual('MP_05', self.parser.getMapsSoundingLike('novi'))
        self.assertEqual('MP_05', self.parser.getMapsSoundingLike('WARZONE'))

    def test_MP_10(self):
        self.assertEqual('MP_10',
                         self.parser.getMapsSoundingLike('sarajevo stadium'))
        self.assertEqual('MP_10',
                         self.parser.getMapsSoundingLike('sarajevostadium'))
        self.assertEqual('MP_10', self.parser.getMapsSoundingLike('sarajevo'))
        self.assertEqual('MP_10', self.parser.getMapsSoundingLike('stadium'))

    def test_MP_12(self):
        self.assertEqual('MP_12',
                         self.parser.getMapsSoundingLike('basilan aftermath'))
        self.assertEqual('MP_12',
                         self.parser.getMapsSoundingLike('basilanaftermath'))
        self.assertEqual('MP_12', self.parser.getMapsSoundingLike('basilan'))
        self.assertEqual('MP_12', self.parser.getMapsSoundingLike('aftermath'))

    def test_MP_13(self):
        self.assertEqual('MP_13',
                         self.parser.getMapsSoundingLike('hara dunes'))
        self.assertEqual('MP_13', self.parser.getMapsSoundingLike('haradunes'))
        self.assertEqual('MP_13', self.parser.getMapsSoundingLike('hara'))
        self.assertEqual('MP_13', self.parser.getMapsSoundingLike('dunes'))

    def test_MP_16(self):
        self.assertEqual('MP_16',
                         self.parser.getMapsSoundingLike('al fara cliffside'))
        self.assertEqual('MP_16',
                         self.parser.getMapsSoundingLike('alfaracliffside'))
        self.assertEqual('MP_16', self.parser.getMapsSoundingLike('alfara'))
        self.assertEqual('MP_16',
                         self.parser.getMapsSoundingLike('faracliffside'))
        self.assertEqual('MP_16', self.parser.getMapsSoundingLike('fara'))
        self.assertEqual('MP_16', self.parser.getMapsSoundingLike('cliffside'))

    def test_MP_18(self):
        self.assertEqual('MP_18',
                         self.parser.getMapsSoundingLike('shogore valley'))
        self.assertEqual('MP_18',
                         self.parser.getMapsSoundingLike('shogorevalley'))
        self.assertEqual('MP_18', self.parser.getMapsSoundingLike('shogore'))
        self.assertEqual('MP_18', self.parser.getMapsSoundingLike('valley'))

    def test_MP_19(self):
        self.assertEqual('MP_19',
                         self.parser.getMapsSoundingLike('tungunan jungle'))
        self.assertEqual('MP_19',
                         self.parser.getMapsSoundingLike('tungunanjungle'))
        self.assertEqual('MP_19', self.parser.getMapsSoundingLike('tungunan'))
        self.assertEqual('MP_19', self.parser.getMapsSoundingLike('jungle'))

    def test_MP_20(self):
        self.assertEqual('MP_20',
                         self.parser.getMapsSoundingLike('darra gun market'))
        self.assertEqual('MP_20',
                         self.parser.getMapsSoundingLike('darragunmarket'))
        self.assertEqual('MP_20', self.parser.getMapsSoundingLike('darra'))
        self.assertEqual('MP_20', self.parser.getMapsSoundingLike('darragun'))
        self.assertEqual('MP_20', self.parser.getMapsSoundingLike('market'))

    def test_MP_21(self):
        self.assertEqual('MP_21',
                         self.parser.getMapsSoundingLike('chitrail compound'))
        self.assertEqual('MP_21',
                         self.parser.getMapsSoundingLike('chitrailcompound'))
        self.assertEqual('MP_21', self.parser.getMapsSoundingLike('chitrail'))
        self.assertEqual('MP_21', self.parser.getMapsSoundingLike('compound'))

    def test_suggestions(self):
        self.assertEqual(
            ['shogore valley', 'sarajevo stadium', 'tungunan jungle'],
            self.parser.getMapsSoundingLike(''))
class Test_bf3_maps(BF3TestCase):

    def setUp(self):
        BF3TestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = Bf3Parser(self.conf)


    def test_each_map_has_at_least_one_gamemode(self):
        for map_id in MAP_NAME_BY_ID:
            self.assertIn(map_id, GAME_MODES_BY_MAP_ID)
            self.assertGreater(len(GAME_MODES_BY_MAP_ID[map_id]), 0)


    def test_each_gamemode_is_valid(self):
        game_modes_found = set()
        list(map(game_modes_found.update, list(GAME_MODES_BY_MAP_ID.values())))
        self.assertSetEqual(set(GAME_MODES_NAMES.keys()), game_modes_found)
        for game_mode in game_modes_found:
            self.assertIn(game_mode, GAME_MODES_NAMES)


    def test_getEasyName(self):
        self.assertEqual('Grand Bazaar', self.parser.getEasyName('MP_001'))
        self.assertEqual('Tehran Highway', self.parser.getEasyName('MP_003'))
        self.assertEqual('Caspian Border', self.parser.getEasyName('MP_007'))
        self.assertEqual('Seine Crossing', self.parser.getEasyName('MP_011'))
        self.assertEqual('Operation Firestorm', self.parser.getEasyName('MP_012'))
        self.assertEqual('Damavand Peak', self.parser.getEasyName('MP_013'))
        self.assertEqual('Noshahar Canals', self.parser.getEasyName('MP_017'))
        self.assertEqual('Kharg Island', self.parser.getEasyName('MP_018'))
        self.assertEqual('Operation Metro', self.parser.getEasyName('MP_Subway'))
        self.assertEqual('Strike At Karkand', self.parser.getEasyName('XP1_001'))
        self.assertEqual('Gulf of Oman', self.parser.getEasyName('XP1_002'))
        self.assertEqual('Sharqi Peninsula', self.parser.getEasyName('XP1_003'))
        self.assertEqual('Wake Island', self.parser.getEasyName('XP1_004'))
        self.assertEqual('Scrapmetal', self.parser.getEasyName('XP2_Factory'))
        self.assertEqual('Operation 925', self.parser.getEasyName('XP2_Office'))
        self.assertEqual('Donya Fortress', self.parser.getEasyName('XP2_Palace'))
        self.assertEqual('Ziba Tower', self.parser.getEasyName('XP2_Skybar'))
        self.assertEqual('Bandar Desert', self.parser.getEasyName('XP3_Desert'))
        self.assertEqual('Alborz Mountains', self.parser.getEasyName('XP3_Alborz'))
        self.assertEqual('Armored Shield', self.parser.getEasyName('XP3_Shield'))
        self.assertEqual('Death Valley', self.parser.getEasyName('XP3_Valley'))
        self.assertEqual('Epicenter', self.parser.getEasyName('XP4_Quake'))
        self.assertEqual('Markaz Monolith', self.parser.getEasyName('XP4_FD'))
        self.assertEqual('Azadi Palace', self.parser.getEasyName('XP4_Parl'))
        self.assertEqual('Talah market', self.parser.getEasyName('XP4_Rubble'))
        self.assertEqual('Operation Riverside', self.parser.getEasyName('XP5_001'))
        self.assertEqual('Nebandan Flats', self.parser.getEasyName('XP5_002'))
        self.assertEqual('Kiasar Railroad', self.parser.getEasyName('XP5_003'))
        self.assertEqual('Sabalan Pipeline', self.parser.getEasyName('XP5_004'))
        self.assertEqual('f00', self.parser.getEasyName('f00'))


    def test_getHardName(self):
        self.assertEqual('MP_001', self.parser.getHardName('Grand Bazaar'))
        self.assertEqual('MP_003', self.parser.getHardName('Tehran Highway'))
        self.assertEqual('MP_007', self.parser.getHardName('Caspian Border'))
        self.assertEqual('MP_011', self.parser.getHardName('Seine Crossing'))
        self.assertEqual('MP_012', self.parser.getHardName('Operation Firestorm'))
        self.assertEqual('MP_013', self.parser.getHardName('Damavand Peak'))
        self.assertEqual('MP_017', self.parser.getHardName('Noshahar Canals'))
        self.assertEqual('MP_018', self.parser.getHardName('Kharg Island'))
        self.assertEqual('MP_Subway', self.parser.getHardName('Operation Metro'))
        self.assertEqual('XP1_001', self.parser.getHardName('Strike At Karkand'))
        self.assertEqual('XP1_002', self.parser.getHardName('Gulf of Oman'))
        self.assertEqual('XP1_003', self.parser.getHardName('Sharqi Peninsula'))
        self.assertEqual('XP1_004', self.parser.getHardName('Wake Island'))
        self.assertEqual('XP2_Factory', self.parser.getHardName('Scrapmetal'))
        self.assertEqual('XP2_Office', self.parser.getHardName('Operation 925'))
        self.assertEqual('XP2_Palace', self.parser.getHardName('Donya Fortress'))
        self.assertEqual('XP2_Skybar', self.parser.getHardName('Ziba Tower'))
        self.assertEqual('XP3_Desert', self.parser.getHardName('Bandar Desert'))
        self.assertEqual('XP3_Alborz', self.parser.getHardName('Alborz Mountains'))
        self.assertEqual('XP3_Shield', self.parser.getHardName('Armored Shield'))
        self.assertEqual('XP3_Valley', self.parser.getHardName('Death Valley'))
        self.assertEqual('XP4_Quake', self.parser.getHardName('Epicenter'))
        self.assertEqual('XP4_FD', self.parser.getHardName('Markaz Monolith'))
        self.assertEqual('XP4_Parl', self.parser.getHardName('Azadi Palace'))
        self.assertEqual('XP4_Rubble', self.parser.getHardName('Talah market'))
        self.assertEqual('XP5_001', self.parser.getHardName('Operation Riverside'))
        self.assertEqual('XP5_002', self.parser.getHardName('Nebandan Flats'))
        self.assertEqual('XP5_003', self.parser.getHardName('Kiasar Railroad'))
        self.assertEqual('XP5_004', self.parser.getHardName('Sabalan Pipeline'))
        self.assertEqual('f00', self.parser.getHardName('f00'))


    def test_getMapsSoundingLike(self):
        self.assertEqual(['damavand peak', 'operation metro', 'death valley'], self.parser.getMapsSoundingLike(''), '')
        self.assertEqual('MP_Subway', self.parser.getMapsSoundingLike('Operation Metro'), 'Operation Metro')
        self.assertEqual('MP_001', self.parser.getMapsSoundingLike('grand'))
        self.assertEqual(['operation metro', 'operation 925', 'operation firestorm'], self.parser.getMapsSoundingLike('operation'))
        self.assertEqual('XP3_Desert', self.parser.getMapsSoundingLike('bandar'))
        self.assertEqual('XP3_Desert', self.parser.getMapsSoundingLike('desert'))
        self.assertEqual('XP3_Alborz', self.parser.getMapsSoundingLike('alborz'))
        self.assertEqual('XP3_Alborz', self.parser.getMapsSoundingLike('mountains'))
        self.assertEqual('XP3_Alborz', self.parser.getMapsSoundingLike('mount'))
        self.assertEqual('XP3_Shield', self.parser.getMapsSoundingLike('armored'))
        self.assertEqual('XP3_Shield', self.parser.getMapsSoundingLike('shield'))
        self.assertEqual('XP3_Valley', self.parser.getMapsSoundingLike('Death'))
        self.assertEqual('XP3_Valley', self.parser.getMapsSoundingLike('valley'))
        self.assertEqual('XP4_Quake', self.parser.getMapsSoundingLike('Epicenter'))
        self.assertEqual('XP4_Quake', self.parser.getMapsSoundingLike('Epicentre'))
        self.assertEqual('XP4_Quake', self.parser.getMapsSoundingLike('epi'))
        self.assertEqual('XP4_FD', self.parser.getMapsSoundingLike('markaz Monolith'))
        self.assertEqual('XP4_FD', self.parser.getMapsSoundingLike('markazMonolith'))
        self.assertEqual('XP4_FD', self.parser.getMapsSoundingLike('markaz Monolit'))
        self.assertEqual('XP4_FD', self.parser.getMapsSoundingLike('markaz Mono'))
        self.assertEqual('XP4_FD', self.parser.getMapsSoundingLike('markaz'))
        self.assertEqual('XP4_FD', self.parser.getMapsSoundingLike('Monolith'))
        self.assertEqual('XP4_Parl', self.parser.getMapsSoundingLike('Azadi Palace'))
        self.assertEqual('XP4_Parl', self.parser.getMapsSoundingLike('AzadiPalace'))
        self.assertEqual('XP4_Parl', self.parser.getMapsSoundingLike('Azadi'))
        self.assertEqual('XP4_Parl', self.parser.getMapsSoundingLike('Palace'))
        self.assertEqual('XP4_Parl', self.parser.getMapsSoundingLike('Azadi Place'))
        self.assertEqual('XP4_Rubble', self.parser.getMapsSoundingLike('Talah market'))
        self.assertEqual('XP4_Rubble', self.parser.getMapsSoundingLike('Talahmarket'))
        self.assertEqual('XP4_Rubble', self.parser.getMapsSoundingLike('Talah'))
        self.assertEqual('XP4_Rubble', self.parser.getMapsSoundingLike('market'))
        self.assertEqual('XP5_001', self.parser.getMapsSoundingLike('Operation Riverside'))
        self.assertEqual('XP5_001', self.parser.getMapsSoundingLike('Operationriverside'))
        self.assertEqual('XP5_001', self.parser.getMapsSoundingLike('Riverside'))
        self.assertEqual('XP5_001', self.parser.getMapsSoundingLike('riverside'))
        self.assertEqual('XP5_002', self.parser.getMapsSoundingLike('Nebandan Flats'))
        self.assertEqual('XP5_002', self.parser.getMapsSoundingLike('NebandanFlats'))
        self.assertEqual('XP5_002', self.parser.getMapsSoundingLike('Nebandan'))
        self.assertEqual('XP5_002', self.parser.getMapsSoundingLike('Flats'))
        self.assertEqual('XP5_003', self.parser.getMapsSoundingLike('Kiasar Railroad'))
        self.assertEqual('XP5_003', self.parser.getMapsSoundingLike('KiasarRailroad'))
        self.assertEqual('XP5_003', self.parser.getMapsSoundingLike('Kiasar'))
        self.assertEqual('XP5_003', self.parser.getMapsSoundingLike('Railroad'))
        self.assertEqual('XP5_004', self.parser.getMapsSoundingLike('Sabalan Pipeline'))
        self.assertEqual('XP5_004', self.parser.getMapsSoundingLike('SabalanPipeline'))
        self.assertEqual('XP5_004', self.parser.getMapsSoundingLike('Sabalan'))
        self.assertEqual('XP5_004', self.parser.getMapsSoundingLike('Pipeline'))

    def test_getGamemodeSoundingLike(self):
        self.assertEqual('ConquestSmall0', self.parser.getGamemodeSoundingLike('MP_011', 'ConquestSmall0'), 'ConquestSmall0')
        self.assertEqual('ConquestSmall0', self.parser.getGamemodeSoundingLike('MP_011', 'Conquest'), 'Conquest')
        self.assertListEqual(['Squad Deathmatch', 'Team Deathmatch'], self.parser.getGamemodeSoundingLike('MP_011', 'Deathmatch'), 'Deathmatch')
        self.assertListEqual(['Rush', 'Conquest', 'Conquest64'], self.parser.getGamemodeSoundingLike('MP_011', 'foo'))
        self.assertEqual('TeamDeathMatch0', self.parser.getGamemodeSoundingLike('MP_011', 'tdm'), 'tdm')
        self.assertEqual('TeamDeathMatch0', self.parser.getGamemodeSoundingLike('MP_011', 'teamdeathmatch'), 'teamdeathmatch')
        self.assertEqual('TeamDeathMatch0', self.parser.getGamemodeSoundingLike('MP_011', 'team death match'), 'team death match')
        self.assertEqual('ConquestLarge0', self.parser.getGamemodeSoundingLike('MP_011', 'CQ64'), 'CQ64')
        self.assertEqual('TankSuperiority0', self.parser.getGamemodeSoundingLike('XP3_Valley', 'tank superiority'), 'tank superiority')
        self.assertEqual('TankSuperiority0', self.parser.getGamemodeSoundingLike('XP3_Valley', 'tanksuperiority'), 'tanksuperiority')
        self.assertEqual('TankSuperiority0', self.parser.getGamemodeSoundingLike('XP3_Valley', 'tanksup'), 'tanksup')
        self.assertEqual('TankSuperiority0', self.parser.getGamemodeSoundingLike('XP3_Valley', 'tank'), 'tank')
        self.assertEqual('TankSuperiority0', self.parser.getGamemodeSoundingLike('XP3_Valley', 'superiority'), 'superiority')
        self.assertEqual('SquadDeathMatch0', self.parser.getGamemodeSoundingLike('XP4_Quake', 'sqdm'), 'sqdm')
        self.assertEqual('Scavenger0', self.parser.getGamemodeSoundingLike('XP4_Quake', 'scavenger'), 'scavenger')
        self.assertEqual('Scavenger0', self.parser.getGamemodeSoundingLike('XP4_Quake', 'scav'), 'scav')
        self.assertEqual('Scavenger0', self.parser.getGamemodeSoundingLike('XP4_FD', 'scav'), 'scav')
        self.assertEqual('Scavenger0', self.parser.getGamemodeSoundingLike('XP4_Parl', 'scav'), 'scav')
        self.assertEqual('Scavenger0', self.parser.getGamemodeSoundingLike('XP4_Rubble', 'scav'), 'scav')
        self.assertEqual('CaptureTheFlag0', self.parser.getGamemodeSoundingLike('XP5_001', 'ctf'), 'ctf')
        self.assertEqual('CaptureTheFlag0', self.parser.getGamemodeSoundingLike('XP5_002', 'ctf'), 'ctf')
        self.assertEqual('CaptureTheFlag0', self.parser.getGamemodeSoundingLike('XP5_003', 'ctf'), 'ctf')
        self.assertEqual('CaptureTheFlag0', self.parser.getGamemodeSoundingLike('XP5_004', 'ctf'), 'ctf')
        self.assertEqual('CaptureTheFlag0', self.parser.getGamemodeSoundingLike('XP5_004', 'flag'), 'flag')
        self.assertEqual('CaptureTheFlag0', self.parser.getGamemodeSoundingLike('XP5_004', 'cap'), 'cap')
        self.assertEqual('CaptureTheFlag0', self.parser.getGamemodeSoundingLike('XP5_004', 'capture'), 'capture')
        self.assertEqual('AirSuperiority0', self.parser.getGamemodeSoundingLike('XP5_001', 'airsuperiority'), 'airsuperiority')
        self.assertEqual('AirSuperiority0', self.parser.getGamemodeSoundingLike('XP5_002', 'airsuperiority'), 'airsuperiority')
        self.assertEqual('AirSuperiority0', self.parser.getGamemodeSoundingLike('XP5_003', 'airsuperiority'), 'airsuperiority')
        self.assertEqual('AirSuperiority0', self.parser.getGamemodeSoundingLike('XP5_004', 'airsuperiority'), 'airsuperiority')
        self.assertEqual('AirSuperiority0', self.parser.getGamemodeSoundingLike('XP5_004', 'air'), 'air')
        self.assertEqual('AirSuperiority0', self.parser.getGamemodeSoundingLike('XP5_004', 'airsup'), 'airsup')
        self.assertEqual('AirSuperiority0', self.parser.getGamemodeSoundingLike('XP5_004', 'superiority'), 'superiority')
class Test_punkbuster_events(BF3TestCase):

    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = Bf3Parser(self.conf)
        self.parser.startup()

    def pb(self, msg):
        return self.parser.OnPunkbusterMessage(action=None, data=[msg])

    def assert_pb_misc_evt(self, msg):
        assert str(self.pb(msg)).startswith('Event<EVT_PUNKBUSTER_MISC>')

    def test_PB_SV_BanList(self):
        self.assert_pb_misc_evt('PunkBuster Server: 1   b59ffffffffffffffffffffffffffc7d {13/15} "Cucurbitaceae" "87.45.14.2:3659" retest" ""')
        self.assert_pb_misc_evt('PunkBuster Server: 1   b59ffffffffffffffffffffffffffc7d {0/1440} "Cucurbitaceae" "87.45.14.2:3659" mlkjsqfd" ""')

        self.assertEqual(
            '''Event<EVT_PUNKBUSTER_UNKNOWN>(['PunkBuster Server: 1   (UnBanned) b59ffffffffffffffffffffffffffc7d {15/15} "Cucurbitaceae" "87.45.14.2:3659" retest" ""'], None, None)''',
            str(self.pb('PunkBuster Server: 1   (UnBanned) b59ffffffffffffffffffffffffffc7d {15/15} "Cucurbitaceae" "87.45.14.2:3659" retest" ""')))

        self.assert_pb_misc_evt('PunkBuster Server: Guid=b59ffffffffffffffffffffffffffc7d" Not Found in the Ban List')
        self.assert_pb_misc_evt('PunkBuster Server: End of Ban List (1 of 1 displayed)')

    def test_PB_UCON_message(self):
        result = self.pb('PunkBuster Server: PB UCON "ggc_85.214.107.154"@85.214.107.154:14516 [admin.say "GGC-Stream.com - Welcome Cucurbitaceae with the GUID 31077c7d to our server." all]\n')
        self.assertEqual('Event<EVT_PUNKBUSTER_UCON>({\'ip\': \'85.214.107.154\', \'cmd\': \'admin.say "GGC-Stream.com - Welcome Cucurbitaceae with the GUID 31077c7d to our server." all\', \'from\': \'ggc_85.214.107.154\', \'port\': \'14516\'}, None, None)', str(result))

    def test_PB_Screenshot_received_message(self):
        result = self.pb('PunkBuster Server: Screenshot C:\\games\\bf3\\173_199_73_213_25200\\862147\\bf3\\pb\\svss\\pb000709.png successfully received (MD5=4576546546546546546546546543E1E1) from 19 Jaffar [da876546546546546546546546547673(-) 111.22.33.111:3659]\n')
        self.assertEqual(r"Event<EVT_PUNKBUSTER_SCREENSHOT_RECEIVED>({'slot': '19', 'name': 'Jaffar', 'ip': '111.22.33.111', 'pbid': 'da876546546546546546546546547673', 'imgpath': 'C:\\games\\bf3\\173_199_73_213_25200\\862147\\bf3\\pb\\svss\\pb000709.png', 'port': '3659', 'md5': '4576546546546546546546546543E1E1'}, None, None)", str(result))

    def test_PB_SV_PList(self):
        self.assert_pb_misc_evt("PunkBuster Server: Player List: [Slot #] [GUID] [Address] [Status] [Power] [Auth Rate] [Recent SS] [O/S] [Name]")
        self.assert_pb_misc_evt('PunkBuster Server: End of Player List (0 Players)')

    def test_PB_Ver(self):
        self.assertIsNone(self.pb('PunkBuster Server: PunkBuster Server for BF3 (v1.839 | A1386 C2.279) Enabled\n'))

    def test_PB_SV_BanGuid(self):
        self.assert_pb_misc_evt('PunkBuster Server: Ban Added to Ban List')
        self.assert_pb_misc_evt('PunkBuster Server: Ban Failed')

    def test_PB_SV_UnBanGuid(self):
        self.assert_pb_misc_evt('PunkBuster Server: Guid b59f190e5ef725e06531387231077c7d has been Unbanned')

    def test_PB_SV_UpdBanFile(self):
        self.assert_pb_misc_evt("PunkBuster Server: 0 Ban Records Updated in d:\\localuser\\g119142\\pb\\pbbans.dat")

    def test_misc(self):
        self.assertEqual("Event<EVT_PUNKBUSTER_LOST_PLAYER>({'slot': '1', 'ip': 'x.x.x.x', 'port': '3659', 'name': 'joe', 'pbuid': '0837c128293d42aaaaaaaaaaaaaaaaa'}, None, None)",
            str(self.pb("PunkBuster Server: Lost Connection (slot #1) x.x.x.x:3659 0837c128293d42aaaaaaaaaaaaaaaaa(-) joe")))

        self.assert_pb_misc_evt("PunkBuster Server: Invalid Player Specified: None")
        self.assert_pb_misc_evt("PunkBuster Server: Matched: Cucurbitaceae (slot #1)")
        self.assert_pb_misc_evt("PunkBuster Server: Received Master Security Information")
        self.assert_pb_misc_evt("PunkBuster Server: Auto Screenshot 000714 Requested from 25 Goldbat")
class Iourt41TestCase(unittest.TestCase):
    """
    Test case that is suitable for testing Iourt41 parser specific features
    """
    @classmethod
    def setUpClass(cls):
        with logging_disabled():
            from b3.parsers.q3a.abstractParser import AbstractParser
            from b3.fake import FakeConsole
            AbstractParser.__bases__ = (FakeConsole, )
            # Now parser inheritance hierarchy is :
            # Iourt41Parser -> abstractParser -> FakeConsole -> Parser

    def setUp(self):
        with logging_disabled():
            # create a Iourt41 parser
            self.parser_conf = XmlConfigParser()
            self.parser_conf.loadFromString(
                """<configuration><settings name="server"><set name="game_log"></set></settings></configuration>"""
            )
            self.console = Iourt41Parser(self.parser_conf)
            self.console.startup()

            # load the admin plugin
            if B3version(b3_version) >= B3version("1.10dev"):
                admin_plugin_conf_file = '@b3/conf/plugin_admin.ini'
            else:
                admin_plugin_conf_file = '@b3/conf/plugin_admin.xml'
            with logging_disabled():
                self.adminPlugin = AdminPlugin(self.console,
                                               admin_plugin_conf_file)
                self.adminPlugin.onStartup()

            # make sure the admin plugin obtained by other plugins is our admin plugin
            when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)

            # when starting the PoweradminurtPlugin expects the game server to provide a few cvar values
            when(self.console).getCvar('timelimit').thenReturn(
                Cvar('timelimit', value=20))
            when(self.console).getCvar('g_maxGameClients').thenReturn(
                Cvar('g_maxGameClients', value=16))
            when(self.console).getCvar('sv_maxclients').thenReturn(
                Cvar('sv_maxclients', value=16))
            when(self.console).getCvar('sv_privateClients').thenReturn(
                Cvar('sv_privateClients', value=0))
            when(self.console).getCvar('g_allowvote').thenReturn(
                Cvar('g_allowvote', value=0))

            # prepare a few players
            self.joe = FakeClient(self.console,
                                  name="Joe",
                                  exactName="Joe",
                                  guid="zaerezarezar",
                                  groupBits=1,
                                  team=TEAM_UNKNOWN,
                                  teamId=0,
                                  squad=0)
            self.simon = FakeClient(self.console,
                                    name="Simon",
                                    exactName="Simon",
                                    guid="qsdfdsqfdsqf",
                                    groupBits=0,
                                    team=TEAM_UNKNOWN,
                                    teamId=0,
                                    squad=0)
            self.reg = FakeClient(self.console,
                                  name="Reg",
                                  exactName="Reg",
                                  guid="qsdfdsqfdsqf33",
                                  groupBits=4,
                                  team=TEAM_UNKNOWN,
                                  teamId=0,
                                  squad=0)
            self.moderator = FakeClient(self.console,
                                        name="Moderator",
                                        exactName="Moderator",
                                        guid="sdf455ezr",
                                        groupBits=8,
                                        team=TEAM_UNKNOWN,
                                        teamId=0,
                                        squad=0)
            self.admin = FakeClient(self.console,
                                    name="Level-40-Admin",
                                    exactName="Level-40-Admin",
                                    guid="875sasda",
                                    groupBits=16,
                                    team=TEAM_UNKNOWN,
                                    teamId=0,
                                    squad=0)
            self.superadmin = FakeClient(self.console,
                                         name="God",
                                         exactName="God",
                                         guid="f4qfer654r",
                                         groupBits=128,
                                         team=TEAM_UNKNOWN,
                                         teamId=0,
                                         squad=0)

    def tearDown(self):
        self.console.working = False
Exemple #39
0
class Test_OnPlayerChat(AbstractParser_TestCase):
    def setUp(self):
        log = logging.getLogger('output')
        log.setLevel(logging.NOTSET)

        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = ConcretegameParser(self.conf)

        self.admin_plugin_mock = Mock(spec=AdminPlugin)
        self.admin_plugin_mock._commands = {}
        self.admin_plugin_mock.cmdPrefix = '!'
        self.admin_plugin_mock.cmdPrefixLoud = '@'
        self.admin_plugin_mock.cmdPrefixBig = '&'
        self.parser.getPlugin = Mock(return_value=self.admin_plugin_mock)

        self.joe = Mock(spec=Client)
        self.parser.getClient = Mock(return_value=self.joe)

    def test_normal_text(self):
        self.assertEqual(
            'foo',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', 'foo', 'all')).data)
        self.assertEqual(
            '  foo',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '  foo', 'all')).data)

    def test_command(self):
        self.assertEqual(
            '!1',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '!1', 'all')).data)
        self.assertEqual(
            '!foo',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '!foo', 'all')).data)
        self.assertEqual(
            '!!foo',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '!!foo', 'all')).data)
        self.assertEqual(
            '@foo',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '@foo', 'all')).data)
        self.assertEqual(
            '@@foo',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '@@foo', 'all')).data)
        self.assertEqual(
            r'&foo',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', r'&foo', 'all')).data)
        self.assertEqual(
            r'&&foo',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', r'&&foo', 'all')).data)

    def test_slash_prefix(self):
        self.assertEqual(
            '!1',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '/!1', 'all')).data)
        self.assertEqual(
            '!foo',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '/!foo', 'all')).data)
        self.assertEqual(
            '@foo',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '/@foo', 'all')).data)
        self.assertEqual(
            r'&foo',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', r'/&foo', 'all')).data)
Exemple #40
0
    def setUp(self):
        # create a Iourt43 parser
        parser_conf = XmlConfigParser()
        parser_conf.loadFromString(
            dedent(r"""
            <configuration>
                <settings name="server">
                    <set name="game_log"></set>
                </settings>
            </configuration>
        """))

        self.parser_conf = MainConfig(parser_conf)
        self.console = Iourt43Parser(self.parser_conf)

        # initialize some fixed cvars which will be used by both the plugin and the iourt42 parser
        when(self.console).getCvar('auth').thenReturn(Cvar('auth', value='0'))
        when(self.console).getCvar('auth_owners').thenReturn(None)
        when(self.console).getCvar('fs_basepath').thenReturn(
            Cvar('fs_basepath', value='/fake/basepath'))
        when(self.console).getCvar('fs_homepath').thenReturn(
            Cvar('fs_homepath', value='/fake/homepath'))
        when(self.console).getCvar('fs_game').thenReturn(
            Cvar('fs_game', value='q3ut4'))
        when(self.console).getCvar('gamename').thenReturn(
            Cvar('gamename', value='q3urt43'))

        # start the parser
        self.console.startup()

        with logging_disabled():
            self.adminPlugin = AdminPlugin(self.console,
                                           '@b3/conf/plugin_admin.ini')
            self.adminPlugin.onLoadConfig()
            self.adminPlugin.onStartup()

        # make sure the admin plugin obtained by other plugins is our admin plugin
        when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)

        self.conf = CfgConfigParser()
        self.conf.loadFromString(
            dedent(r"""
            [settings]
            enabled: on
            minlevel: 40
            nbtop: 5
            
            [messages]
            msg_5: ^3$name ^4$score ^7HE grenade kills!
        """))

        self.p = NaderPlugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        with logging_disabled():
            from tests.fake import FakeClient

        # create some clients
        self.mike = FakeClient(console=self.console,
                               name="Mike",
                               guid="mikeguid",
                               team=TEAM_BLUE,
                               groupBits=1)
        self.mark = FakeClient(console=self.console,
                               name="Mark",
                               guid="markguid",
                               team=TEAM_BLUE,
                               groupBits=1)
        self.bill = FakeClient(console=self.console,
                               name="Bill",
                               guid="billguid",
                               team=TEAM_RED,
                               groupBits=1)
        self.mike.connects("1")
        self.bill.connects("2")
        self.mark.connects("3")
Exemple #41
0
class Test_getFullBanList(AbstractParser_TestCase):
    """
    getFullBanList is a method of AbstractParser that calls the Frostbite2 banList.list command the number of
    times required to obtain the exhaustive list of bans.
    """

    bans = (
        ('name', 'Joe', 'perm', '0', '0', 'Banned by admin'),
        ('name', 'Jack', 'rounds', '0', '4', 'tk'),
        ('name', 'Averell', 'seconds', '3576', '0', 'being stupid'),
        ('name', 'William', 'perm', '0', '0', 'hacking'),
        )

    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = ConcretegameParser(self.conf)
        self.parser.startup()

        # simulate responses we can expect from the rcon command mapList.list
        def write(data):
            if type(data) in (tuple, list):
                if data[0].lower() == 'banlist.list':
                    offset = 0
                    if len(data) > 1:
                        try:
                            offset = int(data[1])
                        except ValueError:
                            raise CommandFailedError('InvalidArguments')
                            # simulate that the Frostbite2 server responds with 5 bans at most for the banList.list command
                    bans_to_send = self.__class__.bans[offset:offset + 5]
                    return list(reduce(tuple.__add__, bans_to_send, tuple()))
            return []

        self.parser.write = Mock(side_effect=write)




    def test_empty(self):
        # setup context
        self.__class__.bans = tuple()
        # verify
        bl = self.parser.getFullBanList()
        self.assertEqual(0, len(bl))
        self.assertEqual(1, self.parser.write.call_count)

    def test_one_ban(self):
        # setup context
        self.__class__.bans = (('name', 'Foo1 ', 'perm', '0', '0', 'Banned by admin'),)
        # verify
        mlb = self.parser.getFullBanList()
        self.assertEqual(
            "BanlistContent[{'idType': 'name', 'seconds_left': '0', 'reason': 'Banned by admin', 'banType': 'perm', 'rounds_left': '0', 'id': 'Foo1 '}]"
            , repr(mlb))
        self.assertEqual(2, self.parser.write.call_count)

    def test_two_bans(self):
        # setup context
        self.__class__.bans = (
            ('name', 'Foo1 ', 'perm', '0', '0', 'Banned by admin'),
            ('name', 'Foo2 ', 'perm', '0', '0', 'Banned by admin'),
            )
        # verify
        mlb = self.parser.getFullBanList()
        self.assertEqual("BanlistContent[{'idType': 'name', 'seconds_left': '0', 'reason': 'Banned by admin', 'banType': 'perm', 'rounds_left': '0', 'id': 'Foo1 '}, \
{'idType': 'name', 'seconds_left': '0', 'reason': 'Banned by admin', 'banType': 'perm', 'rounds_left': '0', 'id': 'Foo2 '}]"
            , repr(mlb))
        self.assertEqual(2, self.parser.write.call_count)


    def test_lots_of_bans(self):
        # setup context
        self.__class__.bans = (
            ('name', 'Foo1 ', 'perm', '0', '0', 'Banned by admin'),
            ('name', 'Foo2 ', 'perm', '0', '0', 'Banned by admin'),
            ('name', 'Foo3 ', 'perm', '0', '0', 'Banned by admin'),
            ('name', 'Foo4 ', 'perm', '0', '0', 'Banned by admin'),
            ('name', 'Foo5 ', 'perm', '0', '0', 'Banned by admin'),
            ('name', 'Foo6 ', 'perm', '0', '0', 'Banned by admin'),
            ('name', 'Foo7 ', 'perm', '0', '0', 'Banned by admin'),
            ('name', 'Foo8 ', 'perm', '0', '0', 'Banned by admin'),
            ('name', 'Foo9 ', 'perm', '0', '0', 'Banned by admin'),
            )
        # verify
        mlb = self.parser.getFullBanList()
        self.assertEqual(9, len(mlb))
        # check in details what were the 3 calls made to the write method
        assert [
            ((('banList.list', 0),), {}),
            ((('banList.list', 5),), {}),
            ((('banList.list', 10),), {}),
        ], self.parser.write.call_args_list
Exemple #42
0
class Test_config(AbstractParser_TestCase):
    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""<configuration/>""")
        self.parser = ConcretegameParser(self.conf)
        log = logging.getLogger('output')
        log.setLevel(logging.DEBUG)



    def assert_big_b3_private_responses(self, expected, config):
        self.parser._big_b3_private_responses = None
        self.conf.loadFromString(config)
        self.parser.load_conf_big_b3_private_responses()
        self.assertEqual(expected, self.parser._big_b3_private_responses)

    def test_big_b3_private_responses_on(self):
        self.assert_big_b3_private_responses(True, """<configuration>
                    <settings name="thegame">
                        <set name="big_b3_private_responses">on</set>
                    </settings>
                </configuration>""")

        self.assert_big_b3_private_responses(False, """<configuration>
                    <settings name="thegame">
                        <set name="big_b3_private_responses">off</set>
                    </settings>
                </configuration>""")

        self.assert_big_b3_private_responses(False, """<configuration>
                    <settings name="thegame">
                        <set name="big_b3_private_responses">off</set>
                    </settings>
                </configuration>""")

        self.assert_big_b3_private_responses(False, """<configuration>
                    <settings name="thegame">
                        <set name="big_b3_private_responses">f00</set>
                    </settings>
                </configuration>""")

        self.assert_big_b3_private_responses(False, """<configuration>
                    <settings name="thegame">
                        <set name="big_b3_private_responses"></set>
                    </settings>
                </configuration>""")


    def assert_big_msg_duration(self, expected, config):
        self.parser._big_msg_duration = None
        self.conf.loadFromString(config)
        self.parser.load_conf_big_msg_duration()
        self.assertEqual(expected, self.parser._big_msg_duration)

    def test_big_msg_duration(self):
        default_value = 4
        self.assert_big_msg_duration(0, """<configuration>
                    <settings name="thegame">
                        <set name="big_msg_duration">0</set>
                    </settings>
                </configuration>""")

        self.assert_big_msg_duration(5, """<configuration>
                    <settings name="thegame">
                        <set name="big_msg_duration">5</set>
                    </settings>
                </configuration>""")

        self.assert_big_msg_duration(default_value, """<configuration>
                    <settings name="thegame">
                        <set name="big_msg_duration">5.6</set>
                    </settings>
                </configuration>""")

        self.assert_big_msg_duration(30, """<configuration>
                    <settings name="thegame">
                        <set name="big_msg_duration">30</set>
                    </settings>
                </configuration>""")

        self.assert_big_msg_duration(default_value, """<configuration>
                    <settings name="thegame">
                        <set name="big_msg_duration">f00</set>
                    </settings>
                </configuration>""")

        self.assert_big_msg_duration(default_value, """<configuration>
                    <settings name="thegame">
                        <set name="big_msg_duration"></set>
                    </settings>
                </configuration>""")

    def assert_big_msg_repeat(self, expected, config):
        self.parser._big_msg_repeat = None
        self.conf.loadFromString(config)
        self.parser.load_conf_big_b3_private_responses()
        self.parser.load_conf_big_msg_repeat()
        self.assertEqual(expected, self.parser._big_msg_repeat)

    def test_big_msg_repeat(self):
        default_value = 'pm'
        self.assert_big_msg_repeat('all', """<configuration>
                    <settings name="thegame">
                        <set name="big_b3_private_responses">on</set>
                        <set name="big_msg_repeat">all</set>
                    </settings>
                </configuration>""")

        self.assert_big_msg_repeat('off', """<configuration>
                    <settings name="thegame">
                        <set name="big_msg_repeat">off</set>
                    </settings>
                </configuration>""")

        self.assert_big_msg_repeat(default_value, """<configuration>
                    <settings name="thegame">
                        <set name="big_b3_private_responses">on</set>
                        <set name="big_msg_repeat">pm</set>
                    </settings>
                </configuration>""")

        self.assert_big_msg_repeat(default_value, """<configuration>
                    <settings name="thegame">
                        <set name="big_b3_private_responses">on</set>
                        <set name="big_msg_repeat"></set>
                    </settings>
                </configuration>""")

        self.assert_big_msg_repeat('off', """<configuration>
                    <settings name="thegame">
                        <set name="big_msg_repeat">OFF</set>
                    </settings>
                </configuration>""")

        self.assert_big_msg_repeat(default_value, """<configuration>
                    <settings name="thegame">
                        <set name="big_b3_private_responses">on</set>
                        <set name="big_msg_repeat">junk</set>
                    </settings>
                </configuration>""")
Exemple #43
0
class Test_OnPBPlayerGuid(AbstractParser_TestCase):
    def setUp(self):
        log = logging.getLogger('output')
        log.setLevel(logging.NOTSET)

        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = ConcretegameParser(self.conf)

        self.event_raw_data = ["punkBuster.onMessage", 'PunkBuster Server: 14 300000aaaaaabbbbbbccccc111223300(-) 11.122.103.24:3659 OK   1 3.0 0 (W) "Snoopy"']
        regex_for_OnPBPlistItem = [x for (x, y) in self.parser._punkbusterMessageFormats if y == 'OnPBPlistItem'][0]
        self.event_match = Mock(wraps=re.match(regex_for_OnPBPlistItem, self.event_raw_data[1]))
        self.event_match.__eq__ = Test_OnPBPlayerGuid.SREMatch_equals

    @staticmethod
    def SREMatch_equals(m1, m2):
        """
        @return True if m1 and m2 could be re.match responses for the same regex and data to match
        """
        if m2 is None:
            return False
        else:
            return m1.groups() == m2.groups()


    def test_OnPBPlistItem_is_called(self):
        with patch.object(self.parser, "OnPBPlistItem") as OnPBPlistItem_mock:
            # WHEN
            self.parser.routeFrostbitePacket(self.event_raw_data)
            # THEN
            OnPBPlistItem_mock.assert_called_once_with(self.event_match, self.event_raw_data[1])

    def test_OnPBPlayerGuid_is_called(self):
        with patch.object(self.parser, "OnPBPlayerGuid") as OnPBPlayerGuid_mock:
            # WHEN
            self.parser.routeFrostbitePacket(self.event_raw_data)
            # THEN
            OnPBPlayerGuid_mock.assert_called_once_with(self.event_match, self.event_raw_data[1])

    def test_OnPBPlayerGuid_saves_client_with_guid(self):
        with patch.object(self.parser, "getClient") as getClient_mock:
            # GIVEN
            snoopy = Mock()
            snoopy.guid = 'EA_AAAAAAAABBBBBBBBBBBBBB00000000000012222'
            getClient_mock.return_value = snoopy
            # WHEN
            self.parser.routeFrostbitePacket(self.event_raw_data)
            # THEN
            getClient_mock.assert_called_once_with("Snoopy")
            snoopy.save.assert_called_once_with()

    def test_OnPBPlayerGuid_does_not_save_client_without_guid(self):
        with patch.object(self.parser, "getClient") as getClient_mock:
            # GIVEN
            snoopy = Mock()
            snoopy.guid = ''
            getClient_mock.return_value = snoopy
            # WHEN
            self.parser.routeFrostbitePacket(self.event_raw_data)
            # THEN
            getClient_mock.assert_called_once_with("Snoopy")
            self.assertFalse(snoopy.save.called)
Exemple #44
0
class Iourt43TestCase(unittest.TestCase):
    """
    Test case that is suitable for testing Iourt43 parser specific features
    """
    @classmethod
    def setUpClass(cls):
        with logging_disabled():
            from b3.parsers.iourt43 import Iourt43Parser
            from tests.fake import FakeConsole
            Iourt43Parser.__bases__ = (FakeConsole, )

    def setUp(self):
        with logging_disabled():
            self.parser_conf = XmlConfigParser()
            self.parser_conf.loadFromString(
                """<configuration><settings name="server"><set name="game_log"></set></settings></configuration>"""
            )
            self.console = Iourt43Parser(self.parser_conf)
            self.console.startup()

            admin_plugin_conf_file = '@b3/conf/plugin_admin.ini'
            with logging_disabled():
                self.adminPlugin = AdminPlugin(self.console,
                                               admin_plugin_conf_file)
                self.adminPlugin.onLoadConfig()
                self.adminPlugin.onStartup()

            # make sure the admin plugin obtained by other plugins is our admin plugin
            when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)
            when(self.console).queryClientFrozenSandAccount(...).thenReturn({})

            # prepare a few players
            from tests.fake import FakeClient
            self.joe = FakeClient(self.console,
                                  name="Joe",
                                  exactName="Joe",
                                  guid="zaerezarezar",
                                  groupBits=1,
                                  team=TEAM_UNKNOWN,
                                  teamId=0,
                                  squad=0)
            self.simon = FakeClient(self.console,
                                    name="Simon",
                                    exactName="Simon",
                                    guid="qsdfdsqfdsqf",
                                    groupBits=0,
                                    team=TEAM_UNKNOWN,
                                    teamId=0,
                                    squad=0)
            self.reg = FakeClient(self.console,
                                  name="Reg",
                                  exactName="Reg",
                                  guid="qsdfdsqfdsqf33",
                                  groupBits=4,
                                  team=TEAM_UNKNOWN,
                                  teamId=0,
                                  squad=0)
            self.moderator = FakeClient(self.console,
                                        name="Moderator",
                                        exactName="Moderator",
                                        guid="sdf455ezr",
                                        groupBits=8,
                                        team=TEAM_UNKNOWN,
                                        teamId=0,
                                        squad=0)
            self.admin = FakeClient(self.console,
                                    name="Level-40-Admin",
                                    exactName="Level-40-Admin",
                                    guid="875sasda",
                                    groupBits=16,
                                    team=TEAM_UNKNOWN,
                                    teamId=0,
                                    squad=0)
            self.superadmin = FakeClient(self.console,
                                         name="God",
                                         exactName="God",
                                         guid="f4qfer654r",
                                         groupBits=128,
                                         team=TEAM_UNKNOWN,
                                         teamId=0,
                                         squad=0)

    def tearDown(self):
        self.console.shutdown()

    def init_default_cvar(self):
        when(self.console).getCvar('timelimit').thenReturn(
            Cvar('timelimit', value=20))
        when(self.console).getCvar('g_maxGameClients').thenReturn(
            Cvar('g_maxGameClients', value=16))
        when(self.console).getCvar('sv_maxclients').thenReturn(
            Cvar('sv_maxclients', value=16))
        when(self.console).getCvar('sv_privateClients').thenReturn(
            Cvar('sv_privateClients', value=0))
        when(self.console).getCvar('g_allowvote').thenReturn(
            Cvar('g_allowvote', value=0))
        when(self.console).getCvar('g_gear').thenReturn(
            Cvar('g_gear', value=''))
class Test_bf3_events(BF3TestCase):

    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = Bf3Parser(self.conf)
        self.parser.startup()
        # mock parser queueEvent method so we can make assertions on it later on
        self.parser.queueEvent = Mock(name="queueEvent method")
        self.joe = Mock(name="Joe", spec=Client)

    def test_cmd_rotateMap_generates_EVT_GAME_ROUND_END(self):
        # prepare fake BF3 server responses
        def fake_write(data):
            if data ==  ('mapList.getMapIndices', ):
                return [0, 1]
            else:
                return []
        self.parser.write = Mock(side_effect=fake_write)
        self.parser.getFullMapRotationList = Mock(return_value=MapListBlock(['4', '3', 'MP_007', 'RushLarge0', '4', 'MP_011', 'RushLarge0', '4', 'MP_012',
                                                                             'SquadRush0', '4', 'MP_013', 'SquadRush0', '4']))
        self.parser.rotateMap()
        self.assertEqual(1, self.parser.queueEvent.call_count)
        self.assertEqual(self.parser.getEventID("EVT_GAME_ROUND_END"), self.parser.queueEvent.call_args[0][0].type)
        self.assertIsNone(self.parser.queueEvent.call_args[0][0].data)


    def test_player_onChat_event_all(self):
        self.parser.getClient = Mock(return_value=self.joe)

        self.parser.routeFrostbitePacket(['player.onChat', 'Cucurbitaceae', 'test all', 'all'])
        self.assertEqual(1, self.parser.queueEvent.call_count)

        event = self.parser.queueEvent.call_args[0][0]
        self.assertEqual("Say", self.parser.getEventName(event.type))
        self.assertEqual('test all', event.data)
        self.assertEqual(self.joe, event.client)


    def test_player_onChat_event_team(self):
        self.parser.getClient = Mock(return_value=self.joe)

        self.parser.routeFrostbitePacket(['player.onChat', 'Cucurbitaceae', 'test team', 'team', '1'])
        self.assertEqual(1, self.parser.queueEvent.call_count)

        event = self.parser.queueEvent.call_args[0][0]
        self.assertEqual("Team Say", self.parser.getEventName(event.type))
        self.assertEqual('test team', event.data)
        self.assertEqual(self.joe, event.client)


    def test_player_onChat_event_squad(self):
        self.parser.getClient = Mock(return_value=self.joe)

        self.parser.routeFrostbitePacket(['player.onChat', 'Cucurbitaceae', 'test squad', 'squad', '1', '1'])
        self.assertEqual(1, self.parser.queueEvent.call_count)

        event = self.parser.queueEvent.call_args[0][0]
        self.assertEqual("Squad Say", self.parser.getEventName(event.type))
        self.assertEqual('test squad', event.data)
        self.assertEqual(self.joe, event.client)
Exemple #46
0
class test_functional(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        from b3.fake import FakeConsole
        RavagedParser.__bases__ = (FakeConsole, )
        # Now parser inheritance hierarchy is :
        # RavagedParser -> FakeConsole -> Parser

    def setUp(self):
        self.status_response = None  # defaults to STATUS_RESPONSE module attribute
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""<configuration></configuration>""")
        self.parser = RavagedParser(self.conf)
        self.parser.output = Mock()
        self.parser.output.write = Mock()

        ADMIN_CONFIG = CfgConfigParser()
        ADMIN_CONFIG.load(ADMIN_CONFIG_FILE)
        self.adminPlugin = AdminPlugin(self.parser, ADMIN_CONFIG)
        when(self.parser).getPlugin("admin").thenReturn(self.adminPlugin)
        self.adminPlugin.onLoadConfig()
        self.adminPlugin.onStartup()

        self.parser.startup()

    def tearDown(self):
        if hasattr(self, "parser"):
            del self.parser.clients
            self.parser.working = False

    def test_map(self):
        # GIVEN
        when(self.parser.output).write("getmaplist false").thenReturn(
            u"""0 CTR_Bridge
1 CTR_Canyon
2 CTR_Derelict
3 CTR_IceBreaker
4 CTR_Liberty
5 CTR_Rooftop
6 Thrust_Bridge
7 Thrust_Canyon
8 Thrust_Chasm
9 Thrust_IceBreaker
10 Thrust_Liberty
11 Thrust_Oilrig
12 Thrust_Rooftop
""".encode('UTF-8'))
        admin = FakeClient(console=self.parser,
                           name="admin",
                           guid="guid_admin",
                           groupBits=128)
        admin.connects("guid_admin")
        # WHEN
        with patch.object(self.parser.output,
                          'write',
                          wraps=self.parser.output.write) as write_mock:
            admin.says("!map chasm")
        # THEN
        write_mock.assert_has_calls(
            [call("addmap Thrust_Chasm 1"),
             call("nextmap")])
class Test_bf3_sends_no_guid(BF3TestCase):
    """
    See bug https://github.com/courgette/big-brother-bot/issues/69
    """
    def setUp(self):
        BF3TestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("<configuration/>")
        self.parser = Bf3Parser(self.conf)
        self.parser.startup()

        self.authorizeClients_patcher = patch.object(self.parser.clients, "authorizeClients")
        self.authorizeClients_patcher.start()

        self.write_patcher = patch.object(self.parser, "write")
        self.write_mock = self.write_patcher.start()

        self.event_raw_data = 'PunkBuster Server: 14 300000aaaaaabbbbbbccccc111223300(-) 11.122.103.24:3659 OK   1 3.0 0 (W) "Snoopy"'
        self.regex_for_OnPBPlistItem = [x for (x, y) in self.parser._punkbusterMessageFormats if y == 'OnPBPlistItem'][0]


    def tearDown(self):
        BF3TestCase.tearDown(self)
        self.authorizeClients_patcher.stop()
        self.write_mock = self.write_patcher.stop()


    def test_auth_client_without_guid_but_with_known_pbid(self):
        # GIVEN

        # known superadmin named Snoopy
        superadmin = Client(console=self.parser, name='Snoopy', guid='EA_AAAAAAAABBBBBBBBBBBBBB00000000000012222', pbid='300000aaaaaabbbbbbccccc111223300', group_bits=128, connections=21)
        superadmin.save()

        # bf3 server failing to provide guid
        def write(data):
            if data == ('admin.listPlayers', 'player', 'Snoopy'):
                return ['7', 'name', 'guid', 'teamId', 'squadId', 'kills', 'deaths', 'score', '1', 'Snoopy', '', '2', '8', '0', '0', '0']
            else:
                return DEFAULT
        self.write_mock.side_effect = write

        # WHEN
        self.assertFalse('Snoopy' in self.parser.clients)
        self.parser.OnPBPlayerGuid(match=re.match(self.regex_for_OnPBPlistItem, self.event_raw_data), data=self.event_raw_data)

        # THEN
        # B3 should have authed Snoopy
        self.assertTrue('Snoopy' in self.parser.clients)
        snoopy = self.parser.clients['Snoopy']
        self.assertTrue(snoopy.authed)
        for attb in ('name', 'pbid', 'guid', 'groupBits'):
            self.assertEqual(getattr(superadmin, attb), getattr(snoopy, attb))



    def test_does_not_auth_client_without_guid_and_unknown_pbid(self):
        # GIVEN
        # bf3 server failing to provide guid
        def write(data):
            if data == ('admin.listPlayers', 'player', 'Snoopy'):
                return ['7', 'name', 'guid', 'teamId', 'squadId', 'kills', 'deaths', 'score', '1', 'Snoopy', '', '2', '8', '0', '0', '0']
            else:
                return DEFAULT
        self.write_mock.side_effect = write

        # WHEN
        self.assertFalse('Snoopy' in self.parser.clients)
        self.parser.OnPBPlayerGuid(match=re.match(self.regex_for_OnPBPlistItem, self.event_raw_data), data=self.event_raw_data)

        # THEN
        # B3 should have authed Snoopy
        self.assertTrue('Snoopy' in self.parser.clients)
        snoopy = self.parser.clients['Snoopy']
        self.assertFalse(snoopy.authed)
Exemple #48
0
class RavagedTestCase(unittest.TestCase):
    """
    Test case that is suitable for testing Ravaged parser specific features
    """
    whatever = object()

    @classmethod
    def setUpClass(cls):
        from b3.fake import FakeConsole
        RavagedParser.__bases__ = (FakeConsole, )
        # Now parser inheritance hierarchy is :
        # RavagedParser -> FakeConsole -> Parser

    def setUp(self):
        self.status_response = None  # defaults to STATUS_RESPONSE module attribute
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""<configuration></configuration>""")
        self.parser = RavagedParser(self.conf)
        self.parser.output = Mock()
        self.parser.output.write = Mock()

        self.evt_queue = []

        def queue_event(evt):
            self.evt_queue.append(evt)

        self.queueEvent_patcher = patch.object(self.parser,
                                               "queueEvent",
                                               wraps=queue_event)
        self.queueEvent_mock = self.queueEvent_patcher.start()

        self.parser.startup()

    def tearDown(self):
        self.queueEvent_patcher.stop()
        if hasattr(self, "parser"):
            del self.parser.clients
            self.parser.working = False

    def clear_events(self):
        """
        clear the event queue, so when assert_has_event is called, it will look only at the newly caught events.
        """
        self.evt_queue = []

    def assert_has_event(self,
                         event_type,
                         data=None,
                         client=None,
                         target=None):
        """
        assert that self.evt_queue contains at least one event for the given type that has the given characteristics.
        """
        assert isinstance(event_type, basestring)
        expected_event = self.parser.getEvent(event_type, data, client, target)

        if not len(self.evt_queue):
            self.fail("expecting %s. Got no event instead" % expected_event)
        elif len(self.evt_queue) == 1:
            actual_event = self.evt_queue[0]
            self.assertEqual(expected_event.type, actual_event.type)
            if data != self.whatever:
                self.assertEqual(expected_event.data, actual_event.data)
            if client != self.whatever:
                self.assertTrue(
                    client_equal(expected_event.client, actual_event.client))
            if target != self.whatever:
                self.assertTrue(
                    client_equal(expected_event.target, actual_event.target))
        else:
            for evt in [
                    e for e in self.evt_queue if e.type == expected_event.type
            ]:
                results = [expected_event.type == evt.type]
                if data != self.whatever:
                    results.append(expected_event.data == evt.data)
                if client != self.whatever:
                    results.append(
                        client_equal(expected_event.client, evt.client))
                if target != self.whatever:
                    results.append(
                        client_equal(expected_event.target, evt.target))
                if all(results):
                    return

            self.fail("expecting event %s. Got instead: %s" %
                      (expected_event, map(str, self.evt_queue)))
class Test_getPlayerPings(BF3TestCase):

    def setUp(self):
        BF3TestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = Bf3Parser(self.conf)
        self.p1 = FakeClient(self.parser, name="Player1")
        self.p2 = FakeClient(self.parser, name="Player2")

    def test_no_player(self):
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({}, actual_result)

    def test_one_player(self):
        # GIVEN
        self.p1.connects("Player1")
        when(self.parser).write(('player.ping', self.p1.cid)).thenReturn(['140'])
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)

    def test_two_player(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('player.ping', self.p1.cid)).thenReturn(['140'])
        when(self.parser).write(('player.ping', self.p2.cid)).thenReturn(['450'])
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({self.p1.cid: 140, self.p2.cid: 450}, actual_result)

    def test_two_player_filter_client_ids(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('player.ping', self.p1.cid)).thenReturn(['140'])
        when(self.parser).write(('player.ping', self.p2.cid)).thenReturn(['450'])
        # WHEN
        actual_result = self.parser.getPlayerPings(filter_client_ids=[self.p1.cid])
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)


    def test_bad_data(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('player.ping', self.p1.cid)).thenReturn(['140'])
        when(self.parser).write(('player.ping', self.p2.cid)).thenReturn(['f00'])
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)

    def test_exception(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('player.ping', self.p1.cid)).thenReturn(['140'])
        when(self.parser).write(('player.ping', self.p2.cid)).thenRaise(Exception)
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)
# -*- encoding: utf-8 -*-
from tests import prepare_fakeparser_for_tests

prepare_fakeparser_for_tests()

from b3.fake import fakeConsole, superadmin, FakeConsole
from poweradminbf3 import Poweradminbf3Plugin
from b3.config import XmlConfigParser

conf = XmlConfigParser()
conf.loadFromString("""
<configuration plugin="poweradminbf3">
  <settings name="commands">
    <set name="setnextmap-snmap">20</set>
  </settings>
</configuration>
""")

p = Poweradminbf3Plugin(fakeConsole, conf)
p.onLoadConfig()
p.onStartup()

superadmin.connects('superadmin')

print "\n\n====================================== test !setnextmap nominal case"
superadmin.says('!setnextmap')

print "\n\n====================================== test case map name not recognised"


def my_getMapsSoundingLike_3_suggestions(mapname):
class ChivTestCase(unittest.TestCase):
    """
    Test case that is suitable for testing Chivalry parser specific features
    """
    @classmethod
    def setUpClass(cls):
        from b3.fake import FakeConsole
        ChivParser.__bases__ = (FakeConsole, )
        # Now parser inheritance hierarchy is :
        # ChivParser -> FakeConsole -> Parser

    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""<configuration></configuration>""")
        self.parser = ChivParser(self.conf)
        self.parser._client = Mock()

        self.evt_queue = []

        def queue_event(evt):
            self.evt_queue.append(evt)

        self.queueEvent_patcher = patch.object(self.parser,
                                               "queueEvent",
                                               wraps=queue_event)
        self.queueEvent_mock = self.queueEvent_patcher.start()

    def tearDown(self):
        self.queueEvent_patcher.stop()
        if hasattr(self, "parser"):
            del self.parser.clients
            self.parser.working = False

    def clear_events(self):
        """
        clear the event queue, so when assert_has_event is called, it will look only at the newly caught events.
        """
        self.evt_queue = []

    def assert_has_event(self,
                         event_type,
                         data=WHATEVER,
                         client=WHATEVER,
                         target=WHATEVER):
        """
        assert that self.evt_queue contains at least one event for the given type that has the given characteristics.
        """
        assert isinstance(event_type, str)
        expected_event = self.parser.getEvent(event_type, data, client, target)

        if not len(self.evt_queue):
            self.fail("expecting %s. Got no event instead" % expected_event)
        elif len(self.evt_queue) == 1:
            actual_event = self.evt_queue[0]
            self.assertEqual(expected_event.type, actual_event.type)
            if data != WHATEVER:
                self.assertEqual(expected_event.data, actual_event.data)
            if client != WHATEVER:
                self.assertTrue(
                    client_equal(expected_event.client, actual_event.client))
            if target != WHATEVER:
                self.assertTrue(
                    client_equal(expected_event.target, actual_event.target))
        else:
            for evt in self.evt_queue:
                if expected_event.type == evt.type \
                        and (expected_event.data == evt.data or data == WHATEVER)\
                        and (client_equal(expected_event.client, evt.client) or client == WHATEVER)\
                        and (client_equal(expected_event.target, evt.target) or target == WHATEVER):
                    return

            self.fail("expecting event %s. Got instead: %s" %
                      (expected_event, list(map(str, self.evt_queue))))

    def assert_has_not_event(self,
                             event_type,
                             data=None,
                             client=None,
                             target=None):
        """
        assert that self.evt_queue does not contain at least one event for the given type that has the given characteristics.
        """
        assert isinstance(event_type, str)
        unexpected_event = self.parser.getEvent(event_type, data, client,
                                                target)

        if not len(self.evt_queue):
            return
        else:

            def event_match(evt):
                return (unexpected_event.type == evt.type
                        and (data is None or data == evt.data) and
                        (client is None or client_equal(client, evt.client))
                        and
                        (target is None or client_equal(target, evt.target)))

            if any(map(event_match, self.evt_queue)):
                self.fail("not expecting event %s" %
                          (list(filter(event_match, self.evt_queue))))
class SpawnkillTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        with logging_disabled():
            from b3.parsers.q3a.abstractParser import AbstractParser
            from b3.fake import FakeConsole
            AbstractParser.__bases__ = (FakeConsole, )
            # Now parser inheritance hierarchy is :
            # Iourt42Parser -> abstractParser -> FakeConsole -> Parser

    def setUp(self):
        # create a Iourt42 parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString(
            dedent(r"""
            <configuration>
                <settings name="server">
                    <set name="game_log"></set>
                </settings>
            </configuration>
        """))

        self.console = Iourt42Parser(self.parser_conf)

        # initialize some fixed cvars which will be used by both the plugin and the iourt42 parser
        when(self.console).getCvar('auth').thenReturn(Cvar('auth', value='0'))
        when(self.console).getCvar('fs_basepath').thenReturn(
            Cvar('g_maxGameClients', value='/fake/basepath'))
        when(self.console).getCvar('fs_homepath').thenReturn(
            Cvar('sv_maxclients', value='/fake/homepath'))
        when(self.console).getCvar('fs_game').thenReturn(
            Cvar('fs_game', value='q3ut4'))
        when(self.console).getCvar('gamename').thenReturn(
            Cvar('gamename', value='q3urt42'))

        # start the parser
        self.console.startup()

        self.admin_plugin_conf = CfgConfigParser()
        self.admin_plugin_conf.loadFromString(
            dedent(r"""
            [warn]
            pm_global: yes
            alert_kick_num: 3
            instant_kick_num: 5
            tempban_num: 6
            tempban_duration: 1d
            max_duration: 1d
            message: ^1WARNING^7 [^3$warnings^7]: $reason
            warn_delay: 15
            reason: ^7too many warnings: $reason
            duration_divider: 30
            alert: ^1ALERT^7: $name^7 auto-kick from warnings if not cleared [^3$warnings^7] $reason
            warn_command_abusers: no"""))

        with logging_disabled():
            self.adminPlugin = AdminPlugin(self.console,
                                           self.admin_plugin_conf)
            self.adminPlugin.onLoadConfig()
            self.adminPlugin.onStartup()

        # make sure the admin plugin obtained by other plugins is our admin plugin
        when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)

        with logging_disabled():
            from b3.fake import FakeClient

        # create some clients
        self.mike = FakeClient(console=self.console,
                               name="Mike",
                               guid="mikeguid",
                               team=TEAM_RED,
                               groupBits=1)
        self.bill = FakeClient(console=self.console,
                               name="Bill",
                               guid="billguid",
                               team=TEAM_BLUE,
                               groupBits=1)
        self.mark = FakeClient(console=self.console,
                               name="Mark",
                               guid="markguid",
                               team=TEAM_BLUE,
                               groupBits=128)

        self.conf = CfgConfigParser()
        self.p = SpawnkillPlugin(self.console, self.conf)

    def tearDown(self):
        self.console.working = False
        self.mike.disconnects()
        self.bill.disconnects()
        self.mark.disconnects()

    def init(self, config_content=None):
        if config_content:
            self.conf.loadFromString(config_content)
        else:
            self.conf.loadFromString(
                dedent(r"""
                [hit]
                maxlevel: admin
                delay: 2
                penalty: warn
                duration: 3m
                reason: do not shoot to spawning players!

                [kill]
                maxlevel: admin
                delay: 3
                penalty: warn
                duration: 5m
                reason: spawnkilling is not allowed on this server!
            """))

        self.p.onLoadConfig()
        self.p.onStartup()
class Test_getPlayerPings(BFHTestCase):
    def setUp(self):
        BFHTestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = BfhParser(self.conf)
        self.p1 = FakeClient(self.parser, name="Player1")
        self.p2 = FakeClient(self.parser, name="Player2")

    def test_no_player(self):
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({}, actual_result)

    def test_one_player(self):
        # GIVEN
        self.p1.connects("Player1")
        when(self.parser).write(('admin.listPlayers', 'all')).thenReturn([
            '10', 'name', 'guid', 'teamId', 'squadId', 'kills', 'deaths',
            'score', 'rank', 'ping', 'type', '1', 'Player1', 'EA_XXX', '1',
            '1', '0', '0', '0', '1', '140', '0'
        ])
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)

    def test_two_player(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('admin.listPlayers', 'all')).thenReturn([
            '10', 'name', 'guid', 'teamId', 'squadId', 'kills', 'deaths',
            'score', 'rank', 'ping', 'type', '2', 'Player1', 'EA_XXX', '1',
            '1', '0', '0', '0', '1', '140', '0', 'Player2', 'EA_XXY', '1', '1',
            '0', '0', '0', '1', '450', '0'
        ])
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({
            self.p1.cid: 140,
            self.p2.cid: 450
        }, actual_result)

    def test_two_player_filter_client_ids(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('admin.listPlayers', 'all')).thenReturn([
            '10', 'name', 'guid', 'teamId', 'squadId', 'kills', 'deaths',
            'score', 'rank', 'ping', 'type', '2', 'Player1', 'EA_XXX', '1',
            '1', '0', '0', '0', '1', '140', '0', 'Player2', 'EA_XXY', '1', '1',
            '0', '0', '0', '1', '450', '0'
        ])
        # WHEN
        actual_result = self.parser.getPlayerPings(
            filter_client_ids=[self.p1.cid])
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)

    def test_bad_data_filter_client_ids(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('admin.listPlayers', 'all')).thenReturn([
            '10', 'name', 'guid', 'teamId', 'squadId', 'kills', 'deaths',
            'score', 'rank', 'ping', 'type', '1', 'Player1', 'EA_XXX', '1',
            '1', '0', '0', '0', '1', '140', '0', 'Player2', 'EA_XYZ', '1', '1',
            '0', '0', '0', '1', 'f00', '0'
        ])
        # WHEN
        actual_result = self.parser.getPlayerPings(
            filter_client_ids=[self.p1.cid, self.p2.cid])
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)

    def test_bad_data(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('admin.listPlayers', 'all')).thenReturn([
            '10', 'name', 'guid', 'teamId', 'squadId', 'kills', 'deaths',
            'score', 'rank', 'ping', 'type', '1', 'Player1', 'EA_XXX', '1',
            '1', '0', '0', '0', '1', '140', '0', 'Player2', 'EA_XYZ', '1', '1',
            '0', '0', '0', '1', 'f00', '0'
        ])
        # WHEN
        actual_result = self.parser.getPlayerPings()
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)

    def test_exception(self):
        # GIVEN
        self.p1.connects("Player1")
        self.p2.connects("Player2")
        when(self.parser).write(('admin.listPlayers', 'all')).thenReturn([
            '10', 'name', 'guid', 'teamId', 'squadId', 'kills', 'deaths',
            'score', 'rank', 'ping', 'type', '1', 'Player1', 'EA_XXX', '1',
            '1', '0', '0', '0', '1', '140', '0', 'Player2', 'EA_XYZ', '1', '1',
            '0', '0', '0', '1', 'f00', '0'
        ])
        # WHEN
        actual_result = self.parser.getPlayerPings(
            filter_client_ids=[self.p1.cid, self.p2.cid])
        # THEN
        self.assertDictEqual({self.p1.cid: 140}, actual_result)
Exemple #54
0
conf = XmlConfigParser()
conf.loadFromString("""
<configuration plugin="teamspeak">
	<settings name="teamspeakServer">
		<!-- IP or domain where your teamspeak server is hosted -->
		<set name="host">{ts_host}</set>
		<!-- query port of your teamspeak server (default: 10011) -->
		<set name="queryport">{ts_port}</set>
		<!-- Teamspeak virtual server ID -->
		<set name="id">{ts_id}</set>
		<!-- B3 login information. You need to create a ServerQuery Login for B3. video tutorial : http://bit.ly/a5qcjp -->
		<set name="login">{ts_login}</set>
		<set name="password">{ts_password}</set>
	</settings>
	<settings name="teamspeakChannels">
		<set name="B3">B3 autoswitched channel</set>
		<set name="team1">Team 1</set>
		<set name="team2">Team 2</set>
	</settings>
	<settings name="commands">
		<set name="tsreconnect">100</set>
		<set name="tsdisconnect">100</set>
        <set name="teamspeak-ts">0</set>
        <set name="tsauto-tsa">0</set>
	</settings>
</configuration>
""".format(ts_host=config.get("teamspeak_server", "host"),
           ts_port=config.get("teamspeak_server", "port"),
           ts_id=config.get("teamspeak_server", "id"),
           ts_login=config.get("teamspeak_server", "login"),
           ts_password=config.get("teamspeak_server", "password")))
Exemple #55
0
def plugin_maker_xml(console_obj, conf_content):
    conf = XmlConfigParser()
    conf.loadFromString(conf_content)
    return plugin_maker(console_obj, conf)
 def test_loading_invalid_conf(self):
     config = XmlConfigParser()
     try:
         config.loadFromString(r"""<configuration """)
     except ConfigFileNotValid, e:
         self.assertEqual("'unclosed token: line 1, column 0'", str(e))
Exemple #57
0
class Test_getGamemodeSoundingLike(MohwTestCase):
    """
    make sure that getGamemodeSoundingLike returns expected results
    """
    def setUp(self):
        MohwTestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.parser = MohwParser(self.conf)

    def test_CombatMission(self):
        self.assertEqual(
            'CombatMission',
            self.parser.getGamemodeSoundingLike('MP_03', 'CombatMission'))
        self.assertEqual(
            'CombatMission',
            self.parser.getGamemodeSoundingLike('MP_03', 'Combat Mission'))
        self.assertEqual(
            'CombatMission',
            self.parser.getGamemodeSoundingLike('MP_03', 'Combt Mission'))
        self.assertEqual(
            'CombatMission',
            self.parser.getGamemodeSoundingLike('MP_03', 'Mission'))
        self.assertEqual(
            'CombatMission',
            self.parser.getGamemodeSoundingLike('MP_03', 'combat'))
        self.assertEqual('CombatMission',
                         self.parser.getGamemodeSoundingLike('MP_03', 'cm'))

    def test_Sport(self):
        self.assertEqual('Sport',
                         self.parser.getGamemodeSoundingLike('MP_03', 'Sport'))
        self.assertEqual(
            'Sport', self.parser.getGamemodeSoundingLike('MP_03', 'Home Run'))
        self.assertEqual('Sport',
                         self.parser.getGamemodeSoundingLike('MP_03', 'Home'))
        self.assertEqual('Sport',
                         self.parser.getGamemodeSoundingLike('MP_03', 'run'))
        self.assertEqual(
            'Sport', self.parser.getGamemodeSoundingLike('MP_03', 'homerun'))
        self.assertEqual('Sport',
                         self.parser.getGamemodeSoundingLike('MP_03', 'hr'))

    def test_SectorControl(self):
        self.assertEqual(
            'SectorControl',
            self.parser.getGamemodeSoundingLike('MP_03', 'SectorControl'))
        self.assertEqual(
            'SectorControl',
            self.parser.getGamemodeSoundingLike('MP_03', 'Sector Control'))
        self.assertEqual(
            'SectorControl',
            self.parser.getGamemodeSoundingLike('MP_03', 'Sector'))
        self.assertEqual(
            'SectorControl',
            self.parser.getGamemodeSoundingLike('MP_03', 'control'))
        self.assertEqual('SectorControl',
                         self.parser.getGamemodeSoundingLike('MP_03', 'sc'))

    def test_TeamDeathMatch(self):
        self.assertEqual(
            'TeamDeathMatch',
            self.parser.getGamemodeSoundingLike('MP_03', 'TeamDeathMatch'))
        self.assertEqual(
            'TeamDeathMatch',
            self.parser.getGamemodeSoundingLike('MP_03', 'Team DeathMatch'))
        self.assertEqual(
            'TeamDeathMatch',
            self.parser.getGamemodeSoundingLike('MP_03', 'Team Death Match'))
        self.assertEqual(
            'TeamDeathMatch',
            self.parser.getGamemodeSoundingLike('MP_03', 'Death Match'))
        self.assertEqual('TeamDeathMatch',
                         self.parser.getGamemodeSoundingLike('MP_03', 'team'))
        self.assertEqual('TeamDeathMatch',
                         self.parser.getGamemodeSoundingLike('MP_03', 'death'))
        self.assertEqual('TeamDeathMatch',
                         self.parser.getGamemodeSoundingLike('MP_03', 'Match'))
        self.assertEqual('TeamDeathMatch',
                         self.parser.getGamemodeSoundingLike('MP_03', 'tdm'))

    def test_BombSquad(self):
        self.assertEqual(
            'BombSquad',
            self.parser.getGamemodeSoundingLike('MP_03', 'BombSquad'))
        self.assertEqual(
            'BombSquad',
            self.parser.getGamemodeSoundingLike('MP_03', 'Hot Spot'))
        self.assertEqual(
            'BombSquad',
            self.parser.getGamemodeSoundingLike('MP_03', 'Hotspot'))
        self.assertEqual('BombSquad',
                         self.parser.getGamemodeSoundingLike('MP_03', 'hot'))
        self.assertEqual('BombSquad',
                         self.parser.getGamemodeSoundingLike('MP_03', 'spot'))
        self.assertEqual('BombSquad',
                         self.parser.getGamemodeSoundingLike('MP_03', 'Bomb'))
        self.assertEqual('BombSquad',
                         self.parser.getGamemodeSoundingLike('MP_03', 'hs'))

    def test_suggestions(self):
        # unrecognizable input, falling back on available gamemodes for current map
        self.assertEqual(['Team Death Match', 'Combat Mission', 'Home Run'],
                         self.parser.getGamemodeSoundingLike('MP_12', ''))
Exemple #58
0
class InsurgencyTestCase(unittest.TestCase):
    """
    Test case that is suitable for testing Insurgency parser specific features
    """
    @classmethod
    def setUpClass(cls):
        from b3.fake import FakeConsole
        InsurgencyParser.__bases__ = (FakeConsole, )
        # Now parser inheritance hierarchy is :
        # InsurgencyParser -> FakeConsole -> Parser

    def setUp(self):
        self.status_response = None  # defaults to STATUS_RESPONSE module attribute
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""<configuration></configuration>""")
        self.parser = InsurgencyParser(self.conf)
        self.parser.output = Mock()
        self.parser.output.write = Mock(wraps=self.output_write)
        when(self.parser).is_sourcemod_installed().thenReturn(True)
        when(self.parser).getMap().thenReturn('buhriz')

        self.evt_queue = []

        def queue_event(evt):
            self.evt_queue.append(evt)

        self.queueEvent_patcher = patch.object(self.parser,
                                               "queueEvent",
                                               wraps=queue_event)
        self.queueEvent_mock = self.queueEvent_patcher.start()
        self.parser.startup()

    def tearDown(self):
        self.queueEvent_patcher.stop()
        if hasattr(self, "parser"):
            del self.parser.clients
            self.parser.working = False

    def clear_events(self):
        """
        clear the event queue, so when assert_has_event is called, it will look only at the newly caught events.
        """
        self.evt_queue = []

    def assert_has_event(self,
                         event_type,
                         data=WHATEVER,
                         client=WHATEVER,
                         target=WHATEVER):
        """
        assert that self.evt_queue contains at least one event for the given type that has the given characteristics.
        """
        assert isinstance(event_type, basestring)
        expected_event = self.parser.getEvent(event_type, data, client, target)

        if not len(self.evt_queue):
            self.fail("expecting %s. Got no event instead" % expected_event)
        elif len(self.evt_queue) == 1:
            actual_event = self.evt_queue[0]
            self.assertEqual(expected_event.type, actual_event.type)
            if data != WHATEVER:
                self.assertEqual(expected_event.data, actual_event.data)
            if client != WHATEVER:
                self.assertTrue(
                    client_equal(expected_event.client, actual_event.client))
            if target != WHATEVER:
                self.assertTrue(
                    client_equal(expected_event.target, actual_event.target))
        else:
            for evt in self.evt_queue:
                if expected_event.type == evt.type \
                        and (expected_event.data == evt.data or data == WHATEVER) \
                        and (client_equal(expected_event.client, evt.client) or client == WHATEVER) \
                        and (client_equal(expected_event.target, evt.target) or target == WHATEVER):
                    return

            self.fail("expecting event %s. Got instead: %s" %
                      (expected_event, map(str, self.evt_queue)))

    def assert_has_not_event(self,
                             event_type,
                             data=None,
                             client=None,
                             target=None):
        """
        assert that self.evt_queue does not contain at least one event for the given type that has the given characteristics.
        """
        assert isinstance(event_type, basestring)
        unexpected_event = self.parser.getEvent(event_type, data, client,
                                                target)

        if not len(self.evt_queue):
            return
        else:

            def event_match(evt):
                return (unexpected_event.type == evt.type
                        and (data is None or data == evt.data) and
                        (client is None or client_equal(client, evt.client))
                        and
                        (target is None or client_equal(target, evt.target)))

            if any(map(event_match, self.evt_queue)):
                self.fail("not expecting event %s" %
                          (filter(event_match, self.evt_queue)))

    def output_write(self, *args, **kwargs):
        """
        Used to override parser self.output.write method so we can control the
        response given to the 'status' rcon command
        """
        if len(args) and args[0] == "status":
            if self.status_response is not None:
                return self.status_response
            else:
                return STATUS_RESPONSE
Exemple #59
0
class Test_ban(AbstractParser_TestCase):
    def setUp(self):
        AbstractParser_TestCase.setUp(self)
        log = logging.getLogger('output')
        log.setLevel(logging.NOTSET)

        self.conf = XmlConfigParser()
        self.conf.loadFromString("<configuration/>")
        self.parser = ConcretegameParser(self.conf)
        self.parser.PunkBuster = None
        self.parser.ban_with_server = True

        self.getMessage_patcher = patch.object(self.parser, "getMessage")
        getMessage_mock = self.getMessage_patcher.start()
        getMessage_mock.return_value = ""

        self.foo = Mock(spec=Client)
        self.foo.cid = 'f00'
        self.foo.guid = 'EA_AAABBBBCCCCDDDDEEEEFFFF00000'
        self.foo.name = 'f00'
        self.foo.ip = '11.22.33.44'

    def tearDown(self):
        AbstractParser_TestCase.tearDown(self)
        self.getMessage_patcher.stop()


    def test_kick_having_cid_and_guid(self):
        with patch.object(AbstractParser, 'write') as write_mock:
            # GIVEN
            self.assertTrue(self.foo.cid)
            self.assertTrue(self.foo.guid)

            # WHEN
            self.parser.ban(self.foo)

            # THEN
            self.assertTrue(write_mock.called)
            write_mock.assert_has_calls([call(('banList.add', 'guid', self.foo.guid, 'perm', ''))])


    def test_kick_having_cid_and_empty_guid(self):
        with patch.object(AbstractParser, 'write') as write_mock:
            # GIVEN
            self.foo.guid = ''
            self.assertTrue(self.foo.cid)
            self.assertFalse(self.foo.guid)

            # WHEN
            self.parser.ban(self.foo)

            # THEN
            self.assertTrue(write_mock.called)
            write_mock.assert_has_calls([call(('banList.add', 'name', self.foo.name, 'perm', ''))])


    def test_kick_having_no_cid(self):
        with patch.object(AbstractParser, 'write') as write_mock:
            # GIVEN
            self.foo.cid = None
            self.assertFalse(self.foo.cid)

            # WHEN
            self.parser.ban(self.foo)

            # THEN
            self.assertTrue(write_mock.called)
            write_mock.assert_has_calls([call(('banList.add', 'guid', self.foo.guid, 'perm', ''))])
Exemple #60
0
class Test_message(AbstractParser_TestCase):
    def setUp(self):
        self.conf = XmlConfigParser()

    def init(self, config_content):
        self.conf.loadFromString(config_content)
        self.parser = ConcretegameParser(self.conf)
        self.parser.startup()
        self.parser._big_msg_duration = '3.1'

        self.write_patcher = patch.object(AbstractParser, 'write')
        self.write_mock = self.write_patcher.start()

        self.player_mock = Mock(spec=Client, name="player")
        self.player_mock.cid = 'theplayer'

    def tearDown(self):
        AbstractParser_TestCase.tearDown(self)
        self.write_patcher.stop()


    def test_message__no_big_when_big_msg_repeat_off(self):
        # GIVEN
        self.init("""
            <configuration>
                <settings name="thegame">
                    <set name="big_b3_private_responses">off</set>
                    <set name="big_msg_repeat">off</set>
                </settings>
            </configuration>
        """)
        # WHEN
        self.parser.message(self.player_mock, 'test')
        # THEN
        self.assertListEqual([
                                 call(('admin.say', 'test', 'player', self.player_mock.cid))
                             ], self.write_mock.mock_calls)

    def test_message__no_big_when_big_msg_repeat_pm(self):
        # GIVEN
        self.init("""
            <configuration>
                <settings name="thegame">
                    <set name="big_b3_private_responses">off</set>
                    <set name="big_msg_repeat">pm</set>
                </settings>
            </configuration>
        """)
        # WHEN
        self.parser.message(self.player_mock, 'test')
        # THEN
        self.assertListEqual([
                                 call(('admin.say', 'test', 'player', 'theplayer'))
                             ], self.write_mock.mock_calls)

    def test_message__no_big_when_big_msg_repeat_all(self):
        # GIVEN
        self.init("""
            <configuration>
                <settings name="thegame">
                    <set name="big_b3_private_responses">off</set>
                    <set name="big_msg_repeat">all</set>
                </settings>
            </configuration>
        """)
        # WHEN
        self.parser.message(self.player_mock, 'test')
        # THEN
        self.assertListEqual([
                                 call(('admin.say', 'test', 'player', self.player_mock.cid))
                             ], self.write_mock.mock_calls)


    def test_message__when_big_msg_repeat_off(self):
        # GIVEN
        self.init("""
            <configuration>
                <settings name="thegame">
                    <set name="big_b3_private_responses">on</set>
                    <set name="big_msg_repeat">off</set>
                </settings>
            </configuration>
        """)
        # WHEN
        self.parser.message(self.player_mock, 'test')
        # THEN
        self.assertListEqual([
                                 call(('admin.yell', 'test', '3', 'player', self.player_mock.cid))
                             ], self.write_mock.mock_calls)

    def test_message__when_big_msg_repeat_pm(self):
        # GIVEN
        self.init("""
            <configuration>
                <settings name="thegame">
                    <set name="big_b3_private_responses">on</set>
                    <set name="big_msg_repeat">pm</set>
                </settings>
            </configuration>
        """)
        # WHEN
        self.parser.message(self.player_mock, 'test')
        # THEN
        self.assertListEqual([
                                 call(('admin.yell', 'test', '3', 'player', self.player_mock.cid)),
                                 call(('admin.say', 'test', 'player', 'theplayer'))
                             ], self.write_mock.mock_calls)

    def test_message__when_big_msg_repeat_all(self):
        # GIVEN
        self.init("""
            <configuration>
                <settings name="thegame">
                    <set name="big_b3_private_responses">on</set>
                    <set name="big_msg_repeat">all</set>
                </settings>
            </configuration>
        """)
        # WHEN
        self.parser.message(self.player_mock, 'test')
        # THEN
        self.assertListEqual([
                                 call(('admin.yell', 'test', '3', 'player', self.player_mock.cid)),
                                 call(('admin.say', 'test', 'player', self.player_mock.cid))
                             ], self.write_mock.mock_calls)