/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos-ctl

  • Committer: Teddy Hogeborn
  • Date: 2019-03-16 00:10:31 UTC
  • mto: This revision was merged to the branch mainline in revision 382.
  • Revision ID: teddy@recompile.se-20190316001031-c5v8it0q3qbvpskx
mandos-ctl: Refactor

* mandos-ctl (main): Call get_managed_objects() to get all client
                     paths and properties.
  (get_managed_objects): New.
  (Test_get_managed_objects): - '' -

Show diffs side-by-side

added added

removed removed

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