Ejemplo n.º 1
0
class SpamcontrolTestCase(B3TestCase):
    """ Ease testcases that need an working B3 console and need to control the Spamcontrol plugin config """

    def setUp(self):
        self.timer_patcher = patch('threading.Timer')
        self.timer_patcher.start()

        self.log = logging.getLogger('output')
        self.log.propagate = False

        B3TestCase.setUp(self)
        self.console.startup()
        self.log.propagate = True

    def tearDown(self):
        B3TestCase.tearDown(self)
        self.timer_patcher.stop()

    def init_plugin(self, config_content):
        self.conf = XmlConfigParser()
        self.conf.setXml(config_content)
        self.p = SpamcontrolPlugin(self.console, self.conf)

        self.log.setLevel(logging.DEBUG)
        self.log.info("============================= Spamcontrol plugin: loading config ============================")
        self.p.onLoadConfig()
        self.log.info("============================= Spamcontrol plugin: starting  =================================")
        self.p.onStartup()
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)
Ejemplo n.º 3
0
 def testAdmins():
     conf = XmlConfigParser()
     conf.setXml("""
   <configuration plugin="adv">
     <settings name="settings">
         <set name="rate">1s</set>
     </settings>
     <ads>
         <ad>^2Do you like B3? Consider donating to the project at www.BigBrotherBot.net</ad>
         <ad>@admins</ad>
     </ads>
 </configuration>
     """)
     p = AdvPlugin(fakeConsole, conf)
     p.onStartup()
     
     p.adv()
     print "-----------------------------"
     time.sleep(4)
     joe.connects(1)
     time.sleep(4)
     moderator.connects(2)
     time.sleep(4)
     superadmin.connects(3)
     
     time.sleep(60)
Ejemplo n.º 4
0
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 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 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'))
Ejemplo n.º 7
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"))
Ejemplo n.º 8
0
    def setUp(self):
        BF3TestCase.setUp(self)
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""
                <configuration>
                </configuration>
            """)
        self.console = Bf3Parser(self.conf)

        from b3 import __file__ as b3_module__file__
        admin_config_file = os.path.normpath(os.path.join(os.path.dirname(b3_module__file__), "conf/plugin_admin.xml"))
        admin_config = XmlConfigParser()
        admin_config.load(admin_config_file)
        self.adminPlugin = AdminPlugin(self.console, admin_config)
        self.adminPlugin.onLoadConfig()
        self.adminPlugin.onStartup()
        when(self.console).getPlugin('admin').thenReturn(self.adminPlugin)

        # monkeypatch the admin plugin
        self.console.patch_b3_admin_plugin()

        self.changeMap_patcher = patch.object(self.console, "changeMap")
        self.changeMap_mock = self.changeMap_patcher.start()

        self.player = FakeClient(self.console, name="Player1", guid="Player1GUID", groupBits=128)
        self.player.connects("p1")

        # GIVEN
        self.console.game.gameType = 'ConquestLarge0'
        when(self.console).write(('mapList.list', 0)).thenReturn(['4', '3', 'MP_001', 'RushLarge0', '1', 'MP_003',
                                                                  'ConquestSmall0', '2', 'XP5_001', 'ConquestSmall0',
                                                                  '2', 'MP_007', 'SquadDeathMatch0', '3'])
        when(self.console).write(('mapList.getMapIndices',)).thenReturn(['0', '0'])
Ejemplo n.º 9
0
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
Ejemplo n.º 10
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
Ejemplo n.º 11
0
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
Ejemplo n.º 12
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()
Ejemplo n.º 13
0
class CensorurtTestCase(B3TestCase):
    """
    Ease testcases that need an working B3 console and need to control the censorurt plugin config
    """
    def setUp(self):
        # Timer needs to be patched or the Censor plugin would schedule a 2nd check one minute after
        # penalizing a player.
        self.timer_patcher = patch('threading.Timer')
        self.timer_patcher.start()

        self.log = logging.getLogger('output')
        self.log.propagate = False

        B3TestCase.setUp(self)
        self.console.startup()
        self.log.propagate = True

        self.joe = FakeClient(self.console, name="Joe", exactName="Joe", guid="zaerezarezar", groupBits=1, team=b3.TEAM_UNKNOWN)

        self.conf = XmlConfigParser()
        self.p = CensorurtPlugin(self.console, self.conf)

    def tearDown(self):
        B3TestCase.tearDown(self)
        self.timer_patcher.stop()

    def init_plugin(self, config_content):
        self.conf.setXml(config_content)
        self.log.setLevel(logging.DEBUG)
        self.log.info("============================= Censor plugin: loading config ============================")
        self.p.onLoadConfig()
        self.log.info("============================= Censor plugin: starting  =================================")
        self.p.onStartup()
Ejemplo n.º 14
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'))
Ejemplo n.º 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'))
Ejemplo n.º 16
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'))
 def test_nominal(self):
     conf = XmlConfigParser()
     conf.setXml("""
     <configuration plugin="teamspeakbf">
     	<settings name="teamspeakServer">
             <set name="host">foo_host</set>
             <set name="queryport">foo_queryport</set>
             <set name="id">1</set>
             <set name="login">foo_login</set>
             <set name="password">foo_password</set>
         </settings>
         <settings name="teamspeakChannels">
             <set name="B3">channel name</set>
             <set name="team1">Team 1 name</set>
             <set name="team2">Team 2 name</set>
             <set name="DefaultTarget">team</set>
         </settings>
     </configuration>
     """)
     p = TeamspeakbfPlugin(fakeConsole, conf)
     p.readConfig()
     self.assertEqual('channel name', p.TS3ChannelB3)
     self.assertEqual('Team 1 name', p.TS3ChannelTeam1)
     self.assertEqual('Team 2 name', p.TS3ChannelTeam2)
     self.assertEqual('team', p.autoswitchDefaultTarget)
Ejemplo n.º 18
0
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()
Ejemplo n.º 19
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)
Ejemplo n.º 20
0
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)
Ejemplo n.º 21
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)
Ejemplo n.º 22
0
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 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
Ejemplo n.º 24
0
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)
Ejemplo n.º 25
0
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
Ejemplo n.º 26
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', ''))
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 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 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
Ejemplo n.º 31
0
 def setUp(self):
     B3TestCase.setUp(self)
     self.conf = XmlConfigParser()
     self.p = AdminPlugin(self.console, self.conf)
Ejemplo n.º 32
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._settings['big_b3_private_responses'] = None
        self.conf.loadFromString(config)
        self.parser.load_conf_big_b3_private_responses()
        self.assertEqual(expected,
                         self.parser._settings['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._settings['big_msg_duration'] = None
        self.conf.loadFromString(config)
        self.parser.load_conf_big_msg_duration()
        self.assertEqual(expected, self.parser._settings['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>""")
Ejemplo n.º 33
0
 def setUp(self):
     self.conf = XmlConfigParser()
     self.conf.loadFromString("""<configuration/>""")
     self.parser = AbstractParser(self.conf)
     log = logging.getLogger('output')
     log.setLevel(logging.DEBUG)
Ejemplo n.º 34
0
class Test_tempban(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'

    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.tempban(self.foo)

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

    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.tempban(self.foo)

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

    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.tempban(self.foo)

            # THEN
            self.assertTrue(write_mock.called)
            write_mock.assert_has_calls([
                call(('banList.add', 'guid', self.foo.guid, 'seconds', '120',
                      ''))
            ])
Ejemplo n.º 35
0
 def setUp(self):
     B3TestCase.setUp(self)
     self.conf = XmlConfigParser()
     self.conf.loadFromString("""<configuration/>""")
     log = logging.getLogger('output')
     log.setLevel(logging.DEBUG)
Ejemplo n.º 36
0
    def test1():
        conf = XmlConfigParser()
        conf.setXml("""
    <configuration plugin="adv">
        <!--
            Note: within ads, you can use the following variables : @nextmap @time
            or rules as defined in the admin plugin config file. ie: /spam#rule1
        -->
        <settings name="settings">
            <!-- rate in minutes-->
            <set name="rate">5</set>
            <!--
                you can either set here a text file that will contain one ad per line
                or fill the <ads> section below
            -->
            <!-- <set name="ads">c:/somewhere/my_ads.txt</set> -->
        </settings>
      <settings name="newsfeed">
            <!--
                you can include newsitems in your adds by setting the section below
                you can add feeditems in the adds like this:
                @feed   (will pick the next newsitem each time it is included in the rotation,
                   rotating until 'items' is reached and then start over.)
                @feed 0 (will pick the latest newsitem available from the feed and add it in the rotation)
                @feed 1 (will pick the second latest item in line)
                etc.
            -->
            <set name="url">http://forum.bigbrotherbot.net/news-2/?type=rss;action=.xml</set>
            <set name="url.bak"></set>
            <set name="items">5</set>
            <set name="pretext">News: </set>
        </settings>
        <ads>
            <ad>^2Big Brother Bot is watching you... www.BigBrotherBot.net</ad>
            <ad>@topstats</ad>
            <ad>@feed</ad>
            <ad>/spam#rule1</ad>
            <ad>@time</ad>
            <ad>@feed</ad>
            <ad>^2Do you like B3? Consider donating to the project at www.BigBrotherBot.net</ad>
            <ad>@nextmap</ad>
        </ads>
    </configuration>
        """)
        p = AdvPlugin(fakeConsole, conf)
        p.onStartup()

        p.adv()
        print "-----------------------------"
        time.sleep(2)

        joe.connects(1)
        joe._maxLevel = 100
        joe.says('!advlist')
        time.sleep(2)
        joe.says('!advrem 0')
        time.sleep(2)
        joe.says('!advrate 5s')
        time.sleep(5)

        time.sleep(60)
Ejemplo n.º 37
0
class IpbanTestCase(unittest2.TestCase):
    def setUp(self):

        if B3version(b3_version) >= B3version("1.10dev"):
            from b3.config import MainConfig
            self.parser_conf = MainConfig(CfgConfigParser(allow_no_value=True))
            self.parser_conf.loadFromString(dedent(r""""""))
            admin_plugin_conf_file = '@b3/conf/plugin_admin.ini'
        else:
            self.parser_conf = XmlConfigParser()
            self.parser_conf.loadFromString(
                dedent(r"""<configuration></configuration>"""))
            admin_plugin_conf_file = '@b3/conf/plugin_admin.xml'

        self.console = FakeConsole(self.parser_conf)
        self.console.gameName = 'f00'
        self.console.startup()

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

        self.evt_queue = []

        # 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

        # prepare a few players
        self.mike = FakeClient(self.console,
                               name="Mike",
                               exactName="Mike",
                               guid="MIKEGUID",
                               groupBits=16,
                               ip='1.1.1.1')
        self.paul = FakeClient(self.console,
                               name="Paul",
                               exactName="Paul",
                               guid="PAULGUID",
                               groupBits=1,
                               ip='2.2.2.2')
        self.john = FakeClient(self.console,
                               name="John",
                               exactName="John",
                               guid="JOHNGUID",
                               groupBits=0,
                               ip='3.3.3.3')
        self.mary = FakeClient(self.console,
                               name="Mary",
                               exactName="Mary",
                               guid="MARYGUID",
                               groupBits=0,
                               ip='4.4.4.4')

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

        # return some mock data
        when(self.p).getBanIps().thenReturn(['2.2.2.2', '6.6.6.6', '7.7.7.7'])
        when(self.p).getTempBanIps().thenReturn(
            ['3.3.3.3', '8.8.8.8', '9.9.9.9'])

    def tearDown(self):
        self.console.working = False
        self.mike.disconnects()
        self.paul.disconnects()
        self.john.disconnects()
        self.mary.disconnects()

    def init(self, config_content=None):
        if config_content:
            self.conf.loadFromString(config_content)
        else:
            self.conf.loadFromString(
                dedent(r"""
                [settings]
                maxlevel: user
            """))
        self.p.onLoadConfig()
        self.p.onStartup()

    ####################################################################################################################
    #                                                                                                                  #
    #   TEST CONFIG                                                                                                    #
    #                                                                                                                  #
    ####################################################################################################################

    def test_with_config_content(self):
        # GIVEN
        self.init(
            dedent(r"""
            [settings]
            maxlevel: admin
        """))
        # THEN
        self.assertEqual(self.p._maxLevel, 40)

    def test_with_empty_config(self):
        # GIVEN
        self.init(dedent(r"""
            [settings]
        """))
        # THEN
        self.assertEqual(self.p._maxLevel, 1)

    ####################################################################################################################
    #                                                                                                                  #
    #   TEST EVENTS                                                                                                    #
    #                                                                                                                  #
    ####################################################################################################################

    def test_higher_group_level_client_connect(self):
        # GIVEN
        self.init()
        self.mike.kick = Mock()
        # WHEN
        self.mike.connects('1')
        # THEN
        self.assertGreater(self.mike.maxLevel, self.p._maxLevel)
        self.assertEqual(self.mike.kick.call_count, 0)

    def test_ip_banned_client_connect(self):
        # GIVEN
        self.init()
        self.paul.kick = Mock()
        # WHEN
        self.paul.connects('1')
        # THEN
        self.assertLessEqual(self.paul.maxLevel, self.p._maxLevel)
        self.assertIn(self.paul.ip, self.p.getBanIps())
        self.paul.kick.assert_called_once_with(
            'Netblocker: Client refused: 2.2.2.2 (Paul) has an active Ban')

    def test_ip_temp_banned_client_connect(self):
        # GIVEN
        self.init()
        self.john.kick = Mock()
        # WHEN
        self.john.connects('1')
        # THEN
        self.assertLessEqual(self.paul.maxLevel, self.p._maxLevel)
        self.assertIn(self.john.ip, self.p.getTempBanIps())
        self.john.kick.assert_called_once_with(
            'Netblocker: Client refused: 3.3.3.3 (John) has an active TempBan')

    def test_clean_client_connect(self):
        # GIVEN
        self.init()
        self.mary.kick = Mock()
        # WHEN
        self.mary.connects('1')
        # THEN
        self.assertLessEqual(self.paul.maxLevel, self.p._maxLevel)
        self.assertNotIn(self.mary.ip, self.p.getBanIps())
        self.assertNotIn(self.mary.ip, self.p.getTempBanIps())
        self.assertEqual(self.mary.kick.call_count, 0)
Ejemplo n.º 38
0
class Test_parser_API(Arma2TestCase):
    def setUp(self):
        self.conf = XmlConfigParser()
        self.conf.loadFromString("""<configuration></configuration>""")
        self.parser = Arma2Parser(self.conf)
        self.parser.output = Mock()

        self.parser.sayqueue.put = Mock(side_effect=self.parser._say)

        self.parser.startup()

        self.player = self.parser.clients.newClient(cid="4",
                                                    guid="theGuid",
                                                    name="theName",
                                                    ip="11.22.33.44")

    def test_getPlayerList(self, sleep_mock):
        # GIVEN
        when(self.parser.output).write('players').thenReturn(u'''\
Players on server:
[#] [IP Address]:[Port] [Ping] [GUID] [Name]
--------------------------------------------------
0   11.111.11.11:2304     63   80a5885eb00000000000000000000000(OK) étoiléàÄ
0   192.168.0.100:2316    0    80a5885eb00000000000000000000000(OK) étoiléàÄ (Lobby)
(1 players in total)
''')
        # WHEN
        players = self.parser.getPlayerList()
        # THEN
        self.maxDiff = 1024
        self.assertDictEqual(
            {
                u'0': {
                    'cid': u'0',
                    'guid': u'80a5885eb00000000000000000000000',
                    'ip': u'192.168.0.100',
                    'lobby': True,
                    'name': u'étoiléàÄ',
                    'ping': u'0',
                    'port': u'2316',
                    'verified': u'OK'
                }
            }, players)

    def test_say(self, sleep_mock):
        # GIVEN
        self.parser.msgPrefix = "[Pre]"
        # WHEN
        self.parser.say("f00")
        # THEN
        self.parser.output.write.assert_has_calls([call('say -1 [Pre] f00')])

    def test_saybig(self, sleep_mock):
        # GIVEN
        self.parser.msgPrefix = "[Pre]"
        # WHEN
        self.parser.saybig("f00")
        # THEN
        self.parser.output.write.assert_has_calls([call('say -1 [Pre] f00')])

    def test_message(self, sleep_mock):
        # GIVEN
        self.parser.msgPrefix = "[Pre]"
        # WHEN
        self.parser.message(self.player, "f00")
        # THEN
        self.parser.output.write.assert_has_calls([call('say 4 [Pre] f00')])

    def test_kick(self, sleep_mock):
        self.parser.kick(self.player, reason="f00")
        self.parser.output.write.assert_has_calls([call('kick 4 f00')])

    def test_ban__by_cid(self, sleep_mock):
        self.assertIsNotNone(self.player.cid)
        self.parser.ban(self.player, reason="f00")
        self.parser.output.write.assert_has_calls(
            [call('ban 4 0 f00'), call('writeBans')])

    def test_ban__by_guid(self, sleep_mock):
        self.player.cid = None
        self.assertIsNone(self.player.cid)
        self.parser.ban(self.player, reason="f00")
        self.parser.output.write.assert_has_calls(
            [call('addBan theGuid 0 f00'),
             call('writeBans')])

    def test_unban(self, sleep_mock):
        # GIVEN
        self.player.cid = None
        self.assertIsNone(self.player.cid)
        when(self.parser).getBanlist().thenReturn({
            'theGuid': {
                'ban_index': '152',
                'guid': 'theGuid',
                'reason': 'the ban reason',
                'min_left': 'perm'
            },
        })
        # WHEN
        self.parser.unban(self.player, reason="f00")
        # THEN
        self.parser.output.write.assert_has_calls(
            [call('removeBan 152'), call('writeBans')])

    def test_tempban__by_cid(self, sleep_mock):
        self.assertIsNotNone(self.player.cid)
        self.parser.tempban(self.player, reason="f00", duration='2h')
        self.parser.output.write.assert_has_calls(
            [call('ban 4 120 f00'), call('writeBans')])

    def test_tempban__by_guid(self, sleep_mock):
        self.player.cid = None
        self.assertIsNone(self.player.cid)
        self.parser.tempban(self.player, reason="f00", duration='2h')
        self.parser.output.write.assert_has_calls(
            [call('addBan theGuid 120 f00'),
             call('writeBans')])

#
#    def test_getMap(self, sleep_mock):
#        pass
#
#
#    def test_getMaps(self, sleep_mock):
#        pass
#
#
#    def test_rotateMap(self, sleep_mock):
#        pass
#
#
#    def test_changeMap(self, sleep_mock):
#        pass

    def test_getPlayerPings(self, sleep_mock):
        # GIVEN
        when(self.parser.output).write('players').thenReturn(u'''\
Players on server:
[#] [IP Address]:[Port] [Ping] [GUID] [Name]
--------------------------------------------------
0   76.108.91.78:2304     63   80a5885ebe2420bab5e158a310fcbc7d(OK) Bravo17
0   192.168.0.100:2316    0    80a5885ebe2420bab5e158a310fcbc7d(OK) Bravo17 (Lobby)
2   111.22.3.4:2316       47   80a50000000000000000000000fcbc7d(?)  bob
(1 players in total)
''')
        # WHEN
        pings = self.parser.getPlayerPings()
        # THEN
        self.maxDiff = 1024
        self.assertDictEqual({u'0': 63, u'2': 47}, pings)
Ejemplo n.º 39
0
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, str)

        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, list(map(str, self.evt_queue))))
Ejemplo n.º 40
0
from tests import *
prepare_fakeparser_for_tests()

import unittest
import b3

from b3.fake import fakeConsole
from b3.fake import joe
import time

from b3.config import XmlConfigParser
from teamspeak import TeamspeakPlugin

conf = XmlConfigParser()
conf.setXml("""
<configuration plugin="teamspeakbf">
	<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>
Ejemplo n.º 41
0
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<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.assertEquals(
            '''Event<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<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<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<PunkBuster client connection lost>({'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"
        )
Ejemplo n.º 42
0
# -*- encoding: utf-8 -*-
from tests import prepare_fakeparser_for_tests
prepare_fakeparser_for_tests()

from b3.fake import fakeConsole
from poweradminbf3 import Poweradminbf3Plugin
from b3.config import XmlConfigParser



conf = XmlConfigParser()
conf.loadFromString("""
<configuration plugin="poweradminbf3">
  <settings name="commands">
    <set name="setmode-mode">60</set>

    <set name="roundnext-rnext">40</set>
    <set name="roundrestart-rrestart">40</set>
    <set name="kill">40</set>

    <set name="changeteam">20</set>
    <set name="swap">20</set>
    <set name="setnextmap-snmap">20</set>
  </settings>
  <settings name="messages">
    <set name="operation_denied">Operation denied</set>
    <set name="operation_denied_level">Operation denied because %(name)s is in the %(group)s group</set>
  </settings>
</configuration>
""")
Ejemplo n.º 43
0
# -*- encoding: utf-8 -*-
from tests import prepare_fakeparser_for_tests
prepare_fakeparser_for_tests()

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

conf = XmlConfigParser()
conf.loadFromString("""
<configuration plugin="poweradminbf3">
  <settings name="commands">
    <set name="kill">0</set>
  </settings>
</configuration>
""")

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

simon.connects("simon")
simon.teamId = 1
simon.squad = 7
joe.connects('Joe')
joe.teamId = 1
joe.squad = 7
superadmin.connects('superadmin')
superadmin.teamId = 2
superadmin.squad = 6
print "Joe's group is " + joe.maxGroup.name
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', ''))
Ejemplo n.º 45
0
    def setUp(self):

        if B3version(b3_version) >= B3version("1.10dev"):
            from b3.config import MainConfig
            self.parser_conf = MainConfig(CfgConfigParser(allow_no_value=True))
            self.parser_conf.loadFromString(dedent(r""""""))
            admin_plugin_conf_file = '@b3/conf/plugin_admin.ini'
        else:
            self.parser_conf = XmlConfigParser()
            self.parser_conf.loadFromString(
                dedent(r"""<configuration></configuration>"""))
            admin_plugin_conf_file = '@b3/conf/plugin_admin.xml'

        self.console = FakeConsole(self.parser_conf)
        self.console.gameName = 'f00'
        self.console.startup()

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

        self.evt_queue = []

        # 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

        # prepare a few players
        self.mike = FakeClient(self.console,
                               name="Mike",
                               exactName="Mike",
                               guid="MIKEGUID",
                               groupBits=16,
                               ip='1.1.1.1')
        self.paul = FakeClient(self.console,
                               name="Paul",
                               exactName="Paul",
                               guid="PAULGUID",
                               groupBits=1,
                               ip='2.2.2.2')
        self.john = FakeClient(self.console,
                               name="John",
                               exactName="John",
                               guid="JOHNGUID",
                               groupBits=0,
                               ip='3.3.3.3')
        self.mary = FakeClient(self.console,
                               name="Mary",
                               exactName="Mary",
                               guid="MARYGUID",
                               groupBits=0,
                               ip='4.4.4.4')

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

        # return some mock data
        when(self.p).getBanIps().thenReturn(['2.2.2.2', '6.6.6.6', '7.7.7.7'])
        when(self.p).getTempBanIps().thenReturn(
            ['3.3.3.3', '8.8.8.8', '9.9.9.9'])
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(''))
# -*- encoding: utf-8 -*-
import os
from tests import prepare_fakeparser_for_tests
prepare_fakeparser_for_tests()

from b3.fake import fakeConsole
from b3.fake import admin

from poweradminbf3 import Poweradminbf3Plugin

from b3.config import XmlConfigParser

conf = XmlConfigParser()
conf.setXml("""
<configuration plugin="poweradminbf3">
    <settings name="commands">
        <set name="listconfig">40</set>
    </settings>
    <settings name="preferences">
        <set name="config_path">%(script_dir)s</set>
    </settings>
</configuration>
""" % {'script_dir': os.path.abspath(os.path.join(os.path.dirname(__file__), '../extplugins/conf/serverconfigs'))})

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

admin.connects(2)
admin.says('!listconfig')
Ejemplo n.º 48
0
# -*- encoding: utf-8 -*-
from tests import *
prepare_fakeparser_for_tests()

from b3.fake import fakeConsole, superadmin
from teamspeakbf import TeamspeakbfPlugin
from b3.config import XmlConfigParser

conf = XmlConfigParser()
conf.loadFromString("""
<configuration plugin="teamspeakbf">
	<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>
Ejemplo n.º 49
0
    def save(self):
        self.playTime += ( (time.time() - time.timezone) - self.lastEventTime ) / 60
        #DelayedSQLObject.save(self)
"""

if __name__ == '__main__':
    """
    Automated tests below
    """
    from b3.fake import fakeConsole
    from b3.fake import superadmin, joe
    import time

    from b3.config import XmlConfigParser

    conf = XmlConfigParser()
    conf.setXml("""
<configuration plugin="stats">
  <settings name="commands">
    <set name="mapstats-mystatalias">0</set>
    <set name="testscore-tscr">0</set>
    <set name="topstats-tops">2</set>
    <set name="topxp-txp">2</set>
  </settings>
  <settings name="settings">
    <set name="startPoints">100</set>
    <set name="resetscore">no</set>
    <set name="resetxp">no</set>
  </settings>
</configuration>
    """)
Ejemplo n.º 50
0
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()
        map(game_modes_found.update, 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('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('f00', self.parser.getHardName('f00'))

    def test_getMapsSoundingLike(self):
        self.assertEqual(['operation metro', 'gulf of oman', 'seine crossing'],
                         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 firestorm', 'operation 925'],
            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'))

    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(['Team Deathmatch', 'Squad 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(
            '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')
    def setUp(self):
        # create a B3 FakeConsole
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString(r"""<configuration/>""")
        self.console = FakeConsole(self.parser_conf)

        # create our plugin instance
        self.plugin_conf = CfgConfigParser()
        self.p = Weaponlimiterbf3Plugin(self.console, self.plugin_conf)

        # initialise the plugin
        self.plugin_conf.loadFromString(r'''
[commands]
weaponlimiter-wpl: 60
weaponlimits: guest
noobkill: 20

[settings]
change servermessage: yes
self_kill_counter: 1
config_strategy: mapname
display_extra_msg: message
yell_duration: 10

[punisher]
kill_player: no
warn_player: yes

[messages]
servermessage: This game uses weapons limits. Use !weaponlimits to show forbidden weapons.
weaponlimiter_enabled: WeaponLimiter for that round activated!
weaponlimiter_disabled: Weaponlimiter disabled! All Weapons allowed.
warn_message: You used a forbidden weapon! ^7!forbidden_weapons show the list of forbidden weapons
forbidden_message: Forbidden Weapons are: %s
allowed_message: Allowed Weapons: %s
extra_warning_message: You have %(victim)s killed with a %(weapon)s. This weapon is forbidden!

[XP2_Skybar]
banned weapons: SMAW, M320, RPG-7, USAS-12
gametype: Domination0
weapons: Weapons/Gadgets/C4/C4,870MCS,DAO-12,jackhammer,M1014,M26Mass,Siaga20k,SPAS-12,USAS-12
''')

        # fake BF3 game
        self.console.game.gameName = 'bf3'
        self.console.game.gameType = 'Domination0'
        self.console.game._mapName = 'XP2_Skybar'
        # startup plugin
        self.p.onLoadConfig()
        self.p.onStartup()
        # enable
        self.p._wpl_is_active = True
        # prepare a few players
        self.joe = FakeClient(self.console,
                              name="Joe",
                              exactName="Joe",
                              guid="zaerezarezar",
                              groupBits=1)
        self.simon = FakeClient(self.console,
                                name="Simon",
                                exactName="Simon",
                                guid="qsdfdsqfdsqf",
                                groupBits=0)
        self.admin = FakeClient(
            self.console,
            name="Level-40-Admin",
            exactName="Level-40-Admin",
            guid="875sasda",
            groupBits=16,
        )
        self.superadmin = FakeClient(self.console,
                                     name="God",
                                     exactName="God",
                                     guid="f4qfer654r",
                                     groupBits=128)
Ejemplo n.º 52
0
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)
Ejemplo n.º 53
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
Ejemplo n.º 54
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()
        # 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.assertEquals('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.assertEquals('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("Team Say", self.parser.getEventName(event.type))
        self.assertEquals('test squad', event.data)
        self.assertEqual(self.joe, event.client)
Ejemplo n.º 55
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)

    def test_slash_no_prefix_no_command(self):
        self.assertNotIn('non_existing_command',
                         self.admin_plugin_mock._commands)
        self.assertEqual(
            '/non_existing_command',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '/non_existing_command',
                                           'all')).data)

    def test_slash_no_prefix_command(self):
        self.admin_plugin_mock._commands['exiting_command'] = Mock()
        self.assertIn('exiting_command', self.admin_plugin_mock._commands)
        self.assertEqual(
            '!exiting_command',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '/exiting_command',
                                           'all')).data)
        self.assertEqual(
            '!exiting_command',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '!exiting_command',
                                           'all')).data)
        self.admin_plugin_mock._commands['a'] = Mock()
        self.assertIn('a', self.admin_plugin_mock._commands)
        self.assertEqual(
            '!a',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '/a', 'all')).data)
        self.assertEqual(
            '!a',
            self.parser.OnPlayerChat(action=None,
                                     data=('joe', '!a', 'all')).data)
Ejemplo n.º 56
0
# -*- encoding: utf-8 -*-
import os
import b3
import time
from tests import prepare_fakeparser_for_tests

prepare_fakeparser_for_tests()

from b3.fake import fakeConsole

from poweradminbf3 import Poweradminbf3Plugin

from b3.config import XmlConfigParser

conf = XmlConfigParser()
conf.setXml("""
<configuration plugin="poweradminbf3">
    <settings name="configmanager">
        <set name="status">on</set>
    </settings>
</configuration>
""")
# make B3 think it has a config file on the filesystem
conf.fileName = os.path.join(os.path.dirname(__file__),
                             '../extplugins/conf/plugin_poweradminbf3.xml')

time.sleep(.5)
print "-" * 50
p = Poweradminbf3Plugin(fakeConsole, conf)
p.onLoadConfig()
p.onStartup()
Ejemplo n.º 57
0
class Bf3TestCase(unittest.TestCase):
    """
    Test case that is suitable for testing BF3 parser specific features
    """
    @classmethod
    def setUpClass(cls):
        # less logging
        logging.getLogger('output').setLevel(logging.ERROR)

        with logging_disabled():
            from b3.parsers.frostbite2.abstractParser import AbstractParser
            from b3.fake import FakeConsole
        AbstractParser.__bases__ = (FakeConsole, )

        # Now parser inheritance hierarchy is :
        # Bf3Parser -> AbstractParser -> FakeConsole -> Parser

        # add method changes_team(newTeam, newSquad=None) to FakeClient
        def changes_team(self, newTeam, newSquad=None):
            self.console.OnPlayerTeamchange(
                None,
                data=[self.cid, newTeam, newSquad if newSquad else self.squad])

        from b3.fake import FakeClient
        FakeClient.changes_team = changes_team

    def setUp(self):
        # create a BF3 parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString("""<configuration />""")
        with logging_disabled():
            self.console = Bf3Parser(self.parser_conf)

        # alter a few settings to speed up the tests
        self.console.sayqueue_get_timeout = 0
        self.console._message_delay = 0

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

        # load the admin plugin
        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
        def getPlugin(name):
            if name == 'admin':
                return self.adminPlugin
            else:
                return self.console.getPlugin(name)

        self.console.getPlugin = getPlugin

        self.console.patch_b3_admin_plugin()

        # prepare a few players
        with logging_disabled():
            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
        self.console.wait_for_threads()
        sys.stdout.write("\tactive threads count : %s " %
                         threading.activeCount())
Ejemplo n.º 58
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)
Ejemplo n.º 59
0
    def setUp(self):
        # create a BF3 parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString("""<configuration />""")
        with logging_disabled():
            self.console = Bf3Parser(self.parser_conf)

        # alter a few settings to speed up the tests
        self.console.sayqueue_get_timeout = 0
        self.console._message_delay = 0

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

        # load the admin plugin
        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
        def getPlugin(name):
            if name == 'admin':
                return self.adminPlugin
            else:
                return self.console.getPlugin(name)

        self.console.getPlugin = getPlugin

        self.console.patch_b3_admin_plugin()

        # prepare a few players
        with logging_disabled():
            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)
            if status.getBoolean():
                self.debug('Playlist Enabled')
                return True
            else:
                self.debug('Playlist Disabled')
                return False


#-------------------------------------------------------------------------------------

if __name__ == '__main__':
    from b3.fake import fakeConsole
    from b3.fake import superadmin
    from b3.config import XmlConfigParser

    conf = XmlConfigParser()
    conf.loadFromString('''
        <configuration plugin="poweradmincod7">
            <settings name="commands">
                <!--
                Following command works on RANKED servers only
                -->
                <set name="pasetmap-setmap">40</set>
                <!--
                Following commands work both on RANKED and UNRANKED servers
                -->
                <set name="paplaylist-playlist">40</set>
                <set name="pagetplaylists-getplaylists">100</set>
                <set name="pasetplaylist-setplaylist">100</set>
                <set name="paexcludemaps-excludemaps">100</set>
                <set name="paversion">1</set>