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