1065
1008
for client in self.clients:
1066
1009
self.assertFalse(client.attributes["Enabled"])
1068
class Unique(object):
1069
"""Class for objects which exist only to be unique objects, since
1070
unittest.mock.sentinel only exists in Python 3.3"""
1072
class TestPropertyCmd(TestCmd):
1073
"""Abstract class for tests of PropertyCmd classes"""
1075
if not hasattr(self, "command"):
1077
values_to_get = getattr(self, "values_to_get",
1079
for value_to_set, value_to_get in zip(self.values_to_set,
1081
for client in self.clients:
1082
old_value = client.attributes[self.property]
1083
self.assertNotIsInstance(old_value, Unique)
1084
client.attributes[self.property] = Unique()
1085
self.run_command(value_to_set, self.clients)
1086
for client in self.clients:
1087
value = client.attributes[self.property]
1088
self.assertNotIsInstance(value, Unique)
1089
self.assertEqual(value, value_to_get)
1090
def run_command(self, value, clients):
1091
self.command().run(None, clients)
1093
class TestBumpTimeoutCmd(TestPropertyCmd):
1094
command = BumpTimeoutCmd
1095
property = "LastCheckedOK"
1096
values_to_set = [""]
1098
class TestStartCheckerCmd(TestPropertyCmd):
1099
command = StartCheckerCmd
1100
property = "CheckerRunning"
1101
values_to_set = [dbus.Boolean(True)]
1103
class TestStopCheckerCmd(TestPropertyCmd):
1104
command = StopCheckerCmd
1105
property = "CheckerRunning"
1106
values_to_set = [dbus.Boolean(False)]
1108
class TestApproveByDefaultCmd(TestPropertyCmd):
1109
command = ApproveByDefaultCmd
1110
property = "ApprovedByDefault"
1111
values_to_set = [dbus.Boolean(True)]
1113
class TestDenyByDefaultCmd(TestPropertyCmd):
1114
command = DenyByDefaultCmd
1115
property = "ApprovedByDefault"
1116
values_to_set = [dbus.Boolean(False)]
1118
class TestValueArgumentPropertyCmd(TestPropertyCmd):
1119
"""Abstract class for tests of PropertyCmd classes using the
1120
ValueArgumentMixIn"""
1122
if type(self) is TestValueArgumentPropertyCmd:
1124
return super(TestValueArgumentPropertyCmd, self).runTest()
1125
def run_command(self, value, clients):
1126
self.command(value).run(None, clients)
1128
class TestSetCheckerCmd(TestValueArgumentPropertyCmd):
1129
command = SetCheckerCmd
1130
property = "Checker"
1131
values_to_set = ["", ":", "fping -q -- %s"]
1133
class TestSetHostCmd(TestValueArgumentPropertyCmd):
1134
command = SetHostCmd
1136
values_to_set = ["192.0.2.3", "foo.example.org"]
1138
class TestSetSecretCmd(TestValueArgumentPropertyCmd):
1139
command = SetSecretCmd
1141
values_to_set = [io.BytesIO(b""),
1142
io.BytesIO(b"secret\0xyzzy\nbar")]
1143
values_to_get = [b"", b"secret\0xyzzy\nbar"]
1145
class TestSetTimeoutCmd(TestValueArgumentPropertyCmd):
1146
command = SetTimeoutCmd
1147
property = "Timeout"
1148
values_to_set = [datetime.timedelta(),
1149
datetime.timedelta(minutes=5),
1150
datetime.timedelta(seconds=1),
1151
datetime.timedelta(weeks=1),
1152
datetime.timedelta(weeks=52)]
1153
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1155
class TestSetExtendedTimeoutCmd(TestValueArgumentPropertyCmd):
1156
command = SetExtendedTimeoutCmd
1157
property = "ExtendedTimeout"
1158
values_to_set = [datetime.timedelta(),
1159
datetime.timedelta(minutes=5),
1160
datetime.timedelta(seconds=1),
1161
datetime.timedelta(weeks=1),
1162
datetime.timedelta(weeks=52)]
1163
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1165
class TestSetIntervalCmd(TestValueArgumentPropertyCmd):
1166
command = SetIntervalCmd
1167
property = "Interval"
1168
values_to_set = [datetime.timedelta(),
1169
datetime.timedelta(minutes=5),
1170
datetime.timedelta(seconds=1),
1171
datetime.timedelta(weeks=1),
1172
datetime.timedelta(weeks=52)]
1173
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1175
class TestSetApprovalDelayCmd(TestValueArgumentPropertyCmd):
1176
command = SetApprovalDelayCmd
1177
property = "ApprovalDelay"
1178
values_to_set = [datetime.timedelta(),
1179
datetime.timedelta(minutes=5),
1180
datetime.timedelta(seconds=1),
1181
datetime.timedelta(weeks=1),
1182
datetime.timedelta(weeks=52)]
1183
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1185
class TestSetApprovalDurationCmd(TestValueArgumentPropertyCmd):
1186
command = SetApprovalDurationCmd
1187
property = "ApprovalDuration"
1188
values_to_set = [datetime.timedelta(),
1189
datetime.timedelta(minutes=5),
1190
datetime.timedelta(seconds=1),
1191
datetime.timedelta(weeks=1),
1192
datetime.timedelta(weeks=52)]
1193
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1195
class Test_command_from_options(unittest.TestCase):
1197
self.parser = argparse.ArgumentParser()
1198
add_command_line_options(self.parser)
1199
def assert_command_from_args(self, args, command_cls, **cmd_attrs):
1200
"""Assert that parsing ARGS should result in an instance of
1201
COMMAND_CLS with (optionally) all supplied attributes (CMD_ATTRS)."""
1202
options = self.parser.parse_args(args)
1203
check_option_syntax(self.parser, options)
1204
commands = commands_from_options(options)
1205
self.assertEqual(len(commands), 1)
1206
command = commands[0]
1207
self.assertIsInstance(command, command_cls)
1208
for key, value in cmd_attrs.items():
1209
self.assertEqual(getattr(command, key), value)
1210
def test_print_table(self):
1211
self.assert_command_from_args([], PrintTableCmd,
1214
def test_print_table_verbose(self):
1215
self.assert_command_from_args(["--verbose"], PrintTableCmd,
1218
def test_print_table_verbose_short(self):
1219
self.assert_command_from_args(["-v"], PrintTableCmd,
1222
def test_enable(self):
1223
self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1225
def test_enable_short(self):
1226
self.assert_command_from_args(["-e", "foo"], EnableCmd)
1228
def test_disable(self):
1229
self.assert_command_from_args(["--disable", "foo"],
1232
def test_disable_short(self):
1233
self.assert_command_from_args(["-d", "foo"], DisableCmd)
1235
def test_bump_timeout(self):
1236
self.assert_command_from_args(["--bump-timeout", "foo"],
1239
def test_bump_timeout_short(self):
1240
self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1242
def test_start_checker(self):
1243
self.assert_command_from_args(["--start-checker", "foo"],
1246
def test_stop_checker(self):
1247
self.assert_command_from_args(["--stop-checker", "foo"],
1250
def test_remove(self):
1251
self.assert_command_from_args(["--remove", "foo"],
1254
def test_remove_short(self):
1255
self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1257
def test_checker(self):
1258
self.assert_command_from_args(["--checker", ":", "foo"],
1259
SetCheckerCmd, value_to_set=":")
1261
def test_checker_empty(self):
1262
self.assert_command_from_args(["--checker", "", "foo"],
1263
SetCheckerCmd, value_to_set="")
1265
def test_checker_short(self):
1266
self.assert_command_from_args(["-c", ":", "foo"],
1267
SetCheckerCmd, value_to_set=":")
1269
def test_timeout(self):
1270
self.assert_command_from_args(["--timeout", "PT5M", "foo"],
1272
value_to_set=300000)
1274
def test_timeout_short(self):
1275
self.assert_command_from_args(["-t", "PT5M", "foo"],
1277
value_to_set=300000)
1279
def test_extended_timeout(self):
1280
self.assert_command_from_args(["--extended-timeout", "PT15M",
1282
SetExtendedTimeoutCmd,
1283
value_to_set=900000)
1285
def test_interval(self):
1286
self.assert_command_from_args(["--interval", "PT2M", "foo"],
1288
value_to_set=120000)
1290
def test_interval_short(self):
1291
self.assert_command_from_args(["-i", "PT2M", "foo"],
1293
value_to_set=120000)
1295
def test_approve_by_default(self):
1296
self.assert_command_from_args(["--approve-by-default", "foo"],
1297
ApproveByDefaultCmd)
1299
def test_deny_by_default(self):
1300
self.assert_command_from_args(["--deny-by-default", "foo"],
1303
def test_approval_delay(self):
1304
self.assert_command_from_args(["--approval-delay", "PT30S",
1305
"foo"], SetApprovalDelayCmd,
1308
def test_approval_duration(self):
1309
self.assert_command_from_args(["--approval-duration", "PT1S",
1310
"foo"], SetApprovalDurationCmd,
1313
def test_host(self):
1314
self.assert_command_from_args(["--host", "foo.example.org",
1316
value_to_set="foo.example.org")
1318
def test_host_short(self):
1319
self.assert_command_from_args(["-H", "foo.example.org",
1321
value_to_set="foo.example.org")
1323
def test_secret_devnull(self):
1324
self.assert_command_from_args(["--secret", os.path.devnull,
1325
"foo"], SetSecretCmd,
1328
def test_secret_tempfile(self):
1329
with tempfile.NamedTemporaryFile(mode="r+b") as f:
1330
value = b"secret\0xyzzy\nbar"
1333
self.assert_command_from_args(["--secret", f.name,
1334
"foo"], SetSecretCmd,
1337
def test_secret_devnull_short(self):
1338
self.assert_command_from_args(["-s", os.path.devnull, "foo"],
1339
SetSecretCmd, value_to_set=b"")
1341
def test_secret_tempfile_short(self):
1342
with tempfile.NamedTemporaryFile(mode="r+b") as f:
1343
value = b"secret\0xyzzy\nbar"
1346
self.assert_command_from_args(["-s", f.name, "foo"],
1350
def test_approve(self):
1351
self.assert_command_from_args(["--approve", "foo"],
1354
def test_approve_short(self):
1355
self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1357
def test_deny(self):
1358
self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1360
def test_deny_short(self):
1361
self.assert_command_from_args(["-D", "foo"], DenyCmd)
1363
def test_dump_json(self):
1364
self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1366
def test_is_enabled(self):
1367
self.assert_command_from_args(["--is-enabled", "foo"],
1370
def test_is_enabled_short(self):
1371
self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1373
def test_deny_before_remove(self):
1374
options = self.parser.parse_args(["--deny", "--remove", "foo"])
1375
check_option_syntax(self.parser, options)
1376
commands = commands_from_options(options)
1377
self.assertEqual(len(commands), 2)
1378
self.assertIsInstance(commands[0], DenyCmd)
1379
self.assertIsInstance(commands[1], RemoveCmd)
1381
def test_deny_before_remove_reversed(self):
1382
options = self.parser.parse_args(["--remove", "--deny", "--all"])
1383
check_option_syntax(self.parser, options)
1384
commands = commands_from_options(options)
1385
self.assertEqual(len(commands), 2)
1386
self.assertIsInstance(commands[0], DenyCmd)
1387
self.assertIsInstance(commands[1], RemoveCmd)
1390
class Test_check_option_syntax(unittest.TestCase):
1391
# This mostly corresponds to the definition from has_actions() in
1392
# check_option_syntax()
1394
# The actual values set here are not that important, but we do
1395
# at least stick to the correct types, even though they are
1399
"bump_timeout": True,
1400
"start_checker": True,
1401
"stop_checker": True,
1405
"timeout": datetime.timedelta(),
1406
"extended_timeout": datetime.timedelta(),
1407
"interval": datetime.timedelta(),
1408
"approved_by_default": True,
1409
"approval_delay": datetime.timedelta(),
1410
"approval_duration": datetime.timedelta(),
1412
"secret": io.BytesIO(b"x"),
1418
self.parser = argparse.ArgumentParser()
1419
add_command_line_options(self.parser)
1421
@contextlib.contextmanager
1422
def assertParseError(self):
1423
with self.assertRaises(SystemExit) as e:
1424
with self.temporarily_suppress_stderr():
1426
# Exit code from argparse is guaranteed to be "2". Reference:
1427
# https://docs.python.org/3/library/argparse.html#exiting-methods
1428
self.assertEqual(e.exception.code, 2)
1431
@contextlib.contextmanager
1432
def temporarily_suppress_stderr():
1433
null = os.open(os.path.devnull, os.O_RDWR)
1434
stderrcopy = os.dup(sys.stderr.fileno())
1435
os.dup2(null, sys.stderr.fileno())
1441
os.dup2(stderrcopy, sys.stderr.fileno())
1442
os.close(stderrcopy)
1444
def check_option_syntax(self, options):
1445
check_option_syntax(self.parser, options)
1447
def test_actions_requires_client_or_all(self):
1448
for action, value in self.actions.items():
1449
options = self.parser.parse_args()
1450
setattr(options, action, value)
1451
with self.assertParseError():
1452
self.check_option_syntax(options)
1454
def test_actions_conflicts_with_verbose(self):
1455
for action, value in self.actions.items():
1456
options = self.parser.parse_args()
1457
setattr(options, action, value)
1458
options.verbose = True
1459
with self.assertParseError():
1460
self.check_option_syntax(options)
1462
def test_dump_json_conflicts_with_verbose(self):
1463
options = self.parser.parse_args()
1464
options.dump_json = True
1465
options.verbose = True
1466
with self.assertParseError():
1467
self.check_option_syntax(options)
1469
def test_dump_json_conflicts_with_action(self):
1470
for action, value in self.actions.items():
1471
options = self.parser.parse_args()
1472
setattr(options, action, value)
1473
options.dump_json = True
1474
with self.assertParseError():
1475
self.check_option_syntax(options)
1477
def test_all_can_not_be_alone(self):
1478
options = self.parser.parse_args()
1480
with self.assertParseError():
1481
self.check_option_syntax(options)
1483
def test_all_is_ok_with_any_action(self):
1484
for action, value in self.actions.items():
1485
options = self.parser.parse_args()
1486
setattr(options, action, value)
1488
self.check_option_syntax(options)
1490
def test_is_enabled_fails_without_client(self):
1491
options = self.parser.parse_args()
1492
options.is_enabled = True
1493
with self.assertParseError():
1494
self.check_option_syntax(options)
1496
def test_is_enabled_works_with_one_client(self):
1497
options = self.parser.parse_args()
1498
options.is_enabled = True
1499
options.client = ["foo"]
1500
self.check_option_syntax(options)
1502
def test_is_enabled_fails_with_two_clients(self):
1503
options = self.parser.parse_args()
1504
options.is_enabled = True
1505
options.client = ["foo", "barbar"]
1506
with self.assertParseError():
1507
self.check_option_syntax(options)
1509
def test_remove_can_only_be_combined_with_action_deny(self):
1510
for action, value in self.actions.items():
1511
if action in {"remove", "deny"}:
1513
options = self.parser.parse_args()
1514
setattr(options, action, value)
1516
options.remove = True
1517
with self.assertParseError():
1518
self.check_option_syntax(options)
1522
1013
def should_only_run_tests():