示例#1
0
    def test_nominal(self):
        # GIVEN
        conf = CfgConfigParser()
        conf.loadFromString(
            dedent(r"""
            [commands]
            mapstats-stats: 2
            testscore-ts: 2
            topstats-top: 20
            topxp: 20

            [settings]
            startPoints: 150
            resetscore: yes
            resetxp: yes
            show_awards: yes
            show_awards_xp: yes
        """))
        self.p = StatsPlugin(self.console, conf)
        # WHEN
        self.p.onLoadConfig()
        # THEN
        self.assertEqual(2, self.p.mapstatslevel)
        self.assertEqual(2, self.p.testscorelevel)
        self.assertEqual(20, self.p.topstatslevel)
        self.assertEqual(20, self.p.topxplevel)
        self.assertEqual(150, self.p.startPoints)
        self.assertTrue(self.p.resetscore)
        self.assertTrue(self.p.resetxp)
        self.assertTrue(self.p.show_awards)
        self.assertTrue(self.p.show_awards_xp)
示例#2
0
class Test_cmd_jump(Iourt42TestCase):
    def setUp(self):
        super(Test_cmd_jump, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString(
            """
[commands]
pajump-jump: 20           ; change game type to Jump
        """
        )
        self.p = PoweradminurtPlugin(self.console, self.conf)
        self.init_default_cvar()
        self.p.onLoadConfig()
        self.p.onStartup()

        self.console.say = Mock()
        self.console.write = Mock()

        self.moderator.connects("2")

    def test_nominal(self):
        self.moderator.message_history = []
        self.moderator.says("!jump")
        self.console.write.assert_has_calls([call('set g_gametype "9"')])
        self.assertEqual(["game type changed to Jump"], self.moderator.message_history)
示例#3
0
    def setUp(self):
        # create a FakeConsole parser
        parser_ini_conf = CfgConfigParser()
        parser_ini_conf.loadFromString(r'''''')
        self.parser_main_conf = MainConfig(parser_ini_conf)

        with logging_disabled():
            from tests.fake import FakeConsole
            self.console = FakeConsole(self.parser_main_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).getPlugin('admin').thenReturn(self.adminPlugin)

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

        with logging_disabled():
            from tests.fake import FakeClient

        self.mike = FakeClient(console=self.console,
                               name="Mike",
                               guid="MIKEGUID",
                               groupBits=1)
        self.bill = FakeClient(console=self.console,
                               name="Bill",
                               guid="BILLGUID",
                               groupBits=1)
class mixin_cmd_nuke(object):
    def setUp(self):
        super(mixin_cmd_nuke, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
panuke-nuke: 20
        """)
        self.p = PoweradminurtPlugin(self.console, self.conf)
        self.init_default_cvar()
        self.p.onLoadConfig()
        self.p.onStartup()

        self.sleep_patcher = patch.object(time, 'sleep')
        self.sleep_patcher.start()

        self.console.say = Mock()
        self.console.saybig = Mock()
        self.console.write = Mock()

        self.moderator.connects("2")


    def tearDown(self):
        super(mixin_cmd_nuke, self).tearDown()
        self.sleep_patcher.stop()


    def test_no_argument(self):
        self.moderator.message_history = []
        self.moderator.says("!nuke")
        self.assertEqual(['Invalid data, try !help panuke'], self.moderator.message_history)
        self.console.write.assert_has_calls([])


    def test_unknown_player(self):
        self.moderator.message_history = []
        self.moderator.says("!nuke f00")
        self.assertEqual(['No players found matching f00'], self.moderator.message_history)
        self.console.write.assert_has_calls([])

    def test_joe(self):
        self.joe.connects('3')
        self.moderator.message_history = []
        self.moderator.says("!nuke joe")
        self.assertEqual([], self.moderator.message_history)
        self.assertEqual([], self.joe.message_history)
        self.console.write.assert_has_calls([call('nuke 3')])

    def test_joe_multi(self):
        def _start_new_thread(function, args):
            function(*args)

        with patch.object(thread, 'start_new_thread', wraps=_start_new_thread):
            self.joe.connects('3')
            self.moderator.message_history = []
            self.moderator.says("!nuke joe 3")
            self.assertEqual([], self.moderator.message_history)
            self.assertEqual([], self.joe.message_history)
            self.console.write.assert_has_calls([call('nuke 3'), call('nuke 3'), call('nuke 3')])
class Test_cmd_scramble(Bf3TestCase):
    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
scramble: 20
        """)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
        self.p._scrambler = Mock()
        self.superadmin.connects('superadmin')
        self.superadmin.clearMessageHistory()

    def test_none(self):
        self.p._scrambling_planned = None
        self.superadmin.says('!scramble')
        self.assertEqual(['Teams will be scrambled at next round start'],
                         self.superadmin.message_history)
        self.assertTrue(self.p._scrambling_planned)

    def test_true(self):
        self.p._scrambling_planned = True
        self.superadmin.says('!scramble')
        self.assertEqual(['Teams scrambling canceled for next round'],
                         self.superadmin.message_history)
        self.assertFalse(self.p._scrambling_planned)

    def test_false(self):
        self.p._scrambling_planned = False
        self.superadmin.says('!scramble')
        self.assertEqual(['Teams will be scrambled at next round start'],
                         self.superadmin.message_history)
        self.assertTrue(self.p._scrambling_planned)
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 = CfgConfigParser()
        self.conf.loadFromString(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_yellplayer(Bf3TestCase):

    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
yellplayer: 20

[preferences]
yell_duration: 2
        """)
        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("!yellplayer")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('invalid parameters, try !help yellplayer', self.moderator.message_history[0])

    def test_nominal(self):
        self.joe.connects('joe')
        self.moderator.connects("moderator")
        self.moderator.says("!yellplayer joe changing map soon !")
        self.console.write.assert_called_once_with(('admin.yell', 'changing map soon !', '2', 'player', 'joe'))
class Test_cmd_yellsquad(Bf3TestCase):

    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
yellsquad: 20

[preferences]
yell_duration: 2
        """)
        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("!yellsquad")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('missing parameter, try !help yellsquad', self.moderator.message_history[0])

    def test_nominal(self):
        self.moderator.connects("moderator")
        self.moderator.teamId = 3
        self.moderator.squad = 4
        self.moderator.says("!yellsquad changing map soon !")
        self.console.write.assert_called_once_with(('admin.yell', 'changing map soon !', '2', 'squad', '3', '4'))
class Test_cmd_serverreboot(Bf3TestCase):
    def setUp(self):
        super(Test_cmd_serverreboot, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
serverreboot: 100
        """)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()


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

    def test_frostbite_error(self, sleep_mock):
        self.console.write.expect(('admin.shutDown',)).thenRaise(CommandFailedError(['fOO']))
        self.superadmin.connects("god")
        self.superadmin.message_history = []
        self.superadmin.says("!serverreboot")
        self.console.write.verify_expected_calls()
        self.assertEqual(['Error: fOO'], self.superadmin.message_history)
class mixin_cmd_nuke(object):
    def setUp(self):
        super(mixin_cmd_nuke, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
panuke-nuke: 20
        """)
        self.p = PoweradminurtPlugin(self.console, self.conf)
        self.init_default_cvar()
        self.p.onLoadConfig()
        self.p.onStartup()

        self.sleep_patcher = patch.object(time, 'sleep')
        self.sleep_patcher.start()

        self.console.say = Mock()
        self.console.saybig = Mock()
        self.console.write = Mock()

        self.moderator.connects("2")


    def tearDown(self):
        super(mixin_cmd_nuke, self).tearDown()
        self.sleep_patcher.stop()


    def test_no_argument(self):
        self.moderator.message_history = []
        self.moderator.says("!nuke")
        self.assertEqual(['Invalid data, try !help panuke'], self.moderator.message_history)
        self.console.write.assert_has_calls([])


    def test_unknown_player(self):
        self.moderator.message_history = []
        self.moderator.says("!nuke f00")
        self.assertEqual(['No players found matching f00'], self.moderator.message_history)
        self.console.write.assert_has_calls([])

    def test_joe(self):
        self.joe.connects('3')
        self.moderator.message_history = []
        self.moderator.says("!nuke joe")
        self.assertEqual([], self.moderator.message_history)
        self.assertEqual([], self.joe.message_history)
        self.console.write.assert_has_calls([call('nuke 3')])

    def test_joe_multi(self):
        def _start_new_thread(function, args):
            function(*args)

        with patch.object(thread, 'start_new_thread', wraps=_start_new_thread):
            self.joe.connects('3')
            self.moderator.message_history = []
            self.moderator.says("!nuke joe 3")
            self.assertEqual([], self.moderator.message_history)
            self.assertEqual([], self.joe.message_history)
            self.console.write.assert_has_calls([call('nuke 3'), call('nuke 3'), call('nuke 3')])
示例#11
0
class Test_cmd_instagib(Iourt43TestCase):
    def setUp(self):
        super(Test_cmd_instagib, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
painstagib-instagib: 20           ; change game mode to Instagib
        """)
        self.p = PoweradminurtPlugin(self.console, self.conf)
        self.init_default_cvar()
        self.p.onLoadConfig()
        self.p.onStartup()

        self.console.say = Mock()
        self.console.write = Mock()

        self.moderator.connects("2")

    def test_nominal(self):
        self.moderator.message_history = []
        self.moderator.says("!instagib on")
        self.console.write.assert_has_calls([call('set g_instagib "1"')])

        self.moderator.says("!instagib off")
        self.console.write.assert_has_calls([call('set g_instagib "0"')])
class Test_cmd_skins(Iourt42TestCase):
    def setUp(self):
        super(Test_cmd_skins, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
pagoto-goto: 20         ; set the goto <on/off>
        """)
        self.p = PoweradminurtPlugin(self.console, self.conf)
        self.init_default_cvar()
        self.p.onLoadConfig()
        self.p.onStartup()

        self.console.say = Mock()
        self.console.write = Mock()

        self.moderator.connects("2")

    def test_missing_parameter(self):
        self.moderator.message_history = []
        self.moderator.says("!goto")
        self.assertListEqual(["invalid or missing data, try !help pagoto"], self.moderator.message_history)

    def test_junk(self):
        self.moderator.message_history = []
        self.moderator.says("!goto qsdf")
        self.assertListEqual(["invalid or missing data, try !help pagoto"], self.moderator.message_history)

    def test_on(self):
        self.moderator.says("!goto on")
        self.console.write.assert_has_calls([call('set g_allowgoto "1"')])

    def test_off(self):
        self.moderator.says("!goto off")
        self.console.write.assert_has_calls([call('set g_allowgoto "0"')])
class Test_cmd_punkbuster(Bf3TestCase):
    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString(
            """[commands]
punkbuster-punk: 20
        """
        )
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
        self.superadmin.connects("superadmin")

    def test_pb_inactive(self):
        when(self.console).write(("punkBuster.isActive",)).thenReturn(["false"])
        self.superadmin.clearMessageHistory()
        self.superadmin.says("!punkbuster test")
        self.assertEqual(["Punkbuster is not active"], self.superadmin.message_history)

    def test_pb_active(self):
        when(self.console).write(("punkBuster.isActive",)).thenReturn(["true"])
        self.superadmin.clearMessageHistory()
        self.superadmin.says("!punkbuster test")
        self.assertEqual([], self.superadmin.message_history)
        verify(self.console).write(("punkBuster.pb_sv_command", "test"))

    def test_pb_active(self):
        when(self.console).write(("punkBuster.isActive",)).thenReturn(["true"])
        self.superadmin.clearMessageHistory()
        self.superadmin.says("!punk test")
        self.assertEqual([], self.superadmin.message_history)
        verify(self.console).write(("punkBuster.pb_sv_command", "test"))
class Test_config(Bf3TestCase):
    default_value = 3
    minimum_value = 2

    def assert_config_value(self, expected, conf_value):
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[preferences]
team_swap_threshold: %s
                    """ % conf_value)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.assertEqual(expected, self.p._team_swap_threshold)

    def test_default_value(self):
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[foo]""")
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.assertEqual(self.default_value, self.p._team_swap_threshold)

    def test_nominal(self):
        self.assert_config_value(6, '6')

    def test_value_too_low(self):
        self.assert_config_value(self.minimum_value, '1')

    def test_negative_value(self):
        self.assert_config_value(self.minimum_value, '-2')

    def test_float(self):
        self.assert_config_value(self.default_value, '3.54')

    def test_junk(self):
        self.assert_config_value(self.default_value, 'junk')
class Test_commands(PluginTestCase):
    def setUp(self):
        super(Test_commands, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
vaccheck: 20
        """)
        self.p = VacbanPlugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        when(self.p)._query_service(
            anything()).thenReturn(vac_response_not_banned)
        self.moderator.connects("2")

    def test_vaccheck(self):
        # GIVEN
        self.moderator.message_history = []
        # WHEN
        with patch.object(
                self.p,
                '_checkConnectedPlayers') as mock_checkConnectedPlayers:
            self.moderator.says("!vaccheck")
        # THEN
        self.assertEqual(['checking players ...', 'done'],
                         self.moderator.message_history)
        self.assertEqual(1, mock_checkConnectedPlayers.call_count)
示例#16
0
class mixin_cmd_version:
    def setUp(self):
        super(mixin_cmd_version, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
paversion-version: 20
        """)
        self.p = PoweradminurtPlugin(self.console, self.conf)
        self.init_default_cvar()
        self.p.onLoadConfig()
        self.p.onStartup()

        self.sleep_patcher = patch.object(time, 'sleep')
        self.sleep_patcher.start()

        self.console.say = Mock()
        self.console.saybig = Mock()
        self.console.write = Mock()

        self.moderator.connects("2")

    def tearDown(self):
        super(mixin_cmd_version, self).tearDown()
        self.sleep_patcher.stop()

    def test_nominal(self):
        self.moderator.message_history = []
        self.moderator.says("!version")
        self.assertEqual(['I am PowerAdminUrt version %s by %s' % (plugin_version, plugin_author)],
                         self.moderator.message_history)
示例#17
0
class Welcome_functional_test(B3TestCase):

    def setUp(self):

        B3TestCase.setUp(self)

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

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

            self.joe = FakeClient(self.console, name="Joe", guid="joeguid", groupBits=1, team=b3.TEAM_RED)
            self.mike = FakeClient(self.console, name="Mike", guid="mikeguid", groupBits=1, team=b3.TEAM_RED)
            self.bill = FakeClient(self.console, name="Bill", guid="billguid", groupBits=1, team=b3.TEAM_RED)
            self.superadmin = FakeClient(self.console, name="SuperAdmin", guid="superadminguid", groupBits=128, team=b3.TEAM_RED)

    def load_config(self, config_content=None):
        """
        load the given config content, or the default config if config_content is None.
        """
        if config_content is None:
            self.conf.load(b3.getAbsolutePath('@b3/conf/plugin_welcome.ini'))
        else:
            self.conf.loadFromString(config_content)
        self.p.onLoadConfig()
        self.p.onStartup()
class Test_cmd_listconfig(Bf3TestCase):

    def setUp(self):
        super(Test_cmd_listconfig, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
listconfig: 40

[preferences]
config_path: %(script_dir)s
            """ % {'script_dir': os.path.abspath(
            os.path.join(os.path.dirname(__file__), '../extplugins/conf/serverconfigs'))})
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
        self.admin.connects("admin")
        self.admin.clearMessageHistory()

    def test_nominal(self):
        with patch.object(os, "listdir") as listdir_mock:
            listdir_mock.return_value = ["junk.txt", "conf1.cfg", "conf2.cfg", "hardcore.cfg"]
            self.admin.says('!listconfig')
            self.assertEqual(['Available config files: conf1, conf2, hardcore'], self.admin.message_history)

    def test_no_config(self):
        with patch.object(os, "listdir") as listdir_mock:
            listdir_mock.return_value = ["junk.txt"]
            self.admin.says('!listconfig')
            self.assertEqual(['No server config files found'], self.admin.message_history)
示例#19
0
class Test_client_connects(PluginTestCase):
    def setUp(self):
        super(Test_client_connects, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[foo]""")
        self.p = VacbanPlugin(self.console, self.conf)
        self.p.onLoadConfig()
        when(self.p)._checkConnectedPlayers().thenReturn()
        self.p.onStartup()
        when(self.p)._query_service(
            anything()).thenReturn(vac_response_not_banned)

    def test_player_connects(self):
        # GIVEN
        with patch.object(self.p, '_checkClient') as mock_checkClient:
            # WHEN
            self.joe.connects("slot1")
            self.p.stop_worker()
            self.p._workerThread.join()
        # THEN
        mock_checkClient.assert_has_calls([call(self.joe)])
        self.assertEqual(1, mock_checkClient.call_count)

    def test_2_players_connect(self):
        # GIVEN
        with patch.object(self.p, '_checkClient') as mock_checkClient:
            # WHEN
            self.joe.connects("slot1")
            self.simon.connects("slot2")
            self.p.stop_worker()
            self.p._workerThread.join()
            # THEN
        mock_checkClient.assert_has_calls([call(self.joe), call(self.simon)])
        self.assertEqual(2, mock_checkClient.call_count)
示例#20
0
    def setUp(self):
        # create a FakeConsole parser
        parser_ini_conf = CfgConfigParser()
        parser_ini_conf.loadFromString(r'''''')
        self.parser_main_conf = MainConfig(parser_ini_conf)

        with logging_disabled():
            from b3.fake import FakeConsole
            self.console = FakeConsole(self.parser_main_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).getPlugin('admin').thenReturn(self.adminPlugin)

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

        with logging_disabled():
            from b3.fake import FakeClient

        self.mike = FakeClient(console=self.console, name="Mike", guid="MIKEGUID", groupBits=1)
        self.bill = FakeClient(console=self.console, name="Bill", guid="BILLGUID", groupBits=1)
class Test_cmd_lms(Iourt42TestCase):
    def setUp(self):
        super(Test_cmd_lms, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
palms-lms: 20           ; change game type to Last Man Standing
        """)
        self.p = PoweradminurtPlugin(self.console, self.conf)

        when(self.console).getCvar('timelimit').thenReturn(Cvar('timelimit', value=20))
        when(self.console).getCvar('g_maxGameClients').thenReturn(Cvar('g_maxGameClients', value=16))
        when(self.console).getCvar('sv_maxclients').thenReturn(Cvar('sv_maxclients', value=16))
        when(self.console).getCvar('sv_privateClients').thenReturn(Cvar('sv_privateClients', value=0))
        when(self.console).getCvar('g_allowvote').thenReturn(Cvar('g_allowvote', value=0))
        self.p.onLoadConfig()
        self.p.onStartup()

        self.console.say = Mock()
        self.console.write = Mock()

        self.moderator.connects("2")


    def test_nominal(self):
        self.moderator.message_history = []
        self.moderator.says("!lms")
        self.console.write.assert_has_calls([call('g_gametype 1')])
        self.assertEqual(['game type changed to Last Man Standing'], self.moderator.message_history)
class Test_cmd_roundrestart(Bf3TestCase):

    @classmethod
    def setUpClass(cls):
        Bf3TestCase.setUpClass()
        cls.sleep_patcher = patch.object(time, "sleep")
        cls.sleep_patcher.start()

    @classmethod
    def tearDownClass(cls):
        cls.sleep_patcher.stop()

    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
roundrestart: 20
        """)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
        self.superadmin.connects('superadmin')


    def test_nominal(self):
        self.superadmin.clearMessageHistory()
        self.superadmin.says('!roundrestart')
        self.assertEqual([], self.superadmin.message_history)
        self.console.write.assert_has_calls([call(('mapList.restartRound',))])
class Test_commands(PluginTestCase):
    def setUp(self):
        super(Test_commands, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
vaccheck: 20
        """)
        self.p = VacbanPlugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        when(self.p)._query_service(anything()).thenReturn(vac_response_not_banned)
        self.moderator.connects("2")



    def test_vaccheck(self):
        # GIVEN
        self.moderator.message_history = []
        # WHEN
        with patch.object(self.p, '_checkConnectedPlayers') as mock_checkConnectedPlayers:
            self.moderator.says("!vaccheck")
        # THEN
        self.assertEqual(['checking players ...', 'done'], self.moderator.message_history)
        self.assertEqual(1, mock_checkConnectedPlayers.call_count)
示例#24
0
    def setUp(self):
        B3TestCase.setUp(self)

        with logging_disabled():
            admin_conf = CfgConfigParser()
            admin_plugin = AdminPlugin(self.console, admin_conf)
            admin_plugin.onLoadConfig()
            admin_plugin.onStartup()
            when(self.console).getPlugin('admin').thenReturn(admin_plugin)

        conf = CfgConfigParser()
        conf.loadFromString(dedent(r"""
            [commands]
            mapstats-stats: 0
            testscore-ts: 0
            topstats-top: 0
            topxp: 0

            [settings]
            startPoints: 100
            resetscore: no
            resetxp: no
            show_awards: no
            show_awards_xp: no
        """))
        self.p = StatsPlugin(self.console, conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        self.joe = FakeClient(self.console, name="Joe", guid="joeguid", groupBits=1, team=TEAM_RED)
        self.mike = FakeClient(self.console, name="Mike", guid="mikeguid", groupBits=1, team=TEAM_RED)
        self.joe.connects(1)
        self.mike.connects(2)
class Test_other_statuses(Bf3TestCase):
    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
bf3stats: 0
""")
        self.p = Bf3StatsPlugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

    @patch("urllib.urlopen", new=urlopen_not_found_mock)
    def test_not_found(self):
        self.joe.connects('Joe')
        self.joe.says("!bf3stats")
        self.assertEqual(["Error while querying bf3stats.com. Player 'Joe' not found"], self.joe.message_history)

    @patch("urllib.urlopen", new=urlopen_invalid_name_mock)
    def test_invalid_name(self):
        self.joe.connects('Joe')
        self.joe.says("!bf3stats")
        self.assertEqual(["Error while querying bf3stats.com. Error while querying 'Joe' : invalid_name"],
                         self.joe.message_history)

    @patch("urllib.urlopen", new=urlopen_pifound_mock)
    def test_pifound(self):
        self.joe.connects('Joe')
        self.joe.says("!bf3stats")
        self.assertEqual(['bf3stats.com has no stats for Joe'], self.joe.message_history)
class Test_command_cancelvote(Bf3TestCase):
    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""\
[commands]
cancelvote-cv: 20
""")
        self.p = VotemapPlugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

    def test_no_vote(self):
        self.admin.connects('admin')
        self.admin.says('!cancelvote')
        self.assertEqual(['There is no vote to cancel'], self.admin.message_history)

    def test_nominal(self):
        self.admin.connects('admin')
        self.p.current_vote_session = Mock()
        self.p.current_vote_session_timer = Mock()
        self.admin.says('!cancelvote')
        self.assertEqual(['Vote canceled'], self.admin.message_history)
        self.assertIsNone(self.p.current_vote_session)
        self.assertIsNone(self.p.current_vote_session_timer)

    def test_alias(self):
        self.admin.connects('admin')
        self.admin.clearMessageHistory()
        self.admin.says('!cv')
        self.assertEqual(['There is no vote to cancel'], self.admin.message_history)
class Test_cmd_punkbuster(Bf4TestCase):

    def setUp(self):
        Bf4TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
punkbuster-punk: 20
        """)
        self.p = Poweradminbf4Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
        self.superadmin.connects('superadmin')


    def test_pb_inactive(self):
        when(self.console).write(('punkBuster.isActive',)).thenReturn(['false'])
        self.superadmin.clearMessageHistory()
        self.superadmin.says('!punkbuster test')
        self.assertEqual(['Punkbuster is not active'], self.superadmin.message_history)

    def test_pb_active(self):
        when(self.console).write(('punkBuster.isActive',)).thenReturn(['true'])
        self.superadmin.clearMessageHistory()
        self.superadmin.says('!punkbuster test')
        self.assertEqual([], self.superadmin.message_history)
        verify(self.console).write(('punkBuster.pb_sv_command', 'test'))

    def test_pb_active(self):
        when(self.console).write(('punkBuster.isActive',)).thenReturn(['true'])
        self.superadmin.clearMessageHistory()
        self.superadmin.says('!punk test')
        self.assertEqual([], self.superadmin.message_history)
        verify(self.console).write(('punkBuster.pb_sv_command', 'test'))
示例#28
0
class Test_cmd_punkbuster(Bf3TestCase):
    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
punkbuster-punk: 20
        """)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
        self.superadmin.connects('superadmin')

    def test_pb_inactive(self):
        when(self.console).write(
            ('punkBuster.isActive', )).thenReturn(['false'])
        self.superadmin.clearMessageHistory()
        self.superadmin.says('!punkbuster test')
        self.assertEqual(['Punkbuster is not active'],
                         self.superadmin.message_history)

    def test_pb_active(self):
        when(self.console).write(
            ('punkBuster.isActive', )).thenReturn(['true'])
        self.superadmin.clearMessageHistory()
        self.superadmin.says('!punkbuster test')
        self.assertEqual([], self.superadmin.message_history)
        verify(self.console).write(('punkBuster.pb_sv_command', 'test'))

    def test_pb_active(self):
        when(self.console).write(
            ('punkBuster.isActive', )).thenReturn(['true'])
        self.superadmin.clearMessageHistory()
        self.superadmin.says('!punk test')
        self.assertEqual([], self.superadmin.message_history)
        verify(self.console).write(('punkBuster.pb_sv_command', 'test'))
示例#29
0
class PluginmanagerTestCase(B3TestCase):

    def setUp(self):

        B3TestCase.setUp(self)
        self.console.gameName = 'f00'

        self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.ini')
        when(self.console).getPlugin("admin").thenReturn(self.adminPlugin)
        self.adminPlugin.onLoadConfig()
        self.adminPlugin.onStartup()

        self.conf = CfgConfigParser()
        self.conf.loadFromString(dedent(r"""
            [commands]
            plugin: superadmin
        """))

        self.p = PluginmanagerPlugin(self.console, self.conf)
        when(self.console).getPlugin("pluginmanager").thenReturn(self.adminPlugin)
        self.p.onLoadConfig()
        self.p.onStartup()

        when(self.console.config).get_external_plugins_dir().thenReturn(b3.getAbsolutePath('@b3\\extplugins'))

        # store them also in the console _plugins dict
        self.console._plugins['admin'] = self.adminPlugin
        self.console._plugins['pluginmanager'] = self.p

    def tearDown(self):
        self.console._plugins.clear()
        B3TestCase.tearDown(self)
class Test_cmd_scramble(Bf3TestCase):

    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
scramble: 20
        """)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
        self.p._scrambler = Mock()
        self.superadmin.connects('superadmin')
        self.superadmin.clearMessageHistory()

    def test_none(self):
        self.p._scrambling_planned = None
        self.superadmin.says('!scramble')
        self.assertEqual(['Teams will be scrambled at next round start'], self.superadmin.message_history)
        self.assertTrue(self.p._scrambling_planned)

    def test_true(self):
        self.p._scrambling_planned = True
        self.superadmin.says('!scramble')
        self.assertEqual(['Teams scrambling canceled for next round'], self.superadmin.message_history)
        self.assertFalse(self.p._scrambling_planned)

    def test_false(self):
        self.p._scrambling_planned = False
        self.superadmin.says('!scramble')
        self.assertEqual(['Teams will be scrambled at next round start'], self.superadmin.message_history)
        self.assertTrue(self.p._scrambling_planned)
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 = CfgConfigParser()
        self.conf.loadFromString(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()
示例#32
0
class Test_cmd_roundnext(Bf3TestCase):
    @classmethod
    def setUpClass(cls):
        Bf3TestCase.setUpClass()
        cls.sleep_patcher = patch.object(time, "sleep")
        cls.sleep_patcher.start()

    @classmethod
    def tearDownClass(cls):
        cls.sleep_patcher.stop()

    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
roundnext: 20
        """)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
        self.superadmin.connects('superadmin')

    def test_nominal(self):
        when(self.console).write()
        self.superadmin.clearMessageHistory()
        self.superadmin.says('!roundnext')
        self.assertEqual([], self.superadmin.message_history)
        verify(self.console).write(('mapList.runNextRound', ))
class Test_cmd_vipclear(Bf3TestCase):
    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
vipclear: 20
        """)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        self.moderator.connects("moderator")


    def test_nominal(self):
        when(self.console).write(('reservedSlotsList.clear',)).thenReturn([])
        self.moderator.connects("moderator")
        self.moderator.message_history = []
        self.moderator.says("!vipclear")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('VIP list is now empty', self.moderator.message_history[0])

    def test_frostbite_error(self):
        when(self.console).write(('reservedSlotsList.clear',)).thenRaise(CommandFailedError(['f00']))
        self.moderator.connects("moderator")
        self.moderator.message_history = []
        self.moderator.says("!vipclear")
        self.assertEqual(["Error: f00"], self.moderator.message_history)
示例#34
0
    def test_nominal(self):
        # GIVEN
        conf = CfgConfigParser()
        conf.loadFromString(dedent(r"""
            [commands]
            mapstats-stats: 2
            testscore-ts: 2
            topstats-top: 20
            topxp: 20

            [settings]
            startPoints: 150
            resetscore: yes
            resetxp: yes
            show_awards: yes
            show_awards_xp: yes
        """))
        self.p = StatsPlugin(self.console, conf)
        # WHEN
        self.p.onLoadConfig()
        # THEN
        self.assertEqual(2, self.p.mapstatslevel)
        self.assertEqual(2, self.p.testscorelevel)
        self.assertEqual(20, self.p.topstatslevel)
        self.assertEqual(20, self.p.topxplevel)
        self.assertEqual(150, self.p.startPoints)
        self.assertTrue(self.p.resetscore)
        self.assertTrue(self.p.resetxp)
        self.assertTrue(self.p.show_awards)
        self.assertTrue(self.p.show_awards_xp)
class Test_cmd_vipclear(Bf3TestCase):
    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
vipclear: 20
        """)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        self.moderator.connects("moderator")

    def test_nominal(self):
        when(self.console).write(('reservedSlotsList.clear', )).thenReturn([])
        self.moderator.connects("moderator")
        self.moderator.message_history = []
        self.moderator.says("!vipclear")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('VIP list is now empty',
                         self.moderator.message_history[0])

    def test_frostbite_error(self):
        when(self.console).write(('reservedSlotsList.clear', )).thenRaise(
            CommandFailedError(['f00']))
        self.moderator.connects("moderator")
        self.moderator.message_history = []
        self.moderator.says("!vipclear")
        self.assertEqual(["Error: f00"], self.moderator.message_history)
示例#36
0
class Test_config(Bf3TestCase):
    default_value = 3
    minimum_value = 2

    def assert_config_value(self, expected, conf_value):
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[preferences]
team_swap_threshold: %s
                    """ % conf_value)
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.assertEqual(expected, self.p._team_swap_threshold)

    def test_default_value(self):
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[foo]""")
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.assertEqual(self.default_value, self.p._team_swap_threshold)

    def test_nominal(self):
        self.assert_config_value(6, '6')

    def test_value_too_low(self):
        self.assert_config_value(self.minimum_value, '1')

    def test_negative_value(self):
        self.assert_config_value(self.minimum_value, '-2')

    def test_float(self):
        self.assert_config_value(self.default_value, '3.54')

    def test_junk(self):
        self.assert_config_value(self.default_value, 'junk')
class Test_cmd_listconfig(Bf3TestCase):

    def setUp(self):
        super(Test_cmd_listconfig, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
listconfig: 40

[preferences]
config_path: %(script_dir)s
            """ % {'script_dir': os.path.abspath(
            os.path.join(os.path.dirname(__file__), '../extplugins/conf/serverconfigs'))})
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
        self.admin.connects("admin")
        self.admin.clearMessageHistory()

    def test_nominal(self):
        with patch.object(os, "listdir") as listdir_mock:
            listdir_mock.return_value = ["junk.txt", "conf1.cfg", "conf2.cfg", "hardcore.cfg"]
            self.admin.says('!listconfig')
            self.assertEqual(['Available config files: conf1, conf2, hardcore'], self.admin.message_history)

    def test_no_config(self):
        with patch.object(os, "listdir") as listdir_mock:
            listdir_mock.return_value = ["junk.txt"]
            self.admin.says('!listconfig')
            self.assertEqual(['No server config files found'], self.admin.message_history)
示例#38
0
class PluginmanagerTestCase(B3TestCase):
    def setUp(self):

        B3TestCase.setUp(self)
        self.console.gameName = 'f00'

        self.adminPlugin = AdminPlugin(self.console,
                                       '@b3/conf/plugin_admin.ini')
        when(self.console).getPlugin("admin").thenReturn(self.adminPlugin)
        self.adminPlugin.onLoadConfig()
        self.adminPlugin.onStartup()

        self.conf = CfgConfigParser()
        self.conf.loadFromString(
            dedent(r"""
            [commands]
            plugin: superadmin
        """))

        self.p = PluginmanagerPlugin(self.console, self.conf)
        when(self.console).getPlugin("pluginmanager").thenReturn(
            self.adminPlugin)
        self.p.onLoadConfig()
        self.p.onStartup()

        when(self.console.config).get_external_plugins_dir().thenReturn(
            b3.getAbsolutePath('@b3\\extplugins'))

        # store them also in the console _plugins dict
        self.console._plugins['admin'] = self.adminPlugin
        self.console._plugins['pluginmanager'] = self.p

    def tearDown(self):
        self.console._plugins.clear()
        B3TestCase.tearDown(self)
class Votesession_TestCase(Bf3TestCase):
    map_list = MapListBlock(
        ['3', '3', 'MP_001', 'RushLarge0', '1', 'MP_003', 'ConquestSmall0', '2', 'MP_007', 'SquadDeathMatch0', '3'])

    @staticmethod
    def write(data):
        """ simulate the write method of the B3 parser used to communicate with the BF3 server """
        if data == ('mapList.getMapIndices',):
            return ['0', '1']

    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString(self.__class__.CONFIG)
        self.p = VotemapPlugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        self.getFullMapRotationList_patcher = patch.object(self.console, 'getFullMapRotationList',
            Mock(return_value=Test_command_votemap.map_list))
        self.getFullMapRotationList_patcher.start()

        self.write_patcher = patch.object(self.console, 'write', wraps=Test_command_votemap.write)
        self.write_mock = self.write_patcher.start()

    def tearDown(self):
        Bf3TestCase.tearDown(self)
        if hasattr(self.p, 'current_vote_session_timer') and self.p.current_vote_session_timer:
            self.p.current_vote_session_timer.cancel()
        self.getFullMapRotationList_patcher.stop()
        self.write_patcher.stop()
class Test_cmd_yellteam(Bf4TestCase):

    def setUp(self):
        Bf4TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
yellteam: 20

[preferences]
yell_duration: 2
        """)
        self.p = Poweradminbf4Plugin(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("!yellteam")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('missing parameter, try !help yellteam', self.moderator.message_history[0])

    def test_nominal(self):
        self.moderator.connects("moderator")
        self.moderator.teamId = 3
        with patch.object(self.console, "write") as write_mock:
            self.moderator.says("!yellteam changing map soon !")
        write_mock.assert_called_once_with(('admin.yell', 'changing map soon !', '2', 'team', '3'))
示例#41
0
class Admin_functional_test(B3TestCase):
    """ tests from a class inheriting from Admin_functional_test must call self.init() """
    def setUp(self):
        B3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        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:
            self.conf.load(b3.getAbsolutePath("@b3/conf/plugin_admin.ini"))
        else:
            self.conf.loadFromString(config_content)

        self.p._commands = {}
        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 mixin_cmd_version(object):
    def setUp(self):
        super(mixin_cmd_version, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
paversion-version: 20
        """)
        self.p = PoweradminurtPlugin(self.console, self.conf)
        self.init_default_cvar()
        self.p.onLoadConfig()
        self.p.onStartup()

        self.sleep_patcher = patch.object(time, 'sleep')
        self.sleep_patcher.start()

        self.console.say = Mock()
        self.console.saybig = Mock()
        self.console.write = Mock()

        self.moderator.connects("2")


    def tearDown(self):
        super(mixin_cmd_version, self).tearDown()
        self.sleep_patcher.stop()


    def test_nominal(self):
        self.moderator.message_history = []
        self.moderator.says("!version")
        self.assertEqual(['I am PowerAdminUrt version %s by %s' % (plugin_version, plugin_author)], self.moderator.message_history)
示例#43
0
    def setUp(self):
        # create a FakeConsole parser
        parser_ini_conf = CfgConfigParser()
        parser_ini_conf.loadFromString(r'''''')
        self.parser_main_conf = MainConfig(parser_ini_conf)

        with logging_disabled():
            from b3.fake import FakeConsole
            self.console = FakeConsole(self.parser_main_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).getPlugin('admin').thenReturn(self.adminPlugin)

        # simulate geolocation plugin registering events
        self.console.createEvent('EVT_CLIENT_GEOLOCATION_SUCCESS', 'Event client geolocation success')

        self.console.screen = Mock()
        self.console.time = time.time
        self.console.upTime = Mock(return_value=1000)
        self.console.cron.stop()


        self.conf = CfgConfigParser()
        self.conf.loadFromString(dedent(r"""
            [settings]
            announce: yes

            [messages]
            client_connect: ^7$name ^3from ^7$city ^3(^7$country^3) connected
            cmd_locate: ^7$name ^3is connected from ^7$city ^3(^7$country^3)
            cmd_locate_failed: ^7Could not locate ^1$name
            cmd_distance: ^7$name ^3is ^7$distance ^3km away from you
            cmd_distance_self: ^7Sorry, I'm not that smart...meh!
            cmd_distance_failed: ^7Could not compute distance with ^1$name
            cmd_isp: ^7$name ^3is using ^7$isp ^3as isp
            cmd_isp_failed: ^7Could not determine ^1$name ^7isp

            [commands]
            locate: user
            distance: user
            isp: mod
        """))

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

        with logging_disabled():
            from b3.fake import FakeClient

        self.mike = FakeClient(console=self.console, name="Mike", guid="MIKEGUID", groupBits=1)
        self.bill = FakeClient(console=self.console, name="Bill", guid="BILLGUID", groupBits=16)
        self.mike.location = LOCATION_MIKE
        self.bill.location = LOCATION_BILL
class Test_cmd_autoscramble(Bf3TestCase):

    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
autoscramble: mod
""")
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
        self.p._scrambler = Mock()
        self.superadmin.connects('superadmin')
        self.superadmin.clearMessageHistory()
        self.p._autoscramble_rounds = None
        self.p._autoscramble_maps = None

    def test_no_arguments(self):
        self.superadmin.says('!autoscramble')
        self.assertEqual(["invalid data. Expecting one of [off, round, map]"], self.superadmin.message_history)
        self.assertIsNone(self.p._autoscramble_rounds)
        self.assertIsNone(self.p._autoscramble_maps)

    def test_bad_arguments(self):
        self.superadmin.says('!autoscramble f00')
        self.assertEqual(["invalid data. Expecting one of [off, round, map]"], self.superadmin.message_history)
        self.assertIsNone(self.p._autoscramble_rounds)
        self.assertIsNone(self.p._autoscramble_maps)

    def test_round(self):
        self.superadmin.says('!autoscramble round')
        self.assertEqual(['Auto scrambler will run at every round start'], self.superadmin.message_history)
        self.assertTrue(self.p._autoscramble_rounds)
        self.assertFalse(self.p._autoscramble_maps)

    def test_r(self):
        self.superadmin.says('!autoscramble r')
        self.assertEqual(['Auto scrambler will run at every round start'], self.superadmin.message_history)
        self.assertTrue(self.p._autoscramble_rounds)
        self.assertFalse(self.p._autoscramble_maps)

    def test_map(self):
        self.superadmin.says('!autoscramble map')
        self.assertEqual(['Auto scrambler will run at every map change'], self.superadmin.message_history)
        self.assertFalse(self.p._autoscramble_rounds)
        self.assertTrue(self.p._autoscramble_maps)

    def test_m(self):
        self.superadmin.says('!autoscramble m')
        self.assertEqual(['Auto scrambler will run at every map change'], self.superadmin.message_history)
        self.assertFalse(self.p._autoscramble_rounds)
        self.assertTrue(self.p._autoscramble_maps)

    def test_off(self):
        self.superadmin.says('!autoscramble off')
        self.assertEqual(['Auto scrambler now disabled'], self.superadmin.message_history)
        self.assertFalse(self.p._autoscramble_rounds)
        self.assertFalse(self.p._autoscramble_maps)
示例#45
0
class Test_cmd_autoscramble(Bf3TestCase):

    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
autoscramble: mod
""")
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
        self.p._scrambler = Mock()
        self.superadmin.connects('superadmin')
        self.superadmin.clearMessageHistory()
        self.p._autoscramble_rounds = None
        self.p._autoscramble_maps = None

    def test_no_arguments(self):
        self.superadmin.says('!autoscramble')
        self.assertEqual(["invalid data. Expecting one of [off, round, map]"], self.superadmin.message_history)
        self.assertIsNone(self.p._autoscramble_rounds)
        self.assertIsNone(self.p._autoscramble_maps)

    def test_bad_arguments(self):
        self.superadmin.says('!autoscramble f00')
        self.assertEqual(["invalid data. Expecting one of [off, round, map]"], self.superadmin.message_history)
        self.assertIsNone(self.p._autoscramble_rounds)
        self.assertIsNone(self.p._autoscramble_maps)

    def test_round(self):
        self.superadmin.says('!autoscramble round')
        self.assertEqual(['Auto scrambler will run at every round start'], self.superadmin.message_history)
        self.assertTrue(self.p._autoscramble_rounds)
        self.assertFalse(self.p._autoscramble_maps)

    def test_r(self):
        self.superadmin.says('!autoscramble r')
        self.assertEqual(['Auto scrambler will run at every round start'], self.superadmin.message_history)
        self.assertTrue(self.p._autoscramble_rounds)
        self.assertFalse(self.p._autoscramble_maps)

    def test_map(self):
        self.superadmin.says('!autoscramble map')
        self.assertEqual(['Auto scrambler will run at every map change'], self.superadmin.message_history)
        self.assertFalse(self.p._autoscramble_rounds)
        self.assertTrue(self.p._autoscramble_maps)

    def test_m(self):
        self.superadmin.says('!autoscramble m')
        self.assertEqual(['Auto scrambler will run at every map change'], self.superadmin.message_history)
        self.assertFalse(self.p._autoscramble_rounds)
        self.assertTrue(self.p._autoscramble_maps)

    def test_off(self):
        self.superadmin.says('!autoscramble off')
        self.assertEqual(['Auto scrambler now disabled'], self.superadmin.message_history)
        self.assertFalse(self.p._autoscramble_rounds)
        self.assertFalse(self.p._autoscramble_maps)
class mixin_cmd_pasetnextmap(object):
    def setUp(self):
        super(mixin_cmd_pasetnextmap, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
pasetnextmap-snmap: 20
        """)
        self.p = PoweradminurtPlugin(self.console, self.conf)

        when(self.console).getCvar('timelimit').thenReturn(Cvar('timelimit', value=20))
        when(self.console).getCvar('g_maxGameClients').thenReturn(Cvar('g_maxGameClients', value=16))
        when(self.console).getCvar('sv_maxclients').thenReturn(Cvar('sv_maxclients', value=16))
        when(self.console).getCvar('sv_privateClients').thenReturn(Cvar('sv_privateClients', value=0))
        when(self.console).getCvar('g_allowvote').thenReturn(Cvar('g_allowvote', value=0))
        self.p.onLoadConfig()
        self.p.onStartup()

        self.sleep_patcher = patch.object(time, 'sleep')
        self.sleep_patcher.start()

        self.console.say = Mock()
        self.console.saybig = Mock()
        self.console.write = Mock()

        self.moderator.connects("2")


    def tearDown(self):
        super(mixin_cmd_pasetnextmap, self).tearDown()
        self.sleep_patcher.stop()


    def test_missing_parameter(self):
        self.moderator.clearMessageHistory()
        self.moderator.says("!snmap")
        self.assertEqual(['Invalid or missing data, try !help setnextmap'], self.moderator.message_history)


    def test_existing_map(self):
        # GIVEN
        when(self.console).getMapsSoundingLike('f00').thenReturn('f00')
        # WHEN
        self.moderator.clearMessageHistory()
        self.moderator.says("!snmap f00")
        # THEN
        verify(self.console).getMapsSoundingLike('f00')
        self.assertEqual(['nextmap set to f00'], self.moderator.message_history)


    def test_suggestions(self):
        # GIVEN
        when(self.console).getMapsSoundingLike('f00').thenReturn(['f001', 'foo2'])
        # WHEN
        self.moderator.clearMessageHistory()
        self.moderator.says("!snmap f00")
        # THEN
        verify(self.console).getMapsSoundingLike('f00')
        self.assertEqual(['do you mean : f001, foo2 ?'], self.moderator.message_history)
class Test_cmd_vips(Bf3TestCase):
    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
vips: mod
""")
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        self.console.say = Mock()
        self.console.saybig = Mock()

        self.moderator.connects("moderator")

        self.joe.connects('joe')
        self.joe.teamId = 2

        self.console.write.return_value = []


    def test_empty_vip_list(self):
        self.console.write.expect(('reservedSlotsList.list', 0)).thenReturn([])
        self.moderator.connects("moderator")
        self.moderator.message_history = []
        self.moderator.says("!vips")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('No VIP connected', self.moderator.message_history[0])
        self.console.write.assert_has_calls([call(('reservedSlotsList.list', 0))])


    def test_4_vips(self):
        self.console.write.expect(('reservedSlotsList.list', 0)).thenReturn(['name1', 'name2', 'name3', 'name2'])
        self.console.write.expect(('reservedSlotsList.list', 4)).thenReturn(['name4'])
        self.console.write.expect(('reservedSlotsList.list', 5)).thenReturn([])
        self.moderator.connects("moderator")
        self.moderator.message_history = []
        self.moderator.says("!vips")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('No VIP connected', self.moderator.message_history[0])
        self.console.write.assert_has_calls([call(('reservedSlotsList.list', 0))])
        self.console.write.assert_has_calls([call(('reservedSlotsList.list', 4))])
        self.console.write.assert_has_calls([call(('reservedSlotsList.list', 5))])


    def test_4_vips_one_is_connected(self):
        self.console.write.expect(('reservedSlotsList.list', 0)).thenReturn(['name1', 'name2', 'name3', 'Joe'])
        self.console.write.expect(('reservedSlotsList.list', 4)).thenReturn([])
        self.joe.connects("Joe")
        self.moderator.connects("moderator")
        self.moderator.message_history = []
        self.moderator.says("!vips")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('Connected VIPs: Joe', self.moderator.message_history[0])
        self.console.write.assert_has_calls([call(('reservedSlotsList.list', 0))])
        self.console.write.assert_has_calls([call(('reservedSlotsList.list', 4))])
    def init(self, xml_content, cfg_content):
        xml_parser = XmlConfigParser()
        xml_parser.loadFromString(xml_content)
        conf_xml = MainConfig(xml_parser)
        cfg_parser = CfgConfigParser(allow_no_value=True)
        cfg_parser.loadFromString(cfg_content)
        conf_cfg = MainConfig(cfg_parser)

        return conf_xml, conf_cfg
示例#49
0
class Test_getServerInfo(BFHTestCase):
    def setUp(self):
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[configuration]""")
        self.parser = BfhParser(self.conf)
        self.parser.startup()

    def test_getServerInfo(self):
        # GIVEN
        when(self.parser).write(('serverInfo', )).thenReturn([
            '[WASP] Hotwire all maps -- Working kick on kills', '0', '14',
            'Hotwire0', 'MP_Eastside', '0', '2', '0', '0', '', 'true', 'true',
            'false', '428710', '6019', '108.61.98.177:40000', '', 'true', 'EU',
            'ams', 'NL', '0', 'IN_GAME'
        ])

        # WHEN
        self.parser.getServerInfo()
        # THEN
        self.assertEqual('[WASP] Hotwire all maps -- Working kick on kills',
                         self.parser.game.sv_hostname)
        self.assertEqual(14, self.parser.game.sv_maxclients)
        self.assertEqual("MP_Eastside", self.parser.game.mapName)
        self.assertEqual("Hotwire0", self.parser.game.gameType)
        self.assertEqual("108.61.98.177", self.parser._publicIp)
        self.assertEqual('40000', self.parser._gamePort)
        self.assertDictEqual(
            {
                'punkBusterVersion': '',
                'team2score': None,
                'numPlayers': '0',
                'maxPlayers': '14',
                'targetScore': '0',
                'closestPingSite': 'ams',
                'blazeGameState': 'IN_GAME',
                'onlineState': '',
                'serverName':
                '[WASP] Hotwire all maps -- Working kick on kills',
                'gamemode': 'Hotwire0',
                'hasPunkbuster': 'true',
                'hasPassword': '******',
                'numTeams': '0',
                'team1score': None,
                'roundTime': '6019',
                'blazePlayerCount': '0',
                'isRanked': 'true',
                'roundsPlayed': '0',
                'serverUptime': '428710',
                'team4score': None,
                'level': 'MP_Eastside',
                'country': 'NL',
                'region': 'EU',
                'joinQueueEnabled': 'true',
                'roundsTotal': '2',
                'gameIpAndPort': '108.61.98.177:40000',
                'team3score': None
            }, self.parser.game.serverinfo)
示例#50
0
class Test_cmd_ident(Iourt43TestCase):
    def setUp(self):
        super(Test_cmd_ident, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
paident-id: 20

[special]
paident_full_level: 40
        """)
        self.p = PoweradminurtPlugin(self.console, self.conf)
        self.init_default_cvar()
        self.parser_conf._settings.update({'b3': {"time_zone": "UTC", "time_format": "%I:%M%p %Z %m/%d/%y"}})
        self.p.onLoadConfig()
        self.p.onStartup()

        self.console.say = Mock()
        self.console.write = Mock()

        self.moderator.connects("2")
        self.moderator.message_history = []

    def test_no_parameter(self):
        # WHEN
        self.moderator.says("!id")
        # THEN
        self.assertListEqual(["Your id is @2"], self.moderator.message_history)

    def test_junk(self):
        # WHEN
        self.moderator.says("!id qsdfsqdq sqfd qf")
        # THEN
        self.assertListEqual(["No players found matching qsdfsqdq"], self.moderator.message_history)

    def test_nominal_under_full_level(self):
        # GIVEN
        self.joe.pbid = "joe_pbid"
        self.joe.connects('3')
        # WHEN
        with patch('time.time', return_value=0.0) as time_mock:
            self.moderator.says("!id joe")
        # THEN
        self.assertListEqual(['12:00AM UTC 01/01/70 @3 Joe'], self.moderator.message_history)

    def test_nominal_above_full_level(self):
        # GIVEN
        self.joe.pbid = "joe_pbid"
        self.joe.connects('3')
        self.joe.timeAdd = 90 * 60.0
        self.superadmin.connects('1')
        # WHEN
        with patch('time.time', return_value=180 * 60.0):
            self.superadmin.says("!id joe")
        # THEN
        self.assertListEqual(['03:00AM UTC 01/01/70 @3 Joe  [joe_pbid] since 01:30AM UTC 01/01/70'],
                             self.superadmin.message_history)
class Test_cmd_loadconfig(Bf4TestCase):

    def setUp(self):
        super(Test_cmd_loadconfig, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""[commands]
loadconfig: 40
            """)
        self.p = Poweradminbf4Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()


    def test_no_config_dir(self):
        self._configPath = None
        self.admin.connects("admin")
        self.admin.clearMessageHistory()
        self.admin.says("!loadconfig")
        self.assertEqual(['The directory containing the config files is unknown, check the plugin configuration file'], self.admin.message_history)

    def test_no_argument(self):
        self.admin.connects("admin")
        self.admin.clearMessageHistory()
        self.p._configPath = "some_path"
        self.admin.says("!loadconfig")
        self.assertEqual(['Invalid or missing data, try !help loadconfig'], self.admin.message_history)

    def test_bad_argument(self):
        self.admin.connects("admin")
        self.admin.clearMessageHistory()
        self.p._configPath = "some_path"
        with patch.object(os, "listdir") as listdir_mock:
            listdir_mock.return_value = ["junk.txt", "conf1.cfg", "conf2.cfg", "hardcore.cfg", "hardcore-sqdm.cfg"]
            self.admin.says("!loadconfig hard")
        self.assertEqual(['Do you mean : hardcore, hardcore-sqdm ?'], self.admin.message_history)

    def test_no_config_available(self):
        self.admin.connects("admin")
        self.admin.clearMessageHistory()
        self.p._configPath = "some_path"
        with patch.object(os, "listdir") as listdir_mock:
            listdir_mock.return_value = ["junk.txt"]
            self.admin.says("!loadconfig hard")
        self.assertEqual(['Cannot find any config file named hard.cfg'], self.admin.message_history)

    def test_nominal(self):
        self.admin.connects("admin")
        self.admin.clearMessageHistory()
        self.p._load_server_config_from_file = Mock()
        self.p._configPath = "some_path"
        with patch.object(os, "listdir") as listdir_mock:
            listdir_mock.return_value = ["theconfig.cfg"]
            self.admin.says("!loadconfig theconfig")
        self.assertEqual(['Loading config theconfig ...'], self.admin.message_history)
        self.p._load_server_config_from_file.assert_called_once_with(self.admin, config_name="theconfig", file_path=ANY, threaded=ANY)
示例#52
0
class Test_cmd_captain(Iourt43TestCase):
    def setUp(self):
        super(Test_cmd_captain, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
pacaptain-captain: 40   ; set the the given client as the captain for its team
        """)
        self.p = PoweradminurtPlugin(self.console, self.conf)
        self.init_default_cvar()
        self.p.onLoadConfig()
        self.p.onStartup()
        self.console.say = Mock()
        self.console.write = Mock()
        self.admin.connects("2")
        self.moderator.connects("3")

    def test_match_mode_deactivated(self):
        self.p._matchmode = False
        self.admin.message_history = []
        self.admin.says("!captain")
        self.assertListEqual(
            ["!pacaptain command is available only in match mode"],
            self.admin.message_history)

    def test_client_spectator(self):
        self.p._matchmode = True
        self.admin.message_history = []
        self.admin.team = TEAM_SPEC
        self.admin.says("!captain")
        self.assertListEqual(
            ["Level-40-Admin is a spectator! - Can't set captain status"],
            self.admin.message_history)

    def test_client_with_no_parameters(self):
        self.p._matchmode = True
        self.admin.message_history = []
        self.admin.team = TEAM_RED
        self.admin.says("!captain")
        self.console.write.assert_has_calls(
            [call('forcecaptain %s' % self.admin.cid)])

    def test_client_with_parameters(self):
        self.p._matchmode = True
        self.admin.message_history = []
        self.admin.team = TEAM_RED
        self.moderator.message_history = []
        self.moderator.team = TEAM_BLUE
        self.admin.says("!captain 3")
        self.console.write.assert_has_calls(
            [call('forcecaptain %s' % self.moderator.cid)])
        self.assertListEqual(
            ["You were set as captain for the BLUE team by the Admin"],
            self.moderator.message_history)
示例#53
0
class mixin_cmd_pasetnextmap(object):
    def setUp(self):
        super(mixin_cmd_pasetnextmap, self).setUp()
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
pasetnextmap-snmap: 20
        """)
        self.p = PoweradminurtPlugin(self.console, self.conf)
        self.init_default_cvar()
        self.p.onLoadConfig()
        self.p.onStartup()

        self.sleep_patcher = patch.object(time, 'sleep')
        self.sleep_patcher.start()

        self.console.say = Mock()
        self.console.saybig = Mock()
        self.console.write = Mock()

        self.moderator.connects("2")

    def tearDown(self):
        super(mixin_cmd_pasetnextmap, self).tearDown()
        self.sleep_patcher.stop()

    def test_missing_parameter(self):
        self.moderator.clearMessageHistory()
        self.moderator.says("!snmap")
        self.assertEqual(['Invalid or missing data, try !help pasetnextmap'],
                         self.moderator.message_history)

    def test_existing_map(self):
        # GIVEN
        when(self.console).getMapsSoundingLike('f00').thenReturn('f00')
        # WHEN
        self.moderator.clearMessageHistory()
        self.moderator.says("!snmap f00")
        # THEN
        verify(self.console).getMapsSoundingLike('f00')
        self.assertEqual(['nextmap set to f00'],
                         self.moderator.message_history)

    def test_suggestions(self):
        # GIVEN
        when(self.console).getMapsSoundingLike('f00').thenReturn(
            ['f001', 'foo2'])
        # WHEN
        self.moderator.clearMessageHistory()
        self.moderator.says("!snmap f00")
        # THEN
        verify(self.console).getMapsSoundingLike('f00')
        self.assertEqual(['do you mean : f001, foo2 ?'],
                         self.moderator.message_history)
class Test_cmd_vips(Bf3TestCase):
    def setUp(self):
        Bf3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("""
[commands]
vips: mod
""")
        self.p = Poweradminbf3Plugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        self.console.say = Mock()
        self.console.saybig = Mock()

        self.moderator.connects("moderator")

        self.joe.connects('joe')
        self.joe.teamId = 2

    def test_empty_vip_list(self):
        when(self.console).write(('reservedSlotsList.list', 0)).thenReturn([])
        self.moderator.connects("moderator")
        self.moderator.message_history = []
        self.moderator.says("!vips")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('No VIP connected', self.moderator.message_history[0])

    def test_4_vips(self):
        when(self.console).write(
            ('reservedSlotsList.list',
             0)).thenReturn(['name1', 'name2', 'name3', 'name2'])
        when(self.console).write(
            ('reservedSlotsList.list', 4)).thenReturn(['name4'])
        when(self.console).write(('reservedSlotsList.list', 5)).thenReturn([])
        self.moderator.connects("moderator")
        self.moderator.message_history = []
        self.moderator.says("!vips")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('No VIP connected', self.moderator.message_history[0])

    def test_4_vips_one_is_connected(self):
        when(self.console).write(
            ('reservedSlotsList.list',
             0)).thenReturn(['name1', 'name2', 'name3', 'Joe'])
        when(self.console).write(('reservedSlotsList.list', 4)).thenReturn([])
        self.joe.connects("Joe")
        self.moderator.connects("moderator")
        self.moderator.message_history = []
        self.moderator.says("!vips")
        self.assertEqual(1, len(self.moderator.message_history))
        self.assertEqual('Connected VIPs: Joe',
                         self.moderator.message_history[0])
示例#55
0
class NickregTestCase(unittest2.TestCase):
    def setUp(self):
        # 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).getPlugin('admin').thenReturn(self.adminPlugin)

        self.conf = CfgConfigParser()
        self.conf.loadFromString(
            dedent("""
            [settings]
            min_level: mod
            min_level_global_manage: admin
            max_nicks: 3
            interval: 30
        """))

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

        with logging_disabled():
            from b3.fake import FakeClient
            self.senioradmin = FakeClient(console=self.console,
                                          name="SeniorAdmin",
                                          guid="SENIORADMIN",
                                          groupBits=64)
            self.admin = FakeClient(console=self.console,
                                    name="Admin",
                                    guid="ADMIN",
                                    groupBits=16)
            self.guest = FakeClient(console=self.console,
                                    name="Guest",
                                    guid="GUEST",
                                    groupBits=0)

        self.admin.connects("1")
        self.guest.connects("2")
        self.senioradmin.connects("3")

    def tearDown(self):
        pass
示例#56
0
class ServermonitorTestCase(TestCase):
    """
    TestCase suitable for testing the ServermonitorPlugin class
    """
    def setUp(self):
        # less logging
        self.logger = logging.getLogger('output')
        self.logger.setLevel(logging.ERROR)
        self.logger.propagate = False

        from b3.fake import FakeConsole, FakeClient

        # create a Fake parser
        self.parser_conf = XmlConfigParser()
        self.parser_conf.loadFromString(
            """<configuration><settings name="server"><set name="game_log"></set></settings></configuration>"""
        )
        self.console = FakeConsole(self.parser_conf)
        self.console.startup()

        # load the admin plugin
        # load the admin plugin
        if B3version(b3_version) >= B3version("1.10dev"):
            admin_plugin_conf_file = '@b3/conf/plugin_admin.ini'
        else:
            admin_plugin_conf_file = '@b3/conf/plugin_admin.xml'
        with logging_disabled():
            self.adminPlugin = AdminPlugin(self.console,
                                           admin_plugin_conf_file)
            self.adminPlugin.onLoadConfig()
            self.adminPlugin._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)

        # load our plugin
        self.conf = CfgConfigParser()
        self.p = ServermonitorPlugin(self.console, self.conf)

        self.superadmin = FakeClient(self.console,
                                     name="Superadmin",
                                     guid="Superadmin_guid",
                                     groupBits=128)

        self.logger.propagate = True

    def init_plugin(self, config_content):
        self.logger.setLevel(VERBOSE)
        self.conf.loadFromString(config_content)
        self.p.onLoadConfig()
        self.p.onStartup()
示例#57
0
class Test_CfgConfigParser(CommonTestMethodsMixin, B3TestCase):
    assert_func_template = """
[section_foo]
foo = %s
"""

    def setUp(self):
        B3TestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString("[foo]")
        log = logging.getLogger('output')
        log.setLevel(logging.DEBUG)
示例#58
0
class Test_conf(unittest.TestCase):
    def setUp(self):
        with logging_disabled():
            from b3.fake import FakeConsole
            self.console = FakeConsole('@b3/conf/b3.distribution.xml')
        self.conf = CfgConfigParser()
        self.p = GaPlugin(self.console, self.conf)

    def test_empty_conf(self):
        self.conf.loadFromString("""""")
        self.p.onLoadConfig()
        self.p.onStartup()
        self.assertIsNone(self.p._ga_tracking_id)

    def test_missing_tracking_id(self):
        self.conf.loadFromString(
            dedent("""
            [google analytics]
        """))
        self.p.onLoadConfig()
        self.p.onStartup()
        self.assertIsNone(self.p._ga_tracking_id)

    def test_bad_tracking_id(self):
        self.conf.loadFromString(
            dedent("""
            [google analytics]
            tracking ID: xx-xxxxx-x
        """))
        self.p.onLoadConfig()
        self.p.onStartup()
        self.assertIsNone(self.p._ga_tracking_id)

    def test_bad_tracking_id2(self):
        self.conf.loadFromString(
            dedent("""
            [google analytics]
            tracking ID: UA-123456-x
        """))
        self.p.onLoadConfig()
        self.p.onStartup()
        self.assertIsNone(self.p._ga_tracking_id)

    def test_nominal(self):
        self.conf.loadFromString(
            dedent("""
            [google analytics]
            tracking ID: UA-1234567-8
        """))
        self.p.onLoadConfig()
        self.p.onStartup()
        self.assertEqual("UA-1234567-8", self.p._ga_tracking_id)