combine reload pythonic action tests to single test, use existing action.d/action.py from test-suite instead of create action on demand

This commit is contained in:
sebres 2026-11-15 19:31:53 +01:00
parent 5bfe1c4d7d
commit 9e1fa80f82
3 changed files with 53 additions and 60 deletions

View file

@ -15,11 +15,9 @@ ver. 1.1.2-dev-1 (20??/??/??) - development nightly edition
without replaying previously banned tickets into the new actions (gh-2716).
* `fail2ban-client reload` resets the jail options removed from configuration to their defaults now: `bantime.increment` and
other `bantime.*` options, `ignoreself`, `ignorecommand`, `ignorecache`, `logtimezone`, `prefregex`, `maxlines` and `datepattern`
retained their previous values until restart of the jail, if they were no more specified in config
* reload keeps existing actions: a Python action without `reload` method (e. g. `smtp.py`) was replaced with new instance
and started by every reload, but the previous instance was never stopped and the new one did not know current bans;
now the existing instance is retained (neither stopped nor started again), changed parameters of such action
take effect after restart of the jail (logged by reload)
retained their previous values until restart of the jail, if they were no more specified in config;
pythonic actions without `reload` method remain unchanged (neither stopped nor started again),
changed parameters of such action take effect after restart of the jail only (logged by reload)
* `fail2ban-client statistic`: format the existing singular alias as the same
statistics table as `stats` and `statistics` (gh-4266).
* backend `pyinotify`: fixes monitoring on systems with native inotify other than Linux (e. g. FreeBSD 15+),

View file

@ -111,66 +111,55 @@ class ExecuteActions(LogCaptureTestCase):
self.assertNotLogged("stdout: 'unexpected-reload'")
self.__actions.stopActions()
def testExistingPythonActionReloadsWithoutClearingParameters(self):
self.__actions.add('existing',
def testExistingPythonActionReloads(self):
self.__actions.add('act',
os.path.join(TEST_FILES_DIR, 'action.d/action.py'), {'opt1': 'initial'})
existing = self.__actions['existing']
calls = []
existing.reload = lambda **kwargs: calls.append(kwargs)
existing.start = lambda: self.fail('existing action must not start again')
self.__actions.reload(begin=True)
self.__actions.add('existing', initOpts={'opt1': 'changed'}, reload=True)
self.assertEqual(calls, [])
self.__actions.reload(begin=False)
self.assertIs(self.__actions['existing'], existing)
self.assertEqual(calls, [{'opt1': 'changed'}])
self.__actions.stopActions()
@with_tmpdir
def testExistingPythonActionWithoutReloadRetainedOnReload(self, tmp):
# python action without reload method (like smtp.py) is retained by reload (same instance,
# neither stopped nor started again); test action logs "<name>-<tag> <method> [<ip>]":
pyact = os.path.join(tmp, 'action.py')
with open(pyact, 'w') as f:
f.write("\n".join((
"from fail2ban.server.action import ActionBase",
"class Action(ActionBase):",
" def __init__(self, jail, name, tag):",
" super(Action, self).__init__(jail, name)",
" self._pref = '%s-%s' % (name, tag)",
" def start(self): self._logSys.info('%s start', self._pref)",
" def stop(self): self._logSys.info('%s stop', self._pref)",
" def ban(self, aInfo): self._logSys.info('%s ban %s', self._pref, aInfo['ip'])",
" def unban(self, aInfo): self._logSys.info('%s unban %s', self._pref, aInfo['ip'])",
""
)))
self.__actions.add('act', pyact, {'tag': 'old'})
self.__actions.add('other')
act = self.__actions['act']
self.assertFalse(hasattr(act, 'reload'))
self.__actions.start()
self.assertLogged('act-old start', wait=True)
self.assertLogged('TestAction action start', wait=True)
self.assertEqual(act.opt1, "initial")
self.__actions.addBannedIP('192.0.2.1')
self.assertLogged('act-old ban 192.0.2.1')
self.pruneLog('[test-phase] reload')
self.assertLogged('TestAction action ban 192.0.2.1', wait=True)
# firstly action with reload method:
self.pruneLog('[test-phase 1] with reload method')
act.reload = act._testreload
self.__actions.reload(begin=True)
self.__actions.add('act', pyact, {'tag': 'new'}, reload=True)
self.__actions.add('other', reload=True)
self.__actions.add('act', initOpts={'opt1': 'reload', 'name': 'ReloadedAction'}, reload=True)
self.__actions.reload(begin=False)
# same instance, not stopped, not started again, no new instance created:
self.assertIs(self.__actions['act'], act)
self.assertNotLogged('act-old stop', 'act-old start', 'act-new', all=True)
self.assertLogged("Jail 'DummyJail' action 'act' does not support reload, changed "
"parameters take effect after restart of the jail")
self.assertEqual(list(self.__actions), ['act', 'other'])
# further bans reach the retained instance, stop unbans all and stops it once:
self.pruneLog('[test-phase] after reload')
self.assertEqual(act.opt1, "reload")
self.assertLogged('TestAction action reload', wait=True)
self.assertNotLogged('action stop', 'action start', all=True)
self.__actions.addBannedIP('192.0.2.2')
self.assertLogged('act-old ban 192.0.2.2')
self.assertLogged('ReloadedAction action ban 192.0.2.2', wait=True)
# then without reload method - same instance, not stopped, not started again,
# no new instance created, furthermore, no parameters are updated (which is to be expected,
# given that no reloading takes place):
self.pruneLog('[test-phase 2] no reload method')
del act.reload
self.assertFalse(hasattr(act, 'reload'))
self.__actions.reload(begin=True)
self.__actions.add('act', act, {'opt1': 'no-reload', 'name': 'NoReloadAction'}, reload=True)
self.__actions.reload(begin=False)
self.assertEqual(act.opt1, "reload") # no reload method, remain changed by 1st phase
self.assertLogged("Jail 'DummyJail' action 'act' does not support reload, changed "
"parameters take effect after restart of the jail",
wait=True)
self.assertIs(self.__actions['act'], act)
self.assertNotLogged('action reload', 'action stop', 'action start', all=True)
self.__actions.addBannedIP('192.0.2.3')
self.assertLogged('ReloadedAction action ban 192.0.2.3', wait=True)
# stop
self.pruneLog('[test-phase 3] stop')
self.__actions.stop()
self.__actions.join()
self.assertLogged('act-old unban 192.0.2.1', 'act-old unban 192.0.2.2', 'act-old stop', all=True)
self.assertNotLogged('act-new', all=True)
self.assertLogged(
'ReloadedAction action unban 192.0.2.1',
'ReloadedAction action unban 192.0.2.2',
'ReloadedAction action unban 192.0.2.3',
'ReloadedAction action stop', all=True,
wait=True
)
def testRepeatedReloadDoesNotRestartNewAction(self):
self.__actions.reload(begin=True)

View file

@ -6,22 +6,28 @@ class TestAction(ActionBase):
def __init__(self, jail, name, opt1, opt2=None):
super(TestAction, self).__init__(jail, name)
self._logSys.debug("%s initialised" % self.__class__.__name__)
self._name = self.__class__.__name__
self._logSys.debug("%s initialised", self._name)
self.opt1 = opt1
self.opt2 = opt2
self._opt3 = "Hello"
def _testreload(self, **kwargs):
self._logSys.debug("%s action reload: %r", self._name, kwargs)
self.opt1 = kwargs['opt1']
self._name = kwargs.get('name', self.__class__.__name__)
def start(self):
self._logSys.debug("%s action start" % self.__class__.__name__)
self._logSys.debug("%s action start", self._name)
def stop(self):
self._logSys.debug("%s action stop" % self.__class__.__name__)
self._logSys.debug("%s action stop", self._name)
def ban(self, aInfo):
self._logSys.debug("%s action ban" % self.__class__.__name__)
self._logSys.debug("%s action ban %s", self._name, aInfo['ip'])
def unban(self, aInfo):
self._logSys.debug("%s action unban" % self.__class__.__name__)
self._logSys.debug("%s action unban %s", self._name, aInfo['ip'])
def testmethod(self, text):
return "%s %s %s" % (self._opt3, text, self.opt1)