/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos-ctl

  • Committer: Teddy Hogeborn
  • Date: 2019-03-08 22:47:55 UTC
  • Revision ID: teddy@recompile.se-20190308224755-tmjjfk8njo8pn3xk
mandos-ctl: Add tests for option syntax checks

* mandos-ctl (check_option_syntax): Add doc string.
  (Test_check_option_syntax): New.

Show diffs side-by-side

added added

removed removed

Lines of Context:
42
42
import json
43
43
import unittest
44
44
import logging
 
45
import io
 
46
import tempfile
 
47
import contextlib
45
48
 
46
49
import dbus
47
50
 
268
271
    return value
269
272
 
270
273
 
271
 
class TableOfClients(object):
272
 
    tableheaders = {
273
 
        "Name": "Name",
274
 
        "Enabled": "Enabled",
275
 
        "Timeout": "Timeout",
276
 
        "LastCheckedOK": "Last Successful Check",
277
 
        "LastApprovalRequest": "Last Approval Request",
278
 
        "Created": "Created",
279
 
        "Interval": "Interval",
280
 
        "Host": "Host",
281
 
        "Fingerprint": "Fingerprint",
282
 
        "KeyID": "Key ID",
283
 
        "CheckerRunning": "Check Is Running",
284
 
        "LastEnabled": "Last Enabled",
285
 
        "ApprovalPending": "Approval Is Pending",
286
 
        "ApprovedByDefault": "Approved By Default",
287
 
        "ApprovalDelay": "Approval Delay",
288
 
        "ApprovalDuration": "Approval Duration",
289
 
        "Checker": "Checker",
290
 
        "ExtendedTimeout": "Extended Timeout",
291
 
        "Expires": "Expires",
292
 
        "LastCheckerStatus": "Last Checker Status",
293
 
    }
294
 
 
295
 
    def __init__(self, clients, keywords, tableheaders=None):
296
 
        self.clients = clients
297
 
        self.keywords = keywords
298
 
        if tableheaders is not None:
299
 
            self.tableheaders = tableheaders
300
 
 
301
 
    def __str__(self):
302
 
        return "\n".join(self.rows())
303
 
 
304
 
    if sys.version_info.major == 2:
305
 
        __unicode__ = __str__
306
 
        def __str__(self):
307
 
            return str(self).encode(locale.getpreferredencoding())
308
 
 
309
 
    def rows(self):
310
 
        format_string = self.row_formatting_string()
311
 
        rows = [self.header_line(format_string)]
312
 
        rows.extend(self.client_line(client, format_string)
313
 
                    for client in self.clients)
314
 
        return rows
315
 
 
316
 
    def row_formatting_string(self):
317
 
        "Format string used to format table rows"
318
 
        return " ".join("{{{key}:{width}}}".format(
319
 
            width=max(len(self.tableheaders[key]),
320
 
                      *(len(self.string_from_client(client, key))
321
 
                        for client in self.clients)),
322
 
            key=key)
323
 
                        for key in self.keywords)
324
 
 
325
 
    def string_from_client(self, client, key):
326
 
        return self.valuetostring(client[key], key)
327
 
 
328
 
    @staticmethod
329
 
    def valuetostring(value, keyword):
330
 
        if isinstance(value, dbus.Boolean):
331
 
            return "Yes" if value else "No"
332
 
        if keyword in ("Timeout", "Interval", "ApprovalDelay",
333
 
                       "ApprovalDuration", "ExtendedTimeout"):
334
 
            return milliseconds_to_string(value)
335
 
        return str(value)
336
 
 
337
 
    def header_line(self, format_string):
338
 
        return format_string.format(**self.tableheaders)
339
 
 
340
 
    def client_line(self, client, format_string):
341
 
        return format_string.format(
342
 
            **{key: self.string_from_client(client, key)
343
 
               for key in self.keywords})
344
 
 
345
 
 
346
274
## Classes for commands.
347
275
 
348
276
# Abstract classes first
353
281
        commands which want to operate on all clients at the same time
354
282
        can override this run() method instead."""
355
283
        self.mandos = mandos
356
 
        for client in clients:
357
 
            self.run_on_one_client(client)
 
284
        for client, properties in clients.items():
 
285
            self.run_on_one_client(client, properties)
358
286
 
359
287
class PrintCmd(Command):
360
288
    """Abstract class for commands printing client details"""
370
298
 
371
299
class PropertyCmd(Command):
372
300
    """Abstract class for Actions for setting one client property"""
373
 
    def run_on_one_client(self, client):
 
301
    def run_on_one_client(self, client, properties):
374
302
        """Set the Client's D-Bus property"""
375
303
        client.Set(client_interface, self.property, self.value_to_set,
376
304
                   dbus_interface=dbus.PROPERTIES_IFACE)
389
317
    @value_to_set.setter
390
318
    def value_to_set(self, value):
391
319
        """When setting, convert value to a datetime.timedelta"""
392
 
        self._vts = string_to_delta(value).total_seconds() * 1000
 
320
        self._vts = int(round(value.total_seconds() * 1000))
393
321
 
394
322
# Actual (non-abstract) command classes
395
323
 
396
324
class PrintTableCmd(PrintCmd):
397
325
    def __init__(self, verbose=False):
398
326
        self.verbose = verbose
 
327
 
399
328
    def output(self, clients):
 
329
        default_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
 
330
        keywords = default_keywords
400
331
        if self.verbose:
401
332
            keywords = self.all_keywords
402
 
        else:
403
 
            keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
404
 
        return str(TableOfClients(clients.values(), keywords))
 
333
        return str(self.TableOfClients(clients.values(), keywords))
 
334
 
 
335
    class TableOfClients(object):
 
336
        tableheaders = {
 
337
            "Name": "Name",
 
338
            "Enabled": "Enabled",
 
339
            "Timeout": "Timeout",
 
340
            "LastCheckedOK": "Last Successful Check",
 
341
            "LastApprovalRequest": "Last Approval Request",
 
342
            "Created": "Created",
 
343
            "Interval": "Interval",
 
344
            "Host": "Host",
 
345
            "Fingerprint": "Fingerprint",
 
346
            "KeyID": "Key ID",
 
347
            "CheckerRunning": "Check Is Running",
 
348
            "LastEnabled": "Last Enabled",
 
349
            "ApprovalPending": "Approval Is Pending",
 
350
            "ApprovedByDefault": "Approved By Default",
 
351
            "ApprovalDelay": "Approval Delay",
 
352
            "ApprovalDuration": "Approval Duration",
 
353
            "Checker": "Checker",
 
354
            "ExtendedTimeout": "Extended Timeout",
 
355
            "Expires": "Expires",
 
356
            "LastCheckerStatus": "Last Checker Status",
 
357
        }
 
358
 
 
359
        def __init__(self, clients, keywords, tableheaders=None):
 
360
            self.clients = clients
 
361
            self.keywords = keywords
 
362
            if tableheaders is not None:
 
363
                self.tableheaders = tableheaders
 
364
 
 
365
        def __str__(self):
 
366
            return "\n".join(self.rows())
 
367
 
 
368
        if sys.version_info.major == 2:
 
369
            __unicode__ = __str__
 
370
            def __str__(self):
 
371
                return str(self).encode(locale.getpreferredencoding())
 
372
 
 
373
        def rows(self):
 
374
            format_string = self.row_formatting_string()
 
375
            rows = [self.header_line(format_string)]
 
376
            rows.extend(self.client_line(client, format_string)
 
377
                        for client in self.clients)
 
378
            return rows
 
379
 
 
380
        def row_formatting_string(self):
 
381
            "Format string used to format table rows"
 
382
            return " ".join("{{{key}:{width}}}".format(
 
383
                width=max(len(self.tableheaders[key]),
 
384
                          *(len(self.string_from_client(client, key))
 
385
                            for client in self.clients)),
 
386
                key=key)
 
387
                            for key in self.keywords)
 
388
 
 
389
        def string_from_client(self, client, key):
 
390
            return self.valuetostring(client[key], key)
 
391
 
 
392
        @staticmethod
 
393
        def valuetostring(value, keyword):
 
394
            if isinstance(value, dbus.Boolean):
 
395
                return "Yes" if value else "No"
 
396
            if keyword in ("Timeout", "Interval", "ApprovalDelay",
 
397
                           "ApprovalDuration", "ExtendedTimeout"):
 
398
                return milliseconds_to_string(value)
 
399
            return str(value)
 
400
 
 
401
        def header_line(self, format_string):
 
402
            return format_string.format(**self.tableheaders)
 
403
 
 
404
        def client_line(self, client, format_string):
 
405
            return format_string.format(
 
406
                **{key: self.string_from_client(client, key)
 
407
                   for key in self.keywords})
 
408
 
 
409
 
405
410
 
406
411
class DumpJSONCmd(PrintCmd):
407
412
    def output(self, clients):
417
422
        return value
418
423
 
419
424
class IsEnabledCmd(Command):
420
 
    def run_on_one_client(self, client):
421
 
        if self.is_enabled(client):
 
425
    def run_on_one_client(self, client, properties):
 
426
        if self.is_enabled(client, properties):
422
427
            sys.exit(0)
423
428
        sys.exit(1)
424
 
    def is_enabled(self, client):
425
 
        return client.Get(client_interface, "Enabled",
426
 
                          dbus_interface=dbus.PROPERTIES_IFACE)
 
429
    def is_enabled(self, client, properties):
 
430
        return bool(properties["Enabled"])
427
431
 
428
432
class RemoveCmd(Command):
429
 
    def run_on_one_client(self, client):
 
433
    def run_on_one_client(self, client, properties):
430
434
        self.mandos.RemoveClient(client.__dbus_object_path__)
431
435
 
432
436
class ApproveCmd(Command):
433
 
    def run_on_one_client(self, client):
 
437
    def run_on_one_client(self, client, properties):
434
438
        client.Approve(dbus.Boolean(True),
435
439
                       dbus_interface=client_interface)
436
440
 
437
441
class DenyCmd(Command):
438
 
    def run_on_one_client(self, client):
 
442
    def run_on_one_client(self, client, properties):
439
443
        client.Approve(dbus.Boolean(False),
440
444
                       dbus_interface=client_interface)
441
445
 
474
478
    property = "Host"
475
479
 
476
480
class SetSecretCmd(PropertyCmd, ValueArgumentMixIn):
 
481
    @property
 
482
    def value_to_set(self):
 
483
        return self._vts
 
484
    @value_to_set.setter
 
485
    def value_to_set(self, value):
 
486
        """When setting, read data from supplied file object"""
 
487
        self._vts = value.read()
 
488
        value.close()
477
489
    property = "Secret"
478
490
 
479
491
class SetTimeoutCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
494
506
                             MillisecondsValueArgumentMixIn):
495
507
    property = "ApprovalDuration"
496
508
 
497
 
def has_actions(options):
498
 
    return any((options.enable,
499
 
                options.disable,
500
 
                options.bump_timeout,
501
 
                options.start_checker,
502
 
                options.stop_checker,
503
 
                options.is_enabled,
504
 
                options.remove,
505
 
                options.checker is not None,
506
 
                options.timeout is not None,
507
 
                options.extended_timeout is not None,
508
 
                options.interval is not None,
509
 
                options.approved_by_default is not None,
510
 
                options.approval_delay is not None,
511
 
                options.approval_duration is not None,
512
 
                options.host is not None,
513
 
                options.secret is not None,
514
 
                options.approve,
515
 
                options.deny))
516
 
 
517
 
 
518
 
def commands_and_clients_from_options(args=None):
519
 
    if args is None:
520
 
        args=sys.argv[1:]
521
 
    parser = argparse.ArgumentParser()
 
509
def add_command_line_options(parser):
522
510
    parser.add_argument("--version", action="version",
523
511
                        version="%(prog)s {}".format(version),
524
512
                        help="show version number and exit")
549
537
                        help="Remove client")
550
538
    parser.add_argument("-c", "--checker",
551
539
                        help="Set checker command for client")
552
 
    parser.add_argument("-t", "--timeout",
 
540
    parser.add_argument("-t", "--timeout", type=string_to_delta,
553
541
                        help="Set timeout for client")
554
 
    parser.add_argument("--extended-timeout",
 
542
    parser.add_argument("--extended-timeout", type=string_to_delta,
555
543
                        help="Set extended timeout for client")
556
 
    parser.add_argument("-i", "--interval",
 
544
    parser.add_argument("-i", "--interval", type=string_to_delta,
557
545
                        help="Set checker interval for client")
558
546
    approve_deny_default = parser.add_mutually_exclusive_group()
559
547
    approve_deny_default.add_argument(
564
552
        "--deny-by-default", action="store_false",
565
553
        dest="approved_by_default",
566
554
        help="Set client to be denied by default")
567
 
    parser.add_argument("--approval-delay",
 
555
    parser.add_argument("--approval-delay", type=string_to_delta,
568
556
                        help="Set delay before client approve/deny")
569
 
    parser.add_argument("--approval-duration",
 
557
    parser.add_argument("--approval-duration", type=string_to_delta,
570
558
                        help="Set duration of one client approval")
571
559
    parser.add_argument("-H", "--host", help="Set host for client")
572
560
    parser.add_argument("-s", "--secret",
581
569
    parser.add_argument("--check", action="store_true",
582
570
                        help="Run self-test")
583
571
    parser.add_argument("client", nargs="*", help="Client name")
584
 
    options = parser.parse_args(args=args)
585
 
 
586
 
    if has_actions(options) and not (options.client or options.all):
587
 
        parser.error("Options require clients names or --all.")
588
 
    if options.verbose and has_actions(options):
589
 
        parser.error("--verbose can only be used alone.")
590
 
    if options.dump_json and (options.verbose
591
 
                              or has_actions(options)):
592
 
        parser.error("--dump-json can only be used alone.")
593
 
    if options.all and not has_actions(options):
594
 
        parser.error("--all requires an action.")
595
 
    if options.is_enabled and len(options.client) > 1:
596
 
            parser.error("--is-enabled requires exactly one client")
 
572
 
 
573
 
 
574
def commands_from_options(options):
597
575
 
598
576
    commands = []
599
577
 
607
585
        commands.append(DisableCmd())
608
586
 
609
587
    if options.bump_timeout:
610
 
        commands.append(BumpTimeoutCmd(options.bump_timeout))
 
588
        commands.append(BumpTimeoutCmd())
611
589
 
612
590
    if options.start_checker:
613
591
        commands.append(StartCheckerCmd())
622
600
        commands.append(RemoveCmd())
623
601
 
624
602
    if options.checker is not None:
625
 
        commands.append(SetCheckerCmd())
 
603
        commands.append(SetCheckerCmd(options.checker))
626
604
 
627
605
    if options.timeout is not None:
628
606
        commands.append(SetTimeoutCmd(options.timeout))
632
610
            SetExtendedTimeoutCmd(options.extended_timeout))
633
611
 
634
612
    if options.interval is not None:
635
 
        command.append(SetIntervalCmd(options.interval))
 
613
        commands.append(SetIntervalCmd(options.interval))
636
614
 
637
615
    if options.approved_by_default is not None:
638
616
        if options.approved_by_default:
639
 
            command.append(ApproveByDefaultCmd())
 
617
            commands.append(ApproveByDefaultCmd())
640
618
        else:
641
 
            command.append(DenyByDefaultCmd())
 
619
            commands.append(DenyByDefaultCmd())
642
620
 
643
621
    if options.approval_delay is not None:
644
 
        command.append(SetApprovalDelayCmd(options.approval_delay))
 
622
        commands.append(SetApprovalDelayCmd(options.approval_delay))
645
623
 
646
624
    if options.approval_duration is not None:
647
 
        command.append(
 
625
        commands.append(
648
626
            SetApprovalDurationCmd(options.approval_duration))
649
627
 
650
628
    if options.host is not None:
651
 
        command.append(SetHostCmd(options.host))
 
629
        commands.append(SetHostCmd(options.host))
652
630
 
653
631
    if options.secret is not None:
654
 
        command.append(SetSecretCmd(options.secret))
 
632
        commands.append(SetSecretCmd(options.secret))
655
633
 
656
634
    if options.approve:
657
635
        commands.append(ApproveCmd())
664
642
    if not commands:
665
643
        commands.append(PrintTableCmd(verbose=options.verbose))
666
644
 
667
 
    return commands, options.client
 
645
    return commands
 
646
 
 
647
 
 
648
def check_option_syntax(parser, options):
 
649
    """Apply additional restrictions on options, not expressible in
 
650
argparse"""
 
651
 
 
652
    def has_actions(options):
 
653
        return any((options.enable,
 
654
                    options.disable,
 
655
                    options.bump_timeout,
 
656
                    options.start_checker,
 
657
                    options.stop_checker,
 
658
                    options.is_enabled,
 
659
                    options.remove,
 
660
                    options.checker is not None,
 
661
                    options.timeout is not None,
 
662
                    options.extended_timeout is not None,
 
663
                    options.interval is not None,
 
664
                    options.approved_by_default is not None,
 
665
                    options.approval_delay is not None,
 
666
                    options.approval_duration is not None,
 
667
                    options.host is not None,
 
668
                    options.secret is not None,
 
669
                    options.approve,
 
670
                    options.deny))
 
671
 
 
672
    if has_actions(options) and not (options.client or options.all):
 
673
        parser.error("Options require clients names or --all.")
 
674
    if options.verbose and has_actions(options):
 
675
        parser.error("--verbose can only be used alone.")
 
676
    if options.dump_json and (options.verbose
 
677
                              or has_actions(options)):
 
678
        parser.error("--dump-json can only be used alone.")
 
679
    if options.all and not has_actions(options):
 
680
        parser.error("--all requires an action.")
 
681
    if options.is_enabled and len(options.client) > 1:
 
682
        parser.error("--is-enabled requires exactly one client")
668
683
 
669
684
 
670
685
def main():
671
 
    commands, clientnames = commands_and_clients_from_options()
 
686
    parser = argparse.ArgumentParser()
 
687
 
 
688
    add_command_line_options(parser)
 
689
 
 
690
    options = parser.parse_args()
 
691
 
 
692
    check_option_syntax(parser, options)
 
693
 
 
694
    clientnames = options.client
672
695
 
673
696
    try:
674
697
        bus = dbus.SystemBus()
688
711
        def filter(self, record):
689
712
            return False
690
713
    dbus_filter = NullFilter()
691
 
    dbus_logger.addFilter(dbus_filter)
692
714
    try:
693
 
        try:
694
 
            mandos_clients = {path: ifs_and_props[client_interface]
695
 
                              for path, ifs_and_props in
696
 
                              mandos_serv_object_manager
697
 
                              .GetManagedObjects().items()
698
 
                              if client_interface in ifs_and_props}
699
 
        finally:
700
 
            # restore dbus logger
701
 
            dbus_logger.removeFilter(dbus_filter)
 
715
        dbus_logger.addFilter(dbus_filter)
 
716
        mandos_clients = {path: ifs_and_props[client_interface]
 
717
                          for path, ifs_and_props in
 
718
                          mandos_serv_object_manager
 
719
                          .GetManagedObjects().items()
 
720
                          if client_interface in ifs_and_props}
702
721
    except dbus.exceptions.DBusException as e:
703
722
        log.critical("Failed to access Mandos server through D-Bus:"
704
723
                     "\n%s", e)
705
724
        sys.exit(1)
 
725
    finally:
 
726
        # restore dbus logger
 
727
        dbus_logger.removeFilter(dbus_filter)
706
728
 
707
729
    # Compile dict of (clients: properties) to process
708
730
    clients = {}
722
744
                sys.exit(1)
723
745
 
724
746
    # Run all commands on clients
 
747
    commands = commands_from_options(options)
725
748
    for command in commands:
726
749
        command.run(mandos_serv, clients)
727
750
 
741
764
 
742
765
class Test_string_to_delta(unittest.TestCase):
743
766
    def test_handles_basic_rfc3339(self):
 
767
        self.assertEqual(string_to_delta("PT0S"),
 
768
                         datetime.timedelta())
 
769
        self.assertEqual(string_to_delta("P0D"),
 
770
                         datetime.timedelta())
 
771
        self.assertEqual(string_to_delta("PT1S"),
 
772
                         datetime.timedelta(0, 1))
744
773
        self.assertEqual(string_to_delta("PT2H"),
745
774
                         datetime.timedelta(0, 7200))
746
775
    def test_falls_back_to_pre_1_6_1_with_warning(self):
775
804
                self.__dbus_object_path__ = "objpath_{}".format(name)
776
805
                self.attributes = attributes
777
806
                self.attributes["Name"] = name
778
 
            def Set(interface, property, value,
779
 
                    properties_interface):
 
807
                self.calls = []
 
808
            def Set(self, interface, property, value, dbus_interface):
780
809
                testcase.assertEqual(interface, client_interface)
781
 
                testcase.assertEqual(properties_interface,
 
810
                testcase.assertEqual(dbus_interface,
782
811
                                     dbus.PROPERTIES_IFACE)
783
812
                self.attributes[property] = value
784
 
            def Get(interface, property, properties_interface):
 
813
            def Get(self, interface, property, dbus_interface):
785
814
                testcase.assertEqual(interface, client_interface)
786
 
                testcase.assertEqual(properties_interface,
 
815
                testcase.assertEqual(dbus_interface,
787
816
                                     dbus.PROPERTIES_IFACE)
788
817
                return self.attributes[property]
789
 
            def __getitem__(self, key):
790
 
                return self.attributes[key]
791
 
        self.clients = collections.OrderedDict([
792
 
            ("foo",
793
 
             MockClient(
794
 
                 "foo",
795
 
                 KeyID=("92ed150794387c03ce684574b1139a65"
796
 
                        "94a34f895daaaf09fd8ea90a27cddb12"),
797
 
                 Secret=b"secret",
798
 
                 Host="foo.example.org",
799
 
                 Enabled=dbus.Boolean(True),
800
 
                 Timeout=300000,
801
 
                 LastCheckedOK="2019-02-03T00:00:00",
802
 
                 Created="2019-01-02T00:00:00",
803
 
                 Interval=120000,
804
 
                 Fingerprint=("778827225BA7DE539C5A"
805
 
                              "7CFA59CFF7CDBD9A5920"),
806
 
                 CheckerRunning=dbus.Boolean(False),
807
 
                 LastEnabled="2019-01-03T00:00:00",
808
 
                 ApprovalPending=dbus.Boolean(False),
809
 
                 ApprovedByDefault=dbus.Boolean(True),
810
 
                 LastApprovalRequest="",
811
 
                 ApprovalDelay=0,
812
 
                 ApprovalDuration=1000,
813
 
                 Checker="fping -q -- %(host)s",
814
 
                 ExtendedTimeout=900000,
815
 
                 Expires="2019-02-04T00:00:00",
816
 
                 LastCheckerStatus=0)),
817
 
            ("barbar",
818
 
             MockClient(
819
 
                 "barbar",
820
 
                 KeyID=("0558568eedd67d622f5c83b35a115f79"
821
 
                        "6ab612cff5ad227247e46c2b020f441c"),
822
 
                 Secret=b"secretbar",
823
 
                 Host="192.0.2.3",
824
 
                 Enabled=dbus.Boolean(True),
825
 
                 Timeout=300000,
826
 
                 LastCheckedOK="2019-02-04T00:00:00",
827
 
                 Created="2019-01-03T00:00:00",
828
 
                 Interval=120000,
829
 
                 Fingerprint=("3E393AEAEFB84C7E89E2"
830
 
                              "F547B3A107558FCA3A27"),
831
 
                 CheckerRunning=dbus.Boolean(True),
832
 
                 LastEnabled="2019-01-04T00:00:00",
833
 
                 ApprovalPending=dbus.Boolean(False),
834
 
                 ApprovedByDefault=dbus.Boolean(False),
835
 
                 LastApprovalRequest="2019-01-03T00:00:00",
836
 
                 ApprovalDelay=30000,
837
 
                 ApprovalDuration=1000,
838
 
                 Checker=":",
839
 
                 ExtendedTimeout=900000,
840
 
                 Expires="2019-02-05T00:00:00",
841
 
                 LastCheckerStatus=-2)),
 
818
            def Approve(self, approve, dbus_interface):
 
819
                testcase.assertEqual(dbus_interface, client_interface)
 
820
                self.calls.append(("Approve", (approve,
 
821
                                               dbus_interface)))
 
822
        self.client = MockClient(
 
823
            "foo",
 
824
            KeyID=("92ed150794387c03ce684574b1139a65"
 
825
                   "94a34f895daaaf09fd8ea90a27cddb12"),
 
826
            Secret=b"secret",
 
827
            Host="foo.example.org",
 
828
            Enabled=dbus.Boolean(True),
 
829
            Timeout=300000,
 
830
            LastCheckedOK="2019-02-03T00:00:00",
 
831
            Created="2019-01-02T00:00:00",
 
832
            Interval=120000,
 
833
            Fingerprint=("778827225BA7DE539C5A"
 
834
                         "7CFA59CFF7CDBD9A5920"),
 
835
            CheckerRunning=dbus.Boolean(False),
 
836
            LastEnabled="2019-01-03T00:00:00",
 
837
            ApprovalPending=dbus.Boolean(False),
 
838
            ApprovedByDefault=dbus.Boolean(True),
 
839
            LastApprovalRequest="",
 
840
            ApprovalDelay=0,
 
841
            ApprovalDuration=1000,
 
842
            Checker="fping -q -- %(host)s",
 
843
            ExtendedTimeout=900000,
 
844
            Expires="2019-02-04T00:00:00",
 
845
            LastCheckerStatus=0)
 
846
        self.other_client = MockClient(
 
847
            "barbar",
 
848
            KeyID=("0558568eedd67d622f5c83b35a115f79"
 
849
                   "6ab612cff5ad227247e46c2b020f441c"),
 
850
            Secret=b"secretbar",
 
851
            Host="192.0.2.3",
 
852
            Enabled=dbus.Boolean(True),
 
853
            Timeout=300000,
 
854
            LastCheckedOK="2019-02-04T00:00:00",
 
855
            Created="2019-01-03T00:00:00",
 
856
            Interval=120000,
 
857
            Fingerprint=("3E393AEAEFB84C7E89E2"
 
858
                         "F547B3A107558FCA3A27"),
 
859
            CheckerRunning=dbus.Boolean(True),
 
860
            LastEnabled="2019-01-04T00:00:00",
 
861
            ApprovalPending=dbus.Boolean(False),
 
862
            ApprovedByDefault=dbus.Boolean(False),
 
863
            LastApprovalRequest="2019-01-03T00:00:00",
 
864
            ApprovalDelay=30000,
 
865
            ApprovalDuration=1000,
 
866
            Checker=":",
 
867
            ExtendedTimeout=900000,
 
868
            Expires="2019-02-05T00:00:00",
 
869
            LastCheckerStatus=-2)
 
870
        self.clients =  collections.OrderedDict(
 
871
            [
 
872
                (self.client, self.client.attributes),
 
873
                (self.other_client, self.other_client.attributes),
842
874
            ])
 
875
        self.one_client = {self.client: self.client.attributes}
843
876
 
844
877
class TestPrintTableCmd(TestCmd):
845
878
    def test_normal(self):
859
892
"""[1:-1]
860
893
        self.assertEqual(output, expected_output)
861
894
    def test_one_client(self):
862
 
        output = PrintTableCmd().output({"foo": self.clients["foo"]})
 
895
        output = PrintTableCmd().output(self.one_client)
863
896
        expected_output = """
864
897
Name Enabled Timeout  Last Successful Check
865
898
foo  Yes     00:05:00 2019-02-03T00:00:00  
866
899
"""[1:-1]
867
900
        self.assertEqual(output, expected_output)
868
901
 
 
902
class TestDumpJSONCmd(TestCmd):
 
903
    def setUp(self):
 
904
        self.expected_json = {
 
905
            "foo": {
 
906
                "Name": "foo",
 
907
                "KeyID": ("92ed150794387c03ce684574b1139a65"
 
908
                          "94a34f895daaaf09fd8ea90a27cddb12"),
 
909
                "Host": "foo.example.org",
 
910
                "Enabled": True,
 
911
                "Timeout": 300000,
 
912
                "LastCheckedOK": "2019-02-03T00:00:00",
 
913
                "Created": "2019-01-02T00:00:00",
 
914
                "Interval": 120000,
 
915
                "Fingerprint": ("778827225BA7DE539C5A"
 
916
                                "7CFA59CFF7CDBD9A5920"),
 
917
                "CheckerRunning": False,
 
918
                "LastEnabled": "2019-01-03T00:00:00",
 
919
                "ApprovalPending": False,
 
920
                "ApprovedByDefault": True,
 
921
                "LastApprovalRequest": "",
 
922
                "ApprovalDelay": 0,
 
923
                "ApprovalDuration": 1000,
 
924
                "Checker": "fping -q -- %(host)s",
 
925
                "ExtendedTimeout": 900000,
 
926
                "Expires": "2019-02-04T00:00:00",
 
927
                "LastCheckerStatus": 0,
 
928
            },
 
929
            "barbar": {
 
930
                "Name": "barbar",
 
931
                "KeyID": ("0558568eedd67d622f5c83b35a115f79"
 
932
                          "6ab612cff5ad227247e46c2b020f441c"),
 
933
                "Host": "192.0.2.3",
 
934
                "Enabled": True,
 
935
                "Timeout": 300000,
 
936
                "LastCheckedOK": "2019-02-04T00:00:00",
 
937
                "Created": "2019-01-03T00:00:00",
 
938
                "Interval": 120000,
 
939
                "Fingerprint": ("3E393AEAEFB84C7E89E2"
 
940
                                "F547B3A107558FCA3A27"),
 
941
                "CheckerRunning": True,
 
942
                "LastEnabled": "2019-01-04T00:00:00",
 
943
                "ApprovalPending": False,
 
944
                "ApprovedByDefault": False,
 
945
                "LastApprovalRequest": "2019-01-03T00:00:00",
 
946
                "ApprovalDelay": 30000,
 
947
                "ApprovalDuration": 1000,
 
948
                "Checker": ":",
 
949
                "ExtendedTimeout": 900000,
 
950
                "Expires": "2019-02-05T00:00:00",
 
951
                "LastCheckerStatus": -2,
 
952
            },
 
953
        }
 
954
        return super(TestDumpJSONCmd, self).setUp()
 
955
    def test_normal(self):
 
956
        json_data = json.loads(DumpJSONCmd().output(self.clients))
 
957
        self.assertDictEqual(json_data, self.expected_json)
 
958
    def test_one_client(self):
 
959
        clients = self.one_client
 
960
        json_data = json.loads(DumpJSONCmd().output(clients))
 
961
        expected_json = {"foo": self.expected_json["foo"]}
 
962
        self.assertDictEqual(json_data, expected_json)
 
963
 
 
964
class TestIsEnabledCmd(TestCmd):
 
965
    def test_is_enabled(self):
 
966
        self.assertTrue(all(IsEnabledCmd().is_enabled(client, properties)
 
967
                            for client, properties in self.clients.items()))
 
968
    def test_is_enabled_run_exits_successfully(self):
 
969
        with self.assertRaises(SystemExit) as e:
 
970
            IsEnabledCmd().run(None, self.one_client)
 
971
        if e.exception.code is not None:
 
972
            self.assertEqual(e.exception.code, 0)
 
973
        else:
 
974
            self.assertIsNone(e.exception.code)
 
975
    def test_is_enabled_run_exits_with_failure(self):
 
976
        self.client.attributes["Enabled"] = dbus.Boolean(False)
 
977
        with self.assertRaises(SystemExit) as e:
 
978
            IsEnabledCmd().run(None, self.one_client)
 
979
        if isinstance(e.exception.code, int):
 
980
            self.assertNotEqual(e.exception.code, 0)
 
981
        else:
 
982
            self.assertIsNotNone(e.exception.code)
 
983
 
 
984
class TestRemoveCmd(TestCmd):
 
985
    def test_remove(self):
 
986
        class MockMandos(object):
 
987
            def __init__(self):
 
988
                self.calls = []
 
989
            def RemoveClient(self, dbus_path):
 
990
                self.calls.append(("RemoveClient", (dbus_path,)))
 
991
        mandos = MockMandos()
 
992
        super(TestRemoveCmd, self).setUp()
 
993
        RemoveCmd().run(mandos, self.clients)
 
994
        self.assertEqual(len(mandos.calls), 2)
 
995
        for client in self.clients:
 
996
            self.assertIn(("RemoveClient",
 
997
                           (client.__dbus_object_path__,)),
 
998
                          mandos.calls)
 
999
 
 
1000
class TestApproveCmd(TestCmd):
 
1001
    def test_approve(self):
 
1002
        ApproveCmd().run(None, self.clients)
 
1003
        for client in self.clients:
 
1004
            self.assertIn(("Approve", (True, client_interface)),
 
1005
                          client.calls)
 
1006
 
 
1007
class TestDenyCmd(TestCmd):
 
1008
    def test_deny(self):
 
1009
        DenyCmd().run(None, self.clients)
 
1010
        for client in self.clients:
 
1011
            self.assertIn(("Approve", (False, client_interface)),
 
1012
                          client.calls)
 
1013
 
 
1014
class TestEnableCmd(TestCmd):
 
1015
    def test_enable(self):
 
1016
        for client in self.clients:
 
1017
            client.attributes["Enabled"] = False
 
1018
 
 
1019
        EnableCmd().run(None, self.clients)
 
1020
 
 
1021
        for client in self.clients:
 
1022
            self.assertTrue(client.attributes["Enabled"])
 
1023
 
 
1024
class TestDisableCmd(TestCmd):
 
1025
    def test_disable(self):
 
1026
        DisableCmd().run(None, self.clients)
 
1027
 
 
1028
        for client in self.clients:
 
1029
            self.assertFalse(client.attributes["Enabled"])
 
1030
 
 
1031
class Unique(object):
 
1032
    """Class for objects which exist only to be unique objects, since
 
1033
unittest.mock.sentinel only exists in Python 3.3"""
 
1034
 
 
1035
class TestPropertyCmd(TestCmd):
 
1036
    """Abstract class for tests of PropertyCmd classes"""
 
1037
    def runTest(self):
 
1038
        if not hasattr(self, "command"):
 
1039
            return
 
1040
        values_to_get = getattr(self, "values_to_get",
 
1041
                                self.values_to_set)
 
1042
        for value_to_set, value_to_get in zip(self.values_to_set,
 
1043
                                              values_to_get):
 
1044
            for client in self.clients:
 
1045
                old_value = client.attributes[self.property]
 
1046
                self.assertNotIsInstance(old_value, Unique)
 
1047
                client.attributes[self.property] = Unique()
 
1048
            self.run_command(value_to_set, self.clients)
 
1049
            for client in self.clients:
 
1050
                value = client.attributes[self.property]
 
1051
                self.assertNotIsInstance(value, Unique)
 
1052
                self.assertEqual(value, value_to_get)
 
1053
    def run_command(self, value, clients):
 
1054
        self.command().run(None, clients)
 
1055
 
 
1056
class TestBumpTimeoutCmd(TestPropertyCmd):
 
1057
    command = BumpTimeoutCmd
 
1058
    property = "LastCheckedOK"
 
1059
    values_to_set = [""]
 
1060
 
 
1061
class TestStartCheckerCmd(TestPropertyCmd):
 
1062
    command = StartCheckerCmd
 
1063
    property = "CheckerRunning"
 
1064
    values_to_set = [dbus.Boolean(True)]
 
1065
 
 
1066
class TestStopCheckerCmd(TestPropertyCmd):
 
1067
    command = StopCheckerCmd
 
1068
    property = "CheckerRunning"
 
1069
    values_to_set = [dbus.Boolean(False)]
 
1070
 
 
1071
class TestApproveByDefaultCmd(TestPropertyCmd):
 
1072
    command = ApproveByDefaultCmd
 
1073
    property = "ApprovedByDefault"
 
1074
    values_to_set = [dbus.Boolean(True)]
 
1075
 
 
1076
class TestDenyByDefaultCmd(TestPropertyCmd):
 
1077
    command = DenyByDefaultCmd
 
1078
    property = "ApprovedByDefault"
 
1079
    values_to_set = [dbus.Boolean(False)]
 
1080
 
 
1081
class TestValueArgumentPropertyCmd(TestPropertyCmd):
 
1082
    """Abstract class for tests of PropertyCmd classes using the
 
1083
ValueArgumentMixIn"""
 
1084
    def runTest(self):
 
1085
        if type(self) is TestValueArgumentPropertyCmd:
 
1086
            return
 
1087
        return super(TestValueArgumentPropertyCmd, self).runTest()
 
1088
    def run_command(self, value, clients):
 
1089
        self.command(value).run(None, clients)
 
1090
 
 
1091
class TestSetCheckerCmd(TestValueArgumentPropertyCmd):
 
1092
    command = SetCheckerCmd
 
1093
    property = "Checker"
 
1094
    values_to_set = ["", ":", "fping -q -- %s"]
 
1095
 
 
1096
class TestSetHostCmd(TestValueArgumentPropertyCmd):
 
1097
    command = SetHostCmd
 
1098
    property = "Host"
 
1099
    values_to_set = ["192.0.2.3", "foo.example.org"]
 
1100
 
 
1101
class TestSetSecretCmd(TestValueArgumentPropertyCmd):
 
1102
    command = SetSecretCmd
 
1103
    property = "Secret"
 
1104
    values_to_set = [open("/dev/null", "rb"),
 
1105
                     io.BytesIO(b"secret\0xyzzy\nbar")]
 
1106
    values_to_get = [b"", b"secret\0xyzzy\nbar"]
 
1107
 
 
1108
class TestSetTimeoutCmd(TestValueArgumentPropertyCmd):
 
1109
    command = SetTimeoutCmd
 
1110
    property = "Timeout"
 
1111
    values_to_set = [datetime.timedelta(),
 
1112
                     datetime.timedelta(minutes=5),
 
1113
                     datetime.timedelta(seconds=1),
 
1114
                     datetime.timedelta(weeks=1),
 
1115
                     datetime.timedelta(weeks=52)]
 
1116
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1117
 
 
1118
class TestSetExtendedTimeoutCmd(TestValueArgumentPropertyCmd):
 
1119
    command = SetExtendedTimeoutCmd
 
1120
    property = "ExtendedTimeout"
 
1121
    values_to_set = [datetime.timedelta(),
 
1122
                     datetime.timedelta(minutes=5),
 
1123
                     datetime.timedelta(seconds=1),
 
1124
                     datetime.timedelta(weeks=1),
 
1125
                     datetime.timedelta(weeks=52)]
 
1126
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1127
 
 
1128
class TestSetIntervalCmd(TestValueArgumentPropertyCmd):
 
1129
    command = SetIntervalCmd
 
1130
    property = "Interval"
 
1131
    values_to_set = [datetime.timedelta(),
 
1132
                     datetime.timedelta(minutes=5),
 
1133
                     datetime.timedelta(seconds=1),
 
1134
                     datetime.timedelta(weeks=1),
 
1135
                     datetime.timedelta(weeks=52)]
 
1136
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1137
 
 
1138
class TestSetApprovalDelayCmd(TestValueArgumentPropertyCmd):
 
1139
    command = SetApprovalDelayCmd
 
1140
    property = "ApprovalDelay"
 
1141
    values_to_set = [datetime.timedelta(),
 
1142
                     datetime.timedelta(minutes=5),
 
1143
                     datetime.timedelta(seconds=1),
 
1144
                     datetime.timedelta(weeks=1),
 
1145
                     datetime.timedelta(weeks=52)]
 
1146
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1147
 
 
1148
class TestSetApprovalDurationCmd(TestValueArgumentPropertyCmd):
 
1149
    command = SetApprovalDurationCmd
 
1150
    property = "ApprovalDuration"
 
1151
    values_to_set = [datetime.timedelta(),
 
1152
                     datetime.timedelta(minutes=5),
 
1153
                     datetime.timedelta(seconds=1),
 
1154
                     datetime.timedelta(weeks=1),
 
1155
                     datetime.timedelta(weeks=52)]
 
1156
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1157
 
 
1158
class Test_command_from_options(unittest.TestCase):
 
1159
    def setUp(self):
 
1160
        self.parser = argparse.ArgumentParser()
 
1161
        add_command_line_options(self.parser)
 
1162
    def assert_command_from_args(self, args, command_cls, **cmd_attrs):
 
1163
        """Assert that parsing ARGS should result in an instance of
 
1164
COMMAND_CLS with (optionally) all supplied attributes (CMD_ATTRS)."""
 
1165
        options = self.parser.parse_args(args)
 
1166
        check_option_syntax(self.parser, options)
 
1167
        commands = commands_from_options(options)
 
1168
        self.assertEqual(len(commands), 1)
 
1169
        command = commands[0]
 
1170
        self.assertIsInstance(command, command_cls)
 
1171
        for key, value in cmd_attrs.items():
 
1172
            self.assertEqual(getattr(command, key), value)
 
1173
    def test_print_table(self):
 
1174
        self.assert_command_from_args([], PrintTableCmd,
 
1175
                                      verbose=False)
 
1176
 
 
1177
    def test_print_table_verbose(self):
 
1178
        self.assert_command_from_args(["--verbose"], PrintTableCmd,
 
1179
                                      verbose=True)
 
1180
 
 
1181
    def test_print_table_verbose_short(self):
 
1182
        self.assert_command_from_args(["-v"], PrintTableCmd,
 
1183
                                      verbose=True)
 
1184
 
 
1185
    def test_enable(self):
 
1186
        self.assert_command_from_args(["--enable", "foo"], EnableCmd)
 
1187
 
 
1188
    def test_enable_short(self):
 
1189
        self.assert_command_from_args(["-e", "foo"], EnableCmd)
 
1190
 
 
1191
    def test_disable(self):
 
1192
        self.assert_command_from_args(["--disable", "foo"],
 
1193
                                      DisableCmd)
 
1194
 
 
1195
    def test_disable_short(self):
 
1196
        self.assert_command_from_args(["-d", "foo"], DisableCmd)
 
1197
 
 
1198
    def test_bump_timeout(self):
 
1199
        self.assert_command_from_args(["--bump-timeout", "foo"],
 
1200
                                      BumpTimeoutCmd)
 
1201
 
 
1202
    def test_bump_timeout_short(self):
 
1203
        self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
 
1204
 
 
1205
    def test_start_checker(self):
 
1206
        self.assert_command_from_args(["--start-checker", "foo"],
 
1207
                                      StartCheckerCmd)
 
1208
 
 
1209
    def test_stop_checker(self):
 
1210
        self.assert_command_from_args(["--stop-checker", "foo"],
 
1211
                                      StopCheckerCmd)
 
1212
 
 
1213
    def test_remove(self):
 
1214
        self.assert_command_from_args(["--remove", "foo"],
 
1215
                                      RemoveCmd)
 
1216
 
 
1217
    def test_remove_short(self):
 
1218
        self.assert_command_from_args(["-r", "foo"], RemoveCmd)
 
1219
 
 
1220
    def test_checker(self):
 
1221
        self.assert_command_from_args(["--checker", ":", "foo"],
 
1222
                                      SetCheckerCmd, value_to_set=":")
 
1223
 
 
1224
    def test_checker_empty(self):
 
1225
        self.assert_command_from_args(["--checker", "", "foo"],
 
1226
                                      SetCheckerCmd, value_to_set="")
 
1227
 
 
1228
    def test_checker_short(self):
 
1229
        self.assert_command_from_args(["-c", ":", "foo"],
 
1230
                                      SetCheckerCmd, value_to_set=":")
 
1231
 
 
1232
    def test_timeout(self):
 
1233
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
 
1234
                                      SetTimeoutCmd,
 
1235
                                      value_to_set=300000)
 
1236
 
 
1237
    def test_timeout_short(self):
 
1238
        self.assert_command_from_args(["-t", "PT5M", "foo"],
 
1239
                                      SetTimeoutCmd,
 
1240
                                      value_to_set=300000)
 
1241
 
 
1242
    def test_extended_timeout(self):
 
1243
        self.assert_command_from_args(["--extended-timeout", "PT15M",
 
1244
                                       "foo"],
 
1245
                                      SetExtendedTimeoutCmd,
 
1246
                                      value_to_set=900000)
 
1247
 
 
1248
    def test_interval(self):
 
1249
        self.assert_command_from_args(["--interval", "PT2M", "foo"],
 
1250
                                      SetIntervalCmd,
 
1251
                                      value_to_set=120000)
 
1252
 
 
1253
    def test_interval_short(self):
 
1254
        self.assert_command_from_args(["-i", "PT2M", "foo"],
 
1255
                                      SetIntervalCmd,
 
1256
                                      value_to_set=120000)
 
1257
 
 
1258
    def test_approve_by_default(self):
 
1259
        self.assert_command_from_args(["--approve-by-default", "foo"],
 
1260
                                      ApproveByDefaultCmd)
 
1261
 
 
1262
    def test_deny_by_default(self):
 
1263
        self.assert_command_from_args(["--deny-by-default", "foo"],
 
1264
                                      DenyByDefaultCmd)
 
1265
 
 
1266
    def test_approval_delay(self):
 
1267
        self.assert_command_from_args(["--approval-delay", "PT30S",
 
1268
                                       "foo"], SetApprovalDelayCmd,
 
1269
                                      value_to_set=30000)
 
1270
 
 
1271
    def test_approval_duration(self):
 
1272
        self.assert_command_from_args(["--approval-duration", "PT1S",
 
1273
                                       "foo"], SetApprovalDurationCmd,
 
1274
                                      value_to_set=1000)
 
1275
 
 
1276
    def test_host(self):
 
1277
        self.assert_command_from_args(["--host", "foo.example.org",
 
1278
                                       "foo"], SetHostCmd,
 
1279
                                      value_to_set="foo.example.org")
 
1280
 
 
1281
    def test_host_short(self):
 
1282
        self.assert_command_from_args(["-H", "foo.example.org",
 
1283
                                       "foo"], SetHostCmd,
 
1284
                                      value_to_set="foo.example.org")
 
1285
 
 
1286
    def test_secret_devnull(self):
 
1287
        self.assert_command_from_args(["--secret", os.path.devnull,
 
1288
                                       "foo"], SetSecretCmd,
 
1289
                                      value_to_set=b"")
 
1290
 
 
1291
    def test_secret_tempfile(self):
 
1292
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
 
1293
            value = b"secret\0xyzzy\nbar"
 
1294
            f.write(value)
 
1295
            f.seek(0)
 
1296
            self.assert_command_from_args(["--secret", f.name,
 
1297
                                           "foo"], SetSecretCmd,
 
1298
                                          value_to_set=value)
 
1299
 
 
1300
    def test_secret_devnull_short(self):
 
1301
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
 
1302
                                      SetSecretCmd, value_to_set=b"")
 
1303
 
 
1304
    def test_secret_tempfile_short(self):
 
1305
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
 
1306
            value = b"secret\0xyzzy\nbar"
 
1307
            f.write(value)
 
1308
            f.seek(0)
 
1309
            self.assert_command_from_args(["-s", f.name, "foo"],
 
1310
                                          SetSecretCmd,
 
1311
                                          value_to_set=value)
 
1312
 
 
1313
    def test_approve(self):
 
1314
        self.assert_command_from_args(["--approve", "foo"],
 
1315
                                      ApproveCmd)
 
1316
 
 
1317
    def test_approve_short(self):
 
1318
        self.assert_command_from_args(["-A", "foo"], ApproveCmd)
 
1319
 
 
1320
    def test_deny(self):
 
1321
        self.assert_command_from_args(["--deny", "foo"], DenyCmd)
 
1322
 
 
1323
    def test_deny_short(self):
 
1324
        self.assert_command_from_args(["-D", "foo"], DenyCmd)
 
1325
 
 
1326
    def test_dump_json(self):
 
1327
        self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
 
1328
 
 
1329
    def test_is_enabled(self):
 
1330
        self.assert_command_from_args(["--is-enabled", "foo"],
 
1331
                                      IsEnabledCmd)
 
1332
 
 
1333
    def test_is_enabled_short(self):
 
1334
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
 
1335
 
 
1336
 
 
1337
class Test_check_option_syntax(unittest.TestCase):
 
1338
    # This mostly corresponds to the definition from has_actions() in
 
1339
    # check_option_syntax()
 
1340
    actions = {
 
1341
        # The actual values set here are not that important, but we do
 
1342
        # at least stick to the correct types, even though they are
 
1343
        # never used
 
1344
        "enable": True,
 
1345
        "disable": True,
 
1346
        "bump_timeout": True,
 
1347
        "start_checker": True,
 
1348
        "stop_checker": True,
 
1349
        "is_enabled": True,
 
1350
        "remove": True,
 
1351
        "checker": "x",
 
1352
        "timeout": datetime.timedelta(),
 
1353
        "extended_timeout": datetime.timedelta(),
 
1354
        "interval": datetime.timedelta(),
 
1355
        "approved_by_default": True,
 
1356
        "approval_delay": datetime.timedelta(),
 
1357
        "approval_duration": datetime.timedelta(),
 
1358
        "host": "x",
 
1359
        "secret": io.BytesIO(b"x"),
 
1360
        "approve": True,
 
1361
        "deny": True,
 
1362
    }
 
1363
 
 
1364
    def setUp(self):
 
1365
        self.parser = argparse.ArgumentParser()
 
1366
        add_command_line_options(self.parser)
 
1367
 
 
1368
    @contextlib.contextmanager
 
1369
    def assertParseError(self):
 
1370
        with self.assertRaises(SystemExit) as e:
 
1371
            with self.temporarily_suppress_stderr():
 
1372
                yield
 
1373
        # Exit code from argparse is guaranteed to be "2".  Reference:
 
1374
        # https://docs.python.org/3/library/argparse.html#exiting-methods
 
1375
        self.assertEqual(e.exception.code, 2)
 
1376
 
 
1377
    @staticmethod
 
1378
    @contextlib.contextmanager
 
1379
    def temporarily_suppress_stderr():
 
1380
        null = os.open(os.path.devnull, os.O_RDWR)
 
1381
        stderrcopy = os.dup(sys.stderr.fileno())
 
1382
        os.dup2(null, sys.stderr.fileno())
 
1383
        os.close(null)
 
1384
        try:
 
1385
            yield
 
1386
        finally:
 
1387
            # restore stderr
 
1388
            os.dup2(stderrcopy, sys.stderr.fileno())
 
1389
            os.close(stderrcopy)
 
1390
 
 
1391
    def check_option_syntax(self, options):
 
1392
        check_option_syntax(self.parser, options)
 
1393
 
 
1394
    def test_actions_requires_client_or_all(self):
 
1395
        for action, value in self.actions.items():
 
1396
            options = self.parser.parse_args()
 
1397
            setattr(options, action, value)
 
1398
            with self.assertParseError():
 
1399
                self.check_option_syntax(options)
 
1400
 
 
1401
    def test_actions_conflicts_with_verbose(self):
 
1402
        for action, value in self.actions.items():
 
1403
            options = self.parser.parse_args()
 
1404
            setattr(options, action, value)
 
1405
            options.verbose = True
 
1406
            with self.assertParseError():
 
1407
                self.check_option_syntax(options)
 
1408
 
 
1409
    def test_dump_json_conflicts_with_verbose(self):
 
1410
        options = self.parser.parse_args()
 
1411
        options.dump_json = True
 
1412
        options.verbose = True
 
1413
        with self.assertParseError():
 
1414
            self.check_option_syntax(options)
 
1415
 
 
1416
    def test_dump_json_conflicts_with_action(self):
 
1417
        for action, value in self.actions.items():
 
1418
            options = self.parser.parse_args()
 
1419
            setattr(options, action, value)
 
1420
            options.dump_json = True
 
1421
            with self.assertParseError():
 
1422
                self.check_option_syntax(options)
 
1423
 
 
1424
    def test_all_can_not_be_alone(self):
 
1425
        options = self.parser.parse_args()
 
1426
        options.all = True
 
1427
        with self.assertParseError():
 
1428
            self.check_option_syntax(options)
 
1429
 
 
1430
    def test_all_is_ok_with_any_action(self):
 
1431
        for action, value in self.actions.items():
 
1432
            options = self.parser.parse_args()
 
1433
            setattr(options, action, value)
 
1434
            options.all = True
 
1435
            self.check_option_syntax(options)
 
1436
 
 
1437
    def test_is_enabled_fails_without_client(self):
 
1438
        options = self.parser.parse_args()
 
1439
        options.is_enabled = True
 
1440
        with self.assertParseError():
 
1441
            self.check_option_syntax(options)
 
1442
 
 
1443
    def test_is_enabled_works_with_one_client(self):
 
1444
        options = self.parser.parse_args()
 
1445
        options.is_enabled = True
 
1446
        options.client = ["foo"]
 
1447
        self.check_option_syntax(options)
 
1448
 
 
1449
    def test_is_enabled_fails_with_two_clients(self):
 
1450
        options = self.parser.parse_args()
 
1451
        options.is_enabled = True
 
1452
        options.client = ["foo", "barbar"]
 
1453
        with self.assertParseError():
 
1454
            self.check_option_syntax(options)
 
1455
 
869
1456
 
870
1457
 
871
1458
def should_only_run_tests():