/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to mandos-ctl

  • Committer: Teddy Hogeborn
  • Date: 2019-03-07 20:57:16 UTC
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 382.
  • Revision ID: teddy@recompile.se-20190307205716-n1yj0lz23k143u0l
mandos-ctl: Refactor; extract syntax check to separate function

* mandos-ctl (check_option_syntax): New.
  (main): Call check_option_syntax().

Show diffs side-by-side

added added

removed removed

Lines of Context:
44
44
import logging
45
45
import io
46
46
import tempfile
47
 
import contextlib
48
47
 
49
48
import dbus
50
49
 
294
293
                    "ApprovalDuration", "Checker", "ExtendedTimeout",
295
294
                    "Expires", "LastCheckerStatus")
296
295
    def run(self, mandos, clients):
297
 
        print(self.output(clients.values()))
298
 
    def output(self, clients):
299
 
        raise NotImplementedError()
 
296
        print(self.output(clients))
300
297
 
301
298
class PropertyCmd(Command):
302
299
    """Abstract class for Actions for setting one client property"""
303
300
    def run_on_one_client(self, client, properties):
304
301
        """Set the Client's D-Bus property"""
305
 
        log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", busname,
306
 
                  client.__dbus_object_path__,
307
 
                  dbus.PROPERTIES_IFACE, client_interface,
308
 
                  self.propname, self.value_to_set
309
 
                  if not isinstance(self.value_to_set, dbus.Boolean)
310
 
                  else bool(self.value_to_set))
311
 
        client.Set(client_interface, self.propname, self.value_to_set,
 
302
        client.Set(client_interface, self.property, self.value_to_set,
312
303
                   dbus_interface=dbus.PROPERTIES_IFACE)
313
 
    @property
314
 
    def propname(self):
315
 
        raise NotImplementedError()
316
304
 
317
305
class ValueArgumentMixIn(object):
318
306
    """Mixin class for commands taking a value as argument"""
341
329
        keywords = default_keywords
342
330
        if self.verbose:
343
331
            keywords = self.all_keywords
344
 
        return str(self.TableOfClients(clients, keywords))
 
332
        return str(self.TableOfClients(clients.values(), keywords))
345
333
 
346
334
    class TableOfClients(object):
347
335
        tableheaders = {
438
426
            sys.exit(0)
439
427
        sys.exit(1)
440
428
    def is_enabled(self, client, properties):
441
 
        log.debug("D-Bus: %s:%s:%s.Get(%r, %r)", busname,
442
 
                  client.__dbus_object_path__,
443
 
                  dbus.PROPERTIES_IFACE, client_interface,
444
 
                  "Enabled")
445
 
        return bool(client.Get(client_interface, "Enabled",
446
 
                               dbus_interface=dbus.PROPERTIES_IFACE))
 
429
        return bool(properties["Enabled"])
447
430
 
448
431
class RemoveCmd(Command):
449
432
    def run_on_one_client(self, client, properties):
450
 
        log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", busname,
451
 
                  server_path, server_interface,
452
 
                  str(client.__dbus_object_path__))
453
433
        self.mandos.RemoveClient(client.__dbus_object_path__)
454
434
 
455
435
class ApproveCmd(Command):
456
436
    def run_on_one_client(self, client, properties):
457
 
        log.debug("D-Bus: %s:%s.Approve(True)",
458
 
                  client.__dbus_object_path__, client_interface)
459
437
        client.Approve(dbus.Boolean(True),
460
438
                       dbus_interface=client_interface)
461
439
 
462
440
class DenyCmd(Command):
463
441
    def run_on_one_client(self, client, properties):
464
 
        log.debug("D-Bus: %s:%s.Approve(False)",
465
 
                  client.__dbus_object_path__, client_interface)
466
442
        client.Approve(dbus.Boolean(False),
467
443
                       dbus_interface=client_interface)
468
444
 
469
445
class EnableCmd(PropertyCmd):
470
 
    propname = "Enabled"
 
446
    property = "Enabled"
471
447
    value_to_set = dbus.Boolean(True)
472
448
 
473
449
class DisableCmd(PropertyCmd):
474
 
    propname = "Enabled"
 
450
    property = "Enabled"
475
451
    value_to_set = dbus.Boolean(False)
476
452
 
477
453
class BumpTimeoutCmd(PropertyCmd):
478
 
    propname = "LastCheckedOK"
 
454
    property = "LastCheckedOK"
479
455
    value_to_set = ""
480
456
 
481
457
class StartCheckerCmd(PropertyCmd):
482
 
    propname = "CheckerRunning"
 
458
    property = "CheckerRunning"
483
459
    value_to_set = dbus.Boolean(True)
484
460
 
485
461
class StopCheckerCmd(PropertyCmd):
486
 
    propname = "CheckerRunning"
 
462
    property = "CheckerRunning"
487
463
    value_to_set = dbus.Boolean(False)
488
464
 
489
465
class ApproveByDefaultCmd(PropertyCmd):
490
 
    propname = "ApprovedByDefault"
 
466
    property = "ApprovedByDefault"
491
467
    value_to_set = dbus.Boolean(True)
492
468
 
493
469
class DenyByDefaultCmd(PropertyCmd):
494
 
    propname = "ApprovedByDefault"
 
470
    property = "ApprovedByDefault"
495
471
    value_to_set = dbus.Boolean(False)
496
472
 
497
473
class SetCheckerCmd(PropertyCmd, ValueArgumentMixIn):
498
 
    propname = "Checker"
 
474
    property = "Checker"
499
475
 
500
476
class SetHostCmd(PropertyCmd, ValueArgumentMixIn):
501
 
    propname = "Host"
 
477
    property = "Host"
502
478
 
503
479
class SetSecretCmd(PropertyCmd, ValueArgumentMixIn):
504
 
    propname = "Secret"
505
480
    @property
506
481
    def value_to_set(self):
507
482
        return self._vts
510
485
        """When setting, read data from supplied file object"""
511
486
        self._vts = value.read()
512
487
        value.close()
 
488
    property = "Secret"
513
489
 
514
490
class SetTimeoutCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
515
 
    propname = "Timeout"
 
491
    property = "Timeout"
516
492
 
517
493
class SetExtendedTimeoutCmd(PropertyCmd,
518
494
                            MillisecondsValueArgumentMixIn):
519
 
    propname = "ExtendedTimeout"
 
495
    property = "ExtendedTimeout"
520
496
 
521
497
class SetIntervalCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
522
 
    propname = "Interval"
 
498
    property = "Interval"
523
499
 
524
500
class SetApprovalDelayCmd(PropertyCmd,
525
501
                          MillisecondsValueArgumentMixIn):
526
 
    propname = "ApprovalDelay"
 
502
    property = "ApprovalDelay"
527
503
 
528
504
class SetApprovalDurationCmd(PropertyCmd,
529
505
                             MillisecondsValueArgumentMixIn):
530
 
    propname = "ApprovalDuration"
 
506
    property = "ApprovalDuration"
531
507
 
532
508
def add_command_line_options(parser):
533
509
    parser.add_argument("--version", action="version",
589
565
        help="Approve any current client request")
590
566
    approve_deny.add_argument("-D", "--deny", action="store_true",
591
567
                              help="Deny any current client request")
592
 
    parser.add_argument("--debug", action="store_true",
593
 
                        help="Debug mode (show D-Bus commands)")
594
568
    parser.add_argument("--check", action="store_true",
595
569
                        help="Run self-test")
596
570
    parser.add_argument("client", nargs="*", help="Client name")
621
595
    if options.is_enabled:
622
596
        commands.append(IsEnabledCmd())
623
597
 
 
598
    if options.remove:
 
599
        commands.append(RemoveCmd())
 
600
 
624
601
    if options.checker is not None:
625
602
        commands.append(SetCheckerCmd(options.checker))
626
603
 
659
636
    if options.deny:
660
637
        commands.append(DenyCmd())
661
638
 
662
 
    if options.remove:
663
 
        commands.append(RemoveCmd())
664
 
 
665
639
    # If no command option has been given, show table of clients,
666
640
    # optionally verbosely
667
641
    if not commands:
671
645
 
672
646
 
673
647
def check_option_syntax(parser, options):
674
 
    """Apply additional restrictions on options, not expressible in
675
 
argparse"""
676
648
 
677
649
    def has_actions(options):
678
650
        return any((options.enable,
705
677
        parser.error("--all requires an action.")
706
678
    if options.is_enabled and len(options.client) > 1:
707
679
        parser.error("--is-enabled requires exactly one client")
708
 
    if options.remove:
709
 
        options.remove = False
710
 
        if has_actions(options) and not options.deny:
711
 
            parser.error("--remove can only be combined with --deny")
712
 
        options.remove = True
713
680
 
714
681
 
715
682
def main():
723
690
 
724
691
    clientnames = options.client
725
692
 
726
 
    if options.debug:
727
 
        log.setLevel(logging.DEBUG)
728
 
 
729
693
    try:
730
694
        bus = dbus.SystemBus()
731
 
        log.debug("D-Bus: Connect to: (name=%r, path=%r)", busname,
732
 
                  server_path)
733
695
        mandos_dbus_objc = bus.get_object(busname, server_path)
734
696
    except dbus.exceptions.DBusException:
735
697
        log.critical("Could not connect to Mandos server")
748
710
    dbus_filter = NullFilter()
749
711
    try:
750
712
        dbus_logger.addFilter(dbus_filter)
751
 
        log.debug("D-Bus: %s:%s:%s.GetManagedObjects()", busname,
752
 
                  server_path, dbus.OBJECT_MANAGER_IFACE)
753
713
        mandos_clients = {path: ifs_and_props[client_interface]
754
714
                          for path, ifs_and_props in
755
715
                          mandos_serv_object_manager
767
727
    clients = {}
768
728
 
769
729
    if not clientnames:
770
 
        clients = {(log.debug("D-Bus: Connect to: (name=%r, path=%r)",
771
 
                              busname, str(path)) and False) or
772
 
                   bus.get_object(busname, path): properties
 
730
        clients = {bus.get_object(busname, path): properties
773
731
                   for path, properties in mandos_clients.items()}
774
732
    else:
775
733
        for name in clientnames:
776
734
            for path, client in mandos_clients.items():
777
735
                if client["Name"] == name:
778
 
                    log.debug("D-Bus: Connect to: (name=%r, path=%r)",
779
 
                              busname, str(path))
780
736
                    client_objc = bus.get_object(busname, path)
781
737
                    clients[client_objc] = client
782
738
                    break
846
802
                self.attributes = attributes
847
803
                self.attributes["Name"] = name
848
804
                self.calls = []
849
 
            def Set(self, interface, propname, value, dbus_interface):
850
 
                testcase.assertEqual(interface, client_interface)
851
 
                testcase.assertEqual(dbus_interface,
852
 
                                     dbus.PROPERTIES_IFACE)
853
 
                self.attributes[propname] = value
854
 
            def Get(self, interface, propname, dbus_interface):
855
 
                testcase.assertEqual(interface, client_interface)
856
 
                testcase.assertEqual(dbus_interface,
857
 
                                     dbus.PROPERTIES_IFACE)
858
 
                return self.attributes[propname]
 
805
            def Set(self, interface, property, value, dbus_interface):
 
806
                testcase.assertEqual(interface, client_interface)
 
807
                testcase.assertEqual(dbus_interface,
 
808
                                     dbus.PROPERTIES_IFACE)
 
809
                self.attributes[property] = value
 
810
            def Get(self, interface, property, dbus_interface):
 
811
                testcase.assertEqual(interface, client_interface)
 
812
                testcase.assertEqual(dbus_interface,
 
813
                                     dbus.PROPERTIES_IFACE)
 
814
                return self.attributes[property]
859
815
            def Approve(self, approve, dbus_interface):
860
816
                testcase.assertEqual(dbus_interface, client_interface)
861
817
                self.calls.append(("Approve", (approve,
917
873
 
918
874
class TestPrintTableCmd(TestCmd):
919
875
    def test_normal(self):
920
 
        output = PrintTableCmd().output(self.clients.values())
 
876
        output = PrintTableCmd().output(self.clients)
921
877
        expected_output = """
922
878
Name   Enabled Timeout  Last Successful Check
923
879
foo    Yes     00:05:00 2019-02-03T00:00:00  
925
881
"""[1:-1]
926
882
        self.assertEqual(output, expected_output)
927
883
    def test_verbose(self):
928
 
        output = PrintTableCmd(verbose=True).output(
929
 
            self.clients.values())
 
884
        output = PrintTableCmd(verbose=True).output(self.clients)
930
885
        expected_output = """
931
886
Name   Enabled Timeout  Last Successful Check Created             Interval Host            Key ID                                                           Fingerprint                              Check Is Running Last Enabled        Approval Is Pending Approved By Default Last Approval Request Approval Delay Approval Duration Checker              Extended Timeout Expires             Last Checker Status
932
887
foo    Yes     00:05:00 2019-02-03T00:00:00   2019-01-02T00:00:00 00:02:00 foo.example.org 92ed150794387c03ce684574b1139a6594a34f895daaaf09fd8ea90a27cddb12 778827225BA7DE539C5A7CFA59CFF7CDBD9A5920 No               2019-01-03T00:00:00 No                  Yes                                       00:00:00       00:00:01          fping -q -- %(host)s 00:15:00         2019-02-04T00:00:00 0                  
934
889
"""[1:-1]
935
890
        self.assertEqual(output, expected_output)
936
891
    def test_one_client(self):
937
 
        output = PrintTableCmd().output(self.one_client.values())
 
892
        output = PrintTableCmd().output(self.one_client)
938
893
        expected_output = """
939
894
Name Enabled Timeout  Last Successful Check
940
895
foo  Yes     00:05:00 2019-02-03T00:00:00  
1084
1039
        for value_to_set, value_to_get in zip(self.values_to_set,
1085
1040
                                              values_to_get):
1086
1041
            for client in self.clients:
1087
 
                old_value = client.attributes[self.propname]
 
1042
                old_value = client.attributes[self.property]
1088
1043
                self.assertNotIsInstance(old_value, Unique)
1089
 
                client.attributes[self.propname] = Unique()
 
1044
                client.attributes[self.property] = Unique()
1090
1045
            self.run_command(value_to_set, self.clients)
1091
1046
            for client in self.clients:
1092
 
                value = client.attributes[self.propname]
 
1047
                value = client.attributes[self.property]
1093
1048
                self.assertNotIsInstance(value, Unique)
1094
1049
                self.assertEqual(value, value_to_get)
1095
1050
    def run_command(self, value, clients):
1097
1052
 
1098
1053
class TestBumpTimeoutCmd(TestPropertyCmd):
1099
1054
    command = BumpTimeoutCmd
1100
 
    propname = "LastCheckedOK"
 
1055
    property = "LastCheckedOK"
1101
1056
    values_to_set = [""]
1102
1057
 
1103
1058
class TestStartCheckerCmd(TestPropertyCmd):
1104
1059
    command = StartCheckerCmd
1105
 
    propname = "CheckerRunning"
 
1060
    property = "CheckerRunning"
1106
1061
    values_to_set = [dbus.Boolean(True)]
1107
1062
 
1108
1063
class TestStopCheckerCmd(TestPropertyCmd):
1109
1064
    command = StopCheckerCmd
1110
 
    propname = "CheckerRunning"
 
1065
    property = "CheckerRunning"
1111
1066
    values_to_set = [dbus.Boolean(False)]
1112
1067
 
1113
1068
class TestApproveByDefaultCmd(TestPropertyCmd):
1114
1069
    command = ApproveByDefaultCmd
1115
 
    propname = "ApprovedByDefault"
 
1070
    property = "ApprovedByDefault"
1116
1071
    values_to_set = [dbus.Boolean(True)]
1117
1072
 
1118
1073
class TestDenyByDefaultCmd(TestPropertyCmd):
1119
1074
    command = DenyByDefaultCmd
1120
 
    propname = "ApprovedByDefault"
 
1075
    property = "ApprovedByDefault"
1121
1076
    values_to_set = [dbus.Boolean(False)]
1122
1077
 
1123
1078
class TestValueArgumentPropertyCmd(TestPropertyCmd):
1132
1087
 
1133
1088
class TestSetCheckerCmd(TestValueArgumentPropertyCmd):
1134
1089
    command = SetCheckerCmd
1135
 
    propname = "Checker"
 
1090
    property = "Checker"
1136
1091
    values_to_set = ["", ":", "fping -q -- %s"]
1137
1092
 
1138
1093
class TestSetHostCmd(TestValueArgumentPropertyCmd):
1139
1094
    command = SetHostCmd
1140
 
    propname = "Host"
 
1095
    property = "Host"
1141
1096
    values_to_set = ["192.0.2.3", "foo.example.org"]
1142
1097
 
1143
1098
class TestSetSecretCmd(TestValueArgumentPropertyCmd):
1144
1099
    command = SetSecretCmd
1145
 
    propname = "Secret"
1146
 
    values_to_set = [io.BytesIO(b""),
 
1100
    property = "Secret"
 
1101
    values_to_set = [open("/dev/null", "rb"),
1147
1102
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1148
1103
    values_to_get = [b"", b"secret\0xyzzy\nbar"]
1149
1104
 
1150
1105
class TestSetTimeoutCmd(TestValueArgumentPropertyCmd):
1151
1106
    command = SetTimeoutCmd
1152
 
    propname = "Timeout"
 
1107
    property = "Timeout"
1153
1108
    values_to_set = [datetime.timedelta(),
1154
1109
                     datetime.timedelta(minutes=5),
1155
1110
                     datetime.timedelta(seconds=1),
1159
1114
 
1160
1115
class TestSetExtendedTimeoutCmd(TestValueArgumentPropertyCmd):
1161
1116
    command = SetExtendedTimeoutCmd
1162
 
    propname = "ExtendedTimeout"
 
1117
    property = "ExtendedTimeout"
1163
1118
    values_to_set = [datetime.timedelta(),
1164
1119
                     datetime.timedelta(minutes=5),
1165
1120
                     datetime.timedelta(seconds=1),
1169
1124
 
1170
1125
class TestSetIntervalCmd(TestValueArgumentPropertyCmd):
1171
1126
    command = SetIntervalCmd
1172
 
    propname = "Interval"
 
1127
    property = "Interval"
1173
1128
    values_to_set = [datetime.timedelta(),
1174
1129
                     datetime.timedelta(minutes=5),
1175
1130
                     datetime.timedelta(seconds=1),
1179
1134
 
1180
1135
class TestSetApprovalDelayCmd(TestValueArgumentPropertyCmd):
1181
1136
    command = SetApprovalDelayCmd
1182
 
    propname = "ApprovalDelay"
 
1137
    property = "ApprovalDelay"
1183
1138
    values_to_set = [datetime.timedelta(),
1184
1139
                     datetime.timedelta(minutes=5),
1185
1140
                     datetime.timedelta(seconds=1),
1189
1144
 
1190
1145
class TestSetApprovalDurationCmd(TestValueArgumentPropertyCmd):
1191
1146
    command = SetApprovalDurationCmd
1192
 
    propname = "ApprovalDuration"
 
1147
    property = "ApprovalDuration"
1193
1148
    values_to_set = [datetime.timedelta(),
1194
1149
                     datetime.timedelta(minutes=5),
1195
1150
                     datetime.timedelta(seconds=1),
1375
1330
    def test_is_enabled_short(self):
1376
1331
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1377
1332
 
1378
 
    def test_deny_before_remove(self):
1379
 
        options = self.parser.parse_args(["--deny", "--remove", "foo"])
1380
 
        check_option_syntax(self.parser, options)
1381
 
        commands = commands_from_options(options)
1382
 
        self.assertEqual(len(commands), 2)
1383
 
        self.assertIsInstance(commands[0], DenyCmd)
1384
 
        self.assertIsInstance(commands[1], RemoveCmd)
1385
 
 
1386
 
    def test_deny_before_remove_reversed(self):
1387
 
        options = self.parser.parse_args(["--remove", "--deny", "--all"])
1388
 
        check_option_syntax(self.parser, options)
1389
 
        commands = commands_from_options(options)
1390
 
        self.assertEqual(len(commands), 2)
1391
 
        self.assertIsInstance(commands[0], DenyCmd)
1392
 
        self.assertIsInstance(commands[1], RemoveCmd)
1393
 
 
1394
 
 
1395
 
class Test_check_option_syntax(unittest.TestCase):
1396
 
    # This mostly corresponds to the definition from has_actions() in
1397
 
    # check_option_syntax()
1398
 
    actions = {
1399
 
        # The actual values set here are not that important, but we do
1400
 
        # at least stick to the correct types, even though they are
1401
 
        # never used
1402
 
        "enable": True,
1403
 
        "disable": True,
1404
 
        "bump_timeout": True,
1405
 
        "start_checker": True,
1406
 
        "stop_checker": True,
1407
 
        "is_enabled": True,
1408
 
        "remove": True,
1409
 
        "checker": "x",
1410
 
        "timeout": datetime.timedelta(),
1411
 
        "extended_timeout": datetime.timedelta(),
1412
 
        "interval": datetime.timedelta(),
1413
 
        "approved_by_default": True,
1414
 
        "approval_delay": datetime.timedelta(),
1415
 
        "approval_duration": datetime.timedelta(),
1416
 
        "host": "x",
1417
 
        "secret": io.BytesIO(b"x"),
1418
 
        "approve": True,
1419
 
        "deny": True,
1420
 
    }
1421
 
 
1422
 
    def setUp(self):
1423
 
        self.parser = argparse.ArgumentParser()
1424
 
        add_command_line_options(self.parser)
1425
 
 
1426
 
    @contextlib.contextmanager
1427
 
    def assertParseError(self):
1428
 
        with self.assertRaises(SystemExit) as e:
1429
 
            with self.temporarily_suppress_stderr():
1430
 
                yield
1431
 
        # Exit code from argparse is guaranteed to be "2".  Reference:
1432
 
        # https://docs.python.org/3/library/argparse.html#exiting-methods
1433
 
        self.assertEqual(e.exception.code, 2)
1434
 
 
1435
 
    @staticmethod
1436
 
    @contextlib.contextmanager
1437
 
    def temporarily_suppress_stderr():
1438
 
        null = os.open(os.path.devnull, os.O_RDWR)
1439
 
        stderrcopy = os.dup(sys.stderr.fileno())
1440
 
        os.dup2(null, sys.stderr.fileno())
1441
 
        os.close(null)
1442
 
        try:
1443
 
            yield
1444
 
        finally:
1445
 
            # restore stderr
1446
 
            os.dup2(stderrcopy, sys.stderr.fileno())
1447
 
            os.close(stderrcopy)
1448
 
 
1449
 
    def check_option_syntax(self, options):
1450
 
        check_option_syntax(self.parser, options)
1451
 
 
1452
 
    def test_actions_requires_client_or_all(self):
1453
 
        for action, value in self.actions.items():
1454
 
            options = self.parser.parse_args()
1455
 
            setattr(options, action, value)
1456
 
            with self.assertParseError():
1457
 
                self.check_option_syntax(options)
1458
 
 
1459
 
    def test_actions_conflicts_with_verbose(self):
1460
 
        for action, value in self.actions.items():
1461
 
            options = self.parser.parse_args()
1462
 
            setattr(options, action, value)
1463
 
            options.verbose = True
1464
 
            with self.assertParseError():
1465
 
                self.check_option_syntax(options)
1466
 
 
1467
 
    def test_dump_json_conflicts_with_verbose(self):
1468
 
        options = self.parser.parse_args()
1469
 
        options.dump_json = True
1470
 
        options.verbose = True
1471
 
        with self.assertParseError():
1472
 
            self.check_option_syntax(options)
1473
 
 
1474
 
    def test_dump_json_conflicts_with_action(self):
1475
 
        for action, value in self.actions.items():
1476
 
            options = self.parser.parse_args()
1477
 
            setattr(options, action, value)
1478
 
            options.dump_json = True
1479
 
            with self.assertParseError():
1480
 
                self.check_option_syntax(options)
1481
 
 
1482
 
    def test_all_can_not_be_alone(self):
1483
 
        options = self.parser.parse_args()
1484
 
        options.all = True
1485
 
        with self.assertParseError():
1486
 
            self.check_option_syntax(options)
1487
 
 
1488
 
    def test_all_is_ok_with_any_action(self):
1489
 
        for action, value in self.actions.items():
1490
 
            options = self.parser.parse_args()
1491
 
            setattr(options, action, value)
1492
 
            options.all = True
1493
 
            self.check_option_syntax(options)
1494
 
 
1495
 
    def test_is_enabled_fails_without_client(self):
1496
 
        options = self.parser.parse_args()
1497
 
        options.is_enabled = True
1498
 
        with self.assertParseError():
1499
 
            self.check_option_syntax(options)
1500
 
 
1501
 
    def test_is_enabled_works_with_one_client(self):
1502
 
        options = self.parser.parse_args()
1503
 
        options.is_enabled = True
1504
 
        options.client = ["foo"]
1505
 
        self.check_option_syntax(options)
1506
 
 
1507
 
    def test_is_enabled_fails_with_two_clients(self):
1508
 
        options = self.parser.parse_args()
1509
 
        options.is_enabled = True
1510
 
        options.client = ["foo", "barbar"]
1511
 
        with self.assertParseError():
1512
 
            self.check_option_syntax(options)
1513
 
 
1514
 
    def test_remove_can_only_be_combined_with_action_deny(self):
1515
 
        for action, value in self.actions.items():
1516
 
            if action in {"remove", "deny"}:
1517
 
                continue
1518
 
            options = self.parser.parse_args()
1519
 
            setattr(options, action, value)
1520
 
            options.all = True
1521
 
            options.remove = True
1522
 
            with self.assertParseError():
1523
 
                self.check_option_syntax(options)
1524
 
 
1525
1333
 
1526
1334
 
1527
1335
def should_only_run_tests():