/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-17 21:29:32 UTC
  • Revision ID: teddy@recompile.se-20190317212932-r3libgz33mkb85rw
mandos-ctl: Refactor

* mandos-ctl: For Python 2, use StringIO.StringIO as a replacement for
              io.StringIO, since Python 2's io.StringIO won't work
              with print redirection.
  (Output.run, Output.output): Remove.
  (DumpJSON.output): Rename to "run" and change signature to match.
                     Also change code to print instead of returning
                     string.
  (PrintTable.output): - '' -

Show diffs side-by-side

added added

removed removed

Lines of Context:
61
61
 
62
62
if sys.version_info.major == 2:
63
63
    str = unicode
 
64
    import StringIO
 
65
    io.StringIO = StringIO.StringIO
64
66
 
65
67
locale.setlocale(locale.LC_ALL, "")
66
68
 
93
95
    if options.debug:
94
96
        log.setLevel(logging.DEBUG)
95
97
 
96
 
    try:
97
 
        bus = dbus.SystemBus()
98
 
        log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
99
 
                  dbus_busname, server_dbus_path)
100
 
        mandos_dbus_objc = bus.get_object(dbus_busname,
101
 
                                          server_dbus_path)
102
 
    except dbus.exceptions.DBusException:
103
 
        log.critical("Could not connect to Mandos server")
104
 
        sys.exit(1)
105
 
 
106
 
    mandos_serv = dbus.Interface(mandos_dbus_objc,
107
 
                                 dbus_interface=server_dbus_interface)
 
98
    bus = dbus.SystemBus()
 
99
 
 
100
    mandos_dbus_object = get_mandos_dbus_object(bus)
 
101
 
 
102
    mandos_serv = dbus.Interface(
 
103
        mandos_dbus_object, dbus_interface=server_dbus_interface)
108
104
    mandos_serv_object_manager = dbus.Interface(
109
 
        mandos_dbus_objc, dbus_interface=dbus.OBJECT_MANAGER_IFACE)
110
 
 
111
 
    try:
112
 
        log.debug("D-Bus: %s:%s:%s.GetManagedObjects()", dbus_busname,
113
 
                  server_dbus_path, dbus.OBJECT_MANAGER_IFACE)
114
 
        with SilenceLogger("dbus.proxies"):
115
 
            all_clients = {path: ifs_and_props[client_dbus_interface]
116
 
                              for path, ifs_and_props in
117
 
                              mandos_serv_object_manager
118
 
                              .GetManagedObjects().items()
119
 
                              if client_dbus_interface in ifs_and_props}
120
 
    except dbus.exceptions.DBusException as e:
121
 
        log.critical("Failed to access Mandos server through D-Bus:"
122
 
                     "\n%s", e)
123
 
        sys.exit(1)
124
 
 
125
 
    # Compile dict of (clients: properties) to process
126
 
    clients = {}
127
 
 
 
105
        mandos_dbus_object, dbus_interface=dbus.OBJECT_MANAGER_IFACE)
 
106
 
 
107
    managed_objects = get_managed_objects(mandos_serv_object_manager)
 
108
 
 
109
    all_clients = {}
 
110
    for path, ifs_and_props in managed_objects.items():
 
111
        try:
 
112
            all_clients[path] = ifs_and_props[client_dbus_interface]
 
113
        except KeyError:
 
114
            pass
 
115
 
 
116
    # Compile dict of (clientpath: properties) to process
128
117
    if not clientnames:
129
118
        clients = all_clients
130
119
    else:
 
120
        clients = {}
131
121
        for name in clientnames:
132
122
            for objpath, properties in all_clients.items():
133
123
                if properties["Name"] == name:
137
127
                log.critical("Client not found on server: %r", name)
138
128
                sys.exit(1)
139
129
 
140
 
    # Run all commands on clients
141
130
    commands = commands_from_options(options)
 
131
 
142
132
    for command in commands:
143
133
        command.run(clients, bus, mandos_serv)
144
134
 
244
234
    >>> rfc3339_duration_to_delta("")
245
235
    Traceback (most recent call last):
246
236
    ...
247
 
    ValueError: Invalid RFC 3339 duration: u''
 
237
    ValueError: Invalid RFC 3339 duration: ""
248
238
    >>> # Must start with "P":
249
239
    >>> rfc3339_duration_to_delta("1D")
250
240
    Traceback (most recent call last):
251
241
    ...
252
 
    ValueError: Invalid RFC 3339 duration: u'1D'
 
242
    ValueError: Invalid RFC 3339 duration: "1D"
253
243
    >>> # Must use correct order
254
244
    >>> rfc3339_duration_to_delta("PT1S2M")
255
245
    Traceback (most recent call last):
256
246
    ...
257
 
    ValueError: Invalid RFC 3339 duration: u'PT1S2M'
 
247
    ValueError: Invalid RFC 3339 duration: "PT1S2M"
258
248
    >>> # Time needs time marker
259
249
    >>> rfc3339_duration_to_delta("P1H2S")
260
250
    Traceback (most recent call last):
261
251
    ...
262
 
    ValueError: Invalid RFC 3339 duration: u'P1H2S'
 
252
    ValueError: Invalid RFC 3339 duration: "P1H2S"
263
253
    >>> # Weeks can not be combined with anything else
264
254
    >>> rfc3339_duration_to_delta("P1D2W")
265
255
    Traceback (most recent call last):
266
256
    ...
267
 
    ValueError: Invalid RFC 3339 duration: u'P1D2W'
 
257
    ValueError: Invalid RFC 3339 duration: "P1D2W"
268
258
    >>> rfc3339_duration_to_delta("P2W2H")
269
259
    Traceback (most recent call last):
270
260
    ...
271
 
    ValueError: Invalid RFC 3339 duration: u'P2W2H'
 
261
    ValueError: Invalid RFC 3339 duration: "P2W2H"
272
262
    """
273
263
 
274
264
    # Parsing an RFC 3339 duration with regular expressions is not
345
335
                break
346
336
        else:
347
337
            # No currently valid tokens were found
348
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
 
338
            raise ValueError("Invalid RFC 3339 duration: \"{}\""
349
339
                             .format(duration))
350
340
    # End token found
351
341
    return value
436
426
        options.remove = True
437
427
 
438
428
 
 
429
def get_mandos_dbus_object(bus):
 
430
    log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
 
431
              dbus_busname, server_dbus_path)
 
432
    with if_dbus_exception_log_with_exception_and_exit(
 
433
            "Could not connect to Mandos server: %s"):
 
434
        mandos_dbus_object = bus.get_object(dbus_busname,
 
435
                                            server_dbus_path)
 
436
    return mandos_dbus_object
 
437
 
 
438
 
 
439
@contextlib.contextmanager
 
440
def if_dbus_exception_log_with_exception_and_exit(*args, **kwargs):
 
441
    try:
 
442
        yield
 
443
    except dbus.exceptions.DBusException as e:
 
444
        log.critical(*(args + (e,)), **kwargs)
 
445
        sys.exit(1)
 
446
 
 
447
 
 
448
def get_managed_objects(object_manager):
 
449
    log.debug("D-Bus: %s:%s:%s.GetManagedObjects()", dbus_busname,
 
450
              server_dbus_path, dbus.OBJECT_MANAGER_IFACE)
 
451
    with if_dbus_exception_log_with_exception_and_exit(
 
452
            "Failed to access Mandos server through D-Bus:\n%s"):
 
453
        with SilenceLogger("dbus.proxies"):
 
454
            managed_objects = object_manager.GetManagedObjects()
 
455
    return managed_objects
 
456
 
 
457
 
439
458
class SilenceLogger(object):
440
459
    "Simple context manager to silence a particular logger"
441
460
    def __init__(self, loggername):
460
479
    commands = []
461
480
 
462
481
    if options.is_enabled:
463
 
        commands.append(IsEnabledCmd())
 
482
        commands.append(command.IsEnabled())
464
483
 
465
484
    if options.approve:
466
 
        commands.append(ApproveCmd())
 
485
        commands.append(command.Approve())
467
486
 
468
487
    if options.deny:
469
 
        commands.append(DenyCmd())
 
488
        commands.append(command.Deny())
470
489
 
471
490
    if options.remove:
472
 
        commands.append(RemoveCmd())
 
491
        commands.append(command.Remove())
473
492
 
474
493
    if options.dump_json:
475
 
        commands.append(DumpJSONCmd())
 
494
        commands.append(command.DumpJSON())
476
495
 
477
496
    if options.enable:
478
 
        commands.append(EnableCmd())
 
497
        commands.append(command.Enable())
479
498
 
480
499
    if options.disable:
481
 
        commands.append(DisableCmd())
 
500
        commands.append(command.Disable())
482
501
 
483
502
    if options.bump_timeout:
484
 
        commands.append(BumpTimeoutCmd())
 
503
        commands.append(command.BumpTimeout())
485
504
 
486
505
    if options.start_checker:
487
 
        commands.append(StartCheckerCmd())
 
506
        commands.append(command.StartChecker())
488
507
 
489
508
    if options.stop_checker:
490
 
        commands.append(StopCheckerCmd())
 
509
        commands.append(command.StopChecker())
491
510
 
492
511
    if options.approved_by_default is not None:
493
512
        if options.approved_by_default:
494
 
            commands.append(ApproveByDefaultCmd())
 
513
            commands.append(command.ApproveByDefault())
495
514
        else:
496
 
            commands.append(DenyByDefaultCmd())
 
515
            commands.append(command.DenyByDefault())
497
516
 
498
517
    if options.checker is not None:
499
 
        commands.append(SetCheckerCmd(options.checker))
 
518
        commands.append(command.SetChecker(options.checker))
500
519
 
501
520
    if options.host is not None:
502
 
        commands.append(SetHostCmd(options.host))
 
521
        commands.append(command.SetHost(options.host))
503
522
 
504
523
    if options.secret is not None:
505
 
        commands.append(SetSecretCmd(options.secret))
 
524
        commands.append(command.SetSecret(options.secret))
506
525
 
507
526
    if options.timeout is not None:
508
 
        commands.append(SetTimeoutCmd(options.timeout))
 
527
        commands.append(command.SetTimeout(options.timeout))
509
528
 
510
529
    if options.extended_timeout:
511
530
        commands.append(
512
 
            SetExtendedTimeoutCmd(options.extended_timeout))
 
531
            command.SetExtendedTimeout(options.extended_timeout))
513
532
 
514
533
    if options.interval is not None:
515
 
        commands.append(SetIntervalCmd(options.interval))
 
534
        commands.append(command.SetInterval(options.interval))
516
535
 
517
536
    if options.approval_delay is not None:
518
 
        commands.append(SetApprovalDelayCmd(options.approval_delay))
 
537
        commands.append(
 
538
            command.SetApprovalDelay(options.approval_delay))
519
539
 
520
540
    if options.approval_duration is not None:
521
541
        commands.append(
522
 
            SetApprovalDurationCmd(options.approval_duration))
 
542
            command.SetApprovalDuration(options.approval_duration))
523
543
 
524
544
    # If no command option has been given, show table of clients,
525
545
    # optionally verbosely
526
546
    if not commands:
527
 
        commands.append(PrintTableCmd(verbose=options.verbose))
 
547
        commands.append(command.PrintTable(verbose=options.verbose))
528
548
 
529
549
    return commands
530
550
 
531
551
 
532
 
class Command(object):
533
 
    """Abstract class for commands"""
534
 
    def run(self, clients, bus=None, mandos=None):
535
 
        """Normal commands should implement run_on_one_client(), but
536
 
        commands which want to operate on all clients at the same time
537
 
        can override this run() method instead."""
538
 
        self.mandos = mandos
539
 
        for clientpath, properties in clients.items():
540
 
            log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
541
 
                      dbus_busname, str(clientpath))
542
 
            client = bus.get_object(dbus_busname, clientpath)
543
 
            self.run_on_one_client(client, properties)
544
 
 
545
 
 
546
 
class IsEnabledCmd(Command):
547
 
    def run(self, clients, bus=None, mandos=None):
548
 
        client, properties = next(iter(clients.items()))
549
 
        if self.is_enabled(client, properties):
550
 
            sys.exit(0)
551
 
        sys.exit(1)
552
 
    def is_enabled(self, client, properties):
553
 
        return properties["Enabled"]
554
 
 
555
 
 
556
 
class ApproveCmd(Command):
557
 
    def run_on_one_client(self, client, properties):
558
 
        log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
559
 
                  client.__dbus_object_path__, client_dbus_interface)
560
 
        client.Approve(dbus.Boolean(True),
561
 
                       dbus_interface=client_dbus_interface)
562
 
 
563
 
 
564
 
class DenyCmd(Command):
565
 
    def run_on_one_client(self, client, properties):
566
 
        log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
567
 
                  client.__dbus_object_path__, client_dbus_interface)
568
 
        client.Approve(dbus.Boolean(False),
569
 
                       dbus_interface=client_dbus_interface)
570
 
 
571
 
 
572
 
class RemoveCmd(Command):
573
 
    def run_on_one_client(self, client, properties):
574
 
        log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", dbus_busname,
575
 
                  server_dbus_path, server_dbus_interface,
576
 
                  str(client.__dbus_object_path__))
577
 
        self.mandos.RemoveClient(client.__dbus_object_path__)
578
 
 
579
 
 
580
 
class OutputCmd(Command):
581
 
    """Abstract class for commands outputting client details"""
582
 
    all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
583
 
                    "Created", "Interval", "Host", "KeyID",
584
 
                    "Fingerprint", "CheckerRunning", "LastEnabled",
585
 
                    "ApprovalPending", "ApprovedByDefault",
586
 
                    "LastApprovalRequest", "ApprovalDelay",
587
 
                    "ApprovalDuration", "Checker", "ExtendedTimeout",
588
 
                    "Expires", "LastCheckerStatus")
589
 
 
590
 
    def run(self, clients, bus=None, mandos=None):
591
 
        print(self.output(clients.values()))
592
 
 
593
 
    def output(self, clients):
594
 
        raise NotImplementedError()
595
 
 
596
 
 
597
 
class DumpJSONCmd(OutputCmd):
598
 
    def output(self, clients):
599
 
        data = {client["Name"]:
600
 
                {key: self.dbus_boolean_to_bool(client[key])
601
 
                 for key in self.all_keywords}
602
 
                for client in clients}
603
 
        return json.dumps(data, indent=4, separators=(',', ': '))
604
 
 
605
 
    @staticmethod
606
 
    def dbus_boolean_to_bool(value):
607
 
        if isinstance(value, dbus.Boolean):
608
 
            value = bool(value)
609
 
        return value
610
 
 
611
 
 
612
 
class PrintTableCmd(OutputCmd):
613
 
    def __init__(self, verbose=False):
614
 
        self.verbose = verbose
615
 
 
616
 
    def output(self, clients):
617
 
        default_keywords = ("Name", "Enabled", "Timeout",
618
 
                            "LastCheckedOK")
619
 
        keywords = default_keywords
620
 
        if self.verbose:
621
 
            keywords = self.all_keywords
622
 
        return str(self.TableOfClients(clients, keywords))
623
 
 
624
 
    class TableOfClients(object):
625
 
        tableheaders = {
626
 
            "Name": "Name",
627
 
            "Enabled": "Enabled",
628
 
            "Timeout": "Timeout",
629
 
            "LastCheckedOK": "Last Successful Check",
630
 
            "LastApprovalRequest": "Last Approval Request",
631
 
            "Created": "Created",
632
 
            "Interval": "Interval",
633
 
            "Host": "Host",
634
 
            "Fingerprint": "Fingerprint",
635
 
            "KeyID": "Key ID",
636
 
            "CheckerRunning": "Check Is Running",
637
 
            "LastEnabled": "Last Enabled",
638
 
            "ApprovalPending": "Approval Is Pending",
639
 
            "ApprovedByDefault": "Approved By Default",
640
 
            "ApprovalDelay": "Approval Delay",
641
 
            "ApprovalDuration": "Approval Duration",
642
 
            "Checker": "Checker",
643
 
            "ExtendedTimeout": "Extended Timeout",
644
 
            "Expires": "Expires",
645
 
            "LastCheckerStatus": "Last Checker Status",
646
 
        }
647
 
 
648
 
        def __init__(self, clients, keywords):
649
 
            self.clients = clients
650
 
            self.keywords = keywords
651
 
 
652
 
        def __str__(self):
653
 
            return "\n".join(self.rows())
654
 
 
655
 
        if sys.version_info.major == 2:
656
 
            __unicode__ = __str__
 
552
class command(object):
 
553
    """A namespace for command classes"""
 
554
 
 
555
    class Base(object):
 
556
        """Abstract base class for commands"""
 
557
        def run(self, clients, bus=None, mandos=None):
 
558
            """Normal commands should implement run_on_one_client(),
 
559
but commands which want to operate on all clients at the same time can
 
560
override this run() method instead.
 
561
"""
 
562
            self.mandos = mandos
 
563
            for clientpath, properties in clients.items():
 
564
                log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
 
565
                          dbus_busname, str(clientpath))
 
566
                client = bus.get_object(dbus_busname, clientpath)
 
567
                self.run_on_one_client(client, properties)
 
568
 
 
569
 
 
570
    class IsEnabled(Base):
 
571
        def run(self, clients, bus=None, mandos=None):
 
572
            client, properties = next(iter(clients.items()))
 
573
            if self.is_enabled(client, properties):
 
574
                sys.exit(0)
 
575
            sys.exit(1)
 
576
        def is_enabled(self, client, properties):
 
577
            return properties["Enabled"]
 
578
 
 
579
 
 
580
    class Approve(Base):
 
581
        def run_on_one_client(self, client, properties):
 
582
            log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
 
583
                      client.__dbus_object_path__,
 
584
                      client_dbus_interface)
 
585
            client.Approve(dbus.Boolean(True),
 
586
                           dbus_interface=client_dbus_interface)
 
587
 
 
588
 
 
589
    class Deny(Base):
 
590
        def run_on_one_client(self, client, properties):
 
591
            log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
 
592
                      client.__dbus_object_path__,
 
593
                      client_dbus_interface)
 
594
            client.Approve(dbus.Boolean(False),
 
595
                           dbus_interface=client_dbus_interface)
 
596
 
 
597
 
 
598
    class Remove(Base):
 
599
        def run_on_one_client(self, client, properties):
 
600
            log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)",
 
601
                      dbus_busname, server_dbus_path,
 
602
                      server_dbus_interface,
 
603
                      str(client.__dbus_object_path__))
 
604
            self.mandos.RemoveClient(client.__dbus_object_path__)
 
605
 
 
606
 
 
607
    class Output(Base):
 
608
        """Abstract class for commands outputting client details"""
 
609
        all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
 
610
                        "Created", "Interval", "Host", "KeyID",
 
611
                        "Fingerprint", "CheckerRunning",
 
612
                        "LastEnabled", "ApprovalPending",
 
613
                        "ApprovedByDefault", "LastApprovalRequest",
 
614
                        "ApprovalDelay", "ApprovalDuration",
 
615
                        "Checker", "ExtendedTimeout", "Expires",
 
616
                        "LastCheckerStatus")
 
617
 
 
618
 
 
619
    class DumpJSON(Output):
 
620
        def run(self, clients, bus=None, mandos=None):
 
621
            data = {client["Name"]:
 
622
                    {key: self.dbus_boolean_to_bool(client[key])
 
623
                     for key in self.all_keywords}
 
624
                    for client in clients.values()}
 
625
            print(json.dumps(data, indent=4, separators=(',', ': ')))
 
626
 
 
627
        @staticmethod
 
628
        def dbus_boolean_to_bool(value):
 
629
            if isinstance(value, dbus.Boolean):
 
630
                value = bool(value)
 
631
            return value
 
632
 
 
633
 
 
634
    class PrintTable(Output):
 
635
        def __init__(self, verbose=False):
 
636
            self.verbose = verbose
 
637
 
 
638
        def run(self, clients, bus=None, mandos=None):
 
639
            default_keywords = ("Name", "Enabled", "Timeout",
 
640
                                "LastCheckedOK")
 
641
            keywords = default_keywords
 
642
            if self.verbose:
 
643
                keywords = self.all_keywords
 
644
            print(self.TableOfClients(clients.values(), keywords))
 
645
 
 
646
        class TableOfClients(object):
 
647
            tableheaders = {
 
648
                "Name": "Name",
 
649
                "Enabled": "Enabled",
 
650
                "Timeout": "Timeout",
 
651
                "LastCheckedOK": "Last Successful Check",
 
652
                "LastApprovalRequest": "Last Approval Request",
 
653
                "Created": "Created",
 
654
                "Interval": "Interval",
 
655
                "Host": "Host",
 
656
                "Fingerprint": "Fingerprint",
 
657
                "KeyID": "Key ID",
 
658
                "CheckerRunning": "Check Is Running",
 
659
                "LastEnabled": "Last Enabled",
 
660
                "ApprovalPending": "Approval Is Pending",
 
661
                "ApprovedByDefault": "Approved By Default",
 
662
                "ApprovalDelay": "Approval Delay",
 
663
                "ApprovalDuration": "Approval Duration",
 
664
                "Checker": "Checker",
 
665
                "ExtendedTimeout": "Extended Timeout",
 
666
                "Expires": "Expires",
 
667
                "LastCheckerStatus": "Last Checker Status",
 
668
            }
 
669
 
 
670
            def __init__(self, clients, keywords):
 
671
                self.clients = clients
 
672
                self.keywords = keywords
 
673
 
657
674
            def __str__(self):
658
 
                return str(self).encode(locale.getpreferredencoding())
659
 
 
660
 
        def rows(self):
661
 
            format_string = self.row_formatting_string()
662
 
            rows = [self.header_line(format_string)]
663
 
            rows.extend(self.client_line(client, format_string)
664
 
                        for client in self.clients)
665
 
            return rows
666
 
 
667
 
        def row_formatting_string(self):
668
 
            "Format string used to format table rows"
669
 
            return " ".join("{{{key}:{width}}}".format(
670
 
                width=max(len(self.tableheaders[key]),
671
 
                          *(len(self.string_from_client(client, key))
672
 
                            for client in self.clients)),
673
 
                key=key)
674
 
                            for key in self.keywords)
675
 
 
676
 
        def string_from_client(self, client, key):
677
 
            return self.valuetostring(client[key], key)
678
 
 
679
 
        @classmethod
680
 
        def valuetostring(cls, value, keyword):
681
 
            if isinstance(value, dbus.Boolean):
682
 
                return "Yes" if value else "No"
683
 
            if keyword in ("Timeout", "Interval", "ApprovalDelay",
684
 
                           "ApprovalDuration", "ExtendedTimeout"):
685
 
                return cls.milliseconds_to_string(value)
686
 
            return str(value)
687
 
 
688
 
        def header_line(self, format_string):
689
 
            return format_string.format(**self.tableheaders)
690
 
 
691
 
        def client_line(self, client, format_string):
692
 
            return format_string.format(
693
 
                **{key: self.string_from_client(client, key)
694
 
                   for key in self.keywords})
695
 
 
696
 
        @staticmethod
697
 
        def milliseconds_to_string(ms):
698
 
            td = datetime.timedelta(0, 0, 0, ms)
699
 
            return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
700
 
                    .format(days="{}T".format(td.days)
701
 
                            if td.days else "",
702
 
                            hours=td.seconds // 3600,
703
 
                            minutes=(td.seconds % 3600) // 60,
704
 
                            seconds=td.seconds % 60))
705
 
 
706
 
 
707
 
class PropertyCmd(Command):
708
 
    """Abstract class for Actions for setting one client property"""
709
 
 
710
 
    def run_on_one_client(self, client, properties):
711
 
        """Set the Client's D-Bus property"""
712
 
        log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
713
 
                  client.__dbus_object_path__,
714
 
                  dbus.PROPERTIES_IFACE, client_dbus_interface,
715
 
                  self.propname, self.value_to_set
716
 
                  if not isinstance(self.value_to_set, dbus.Boolean)
717
 
                  else bool(self.value_to_set))
718
 
        client.Set(client_dbus_interface, self.propname,
719
 
                   self.value_to_set,
720
 
                   dbus_interface=dbus.PROPERTIES_IFACE)
721
 
 
722
 
    @property
723
 
    def propname(self):
724
 
        raise NotImplementedError()
725
 
 
726
 
 
727
 
class EnableCmd(PropertyCmd):
728
 
    propname = "Enabled"
729
 
    value_to_set = dbus.Boolean(True)
730
 
 
731
 
 
732
 
class DisableCmd(PropertyCmd):
733
 
    propname = "Enabled"
734
 
    value_to_set = dbus.Boolean(False)
735
 
 
736
 
 
737
 
class BumpTimeoutCmd(PropertyCmd):
738
 
    propname = "LastCheckedOK"
739
 
    value_to_set = ""
740
 
 
741
 
 
742
 
class StartCheckerCmd(PropertyCmd):
743
 
    propname = "CheckerRunning"
744
 
    value_to_set = dbus.Boolean(True)
745
 
 
746
 
 
747
 
class StopCheckerCmd(PropertyCmd):
748
 
    propname = "CheckerRunning"
749
 
    value_to_set = dbus.Boolean(False)
750
 
 
751
 
 
752
 
class ApproveByDefaultCmd(PropertyCmd):
753
 
    propname = "ApprovedByDefault"
754
 
    value_to_set = dbus.Boolean(True)
755
 
 
756
 
 
757
 
class DenyByDefaultCmd(PropertyCmd):
758
 
    propname = "ApprovedByDefault"
759
 
    value_to_set = dbus.Boolean(False)
760
 
 
761
 
 
762
 
class PropertyValueCmd(PropertyCmd):
763
 
    """Abstract class for PropertyCmd recieving a value as argument"""
764
 
    def __init__(self, value):
765
 
        self.value_to_set = value
766
 
 
767
 
 
768
 
class SetCheckerCmd(PropertyValueCmd):
769
 
    propname = "Checker"
770
 
 
771
 
 
772
 
class SetHostCmd(PropertyValueCmd):
773
 
    propname = "Host"
774
 
 
775
 
 
776
 
class SetSecretCmd(PropertyValueCmd):
777
 
    propname = "Secret"
778
 
 
779
 
    @property
780
 
    def value_to_set(self):
781
 
        return self._vts
782
 
 
783
 
    @value_to_set.setter
784
 
    def value_to_set(self, value):
785
 
        """When setting, read data from supplied file object"""
786
 
        self._vts = value.read()
787
 
        value.close()
788
 
 
789
 
 
790
 
class MillisecondsPropertyValueArgumentCmd(PropertyValueCmd):
791
 
    """Abstract class for PropertyValueCmd taking a value argument as
 
675
                return "\n".join(self.rows())
 
676
 
 
677
            if sys.version_info.major == 2:
 
678
                __unicode__ = __str__
 
679
                def __str__(self):
 
680
                    return str(self).encode(
 
681
                        locale.getpreferredencoding())
 
682
 
 
683
            def rows(self):
 
684
                format_string = self.row_formatting_string()
 
685
                rows = [self.header_line(format_string)]
 
686
                rows.extend(self.client_line(client, format_string)
 
687
                            for client in self.clients)
 
688
                return rows
 
689
 
 
690
            def row_formatting_string(self):
 
691
                "Format string used to format table rows"
 
692
                return " ".join("{{{key}:{width}}}".format(
 
693
                    width=max(len(self.tableheaders[key]),
 
694
                              *(len(self.string_from_client(client,
 
695
                                                            key))
 
696
                                for client in self.clients)),
 
697
                    key=key)
 
698
                                for key in self.keywords)
 
699
 
 
700
            def string_from_client(self, client, key):
 
701
                return self.valuetostring(client[key], key)
 
702
 
 
703
            @classmethod
 
704
            def valuetostring(cls, value, keyword):
 
705
                if isinstance(value, dbus.Boolean):
 
706
                    return "Yes" if value else "No"
 
707
                if keyword in ("Timeout", "Interval", "ApprovalDelay",
 
708
                               "ApprovalDuration", "ExtendedTimeout"):
 
709
                    return cls.milliseconds_to_string(value)
 
710
                return str(value)
 
711
 
 
712
            def header_line(self, format_string):
 
713
                return format_string.format(**self.tableheaders)
 
714
 
 
715
            def client_line(self, client, format_string):
 
716
                return format_string.format(
 
717
                    **{key: self.string_from_client(client, key)
 
718
                       for key in self.keywords})
 
719
 
 
720
            @staticmethod
 
721
            def milliseconds_to_string(ms):
 
722
                td = datetime.timedelta(0, 0, 0, ms)
 
723
                return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
 
724
                        .format(days="{}T".format(td.days)
 
725
                                if td.days else "",
 
726
                                hours=td.seconds // 3600,
 
727
                                minutes=(td.seconds % 3600) // 60,
 
728
                                seconds=td.seconds % 60))
 
729
 
 
730
 
 
731
    class Property(Base):
 
732
        "Abstract class for Actions for setting one client property"
 
733
 
 
734
        def run_on_one_client(self, client, properties):
 
735
            """Set the Client's D-Bus property"""
 
736
            log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
 
737
                      client.__dbus_object_path__,
 
738
                      dbus.PROPERTIES_IFACE, client_dbus_interface,
 
739
                      self.propname, self.value_to_set
 
740
                      if not isinstance(self.value_to_set,
 
741
                                        dbus.Boolean)
 
742
                      else bool(self.value_to_set))
 
743
            client.Set(client_dbus_interface, self.propname,
 
744
                       self.value_to_set,
 
745
                       dbus_interface=dbus.PROPERTIES_IFACE)
 
746
 
 
747
        @property
 
748
        def propname(self):
 
749
            raise NotImplementedError()
 
750
 
 
751
 
 
752
    class Enable(Property):
 
753
        propname = "Enabled"
 
754
        value_to_set = dbus.Boolean(True)
 
755
 
 
756
 
 
757
    class Disable(Property):
 
758
        propname = "Enabled"
 
759
        value_to_set = dbus.Boolean(False)
 
760
 
 
761
 
 
762
    class BumpTimeout(Property):
 
763
        propname = "LastCheckedOK"
 
764
        value_to_set = ""
 
765
 
 
766
 
 
767
    class StartChecker(Property):
 
768
        propname = "CheckerRunning"
 
769
        value_to_set = dbus.Boolean(True)
 
770
 
 
771
 
 
772
    class StopChecker(Property):
 
773
        propname = "CheckerRunning"
 
774
        value_to_set = dbus.Boolean(False)
 
775
 
 
776
 
 
777
    class ApproveByDefault(Property):
 
778
        propname = "ApprovedByDefault"
 
779
        value_to_set = dbus.Boolean(True)
 
780
 
 
781
 
 
782
    class DenyByDefault(Property):
 
783
        propname = "ApprovedByDefault"
 
784
        value_to_set = dbus.Boolean(False)
 
785
 
 
786
 
 
787
    class PropertyValue(Property):
 
788
        "Abstract class for Property recieving a value as argument"
 
789
        def __init__(self, value):
 
790
            self.value_to_set = value
 
791
 
 
792
 
 
793
    class SetChecker(PropertyValue):
 
794
        propname = "Checker"
 
795
 
 
796
 
 
797
    class SetHost(PropertyValue):
 
798
        propname = "Host"
 
799
 
 
800
 
 
801
    class SetSecret(PropertyValue):
 
802
        propname = "Secret"
 
803
 
 
804
        @property
 
805
        def value_to_set(self):
 
806
            return self._vts
 
807
 
 
808
        @value_to_set.setter
 
809
        def value_to_set(self, value):
 
810
            """When setting, read data from supplied file object"""
 
811
            self._vts = value.read()
 
812
            value.close()
 
813
 
 
814
 
 
815
    class MillisecondsPropertyValueArgument(PropertyValue):
 
816
        """Abstract class for PropertyValue taking a value argument as
792
817
a datetime.timedelta() but should store it as milliseconds."""
793
818
 
794
 
    @property
795
 
    def value_to_set(self):
796
 
        return self._vts
797
 
 
798
 
    @value_to_set.setter
799
 
    def value_to_set(self, value):
800
 
        """When setting, convert value from a datetime.timedelta"""
801
 
        self._vts = int(round(value.total_seconds() * 1000))
802
 
 
803
 
 
804
 
class SetTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
805
 
    propname = "Timeout"
806
 
 
807
 
 
808
 
class SetExtendedTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
809
 
    propname = "ExtendedTimeout"
810
 
 
811
 
 
812
 
class SetIntervalCmd(MillisecondsPropertyValueArgumentCmd):
813
 
    propname = "Interval"
814
 
 
815
 
 
816
 
class SetApprovalDelayCmd(MillisecondsPropertyValueArgumentCmd):
817
 
    propname = "ApprovalDelay"
818
 
 
819
 
 
820
 
class SetApprovalDurationCmd(MillisecondsPropertyValueArgumentCmd):
821
 
    propname = "ApprovalDuration"
 
819
        @property
 
820
        def value_to_set(self):
 
821
            return self._vts
 
822
 
 
823
        @value_to_set.setter
 
824
        def value_to_set(self, value):
 
825
            "When setting, convert value from a datetime.timedelta"
 
826
            self._vts = int(round(value.total_seconds() * 1000))
 
827
 
 
828
 
 
829
    class SetTimeout(MillisecondsPropertyValueArgument):
 
830
        propname = "Timeout"
 
831
 
 
832
 
 
833
    class SetExtendedTimeout(MillisecondsPropertyValueArgument):
 
834
        propname = "ExtendedTimeout"
 
835
 
 
836
 
 
837
    class SetInterval(MillisecondsPropertyValueArgument):
 
838
        propname = "Interval"
 
839
 
 
840
 
 
841
    class SetApprovalDelay(MillisecondsPropertyValueArgument):
 
842
        propname = "ApprovalDelay"
 
843
 
 
844
 
 
845
    class SetApprovalDuration(MillisecondsPropertyValueArgument):
 
846
        propname = "ApprovalDuration"
822
847
 
823
848
 
824
849
 
825
 
class Test_string_to_delta(unittest.TestCase):
826
 
    def test_handles_basic_rfc3339(self):
827
 
        self.assertEqual(string_to_delta("PT0S"),
828
 
                         datetime.timedelta())
829
 
        self.assertEqual(string_to_delta("P0D"),
830
 
                         datetime.timedelta())
831
 
        self.assertEqual(string_to_delta("PT1S"),
832
 
                         datetime.timedelta(0, 1))
833
 
        self.assertEqual(string_to_delta("PT2H"),
834
 
                         datetime.timedelta(0, 7200))
 
850
class TestCaseWithAssertLogs(unittest.TestCase):
 
851
    """unittest.TestCase.assertLogs only exists in Python 3.4"""
 
852
 
 
853
    if not hasattr(unittest.TestCase, "assertLogs"):
 
854
        @contextlib.contextmanager
 
855
        def assertLogs(self, logger, level=logging.INFO):
 
856
            capturing_handler = self.CapturingLevelHandler(level)
 
857
            old_level = logger.level
 
858
            old_propagate = logger.propagate
 
859
            logger.addHandler(capturing_handler)
 
860
            logger.setLevel(level)
 
861
            logger.propagate = False
 
862
            try:
 
863
                yield capturing_handler.watcher
 
864
            finally:
 
865
                logger.propagate = old_propagate
 
866
                logger.removeHandler(capturing_handler)
 
867
                logger.setLevel(old_level)
 
868
            self.assertGreater(len(capturing_handler.watcher.records),
 
869
                               0)
 
870
 
 
871
        class CapturingLevelHandler(logging.Handler):
 
872
            def __init__(self, level, *args, **kwargs):
 
873
                logging.Handler.__init__(self, *args, **kwargs)
 
874
                self.watcher = self.LoggingWatcher([], [])
 
875
            def emit(self, record):
 
876
                self.watcher.records.append(record)
 
877
                self.watcher.output.append(self.format(record))
 
878
 
 
879
            LoggingWatcher = collections.namedtuple("LoggingWatcher",
 
880
                                                    ("records",
 
881
                                                     "output"))
 
882
 
 
883
 
 
884
class Test_string_to_delta(TestCaseWithAssertLogs):
 
885
    # Just test basic RFC 3339 functionality here, the doc string for
 
886
    # rfc3339_duration_to_delta() already has more comprehensive
 
887
    # tests, which is run by doctest.
 
888
 
 
889
    def test_rfc3339_zero_seconds(self):
 
890
        self.assertEqual(datetime.timedelta(),
 
891
                         string_to_delta("PT0S"))
 
892
 
 
893
    def test_rfc3339_zero_days(self):
 
894
        self.assertEqual(datetime.timedelta(), string_to_delta("P0D"))
 
895
 
 
896
    def test_rfc3339_one_second(self):
 
897
        self.assertEqual(datetime.timedelta(0, 1),
 
898
                         string_to_delta("PT1S"))
 
899
 
 
900
    def test_rfc3339_two_hours(self):
 
901
        self.assertEqual(datetime.timedelta(0, 7200),
 
902
                         string_to_delta("PT2H"))
835
903
 
836
904
    def test_falls_back_to_pre_1_6_1_with_warning(self):
837
 
        # assertLogs only exists in Python 3.4
838
 
        if hasattr(self, "assertLogs"):
839
 
            with self.assertLogs(log, logging.WARNING):
840
 
                value = string_to_delta("2h")
841
 
        else:
842
 
            class WarningFilter(logging.Filter):
843
 
                """Don't show, but record the presence of, warnings"""
844
 
                def filter(self, record):
845
 
                    is_warning = record.levelno >= logging.WARNING
846
 
                    self.found = is_warning or getattr(self, "found",
847
 
                                                       False)
848
 
                    return not is_warning
849
 
            warning_filter = WarningFilter()
850
 
            log.addFilter(warning_filter)
851
 
            try:
852
 
                value = string_to_delta("2h")
853
 
            finally:
854
 
                log.removeFilter(warning_filter)
855
 
            self.assertTrue(getattr(warning_filter, "found", False))
856
 
        self.assertEqual(value, datetime.timedelta(0, 7200))
 
905
        with self.assertLogs(log, logging.WARNING):
 
906
            value = string_to_delta("2h")
 
907
        self.assertEqual(datetime.timedelta(0, 7200), value)
857
908
 
858
909
 
859
910
class Test_check_option_syntax(unittest.TestCase):
897
948
    @contextlib.contextmanager
898
949
    def assertParseError(self):
899
950
        with self.assertRaises(SystemExit) as e:
900
 
            with self.temporarily_suppress_stderr():
 
951
            with self.redirect_stderr_to_devnull():
901
952
                yield
902
953
        # Exit code from argparse is guaranteed to be "2".  Reference:
903
954
        # https://docs.python.org/3/library
904
955
        # /argparse.html#exiting-methods
905
 
        self.assertEqual(e.exception.code, 2)
 
956
        self.assertEqual(2, e.exception.code)
906
957
 
907
958
    @staticmethod
908
959
    @contextlib.contextmanager
909
 
    def temporarily_suppress_stderr():
910
 
        null = os.open(os.path.devnull, os.O_RDWR)
911
 
        stderrcopy = os.dup(sys.stderr.fileno())
912
 
        os.dup2(null, sys.stderr.fileno())
913
 
        os.close(null)
914
 
        try:
915
 
            yield
916
 
        finally:
917
 
            # restore stderr
918
 
            os.dup2(stderrcopy, sys.stderr.fileno())
919
 
            os.close(stderrcopy)
 
960
    def redirect_stderr_to_devnull():
 
961
        old_stderr = sys.stderr
 
962
        with contextlib.closing(open(os.devnull, "w")) as null:
 
963
            sys.stderr = null
 
964
            try:
 
965
                yield
 
966
            finally:
 
967
                sys.stderr = old_stderr
920
968
 
921
969
    def check_option_syntax(self, options):
922
970
        check_option_syntax(self.parser, options)
923
971
 
924
 
    def test_actions_conflicts_with_verbose(self):
925
 
        for action, value in self.actions.items():
926
 
            options = self.parser.parse_args()
927
 
            setattr(options, action, value)
928
 
            options.verbose = True
 
972
    def test_actions_all_conflicts_with_verbose(self):
 
973
        for action, value in self.actions.items():
 
974
            options = self.parser.parse_args()
 
975
            setattr(options, action, value)
 
976
            options.all = True
 
977
            options.verbose = True
 
978
            with self.assertParseError():
 
979
                self.check_option_syntax(options)
 
980
 
 
981
    def test_actions_with_client_conflicts_with_verbose(self):
 
982
        for action, value in self.actions.items():
 
983
            options = self.parser.parse_args()
 
984
            setattr(options, action, value)
 
985
            options.verbose = True
 
986
            options.client = ["foo"]
929
987
            with self.assertParseError():
930
988
                self.check_option_syntax(options)
931
989
 
957
1015
            options.all = True
958
1016
            self.check_option_syntax(options)
959
1017
 
 
1018
    def test_any_action_is_ok_with_one_client(self):
 
1019
        for action, value in self.actions.items():
 
1020
            options = self.parser.parse_args()
 
1021
            setattr(options, action, value)
 
1022
            options.client = ["foo"]
 
1023
            self.check_option_syntax(options)
 
1024
 
 
1025
    def test_one_client_with_all_actions_except_is_enabled(self):
 
1026
        options = self.parser.parse_args()
 
1027
        for action, value in self.actions.items():
 
1028
            if action == "is_enabled":
 
1029
                continue
 
1030
            setattr(options, action, value)
 
1031
        options.client = ["foo"]
 
1032
        self.check_option_syntax(options)
 
1033
 
 
1034
    def test_two_clients_with_all_actions_except_is_enabled(self):
 
1035
        options = self.parser.parse_args()
 
1036
        for action, value in self.actions.items():
 
1037
            if action == "is_enabled":
 
1038
                continue
 
1039
            setattr(options, action, value)
 
1040
        options.client = ["foo", "barbar"]
 
1041
        self.check_option_syntax(options)
 
1042
 
 
1043
    def test_two_clients_are_ok_with_actions_except_is_enabled(self):
 
1044
        for action, value in self.actions.items():
 
1045
            if action == "is_enabled":
 
1046
                continue
 
1047
            options = self.parser.parse_args()
 
1048
            setattr(options, action, value)
 
1049
            options.client = ["foo", "barbar"]
 
1050
            self.check_option_syntax(options)
 
1051
 
960
1052
    def test_is_enabled_fails_without_client(self):
961
1053
        options = self.parser.parse_args()
962
1054
        options.is_enabled = True
963
1055
        with self.assertParseError():
964
1056
            self.check_option_syntax(options)
965
1057
 
966
 
    def test_is_enabled_works_with_one_client(self):
967
 
        options = self.parser.parse_args()
968
 
        options.is_enabled = True
969
 
        options.client = ["foo"]
970
 
        self.check_option_syntax(options)
971
 
 
972
1058
    def test_is_enabled_fails_with_two_clients(self):
973
1059
        options = self.parser.parse_args()
974
1060
        options.is_enabled = True
988
1074
                self.check_option_syntax(options)
989
1075
 
990
1076
 
991
 
class Test_SilenceLogger(unittest.TestCase):
992
 
    loggername = "mandos-ctl.Test_SilenceLogger"
993
 
    log = logging.getLogger(loggername)
994
 
    log.propagate = False
995
 
    log.addHandler(logging.NullHandler())
996
 
 
997
 
    def setUp(self):
998
 
        self.counting_filter = self.CountingFilter()
999
 
 
1000
 
    class CountingFilter(logging.Filter):
1001
 
        "Count number of records"
1002
 
        count = 0
1003
 
        def filter(self, record):
1004
 
            self.count += 1
1005
 
            return True
1006
 
 
1007
 
    def test_should_filter_records_only_when_active(self):
 
1077
class Test_get_mandos_dbus_object(TestCaseWithAssertLogs):
 
1078
    def test_calls_and_returns_get_object_on_bus(self):
 
1079
        class MockBus(object):
 
1080
            called = False
 
1081
            def get_object(mockbus_self, busname, dbus_path):
 
1082
                # Note that "self" is still the testcase instance,
 
1083
                # this MockBus instance is in "mockbus_self".
 
1084
                self.assertEqual(dbus_busname, busname)
 
1085
                self.assertEqual(server_dbus_path, dbus_path)
 
1086
                mockbus_self.called = True
 
1087
                return mockbus_self
 
1088
 
 
1089
        mockbus = get_mandos_dbus_object(bus=MockBus())
 
1090
        self.assertIsInstance(mockbus, MockBus)
 
1091
        self.assertTrue(mockbus.called)
 
1092
 
 
1093
    def test_logs_and_exits_on_dbus_error(self):
 
1094
        class MockBusFailing(object):
 
1095
            def get_object(self, busname, dbus_path):
 
1096
                raise dbus.exceptions.DBusException("Test")
 
1097
 
 
1098
        with self.assertLogs(log, logging.CRITICAL):
 
1099
            with self.assertRaises(SystemExit) as e:
 
1100
                bus = get_mandos_dbus_object(bus=MockBusFailing())
 
1101
 
 
1102
        if isinstance(e.exception.code, int):
 
1103
            self.assertNotEqual(0, e.exception.code)
 
1104
        else:
 
1105
            self.assertIsNotNone(e.exception.code)
 
1106
 
 
1107
 
 
1108
class Test_get_managed_objects(TestCaseWithAssertLogs):
 
1109
    def test_calls_and_returns_GetManagedObjects(self):
 
1110
        managed_objects = {"/clients/foo": { "Name": "foo"}}
 
1111
        class MockObjectManager(object):
 
1112
            def GetManagedObjects(self):
 
1113
                return managed_objects
 
1114
        retval = get_managed_objects(MockObjectManager())
 
1115
        self.assertDictEqual(managed_objects, retval)
 
1116
 
 
1117
    def test_logs_and_exits_on_dbus_error(self):
 
1118
        dbus_logger = logging.getLogger("dbus.proxies")
 
1119
 
 
1120
        class MockObjectManagerFailing(object):
 
1121
            def GetManagedObjects(self):
 
1122
                dbus_logger.error("Test")
 
1123
                raise dbus.exceptions.DBusException("Test")
 
1124
 
 
1125
        class CountingHandler(logging.Handler):
 
1126
            count = 0
 
1127
            def emit(self, record):
 
1128
                self.count += 1
 
1129
 
 
1130
        counting_handler = CountingHandler()
 
1131
 
 
1132
        dbus_logger.addHandler(counting_handler)
 
1133
 
1008
1134
        try:
1009
 
            with SilenceLogger(self.loggername):
1010
 
                self.log.addFilter(self.counting_filter)
1011
 
                self.log.info("Filtered log message 1")
1012
 
            self.log.info("Non-filtered message 2")
1013
 
            self.log.info("Non-filtered message 3")
 
1135
            with self.assertLogs(log, logging.CRITICAL) as watcher:
 
1136
                with self.assertRaises(SystemExit) as e:
 
1137
                    get_managed_objects(MockObjectManagerFailing())
1014
1138
        finally:
1015
 
            self.log.removeFilter(self.counting_filter)
1016
 
        self.assertEqual(self.counting_filter.count, 2)
 
1139
            dbus_logger.removeFilter(counting_handler)
 
1140
 
 
1141
        # Make sure the dbus logger was suppressed
 
1142
        self.assertEqual(0, counting_handler.count)
 
1143
 
 
1144
        # Test that the dbus_logger still works
 
1145
        with self.assertLogs(dbus_logger, logging.ERROR):
 
1146
            dbus_logger.error("Test")
 
1147
 
 
1148
        if isinstance(e.exception.code, int):
 
1149
            self.assertNotEqual(0, e.exception.code)
 
1150
        else:
 
1151
            self.assertIsNotNone(e.exception.code)
1017
1152
 
1018
1153
 
1019
1154
class Test_commands_from_options(unittest.TestCase):
1023
1158
 
1024
1159
    def test_is_enabled(self):
1025
1160
        self.assert_command_from_args(["--is-enabled", "foo"],
1026
 
                                      IsEnabledCmd)
 
1161
                                      command.IsEnabled)
1027
1162
 
1028
1163
    def assert_command_from_args(self, args, command_cls,
1029
1164
                                 **cmd_attrs):
1032
1167
        options = self.parser.parse_args(args)
1033
1168
        check_option_syntax(self.parser, options)
1034
1169
        commands = commands_from_options(options)
1035
 
        self.assertEqual(len(commands), 1)
 
1170
        self.assertEqual(1, len(commands))
1036
1171
        command = commands[0]
1037
1172
        self.assertIsInstance(command, command_cls)
1038
1173
        for key, value in cmd_attrs.items():
1039
 
            self.assertEqual(getattr(command, key), value)
 
1174
            self.assertEqual(value, getattr(command, key))
1040
1175
 
1041
1176
    def test_is_enabled_short(self):
1042
 
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
 
1177
        self.assert_command_from_args(["-V", "foo"],
 
1178
                                      command.IsEnabled)
1043
1179
 
1044
1180
    def test_approve(self):
1045
1181
        self.assert_command_from_args(["--approve", "foo"],
1046
 
                                      ApproveCmd)
 
1182
                                      command.Approve)
1047
1183
 
1048
1184
    def test_approve_short(self):
1049
 
        self.assert_command_from_args(["-A", "foo"], ApproveCmd)
 
1185
        self.assert_command_from_args(["-A", "foo"], command.Approve)
1050
1186
 
1051
1187
    def test_deny(self):
1052
 
        self.assert_command_from_args(["--deny", "foo"], DenyCmd)
 
1188
        self.assert_command_from_args(["--deny", "foo"], command.Deny)
1053
1189
 
1054
1190
    def test_deny_short(self):
1055
 
        self.assert_command_from_args(["-D", "foo"], DenyCmd)
 
1191
        self.assert_command_from_args(["-D", "foo"], command.Deny)
1056
1192
 
1057
1193
    def test_remove(self):
1058
1194
        self.assert_command_from_args(["--remove", "foo"],
1059
 
                                      RemoveCmd)
 
1195
                                      command.Remove)
1060
1196
 
1061
1197
    def test_deny_before_remove(self):
1062
1198
        options = self.parser.parse_args(["--deny", "--remove",
1063
1199
                                          "foo"])
1064
1200
        check_option_syntax(self.parser, options)
1065
1201
        commands = commands_from_options(options)
1066
 
        self.assertEqual(len(commands), 2)
1067
 
        self.assertIsInstance(commands[0], DenyCmd)
1068
 
        self.assertIsInstance(commands[1], RemoveCmd)
 
1202
        self.assertEqual(2, len(commands))
 
1203
        self.assertIsInstance(commands[0], command.Deny)
 
1204
        self.assertIsInstance(commands[1], command.Remove)
1069
1205
 
1070
1206
    def test_deny_before_remove_reversed(self):
1071
1207
        options = self.parser.parse_args(["--remove", "--deny",
1072
1208
                                          "--all"])
1073
1209
        check_option_syntax(self.parser, options)
1074
1210
        commands = commands_from_options(options)
1075
 
        self.assertEqual(len(commands), 2)
1076
 
        self.assertIsInstance(commands[0], DenyCmd)
1077
 
        self.assertIsInstance(commands[1], RemoveCmd)
 
1211
        self.assertEqual(2, len(commands))
 
1212
        self.assertIsInstance(commands[0], command.Deny)
 
1213
        self.assertIsInstance(commands[1], command.Remove)
1078
1214
 
1079
1215
    def test_remove_short(self):
1080
 
        self.assert_command_from_args(["-r", "foo"], RemoveCmd)
 
1216
        self.assert_command_from_args(["-r", "foo"], command.Remove)
1081
1217
 
1082
1218
    def test_dump_json(self):
1083
 
        self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
 
1219
        self.assert_command_from_args(["--dump-json"],
 
1220
                                      command.DumpJSON)
1084
1221
 
1085
1222
    def test_enable(self):
1086
 
        self.assert_command_from_args(["--enable", "foo"], EnableCmd)
 
1223
        self.assert_command_from_args(["--enable", "foo"],
 
1224
                                      command.Enable)
1087
1225
 
1088
1226
    def test_enable_short(self):
1089
 
        self.assert_command_from_args(["-e", "foo"], EnableCmd)
 
1227
        self.assert_command_from_args(["-e", "foo"], command.Enable)
1090
1228
 
1091
1229
    def test_disable(self):
1092
1230
        self.assert_command_from_args(["--disable", "foo"],
1093
 
                                      DisableCmd)
 
1231
                                      command.Disable)
1094
1232
 
1095
1233
    def test_disable_short(self):
1096
 
        self.assert_command_from_args(["-d", "foo"], DisableCmd)
 
1234
        self.assert_command_from_args(["-d", "foo"], command.Disable)
1097
1235
 
1098
1236
    def test_bump_timeout(self):
1099
1237
        self.assert_command_from_args(["--bump-timeout", "foo"],
1100
 
                                      BumpTimeoutCmd)
 
1238
                                      command.BumpTimeout)
1101
1239
 
1102
1240
    def test_bump_timeout_short(self):
1103
 
        self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
 
1241
        self.assert_command_from_args(["-b", "foo"],
 
1242
                                      command.BumpTimeout)
1104
1243
 
1105
1244
    def test_start_checker(self):
1106
1245
        self.assert_command_from_args(["--start-checker", "foo"],
1107
 
                                      StartCheckerCmd)
 
1246
                                      command.StartChecker)
1108
1247
 
1109
1248
    def test_stop_checker(self):
1110
1249
        self.assert_command_from_args(["--stop-checker", "foo"],
1111
 
                                      StopCheckerCmd)
 
1250
                                      command.StopChecker)
1112
1251
 
1113
1252
    def test_approve_by_default(self):
1114
1253
        self.assert_command_from_args(["--approve-by-default", "foo"],
1115
 
                                      ApproveByDefaultCmd)
 
1254
                                      command.ApproveByDefault)
1116
1255
 
1117
1256
    def test_deny_by_default(self):
1118
1257
        self.assert_command_from_args(["--deny-by-default", "foo"],
1119
 
                                      DenyByDefaultCmd)
 
1258
                                      command.DenyByDefault)
1120
1259
 
1121
1260
    def test_checker(self):
1122
1261
        self.assert_command_from_args(["--checker", ":", "foo"],
1123
 
                                      SetCheckerCmd, value_to_set=":")
 
1262
                                      command.SetChecker,
 
1263
                                      value_to_set=":")
1124
1264
 
1125
1265
    def test_checker_empty(self):
1126
1266
        self.assert_command_from_args(["--checker", "", "foo"],
1127
 
                                      SetCheckerCmd, value_to_set="")
 
1267
                                      command.SetChecker,
 
1268
                                      value_to_set="")
1128
1269
 
1129
1270
    def test_checker_short(self):
1130
1271
        self.assert_command_from_args(["-c", ":", "foo"],
1131
 
                                      SetCheckerCmd, value_to_set=":")
 
1272
                                      command.SetChecker,
 
1273
                                      value_to_set=":")
1132
1274
 
1133
1275
    def test_host(self):
1134
1276
        self.assert_command_from_args(["--host", "foo.example.org",
1135
 
                                       "foo"], SetHostCmd,
 
1277
                                       "foo"], command.SetHost,
1136
1278
                                      value_to_set="foo.example.org")
1137
1279
 
1138
1280
    def test_host_short(self):
1139
1281
        self.assert_command_from_args(["-H", "foo.example.org",
1140
 
                                       "foo"], SetHostCmd,
 
1282
                                       "foo"], command.SetHost,
1141
1283
                                      value_to_set="foo.example.org")
1142
1284
 
1143
1285
    def test_secret_devnull(self):
1144
1286
        self.assert_command_from_args(["--secret", os.path.devnull,
1145
 
                                       "foo"], SetSecretCmd,
 
1287
                                       "foo"], command.SetSecret,
1146
1288
                                      value_to_set=b"")
1147
1289
 
1148
1290
    def test_secret_tempfile(self):
1151
1293
            f.write(value)
1152
1294
            f.seek(0)
1153
1295
            self.assert_command_from_args(["--secret", f.name,
1154
 
                                           "foo"], SetSecretCmd,
 
1296
                                           "foo"], command.SetSecret,
1155
1297
                                          value_to_set=value)
1156
1298
 
1157
1299
    def test_secret_devnull_short(self):
1158
1300
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
1159
 
                                      SetSecretCmd, value_to_set=b"")
 
1301
                                      command.SetSecret,
 
1302
                                      value_to_set=b"")
1160
1303
 
1161
1304
    def test_secret_tempfile_short(self):
1162
1305
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
1164
1307
            f.write(value)
1165
1308
            f.seek(0)
1166
1309
            self.assert_command_from_args(["-s", f.name, "foo"],
1167
 
                                          SetSecretCmd,
 
1310
                                          command.SetSecret,
1168
1311
                                          value_to_set=value)
1169
1312
 
1170
1313
    def test_timeout(self):
1171
1314
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
1172
 
                                      SetTimeoutCmd,
 
1315
                                      command.SetTimeout,
1173
1316
                                      value_to_set=300000)
1174
1317
 
1175
1318
    def test_timeout_short(self):
1176
1319
        self.assert_command_from_args(["-t", "PT5M", "foo"],
1177
 
                                      SetTimeoutCmd,
 
1320
                                      command.SetTimeout,
1178
1321
                                      value_to_set=300000)
1179
1322
 
1180
1323
    def test_extended_timeout(self):
1181
1324
        self.assert_command_from_args(["--extended-timeout", "PT15M",
1182
1325
                                       "foo"],
1183
 
                                      SetExtendedTimeoutCmd,
 
1326
                                      command.SetExtendedTimeout,
1184
1327
                                      value_to_set=900000)
1185
1328
 
1186
1329
    def test_interval(self):
1187
1330
        self.assert_command_from_args(["--interval", "PT2M", "foo"],
1188
 
                                      SetIntervalCmd,
 
1331
                                      command.SetInterval,
1189
1332
                                      value_to_set=120000)
1190
1333
 
1191
1334
    def test_interval_short(self):
1192
1335
        self.assert_command_from_args(["-i", "PT2M", "foo"],
1193
 
                                      SetIntervalCmd,
 
1336
                                      command.SetInterval,
1194
1337
                                      value_to_set=120000)
1195
1338
 
1196
1339
    def test_approval_delay(self):
1197
1340
        self.assert_command_from_args(["--approval-delay", "PT30S",
1198
 
                                       "foo"], SetApprovalDelayCmd,
 
1341
                                       "foo"],
 
1342
                                      command.SetApprovalDelay,
1199
1343
                                      value_to_set=30000)
1200
1344
 
1201
1345
    def test_approval_duration(self):
1202
1346
        self.assert_command_from_args(["--approval-duration", "PT1S",
1203
 
                                       "foo"], SetApprovalDurationCmd,
 
1347
                                       "foo"],
 
1348
                                      command.SetApprovalDuration,
1204
1349
                                      value_to_set=1000)
1205
1350
 
1206
1351
    def test_print_table(self):
1207
 
        self.assert_command_from_args([], PrintTableCmd,
 
1352
        self.assert_command_from_args([], command.PrintTable,
1208
1353
                                      verbose=False)
1209
1354
 
1210
1355
    def test_print_table_verbose(self):
1211
 
        self.assert_command_from_args(["--verbose"], PrintTableCmd,
 
1356
        self.assert_command_from_args(["--verbose"],
 
1357
                                      command.PrintTable,
1212
1358
                                      verbose=True)
1213
1359
 
1214
1360
    def test_print_table_verbose_short(self):
1215
 
        self.assert_command_from_args(["-v"], PrintTableCmd,
 
1361
        self.assert_command_from_args(["-v"], command.PrintTable,
1216
1362
                                      verbose=True)
1217
1363
 
1218
1364
 
1219
 
class TestCmd(unittest.TestCase):
 
1365
class TestCommand(unittest.TestCase):
1220
1366
    """Abstract class for tests of command classes"""
1221
1367
 
1222
1368
    def setUp(self):
1228
1374
                self.attributes["Name"] = name
1229
1375
                self.calls = []
1230
1376
            def Set(self, interface, propname, value, dbus_interface):
1231
 
                testcase.assertEqual(interface, client_dbus_interface)
1232
 
                testcase.assertEqual(dbus_interface,
1233
 
                                     dbus.PROPERTIES_IFACE)
 
1377
                testcase.assertEqual(client_dbus_interface, interface)
 
1378
                testcase.assertEqual(dbus.PROPERTIES_IFACE,
 
1379
                                     dbus_interface)
1234
1380
                self.attributes[propname] = value
1235
 
            def Get(self, interface, propname, dbus_interface):
1236
 
                testcase.assertEqual(interface, client_dbus_interface)
1237
 
                testcase.assertEqual(dbus_interface,
1238
 
                                     dbus.PROPERTIES_IFACE)
1239
 
                return self.attributes[propname]
1240
1381
            def Approve(self, approve, dbus_interface):
1241
 
                testcase.assertEqual(dbus_interface,
1242
 
                                     client_dbus_interface)
 
1382
                testcase.assertEqual(client_dbus_interface,
 
1383
                                     dbus_interface)
1243
1384
                self.calls.append(("Approve", (approve,
1244
1385
                                               dbus_interface)))
1245
1386
        self.client = MockClient(
1302
1443
        class Bus(object):
1303
1444
            @staticmethod
1304
1445
            def get_object(client_bus_name, path):
1305
 
                self.assertEqual(client_bus_name, dbus_busname)
 
1446
                self.assertEqual(dbus_busname, client_bus_name)
1306
1447
                return {
1307
1448
                    # Note: "self" here is the TestCmd instance, not
1308
1449
                    # the Bus instance, since this is a static method!
1312
1453
        return Bus()
1313
1454
 
1314
1455
 
1315
 
class TestIsEnabledCmd(TestCmd):
1316
 
    def test_is_enabled(self):
1317
 
        self.assertTrue(all(IsEnabledCmd().is_enabled(client,
1318
 
                                                      properties)
1319
 
                            for client, properties
1320
 
                            in self.clients.items()))
 
1456
class TestBaseCommands(TestCommand):
1321
1457
 
1322
 
    def test_is_enabled_run_exits_successfully(self):
 
1458
    def test_IsEnabled_exits_successfully(self):
1323
1459
        with self.assertRaises(SystemExit) as e:
1324
 
            IsEnabledCmd().run(self.one_client)
 
1460
            command.IsEnabled().run(self.one_client)
1325
1461
        if e.exception.code is not None:
1326
 
            self.assertEqual(e.exception.code, 0)
 
1462
            self.assertEqual(0, e.exception.code)
1327
1463
        else:
1328
1464
            self.assertIsNone(e.exception.code)
1329
1465
 
1330
 
    def test_is_enabled_run_exits_with_failure(self):
 
1466
    def test_IsEnabled_exits_with_failure(self):
1331
1467
        self.client.attributes["Enabled"] = dbus.Boolean(False)
1332
1468
        with self.assertRaises(SystemExit) as e:
1333
 
            IsEnabledCmd().run(self.one_client)
 
1469
            command.IsEnabled().run(self.one_client)
1334
1470
        if isinstance(e.exception.code, int):
1335
 
            self.assertNotEqual(e.exception.code, 0)
 
1471
            self.assertNotEqual(0, e.exception.code)
1336
1472
        else:
1337
1473
            self.assertIsNotNone(e.exception.code)
1338
1474
 
1339
 
 
1340
 
class TestApproveCmd(TestCmd):
1341
 
    def test_approve(self):
1342
 
        ApproveCmd().run(self.clients, self.bus)
 
1475
    def test_Approve(self):
 
1476
        command.Approve().run(self.clients, self.bus)
1343
1477
        for clientpath in self.clients:
1344
1478
            client = self.bus.get_object(dbus_busname, clientpath)
1345
1479
            self.assertIn(("Approve", (True, client_dbus_interface)),
1346
1480
                          client.calls)
1347
1481
 
1348
 
 
1349
 
class TestDenyCmd(TestCmd):
1350
 
    def test_deny(self):
1351
 
        DenyCmd().run(self.clients, self.bus)
 
1482
    def test_Deny(self):
 
1483
        command.Deny().run(self.clients, self.bus)
1352
1484
        for clientpath in self.clients:
1353
1485
            client = self.bus.get_object(dbus_busname, clientpath)
1354
1486
            self.assertIn(("Approve", (False, client_dbus_interface)),
1355
1487
                          client.calls)
1356
1488
 
1357
 
 
1358
 
class TestRemoveCmd(TestCmd):
1359
 
    def test_remove(self):
 
1489
    def test_Remove(self):
1360
1490
        class MockMandos(object):
1361
1491
            def __init__(self):
1362
1492
                self.calls = []
1363
1493
            def RemoveClient(self, dbus_path):
1364
1494
                self.calls.append(("RemoveClient", (dbus_path,)))
1365
1495
        mandos = MockMandos()
1366
 
        super(TestRemoveCmd, self).setUp()
1367
 
        RemoveCmd().run(self.clients, self.bus, mandos)
1368
 
        self.assertEqual(len(mandos.calls), 2)
 
1496
        command.Remove().run(self.clients, self.bus, mandos)
1369
1497
        for clientpath in self.clients:
1370
1498
            self.assertIn(("RemoveClient", (clientpath,)),
1371
1499
                          mandos.calls)
1372
1500
 
1373
 
 
1374
 
class TestDumpJSONCmd(TestCmd):
1375
 
    def setUp(self):
1376
 
        self.expected_json = {
1377
 
            "foo": {
1378
 
                "Name": "foo",
1379
 
                "KeyID": ("92ed150794387c03ce684574b1139a65"
1380
 
                          "94a34f895daaaf09fd8ea90a27cddb12"),
1381
 
                "Host": "foo.example.org",
1382
 
                "Enabled": True,
1383
 
                "Timeout": 300000,
1384
 
                "LastCheckedOK": "2019-02-03T00:00:00",
1385
 
                "Created": "2019-01-02T00:00:00",
1386
 
                "Interval": 120000,
1387
 
                "Fingerprint": ("778827225BA7DE539C5A"
1388
 
                                "7CFA59CFF7CDBD9A5920"),
1389
 
                "CheckerRunning": False,
1390
 
                "LastEnabled": "2019-01-03T00:00:00",
1391
 
                "ApprovalPending": False,
1392
 
                "ApprovedByDefault": True,
1393
 
                "LastApprovalRequest": "",
1394
 
                "ApprovalDelay": 0,
1395
 
                "ApprovalDuration": 1000,
1396
 
                "Checker": "fping -q -- %(host)s",
1397
 
                "ExtendedTimeout": 900000,
1398
 
                "Expires": "2019-02-04T00:00:00",
1399
 
                "LastCheckerStatus": 0,
1400
 
            },
1401
 
            "barbar": {
1402
 
                "Name": "barbar",
1403
 
                "KeyID": ("0558568eedd67d622f5c83b35a115f79"
1404
 
                          "6ab612cff5ad227247e46c2b020f441c"),
1405
 
                "Host": "192.0.2.3",
1406
 
                "Enabled": True,
1407
 
                "Timeout": 300000,
1408
 
                "LastCheckedOK": "2019-02-04T00:00:00",
1409
 
                "Created": "2019-01-03T00:00:00",
1410
 
                "Interval": 120000,
1411
 
                "Fingerprint": ("3E393AEAEFB84C7E89E2"
1412
 
                                "F547B3A107558FCA3A27"),
1413
 
                "CheckerRunning": True,
1414
 
                "LastEnabled": "2019-01-04T00:00:00",
1415
 
                "ApprovalPending": False,
1416
 
                "ApprovedByDefault": False,
1417
 
                "LastApprovalRequest": "2019-01-03T00:00:00",
1418
 
                "ApprovalDelay": 30000,
1419
 
                "ApprovalDuration": 93785000,
1420
 
                "Checker": ":",
1421
 
                "ExtendedTimeout": 900000,
1422
 
                "Expires": "2019-02-05T00:00:00",
1423
 
                "LastCheckerStatus": -2,
1424
 
            },
1425
 
        }
1426
 
        return super(TestDumpJSONCmd, self).setUp()
1427
 
 
1428
 
    def test_normal(self):
1429
 
        output = DumpJSONCmd().output(self.clients.values())
1430
 
        json_data = json.loads(output)
1431
 
        self.assertDictEqual(json_data, self.expected_json)
1432
 
 
1433
 
    def test_one_client(self):
1434
 
        output = DumpJSONCmd().output(self.one_client.values())
1435
 
        json_data = json.loads(output)
 
1501
    expected_json = {
 
1502
        "foo": {
 
1503
            "Name": "foo",
 
1504
            "KeyID": ("92ed150794387c03ce684574b1139a65"
 
1505
                      "94a34f895daaaf09fd8ea90a27cddb12"),
 
1506
            "Host": "foo.example.org",
 
1507
            "Enabled": True,
 
1508
            "Timeout": 300000,
 
1509
            "LastCheckedOK": "2019-02-03T00:00:00",
 
1510
            "Created": "2019-01-02T00:00:00",
 
1511
            "Interval": 120000,
 
1512
            "Fingerprint": ("778827225BA7DE539C5A"
 
1513
                            "7CFA59CFF7CDBD9A5920"),
 
1514
            "CheckerRunning": False,
 
1515
            "LastEnabled": "2019-01-03T00:00:00",
 
1516
            "ApprovalPending": False,
 
1517
            "ApprovedByDefault": True,
 
1518
            "LastApprovalRequest": "",
 
1519
            "ApprovalDelay": 0,
 
1520
            "ApprovalDuration": 1000,
 
1521
            "Checker": "fping -q -- %(host)s",
 
1522
            "ExtendedTimeout": 900000,
 
1523
            "Expires": "2019-02-04T00:00:00",
 
1524
            "LastCheckerStatus": 0,
 
1525
        },
 
1526
        "barbar": {
 
1527
            "Name": "barbar",
 
1528
            "KeyID": ("0558568eedd67d622f5c83b35a115f79"
 
1529
                      "6ab612cff5ad227247e46c2b020f441c"),
 
1530
            "Host": "192.0.2.3",
 
1531
            "Enabled": True,
 
1532
            "Timeout": 300000,
 
1533
            "LastCheckedOK": "2019-02-04T00:00:00",
 
1534
            "Created": "2019-01-03T00:00:00",
 
1535
            "Interval": 120000,
 
1536
            "Fingerprint": ("3E393AEAEFB84C7E89E2"
 
1537
                            "F547B3A107558FCA3A27"),
 
1538
            "CheckerRunning": True,
 
1539
            "LastEnabled": "2019-01-04T00:00:00",
 
1540
            "ApprovalPending": False,
 
1541
            "ApprovedByDefault": False,
 
1542
            "LastApprovalRequest": "2019-01-03T00:00:00",
 
1543
            "ApprovalDelay": 30000,
 
1544
            "ApprovalDuration": 93785000,
 
1545
            "Checker": ":",
 
1546
            "ExtendedTimeout": 900000,
 
1547
            "Expires": "2019-02-05T00:00:00",
 
1548
            "LastCheckerStatus": -2,
 
1549
        },
 
1550
    }
 
1551
 
 
1552
    def test_DumpJSON_normal(self):
 
1553
        with self.capture_stdout_to_buffer() as buffer:
 
1554
            command.DumpJSON().run(self.clients)
 
1555
        json_data = json.loads(buffer.getvalue())
 
1556
        self.assertDictEqual(self.expected_json, json_data)
 
1557
 
 
1558
    @staticmethod
 
1559
    @contextlib.contextmanager
 
1560
    def capture_stdout_to_buffer():
 
1561
        capture_buffer = io.StringIO()
 
1562
        old_stdout = sys.stdout
 
1563
        sys.stdout = capture_buffer
 
1564
        try:
 
1565
            yield capture_buffer
 
1566
        finally:
 
1567
            sys.stdout = old_stdout
 
1568
 
 
1569
    def test_DumpJSON_one_client(self):
 
1570
        with self.capture_stdout_to_buffer() as buffer:
 
1571
            command.DumpJSON().run(self.one_client)
 
1572
        json_data = json.loads(buffer.getvalue())
1436
1573
        expected_json = {"foo": self.expected_json["foo"]}
1437
 
        self.assertDictEqual(json_data, expected_json)
1438
 
 
1439
 
 
1440
 
class TestPrintTableCmd(TestCmd):
1441
 
    def test_normal(self):
1442
 
        output = PrintTableCmd().output(self.clients.values())
 
1574
        self.assertDictEqual(expected_json, json_data)
 
1575
 
 
1576
    def test_PrintTable_normal(self):
 
1577
        with self.capture_stdout_to_buffer() as buffer:
 
1578
            command.PrintTable().run(self.clients)
1443
1579
        expected_output = "\n".join((
1444
1580
            "Name   Enabled Timeout  Last Successful Check",
1445
1581
            "foo    Yes     00:05:00 2019-02-03T00:00:00  ",
1446
1582
            "barbar Yes     00:05:00 2019-02-04T00:00:00  ",
1447
 
        ))
1448
 
        self.assertEqual(output, expected_output)
 
1583
        )) + "\n"
 
1584
        self.assertEqual(expected_output, buffer.getvalue())
1449
1585
 
1450
 
    def test_verbose(self):
1451
 
        output = PrintTableCmd(verbose=True).output(
1452
 
            self.clients.values())
 
1586
    def test_PrintTable_verbose(self):
 
1587
        with self.capture_stdout_to_buffer() as buffer:
 
1588
            command.PrintTable(verbose=True).run(self.clients)
1453
1589
        columns = (
1454
1590
            (
1455
1591
                "Name   ",
1537
1673
            )
1538
1674
        )
1539
1675
        num_lines = max(len(rows) for rows in columns)
1540
 
        expected_output = "\n".join("".join(rows[line]
1541
 
                                            for rows in columns)
1542
 
                                    for line in range(num_lines))
1543
 
        self.assertEqual(output, expected_output)
 
1676
        expected_output = ("\n".join("".join(rows[line]
 
1677
                                             for rows in columns)
 
1678
                                     for line in range(num_lines))
 
1679
                           + "\n")
 
1680
        self.assertEqual(expected_output, buffer.getvalue())
1544
1681
 
1545
 
    def test_one_client(self):
1546
 
        output = PrintTableCmd().output(self.one_client.values())
 
1682
    def test_PrintTable_one_client(self):
 
1683
        with self.capture_stdout_to_buffer() as buffer:
 
1684
            command.PrintTable().run(self.one_client)
1547
1685
        expected_output = "\n".join((
1548
1686
            "Name Enabled Timeout  Last Successful Check",
1549
1687
            "foo  Yes     00:05:00 2019-02-03T00:00:00  ",
1550
 
        ))
1551
 
        self.assertEqual(output, expected_output)
1552
 
 
1553
 
 
1554
 
class TestPropertyCmd(TestCmd):
1555
 
    """Abstract class for tests of PropertyCmd classes"""
 
1688
        )) + "\n"
 
1689
        self.assertEqual(expected_output, buffer.getvalue())
 
1690
 
 
1691
 
 
1692
class TestPropertyCmd(TestCommand):
 
1693
    """Abstract class for tests of command.Property classes"""
1556
1694
    def runTest(self):
1557
1695
        if not hasattr(self, "command"):
1558
1696
            return
1563
1701
            for clientpath in self.clients:
1564
1702
                client = self.bus.get_object(dbus_busname, clientpath)
1565
1703
                old_value = client.attributes[self.propname]
1566
 
                self.assertNotIsInstance(old_value, self.Unique)
1567
1704
                client.attributes[self.propname] = self.Unique()
1568
1705
            self.run_command(value_to_set, self.clients)
1569
1706
            for clientpath in self.clients:
1570
1707
                client = self.bus.get_object(dbus_busname, clientpath)
1571
1708
                value = client.attributes[self.propname]
1572
1709
                self.assertNotIsInstance(value, self.Unique)
1573
 
                self.assertEqual(value, value_to_get)
 
1710
                self.assertEqual(value_to_get, value)
1574
1711
 
1575
1712
    class Unique(object):
1576
1713
        """Class for objects which exist only to be unique objects,
1581
1718
 
1582
1719
 
1583
1720
class TestEnableCmd(TestPropertyCmd):
1584
 
    command = EnableCmd
 
1721
    command = command.Enable
1585
1722
    propname = "Enabled"
1586
1723
    values_to_set = [dbus.Boolean(True)]
1587
1724
 
1588
1725
 
1589
1726
class TestDisableCmd(TestPropertyCmd):
1590
 
    command = DisableCmd
 
1727
    command = command.Disable
1591
1728
    propname = "Enabled"
1592
1729
    values_to_set = [dbus.Boolean(False)]
1593
1730
 
1594
1731
 
1595
1732
class TestBumpTimeoutCmd(TestPropertyCmd):
1596
 
    command = BumpTimeoutCmd
 
1733
    command = command.BumpTimeout
1597
1734
    propname = "LastCheckedOK"
1598
1735
    values_to_set = [""]
1599
1736
 
1600
1737
 
1601
1738
class TestStartCheckerCmd(TestPropertyCmd):
1602
 
    command = StartCheckerCmd
 
1739
    command = command.StartChecker
1603
1740
    propname = "CheckerRunning"
1604
1741
    values_to_set = [dbus.Boolean(True)]
1605
1742
 
1606
1743
 
1607
1744
class TestStopCheckerCmd(TestPropertyCmd):
1608
 
    command = StopCheckerCmd
 
1745
    command = command.StopChecker
1609
1746
    propname = "CheckerRunning"
1610
1747
    values_to_set = [dbus.Boolean(False)]
1611
1748
 
1612
1749
 
1613
1750
class TestApproveByDefaultCmd(TestPropertyCmd):
1614
 
    command = ApproveByDefaultCmd
 
1751
    command = command.ApproveByDefault
1615
1752
    propname = "ApprovedByDefault"
1616
1753
    values_to_set = [dbus.Boolean(True)]
1617
1754
 
1618
1755
 
1619
1756
class TestDenyByDefaultCmd(TestPropertyCmd):
1620
 
    command = DenyByDefaultCmd
 
1757
    command = command.DenyByDefault
1621
1758
    propname = "ApprovedByDefault"
1622
1759
    values_to_set = [dbus.Boolean(False)]
1623
1760
 
1635
1772
 
1636
1773
 
1637
1774
class TestSetCheckerCmd(TestPropertyValueCmd):
1638
 
    command = SetCheckerCmd
 
1775
    command = command.SetChecker
1639
1776
    propname = "Checker"
1640
1777
    values_to_set = ["", ":", "fping -q -- %s"]
1641
1778
 
1642
1779
 
1643
1780
class TestSetHostCmd(TestPropertyValueCmd):
1644
 
    command = SetHostCmd
 
1781
    command = command.SetHost
1645
1782
    propname = "Host"
1646
1783
    values_to_set = ["192.0.2.3", "foo.example.org"]
1647
1784
 
1648
1785
 
1649
1786
class TestSetSecretCmd(TestPropertyValueCmd):
1650
 
    command = SetSecretCmd
 
1787
    command = command.SetSecret
1651
1788
    propname = "Secret"
1652
1789
    values_to_set = [io.BytesIO(b""),
1653
1790
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1655
1792
 
1656
1793
 
1657
1794
class TestSetTimeoutCmd(TestPropertyValueCmd):
1658
 
    command = SetTimeoutCmd
 
1795
    command = command.SetTimeout
1659
1796
    propname = "Timeout"
1660
1797
    values_to_set = [datetime.timedelta(),
1661
1798
                     datetime.timedelta(minutes=5),
1666
1803
 
1667
1804
 
1668
1805
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1669
 
    command = SetExtendedTimeoutCmd
 
1806
    command = command.SetExtendedTimeout
1670
1807
    propname = "ExtendedTimeout"
1671
1808
    values_to_set = [datetime.timedelta(),
1672
1809
                     datetime.timedelta(minutes=5),
1677
1814
 
1678
1815
 
1679
1816
class TestSetIntervalCmd(TestPropertyValueCmd):
1680
 
    command = SetIntervalCmd
 
1817
    command = command.SetInterval
1681
1818
    propname = "Interval"
1682
1819
    values_to_set = [datetime.timedelta(),
1683
1820
                     datetime.timedelta(minutes=5),
1688
1825
 
1689
1826
 
1690
1827
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1691
 
    command = SetApprovalDelayCmd
 
1828
    command = command.SetApprovalDelay
1692
1829
    propname = "ApprovalDelay"
1693
1830
    values_to_set = [datetime.timedelta(),
1694
1831
                     datetime.timedelta(minutes=5),
1699
1836
 
1700
1837
 
1701
1838
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1702
 
    command = SetApprovalDurationCmd
 
1839
    command = command.SetApprovalDuration
1703
1840
    propname = "ApprovalDuration"
1704
1841
    values_to_set = [datetime.timedelta(),
1705
1842
                     datetime.timedelta(minutes=5),