/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-15 21:59:44 UTC
  • Revision ID: teddy@recompile.se-20190315215944-lomtn36y7o3jphp8
mandos-ctl: Refactor

* mandos-ctl (main): Call get_mandos_dbus_object() to get
                     "mandos_dbus_objc", and rename it to
                     "mandos_dbus_object".
  (get_mandos_dbus_object): New.
  (Test_get_mandos_dbus_object): - '' -

Show diffs side-by-side

added added

removed removed

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