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)
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_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)
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'))
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_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_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)
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 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)
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 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 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)
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_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_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 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)
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_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 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_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_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_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'))
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)
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)
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))])
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
def setUp(self): Bf3TestCase.setUp(self) self.conf = CfgConfigParser() self.conf.loadFromString("""[commands] yell: 20 [preferences] yell_duration: 2 """) self.p = Poweradminbf3Plugin(self.console, self.conf) self.p.onLoadConfig() self.p.onStartup()
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])
def setUp(self): B3TestCase.setUp(self) with logging_disabled(): self.console.startup() logging.getLogger('output').setLevel(logging.DEBUG) self.conf = CfgConfigParser() self.p = ChatloggerPlugin(self.console, self.conf) when(self.console.config).get('b3', 'time_zone').thenReturn('GMT') self.p.setup_fileLogger = Mock()
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)
def setUp(self): Bf3TestCase.setUp(self) self.conf = CfgConfigParser() self.conf.loadFromString("""[commands] scramblemode: 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 setUp(self): super(Test_issue_14, self).setUp() self.conf = CfgConfigParser() self.conf.loadFromString(""" [commands] changeteam: guest [preferences] no_level_check_level: 20 """) self.p = Poweradminbf4Plugin(self.console, self.conf) self.p.onLoadConfig() self.p.onStartup()
def setUp(self): Bf3TestCase.setUp(self) self.conf = CfgConfigParser() with logging_disabled(): self.p = Poweradminbf3Plugin(self.console, self.conf) when(self.console).write( ('vars.roundStartPlayerCount', )).thenReturn(['0']) when(self.console).write( ('vars.roundLockdownCountdown', )).thenReturn(['3']) self.scrambleTeams_mock = self.p._scrambler.scrambleTeams = Mock( name="scrambleTeams", wraps=self.p._scrambler.scrambleTeams) self.scrambleTeams_mock.reset_mock()
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)
def setUp(self): super(Test_cmd_idle, self).setUp() self.conf = CfgConfigParser() self.conf.loadFromString("""[commands] idle: 40 """) with logging_disabled(): self.p = Poweradminbf3Plugin(self.console, self.conf) self.p.onLoadConfig() self.p.onStartup() self.p.error = Mock(wraps=self.p.error) logging.getLogger('output').setLevel(logging.DEBUG)
def test_no_client_table(self, pluginCronTab_mock): conf = CfgConfigParser() conf.loadFromString(dedent(r""" [settings] interval: 60 output_file: ~/status.xml enableDBsvarSaving: no enableDBclientSaving: no """)) self.p = StatusPlugin(self.console, conf) self.p._tables = { 'svars': 'current_svars', 'cvars': 'current_clients' } self.p.onLoadConfig() self.assertEqual("current_clients", self.p._tables['cvars'])
def setUp(self): super(Test_cmd_setnextmap, self).setUp() self.conf = CfgConfigParser() self.conf.loadFromString("""[commands] setnextmap-snmap: 20 """) self.p = Poweradminbf3Plugin(self.console, self.conf) self.p.onLoadConfig() self.p.onStartup() logging.getLogger('output').setLevel(logging.DEBUG) self.console.game.gameType = 'ConquestSmall0' self.console.game.serverinfo = {'roundsTotal': 2}
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")
class Test_Tk_default_config(B3TestCase): def setUp(self): super(Test_Tk_default_config, self).setUp() self.console.gameName = 'f00' self.conf = CfgConfigParser() self.conf.load(b3.getAbsolutePath('@b3/conf/plugin_tk.ini')) self.p = TkPlugin(self.console, self.conf) self.p.onLoadConfig() def test_settings(self): self.assertEqual(400, self.p._maxPoints) self.assertEqual(40, self.p._maxLevel) self.assertEqual({ 0: (2.0, 1.0, 2), 1: (2.0, 1.0, 2), 2: (1.0, 0.5, 1), 20: (1.0, 0.5, 0), 40: (0.75, 0.5, 0) }, self.p._levels) self.assertEqual(7, self.p._round_grace) self.assertEqual("sfire", self.p._issue_warning) self.assertTrue(self.p._grudge_enable) self.assertTrue(self.p._private_messages) self.assertEqual(100, self.p._damage_threshold) self.assertEqual(2, self.p._warn_level) self.assertEqual(0, self.p._tkpointsHalflife) self.assertEqual('1h', self.p._tk_warn_duration) def test_messages(self): self.assertEqual("^7team damage over limit", self.p.config.get('messages', 'ban')) self.assertEqual("^7$vname^7 has forgiven $aname [^3$points^7]", self.p.config.get('messages', 'forgive')) self.assertEqual("^7$vname^7 has a ^1grudge ^7against $aname [^3$points^7]", self.p.config.get('messages', 'grudged')) self.assertEqual("^7$vname^7 has forgiven $attackers", self.p.config.get('messages', 'forgive_many')) self.assertEqual("^1ALERT^7: $name^7 auto-kick if not forgiven. Type ^3!forgive $cid ^7to forgive. [^3damage: $points^7]", self.p.config.get('messages', 'forgive_warning')) self.assertEqual("^7no one to forgive", self.p.config.get('messages', 'no_forgive')) self.assertEqual("^7Forgive who? %s", self.p.config.get('messages', 'players')) self.assertEqual("^7$name^7 has ^3$points^7 TK points", self.p.config.get('messages', 'forgive_info')) self.assertEqual("^7$name^7 cleared of ^3$points^7 TK points", self.p.config.get('messages', 'forgive_clear')) self.assertEqual("^3Do not attack teammates, ^1Attacked: ^7$vname ^7[^3$points^7]", self.p.config.get('messages', 'tk_warning_reason')) def test__default_messages(self): conf_items = self.p.config.items('messages') for conf_message_id, conf_message in conf_items: if conf_message_id not in self.p._default_messages: self.fail("%s should be added to the _default_messages dict" % conf_message_id) if conf_message != self.p._default_messages[conf_message_id]: self.fail("default message in the _default_messages dict for %s does not match the message from the config file" % conf_message_id) for default_message_id in self.p._default_messages: if default_message_id not in zip(*conf_items)[0]: self.fail("%s exists in the _default_messages dict, but not in the config file" % default_message_id)
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 Cmdmanager_TestCase(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""" [settings] update_config_file: no [commands] cmdlevel: fulladmin cmdalias: fulladmin cmdgrant: superadmin cmdrevoke: superadmin cmduse: superadmin """)) self.p = CmdmanagerPlugin(self.console, self.conf) self.p.onLoadConfig() self.p.onStartup() def assert_cmd_groups(self, cmd_name, groups): """ Assert a command has the given authorized groups set correctly. :param cmd_name: str name of a command :param groups: str minimum group required to run the command or group range """ cmd = self.adminPlugin._commands[cmd_name] self.assertIsNotNone(cmd, "could not find command %r" % cmd_name) self.assertEqual(groups, self.p.get_command_level_string(cmd)) def assert_cmd_alias(self, cmd_name, alias_name): """ Assert a command has the given alias. :param cmd_name: str command name :param alias_name: str expected alias name, or None """ cmd = self.adminPlugin._commands[cmd_name] self.assertIsNotNone(cmd, "could not find command %r" % cmd_name) self.assertEqual(alias_name if alias_name is not None else '', cmd.alias)
def setUp(self): super(mixin_cmd_headshots, self).setUp() self.conf = CfgConfigParser() self.conf.loadFromString(""" [settings] reset_headshots: yes min_level_headshots_cmd: 1 show_awards: yes """) self.p = HeadshotsurtPlugin(self.console, self.conf) self.p.onLoadConfig() self.p.onStartup() self.moderator.connects("2")
class mixin_cmd_pasetnextmap: 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 XlrstatsTestCase(B3TestCase): def setUp(self): """ This method is called before each test. It is meant to set up the SUT (System Under Test) in a manner that will ease the testing of its features. """ with logging_disabled(): # The B3TestCase class provides us a working B3 environment that does not require any database connexion. # The B3 console is then accessible with self.console B3TestCase.setUp(self) # set additional B3 console stuff that will be used by the XLRstats plugin self.console.gameName = "MyGame" self.parser_conf.add_section('b3') self.parser_conf.set('b3', 'time_zone', 'GMT') # we make our own AdminPlugin and make sure it is the one return in any case self.adminPlugin = AdminPlugin(self.console, DEFAULT_ADMIN_CONFIG_FILE) when(self.console).getPlugin("admin").thenReturn(self.adminPlugin) self.adminPlugin.onLoadConfig() self.adminPlugin.onStartup() # We need a config for the Xlrstats plugin self.conf = CfgConfigParser() # It is an empty config but we can fill it up later # Now we create an instance of the SUT (System Under Test) which is the XlrstatsPlugin self.p = XlrstatsPlugin(self.console, self.conf) when(self.console).getPlugin("xlrstats").thenReturn(self.p) # create a client object to represent the game server with patch("b3.clients.Clients.authorizeClients"): # we patch authorizeClients or it will spawn a thread # with a 5 second timer self.console.clients.newClient(-1, name="WORLD", guid="WORLD", hide=True) def init(self, config_content=None): """ Load the config and starts the xlrstats plugin. If no config_content is provided, use the default config file :param config_content: optional XLRstats config :type config_content: str """ if config_content is None: self.conf.load(DEFAULT_XLRSTATS_CONFIG_FILE) else: self.conf.loadFromString(config_content) self.p.onLoadConfig() self.p.minlevel = 1 # tests in this module assume unregistered players aren't considered by Xlrstats self.p.onStartup()
def setUp(self): Iourt42TestCase.setUp(self) self.conf = CfgConfigParser() self.p = Weaponcontrolurt42Plugin(self.console, self.conf) logger = logging.getLogger('output') logger.setLevel(logging.DEBUG) self.player = Test_events.FakeUrtClient(self.console, name="Player", guid="Player_guid", groupBits=4, team=TEAM_RED) self.player.connects("1") self.p.check_client = Mock(wraps=self.p.check_client) self.console.write = Mock()
class mixin_cmd_paset(object): def setUp(self): super(mixin_cmd_paset, self).setUp() self.conf = CfgConfigParser() self.conf.loadFromString(""" [commands] paset: 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.setCvar_patcher = patch.object(self.console, 'setCvar') self.setCvar_mock = self.setCvar_patcher.start() self.moderator.connects("2") def assert_setCvar_calls(self, expected_calls): self.assertListEqual(expected_calls, self.setCvar_mock.mock_calls) def tearDown(self): super(mixin_cmd_paset, self).tearDown() self.sleep_patcher.stop() self.setCvar_patcher.stop() def test_nominal(self): # WHEN self.moderator.says('!paset sv_foo bar') # THEN self.assert_setCvar_calls([call('sv_foo', 'bar')]) self.assertListEqual([], self.moderator.message_history) def test_no_parameter(self): # WHEN self.moderator.says('!paset') # THEN self.assert_setCvar_calls([]) self.assertListEqual(['Invalid or missing data, try !help paset'], self.moderator.message_history) def test_no_value(self): # WHEN self.moderator.says('!paset sv_foo') # THEN self.assert_setCvar_calls([call('sv_foo', '')]) self.assertListEqual([], self.moderator.message_history)
class Test_events(unittest.TestCase): def setUp(self): with logging_disabled(): from b3.fake import FakeConsole, FakeClient self.console = FakeConsole('@b3/conf/b3.distribution.xml') self.conf = CfgConfigParser() self.p = GaPlugin(self.console, self.conf) self.conf.loadFromString( dedent(""" [google analytics] tracking ID: UA-000000-0 """)) self.p.onLoadConfig() self.p.onStartup() self.assertIsNotNone(self.p._ga_tracking_id) self.joe = FakeClient(self.console, name="Joe", guid="GUID_joe", ip="12.12.12.12") self.jack = FakeClient(self.console, name="Jack", guid="GUID_jack", ip="45.45.45.45") def test_auth(self, fire_mock): self.joe.connects("1") # THEN self.assertEqual(1, len(fire_mock.mock_calls)) def test_disconnect(self, fire_mock): self.joe.connects("1") self.joe.disconnects() # THEN self.assertEqual(2, len(fire_mock.mock_calls)) def test_new_round(self, fire_mock): # GIVEN self.joe.connects("1") self.jack.connects("2") # WHEN self.console.game.gameType = "The game type" self.console.game.mapName = "The map name" self.console.queueEvent( self.console.getEvent('EVT_GAME_ROUND_START', data=self.console.game)) # THEN self.assertEqual(4, len(fire_mock.mock_calls))
class Test_cmd_scramblemode(Bf3TestCase): def setUp(self): Bf3TestCase.setUp(self) self.conf = CfgConfigParser() self.conf.loadFromString("""[commands] scramblemode: 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_no_arguments(self): self.superadmin.says('!scramblemode') self.assertEqual(["invalid data. Expecting 'random' or 'score'"], self.superadmin.message_history) self.assertFalse(self.p._scrambler.setStrategy.called) def test_bad_arguments(self): self.superadmin.says('!scramblemode f00') self.assertEqual(["invalid data. Expecting 'random' or 'score'"], self.superadmin.message_history) self.assertFalse(self.p._scrambler.setStrategy.called) def test_random(self): self.superadmin.says('!scramblemode random') self.assertEqual(['Scrambling strategy is now: random'], self.superadmin.message_history) self.p._scrambler.setStrategy.assert_called_once_with("random") def test_r(self): self.superadmin.says('!scramblemode r') self.assertEqual(['Scrambling strategy is now: random'], self.superadmin.message_history) self.p._scrambler.setStrategy.assert_called_once_with("random") def test_score(self): self.superadmin.says('!scramblemode score') self.assertEqual(['Scrambling strategy is now: score'], self.superadmin.message_history) self.p._scrambler.setStrategy.assert_called_once_with("score") def test_s(self): self.superadmin.says('!scramblemode s') self.assertEqual(['Scrambling strategy is now: score'], self.superadmin.message_history) self.p._scrambler.setStrategy.assert_called_once_with("score")
def setUp(self): Iourt42TestCase.setUp(self) self.conf = CfgConfigParser() self.p = Weaponcontrolurt42Plugin(self.console, self.conf) logger = logging.getLogger('output') logger.setLevel(logging.INFO) self.info_patcher = patch.object(self.p, "info", wraps=self.p.info) self.info_mock = self.info_patcher.start() self.warning_patcher = patch.object(self.p, "warning", wraps=self.p.warning) self.warning_mock = self.warning_patcher.start() self.error_patcher = patch.object(self.p, "error", wraps=self.p.error) self.error_mock = self.error_patcher.start()
def setUp(self): super(Test_cmd_swap, self).setUp() self.conf = CfgConfigParser() self.conf.loadFromString(""" [commands] paswap-swap: 20 """) 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 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 setUp(self): CallvoteTestCase.setUp(self) with logging_disabled(): from b3.fake import FakeClient # create some clients self.mike = FakeClient(console=self.console, name="Mike", guid="mikeguid", team=TEAM_RED, groupBits=128) self.bill = FakeClient(console=self.console, name="Bill", guid="billguid", team=TEAM_BLUE, groupBits=16) self.mark = FakeClient(console=self.console, name="Mark", guid="markguid", team=TEAM_RED, groupBits=2) self.sara = FakeClient(console=self.console, name="Sara", guid="saraguid", team=TEAM_SPEC, groupBits=1) self.conf = CfgConfigParser() self.p = CallvotePlugin(self.console, self.conf)
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 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 setUp(self): self.conf = CfgConfigParser() self.conf.loadFromString("""[configuration]""") self.parser = BfhParser(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 event_repr(self): return "Event(%r, data=%r, client=%r, target=%r)" % ( b3.events.eventManager.getName( self.type), self.data, self.client, self.target) b3.events.Event.__repr__ = event_repr