/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos-ctl

  • Committer: Teddy Hogeborn
  • Date: 2019-03-17 10:59:24 UTC
  • Revision ID: teddy@recompile.se-20190317105924-3o9xb4pl8tld3rnp
mandos-ctl: Refactor

* mandos-ctl: Move all command classes into a class acting as a
              namespace.  Remove "Cmd" suffix from command class
              names.  All users of commands changed.  Also unify all
              tests of base commands into one test class.
  (command): New.
  (TestBaseCommands): New.
  (TestIsEnableCmd, TestApproveCmd, TestDenyCmd, TestRemoveCmd,
  TestDumpJSONCmd, TestPrintTableCmd): Remove; move tests into
                                       TestBaseCommands.

Show diffs side-by-side

added added

removed removed

Lines of Context:
477
477
    commands = []
478
478
 
479
479
    if options.is_enabled:
480
 
        commands.append(IsEnabledCmd())
 
480
        commands.append(command.IsEnabled())
481
481
 
482
482
    if options.approve:
483
 
        commands.append(ApproveCmd())
 
483
        commands.append(command.Approve())
484
484
 
485
485
    if options.deny:
486
 
        commands.append(DenyCmd())
 
486
        commands.append(command.Deny())
487
487
 
488
488
    if options.remove:
489
 
        commands.append(RemoveCmd())
 
489
        commands.append(command.Remove())
490
490
 
491
491
    if options.dump_json:
492
 
        commands.append(DumpJSONCmd())
 
492
        commands.append(command.DumpJSON())
493
493
 
494
494
    if options.enable:
495
 
        commands.append(EnableCmd())
 
495
        commands.append(command.Enable())
496
496
 
497
497
    if options.disable:
498
 
        commands.append(DisableCmd())
 
498
        commands.append(command.Disable())
499
499
 
500
500
    if options.bump_timeout:
501
 
        commands.append(BumpTimeoutCmd())
 
501
        commands.append(command.BumpTimeout())
502
502
 
503
503
    if options.start_checker:
504
 
        commands.append(StartCheckerCmd())
 
504
        commands.append(command.StartChecker())
505
505
 
506
506
    if options.stop_checker:
507
 
        commands.append(StopCheckerCmd())
 
507
        commands.append(command.StopChecker())
508
508
 
509
509
    if options.approved_by_default is not None:
510
510
        if options.approved_by_default:
511
 
            commands.append(ApproveByDefaultCmd())
 
511
            commands.append(command.ApproveByDefault())
512
512
        else:
513
 
            commands.append(DenyByDefaultCmd())
 
513
            commands.append(command.DenyByDefault())
514
514
 
515
515
    if options.checker is not None:
516
 
        commands.append(SetCheckerCmd(options.checker))
 
516
        commands.append(command.SetChecker(options.checker))
517
517
 
518
518
    if options.host is not None:
519
 
        commands.append(SetHostCmd(options.host))
 
519
        commands.append(command.SetHost(options.host))
520
520
 
521
521
    if options.secret is not None:
522
 
        commands.append(SetSecretCmd(options.secret))
 
522
        commands.append(command.SetSecret(options.secret))
523
523
 
524
524
    if options.timeout is not None:
525
 
        commands.append(SetTimeoutCmd(options.timeout))
 
525
        commands.append(command.SetTimeout(options.timeout))
526
526
 
527
527
    if options.extended_timeout:
528
528
        commands.append(
529
 
            SetExtendedTimeoutCmd(options.extended_timeout))
 
529
            command.SetExtendedTimeout(options.extended_timeout))
530
530
 
531
531
    if options.interval is not None:
532
 
        commands.append(SetIntervalCmd(options.interval))
 
532
        commands.append(command.SetInterval(options.interval))
533
533
 
534
534
    if options.approval_delay is not None:
535
 
        commands.append(SetApprovalDelayCmd(options.approval_delay))
 
535
        commands.append(
 
536
            command.SetApprovalDelay(options.approval_delay))
536
537
 
537
538
    if options.approval_duration is not None:
538
539
        commands.append(
539
 
            SetApprovalDurationCmd(options.approval_duration))
 
540
            command.SetApprovalDuration(options.approval_duration))
540
541
 
541
542
    # If no command option has been given, show table of clients,
542
543
    # optionally verbosely
543
544
    if not commands:
544
 
        commands.append(PrintTableCmd(verbose=options.verbose))
 
545
        commands.append(command.PrintTable(verbose=options.verbose))
545
546
 
546
547
    return commands
547
548
 
548
549
 
549
 
class Command(object):
550
 
    """Abstract class for commands"""
551
 
    def run(self, clients, bus=None, mandos=None):
552
 
        """Normal commands should implement run_on_one_client(), but
553
 
        commands which want to operate on all clients at the same time
554
 
        can override this run() method instead."""
555
 
        self.mandos = mandos
556
 
        for clientpath, properties in clients.items():
557
 
            log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
558
 
                      dbus_busname, str(clientpath))
559
 
            client = bus.get_object(dbus_busname, clientpath)
560
 
            self.run_on_one_client(client, properties)
561
 
 
562
 
 
563
 
class IsEnabledCmd(Command):
564
 
    def run(self, clients, bus=None, mandos=None):
565
 
        client, properties = next(iter(clients.items()))
566
 
        if self.is_enabled(client, properties):
567
 
            sys.exit(0)
568
 
        sys.exit(1)
569
 
    def is_enabled(self, client, properties):
570
 
        return properties["Enabled"]
571
 
 
572
 
 
573
 
class ApproveCmd(Command):
574
 
    def run_on_one_client(self, client, properties):
575
 
        log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
576
 
                  client.__dbus_object_path__, client_dbus_interface)
577
 
        client.Approve(dbus.Boolean(True),
578
 
                       dbus_interface=client_dbus_interface)
579
 
 
580
 
 
581
 
class DenyCmd(Command):
582
 
    def run_on_one_client(self, client, properties):
583
 
        log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
584
 
                  client.__dbus_object_path__, client_dbus_interface)
585
 
        client.Approve(dbus.Boolean(False),
586
 
                       dbus_interface=client_dbus_interface)
587
 
 
588
 
 
589
 
class RemoveCmd(Command):
590
 
    def run_on_one_client(self, client, properties):
591
 
        log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", dbus_busname,
592
 
                  server_dbus_path, server_dbus_interface,
593
 
                  str(client.__dbus_object_path__))
594
 
        self.mandos.RemoveClient(client.__dbus_object_path__)
595
 
 
596
 
 
597
 
class OutputCmd(Command):
598
 
    """Abstract class for commands outputting client details"""
599
 
    all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
600
 
                    "Created", "Interval", "Host", "KeyID",
601
 
                    "Fingerprint", "CheckerRunning", "LastEnabled",
602
 
                    "ApprovalPending", "ApprovedByDefault",
603
 
                    "LastApprovalRequest", "ApprovalDelay",
604
 
                    "ApprovalDuration", "Checker", "ExtendedTimeout",
605
 
                    "Expires", "LastCheckerStatus")
606
 
 
607
 
    def run(self, clients, bus=None, mandos=None):
608
 
        print(self.output(clients.values()))
609
 
 
610
 
    def output(self, clients):
611
 
        raise NotImplementedError()
612
 
 
613
 
 
614
 
class DumpJSONCmd(OutputCmd):
615
 
    def output(self, clients):
616
 
        data = {client["Name"]:
617
 
                {key: self.dbus_boolean_to_bool(client[key])
618
 
                 for key in self.all_keywords}
619
 
                for client in clients}
620
 
        return json.dumps(data, indent=4, separators=(',', ': '))
621
 
 
622
 
    @staticmethod
623
 
    def dbus_boolean_to_bool(value):
624
 
        if isinstance(value, dbus.Boolean):
625
 
            value = bool(value)
626
 
        return value
627
 
 
628
 
 
629
 
class PrintTableCmd(OutputCmd):
630
 
    def __init__(self, verbose=False):
631
 
        self.verbose = verbose
632
 
 
633
 
    def output(self, clients):
634
 
        default_keywords = ("Name", "Enabled", "Timeout",
635
 
                            "LastCheckedOK")
636
 
        keywords = default_keywords
637
 
        if self.verbose:
638
 
            keywords = self.all_keywords
639
 
        return str(self.TableOfClients(clients, keywords))
640
 
 
641
 
    class TableOfClients(object):
642
 
        tableheaders = {
643
 
            "Name": "Name",
644
 
            "Enabled": "Enabled",
645
 
            "Timeout": "Timeout",
646
 
            "LastCheckedOK": "Last Successful Check",
647
 
            "LastApprovalRequest": "Last Approval Request",
648
 
            "Created": "Created",
649
 
            "Interval": "Interval",
650
 
            "Host": "Host",
651
 
            "Fingerprint": "Fingerprint",
652
 
            "KeyID": "Key ID",
653
 
            "CheckerRunning": "Check Is Running",
654
 
            "LastEnabled": "Last Enabled",
655
 
            "ApprovalPending": "Approval Is Pending",
656
 
            "ApprovedByDefault": "Approved By Default",
657
 
            "ApprovalDelay": "Approval Delay",
658
 
            "ApprovalDuration": "Approval Duration",
659
 
            "Checker": "Checker",
660
 
            "ExtendedTimeout": "Extended Timeout",
661
 
            "Expires": "Expires",
662
 
            "LastCheckerStatus": "Last Checker Status",
663
 
        }
664
 
 
665
 
        def __init__(self, clients, keywords):
666
 
            self.clients = clients
667
 
            self.keywords = keywords
668
 
 
669
 
        def __str__(self):
670
 
            return "\n".join(self.rows())
671
 
 
672
 
        if sys.version_info.major == 2:
673
 
            __unicode__ = __str__
 
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=(',', ': '))
 
630
 
 
631
        @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
 
674
678
            def __str__(self):
675
 
                return str(self).encode(locale.getpreferredencoding())
676
 
 
677
 
        def rows(self):
678
 
            format_string = self.row_formatting_string()
679
 
            rows = [self.header_line(format_string)]
680
 
            rows.extend(self.client_line(client, format_string)
681
 
                        for client in self.clients)
682
 
            return rows
683
 
 
684
 
        def row_formatting_string(self):
685
 
            "Format string used to format table rows"
686
 
            return " ".join("{{{key}:{width}}}".format(
687
 
                width=max(len(self.tableheaders[key]),
688
 
                          *(len(self.string_from_client(client, key))
689
 
                            for client in self.clients)),
690
 
                key=key)
691
 
                            for key in self.keywords)
692
 
 
693
 
        def string_from_client(self, client, key):
694
 
            return self.valuetostring(client[key], key)
695
 
 
696
 
        @classmethod
697
 
        def valuetostring(cls, value, keyword):
698
 
            if isinstance(value, dbus.Boolean):
699
 
                return "Yes" if value else "No"
700
 
            if keyword in ("Timeout", "Interval", "ApprovalDelay",
701
 
                           "ApprovalDuration", "ExtendedTimeout"):
702
 
                return cls.milliseconds_to_string(value)
703
 
            return str(value)
704
 
 
705
 
        def header_line(self, format_string):
706
 
            return format_string.format(**self.tableheaders)
707
 
 
708
 
        def client_line(self, client, format_string):
709
 
            return format_string.format(
710
 
                **{key: self.string_from_client(client, key)
711
 
                   for key in self.keywords})
712
 
 
713
 
        @staticmethod
714
 
        def milliseconds_to_string(ms):
715
 
            td = datetime.timedelta(0, 0, 0, ms)
716
 
            return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
717
 
                    .format(days="{}T".format(td.days)
718
 
                            if td.days else "",
719
 
                            hours=td.seconds // 3600,
720
 
                            minutes=(td.seconds % 3600) // 60,
721
 
                            seconds=td.seconds % 60))
722
 
 
723
 
 
724
 
class PropertyCmd(Command):
725
 
    """Abstract class for Actions for setting one client property"""
726
 
 
727
 
    def run_on_one_client(self, client, properties):
728
 
        """Set the Client's D-Bus property"""
729
 
        log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
730
 
                  client.__dbus_object_path__,
731
 
                  dbus.PROPERTIES_IFACE, client_dbus_interface,
732
 
                  self.propname, self.value_to_set
733
 
                  if not isinstance(self.value_to_set, dbus.Boolean)
734
 
                  else bool(self.value_to_set))
735
 
        client.Set(client_dbus_interface, self.propname,
736
 
                   self.value_to_set,
737
 
                   dbus_interface=dbus.PROPERTIES_IFACE)
738
 
 
739
 
    @property
740
 
    def propname(self):
741
 
        raise NotImplementedError()
742
 
 
743
 
 
744
 
class EnableCmd(PropertyCmd):
745
 
    propname = "Enabled"
746
 
    value_to_set = dbus.Boolean(True)
747
 
 
748
 
 
749
 
class DisableCmd(PropertyCmd):
750
 
    propname = "Enabled"
751
 
    value_to_set = dbus.Boolean(False)
752
 
 
753
 
 
754
 
class BumpTimeoutCmd(PropertyCmd):
755
 
    propname = "LastCheckedOK"
756
 
    value_to_set = ""
757
 
 
758
 
 
759
 
class StartCheckerCmd(PropertyCmd):
760
 
    propname = "CheckerRunning"
761
 
    value_to_set = dbus.Boolean(True)
762
 
 
763
 
 
764
 
class StopCheckerCmd(PropertyCmd):
765
 
    propname = "CheckerRunning"
766
 
    value_to_set = dbus.Boolean(False)
767
 
 
768
 
 
769
 
class ApproveByDefaultCmd(PropertyCmd):
770
 
    propname = "ApprovedByDefault"
771
 
    value_to_set = dbus.Boolean(True)
772
 
 
773
 
 
774
 
class DenyByDefaultCmd(PropertyCmd):
775
 
    propname = "ApprovedByDefault"
776
 
    value_to_set = dbus.Boolean(False)
777
 
 
778
 
 
779
 
class PropertyValueCmd(PropertyCmd):
780
 
    """Abstract class for PropertyCmd recieving a value as argument"""
781
 
    def __init__(self, value):
782
 
        self.value_to_set = value
783
 
 
784
 
 
785
 
class SetCheckerCmd(PropertyValueCmd):
786
 
    propname = "Checker"
787
 
 
788
 
 
789
 
class SetHostCmd(PropertyValueCmd):
790
 
    propname = "Host"
791
 
 
792
 
 
793
 
class SetSecretCmd(PropertyValueCmd):
794
 
    propname = "Secret"
795
 
 
796
 
    @property
797
 
    def value_to_set(self):
798
 
        return self._vts
799
 
 
800
 
    @value_to_set.setter
801
 
    def value_to_set(self, value):
802
 
        """When setting, read data from supplied file object"""
803
 
        self._vts = value.read()
804
 
        value.close()
805
 
 
806
 
 
807
 
class MillisecondsPropertyValueArgumentCmd(PropertyValueCmd):
808
 
    """Abstract class for PropertyValueCmd taking a value argument as
 
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
809
821
a datetime.timedelta() but should store it as milliseconds."""
810
822
 
811
 
    @property
812
 
    def value_to_set(self):
813
 
        return self._vts
814
 
 
815
 
    @value_to_set.setter
816
 
    def value_to_set(self, value):
817
 
        """When setting, convert value from a datetime.timedelta"""
818
 
        self._vts = int(round(value.total_seconds() * 1000))
819
 
 
820
 
 
821
 
class SetTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
822
 
    propname = "Timeout"
823
 
 
824
 
 
825
 
class SetExtendedTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
826
 
    propname = "ExtendedTimeout"
827
 
 
828
 
 
829
 
class SetIntervalCmd(MillisecondsPropertyValueArgumentCmd):
830
 
    propname = "Interval"
831
 
 
832
 
 
833
 
class SetApprovalDelayCmd(MillisecondsPropertyValueArgumentCmd):
834
 
    propname = "ApprovalDelay"
835
 
 
836
 
 
837
 
class SetApprovalDurationCmd(MillisecondsPropertyValueArgumentCmd):
838
 
    propname = "ApprovalDuration"
 
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"
839
851
 
840
852
 
841
853
 
1144
1156
 
1145
1157
    def test_is_enabled(self):
1146
1158
        self.assert_command_from_args(["--is-enabled", "foo"],
1147
 
                                      IsEnabledCmd)
 
1159
                                      command.IsEnabled)
1148
1160
 
1149
1161
    def assert_command_from_args(self, args, command_cls,
1150
1162
                                 **cmd_attrs):
1160
1172
            self.assertEqual(getattr(command, key), value)
1161
1173
 
1162
1174
    def test_is_enabled_short(self):
1163
 
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
 
1175
        self.assert_command_from_args(["-V", "foo"],
 
1176
                                      command.IsEnabled)
1164
1177
 
1165
1178
    def test_approve(self):
1166
1179
        self.assert_command_from_args(["--approve", "foo"],
1167
 
                                      ApproveCmd)
 
1180
                                      command.Approve)
1168
1181
 
1169
1182
    def test_approve_short(self):
1170
 
        self.assert_command_from_args(["-A", "foo"], ApproveCmd)
 
1183
        self.assert_command_from_args(["-A", "foo"], command.Approve)
1171
1184
 
1172
1185
    def test_deny(self):
1173
 
        self.assert_command_from_args(["--deny", "foo"], DenyCmd)
 
1186
        self.assert_command_from_args(["--deny", "foo"], command.Deny)
1174
1187
 
1175
1188
    def test_deny_short(self):
1176
 
        self.assert_command_from_args(["-D", "foo"], DenyCmd)
 
1189
        self.assert_command_from_args(["-D", "foo"], command.Deny)
1177
1190
 
1178
1191
    def test_remove(self):
1179
1192
        self.assert_command_from_args(["--remove", "foo"],
1180
 
                                      RemoveCmd)
 
1193
                                      command.Remove)
1181
1194
 
1182
1195
    def test_deny_before_remove(self):
1183
1196
        options = self.parser.parse_args(["--deny", "--remove",
1185
1198
        check_option_syntax(self.parser, options)
1186
1199
        commands = commands_from_options(options)
1187
1200
        self.assertEqual(len(commands), 2)
1188
 
        self.assertIsInstance(commands[0], DenyCmd)
1189
 
        self.assertIsInstance(commands[1], RemoveCmd)
 
1201
        self.assertIsInstance(commands[0], command.Deny)
 
1202
        self.assertIsInstance(commands[1], command.Remove)
1190
1203
 
1191
1204
    def test_deny_before_remove_reversed(self):
1192
1205
        options = self.parser.parse_args(["--remove", "--deny",
1194
1207
        check_option_syntax(self.parser, options)
1195
1208
        commands = commands_from_options(options)
1196
1209
        self.assertEqual(len(commands), 2)
1197
 
        self.assertIsInstance(commands[0], DenyCmd)
1198
 
        self.assertIsInstance(commands[1], RemoveCmd)
 
1210
        self.assertIsInstance(commands[0], command.Deny)
 
1211
        self.assertIsInstance(commands[1], command.Remove)
1199
1212
 
1200
1213
    def test_remove_short(self):
1201
 
        self.assert_command_from_args(["-r", "foo"], RemoveCmd)
 
1214
        self.assert_command_from_args(["-r", "foo"], command.Remove)
1202
1215
 
1203
1216
    def test_dump_json(self):
1204
 
        self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
 
1217
        self.assert_command_from_args(["--dump-json"],
 
1218
                                      command.DumpJSON)
1205
1219
 
1206
1220
    def test_enable(self):
1207
 
        self.assert_command_from_args(["--enable", "foo"], EnableCmd)
 
1221
        self.assert_command_from_args(["--enable", "foo"],
 
1222
                                      command.Enable)
1208
1223
 
1209
1224
    def test_enable_short(self):
1210
 
        self.assert_command_from_args(["-e", "foo"], EnableCmd)
 
1225
        self.assert_command_from_args(["-e", "foo"], command.Enable)
1211
1226
 
1212
1227
    def test_disable(self):
1213
1228
        self.assert_command_from_args(["--disable", "foo"],
1214
 
                                      DisableCmd)
 
1229
                                      command.Disable)
1215
1230
 
1216
1231
    def test_disable_short(self):
1217
 
        self.assert_command_from_args(["-d", "foo"], DisableCmd)
 
1232
        self.assert_command_from_args(["-d", "foo"], command.Disable)
1218
1233
 
1219
1234
    def test_bump_timeout(self):
1220
1235
        self.assert_command_from_args(["--bump-timeout", "foo"],
1221
 
                                      BumpTimeoutCmd)
 
1236
                                      command.BumpTimeout)
1222
1237
 
1223
1238
    def test_bump_timeout_short(self):
1224
 
        self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
 
1239
        self.assert_command_from_args(["-b", "foo"],
 
1240
                                      command.BumpTimeout)
1225
1241
 
1226
1242
    def test_start_checker(self):
1227
1243
        self.assert_command_from_args(["--start-checker", "foo"],
1228
 
                                      StartCheckerCmd)
 
1244
                                      command.StartChecker)
1229
1245
 
1230
1246
    def test_stop_checker(self):
1231
1247
        self.assert_command_from_args(["--stop-checker", "foo"],
1232
 
                                      StopCheckerCmd)
 
1248
                                      command.StopChecker)
1233
1249
 
1234
1250
    def test_approve_by_default(self):
1235
1251
        self.assert_command_from_args(["--approve-by-default", "foo"],
1236
 
                                      ApproveByDefaultCmd)
 
1252
                                      command.ApproveByDefault)
1237
1253
 
1238
1254
    def test_deny_by_default(self):
1239
1255
        self.assert_command_from_args(["--deny-by-default", "foo"],
1240
 
                                      DenyByDefaultCmd)
 
1256
                                      command.DenyByDefault)
1241
1257
 
1242
1258
    def test_checker(self):
1243
1259
        self.assert_command_from_args(["--checker", ":", "foo"],
1244
 
                                      SetCheckerCmd, value_to_set=":")
 
1260
                                      command.SetChecker,
 
1261
                                      value_to_set=":")
1245
1262
 
1246
1263
    def test_checker_empty(self):
1247
1264
        self.assert_command_from_args(["--checker", "", "foo"],
1248
 
                                      SetCheckerCmd, value_to_set="")
 
1265
                                      command.SetChecker,
 
1266
                                      value_to_set="")
1249
1267
 
1250
1268
    def test_checker_short(self):
1251
1269
        self.assert_command_from_args(["-c", ":", "foo"],
1252
 
                                      SetCheckerCmd, value_to_set=":")
 
1270
                                      command.SetChecker,
 
1271
                                      value_to_set=":")
1253
1272
 
1254
1273
    def test_host(self):
1255
1274
        self.assert_command_from_args(["--host", "foo.example.org",
1256
 
                                       "foo"], SetHostCmd,
 
1275
                                       "foo"], command.SetHost,
1257
1276
                                      value_to_set="foo.example.org")
1258
1277
 
1259
1278
    def test_host_short(self):
1260
1279
        self.assert_command_from_args(["-H", "foo.example.org",
1261
 
                                       "foo"], SetHostCmd,
 
1280
                                       "foo"], command.SetHost,
1262
1281
                                      value_to_set="foo.example.org")
1263
1282
 
1264
1283
    def test_secret_devnull(self):
1265
1284
        self.assert_command_from_args(["--secret", os.path.devnull,
1266
 
                                       "foo"], SetSecretCmd,
 
1285
                                       "foo"], command.SetSecret,
1267
1286
                                      value_to_set=b"")
1268
1287
 
1269
1288
    def test_secret_tempfile(self):
1272
1291
            f.write(value)
1273
1292
            f.seek(0)
1274
1293
            self.assert_command_from_args(["--secret", f.name,
1275
 
                                           "foo"], SetSecretCmd,
 
1294
                                           "foo"], command.SetSecret,
1276
1295
                                          value_to_set=value)
1277
1296
 
1278
1297
    def test_secret_devnull_short(self):
1279
1298
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
1280
 
                                      SetSecretCmd, value_to_set=b"")
 
1299
                                      command.SetSecret,
 
1300
                                      value_to_set=b"")
1281
1301
 
1282
1302
    def test_secret_tempfile_short(self):
1283
1303
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
1285
1305
            f.write(value)
1286
1306
            f.seek(0)
1287
1307
            self.assert_command_from_args(["-s", f.name, "foo"],
1288
 
                                          SetSecretCmd,
 
1308
                                          command.SetSecret,
1289
1309
                                          value_to_set=value)
1290
1310
 
1291
1311
    def test_timeout(self):
1292
1312
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
1293
 
                                      SetTimeoutCmd,
 
1313
                                      command.SetTimeout,
1294
1314
                                      value_to_set=300000)
1295
1315
 
1296
1316
    def test_timeout_short(self):
1297
1317
        self.assert_command_from_args(["-t", "PT5M", "foo"],
1298
 
                                      SetTimeoutCmd,
 
1318
                                      command.SetTimeout,
1299
1319
                                      value_to_set=300000)
1300
1320
 
1301
1321
    def test_extended_timeout(self):
1302
1322
        self.assert_command_from_args(["--extended-timeout", "PT15M",
1303
1323
                                       "foo"],
1304
 
                                      SetExtendedTimeoutCmd,
 
1324
                                      command.SetExtendedTimeout,
1305
1325
                                      value_to_set=900000)
1306
1326
 
1307
1327
    def test_interval(self):
1308
1328
        self.assert_command_from_args(["--interval", "PT2M", "foo"],
1309
 
                                      SetIntervalCmd,
 
1329
                                      command.SetInterval,
1310
1330
                                      value_to_set=120000)
1311
1331
 
1312
1332
    def test_interval_short(self):
1313
1333
        self.assert_command_from_args(["-i", "PT2M", "foo"],
1314
 
                                      SetIntervalCmd,
 
1334
                                      command.SetInterval,
1315
1335
                                      value_to_set=120000)
1316
1336
 
1317
1337
    def test_approval_delay(self):
1318
1338
        self.assert_command_from_args(["--approval-delay", "PT30S",
1319
 
                                       "foo"], SetApprovalDelayCmd,
 
1339
                                       "foo"],
 
1340
                                      command.SetApprovalDelay,
1320
1341
                                      value_to_set=30000)
1321
1342
 
1322
1343
    def test_approval_duration(self):
1323
1344
        self.assert_command_from_args(["--approval-duration", "PT1S",
1324
 
                                       "foo"], SetApprovalDurationCmd,
 
1345
                                       "foo"],
 
1346
                                      command.SetApprovalDuration,
1325
1347
                                      value_to_set=1000)
1326
1348
 
1327
1349
    def test_print_table(self):
1328
 
        self.assert_command_from_args([], PrintTableCmd,
 
1350
        self.assert_command_from_args([], command.PrintTable,
1329
1351
                                      verbose=False)
1330
1352
 
1331
1353
    def test_print_table_verbose(self):
1332
 
        self.assert_command_from_args(["--verbose"], PrintTableCmd,
 
1354
        self.assert_command_from_args(["--verbose"],
 
1355
                                      command.PrintTable,
1333
1356
                                      verbose=True)
1334
1357
 
1335
1358
    def test_print_table_verbose_short(self):
1336
 
        self.assert_command_from_args(["-v"], PrintTableCmd,
 
1359
        self.assert_command_from_args(["-v"], command.PrintTable,
1337
1360
                                      verbose=True)
1338
1361
 
1339
1362
 
1340
 
class TestCmd(unittest.TestCase):
 
1363
class TestCommand(unittest.TestCase):
1341
1364
    """Abstract class for tests of command classes"""
1342
1365
 
1343
1366
    def setUp(self):
1433
1456
        return Bus()
1434
1457
 
1435
1458
 
1436
 
class TestIsEnabledCmd(TestCmd):
 
1459
class TestBaseCommands(TestCommand):
 
1460
 
1437
1461
    def test_is_enabled(self):
1438
 
        self.assertTrue(all(IsEnabledCmd().is_enabled(client,
 
1462
        self.assertTrue(all(command.IsEnabled().is_enabled(client,
1439
1463
                                                      properties)
1440
1464
                            for client, properties
1441
1465
                            in self.clients.items()))
1442
1466
 
1443
1467
    def test_is_enabled_run_exits_successfully(self):
1444
1468
        with self.assertRaises(SystemExit) as e:
1445
 
            IsEnabledCmd().run(self.one_client)
 
1469
            command.IsEnabled().run(self.one_client)
1446
1470
        if e.exception.code is not None:
1447
1471
            self.assertEqual(e.exception.code, 0)
1448
1472
        else:
1451
1475
    def test_is_enabled_run_exits_with_failure(self):
1452
1476
        self.client.attributes["Enabled"] = dbus.Boolean(False)
1453
1477
        with self.assertRaises(SystemExit) as e:
1454
 
            IsEnabledCmd().run(self.one_client)
 
1478
            command.IsEnabled().run(self.one_client)
1455
1479
        if isinstance(e.exception.code, int):
1456
1480
            self.assertNotEqual(e.exception.code, 0)
1457
1481
        else:
1458
1482
            self.assertIsNotNone(e.exception.code)
1459
1483
 
1460
 
 
1461
 
class TestApproveCmd(TestCmd):
1462
1484
    def test_approve(self):
1463
 
        ApproveCmd().run(self.clients, self.bus)
 
1485
        command.Approve().run(self.clients, self.bus)
1464
1486
        for clientpath in self.clients:
1465
1487
            client = self.bus.get_object(dbus_busname, clientpath)
1466
1488
            self.assertIn(("Approve", (True, client_dbus_interface)),
1467
1489
                          client.calls)
1468
1490
 
1469
 
 
1470
 
class TestDenyCmd(TestCmd):
1471
1491
    def test_deny(self):
1472
 
        DenyCmd().run(self.clients, self.bus)
 
1492
        command.Deny().run(self.clients, self.bus)
1473
1493
        for clientpath in self.clients:
1474
1494
            client = self.bus.get_object(dbus_busname, clientpath)
1475
1495
            self.assertIn(("Approve", (False, client_dbus_interface)),
1476
1496
                          client.calls)
1477
1497
 
1478
 
 
1479
 
class TestRemoveCmd(TestCmd):
1480
1498
    def test_remove(self):
1481
1499
        class MockMandos(object):
1482
1500
            def __init__(self):
1484
1502
            def RemoveClient(self, dbus_path):
1485
1503
                self.calls.append(("RemoveClient", (dbus_path,)))
1486
1504
        mandos = MockMandos()
1487
 
        super(TestRemoveCmd, self).setUp()
1488
 
        RemoveCmd().run(self.clients, self.bus, mandos)
 
1505
        super(TestBaseCommands, self).setUp()
 
1506
        command.Remove().run(self.clients, self.bus, mandos)
1489
1507
        self.assertEqual(len(mandos.calls), 2)
1490
1508
        for clientpath in self.clients:
1491
1509
            self.assertIn(("RemoveClient", (clientpath,)),
1492
1510
                          mandos.calls)
1493
1511
 
1494
 
 
1495
 
class TestDumpJSONCmd(TestCmd):
1496
 
    def setUp(self):
1497
 
        self.expected_json = {
1498
 
            "foo": {
1499
 
                "Name": "foo",
1500
 
                "KeyID": ("92ed150794387c03ce684574b1139a65"
1501
 
                          "94a34f895daaaf09fd8ea90a27cddb12"),
1502
 
                "Host": "foo.example.org",
1503
 
                "Enabled": True,
1504
 
                "Timeout": 300000,
1505
 
                "LastCheckedOK": "2019-02-03T00:00:00",
1506
 
                "Created": "2019-01-02T00:00:00",
1507
 
                "Interval": 120000,
1508
 
                "Fingerprint": ("778827225BA7DE539C5A"
1509
 
                                "7CFA59CFF7CDBD9A5920"),
1510
 
                "CheckerRunning": False,
1511
 
                "LastEnabled": "2019-01-03T00:00:00",
1512
 
                "ApprovalPending": False,
1513
 
                "ApprovedByDefault": True,
1514
 
                "LastApprovalRequest": "",
1515
 
                "ApprovalDelay": 0,
1516
 
                "ApprovalDuration": 1000,
1517
 
                "Checker": "fping -q -- %(host)s",
1518
 
                "ExtendedTimeout": 900000,
1519
 
                "Expires": "2019-02-04T00:00:00",
1520
 
                "LastCheckerStatus": 0,
1521
 
            },
1522
 
            "barbar": {
1523
 
                "Name": "barbar",
1524
 
                "KeyID": ("0558568eedd67d622f5c83b35a115f79"
1525
 
                          "6ab612cff5ad227247e46c2b020f441c"),
1526
 
                "Host": "192.0.2.3",
1527
 
                "Enabled": True,
1528
 
                "Timeout": 300000,
1529
 
                "LastCheckedOK": "2019-02-04T00:00:00",
1530
 
                "Created": "2019-01-03T00:00:00",
1531
 
                "Interval": 120000,
1532
 
                "Fingerprint": ("3E393AEAEFB84C7E89E2"
1533
 
                                "F547B3A107558FCA3A27"),
1534
 
                "CheckerRunning": True,
1535
 
                "LastEnabled": "2019-01-04T00:00:00",
1536
 
                "ApprovalPending": False,
1537
 
                "ApprovedByDefault": False,
1538
 
                "LastApprovalRequest": "2019-01-03T00:00:00",
1539
 
                "ApprovalDelay": 30000,
1540
 
                "ApprovalDuration": 93785000,
1541
 
                "Checker": ":",
1542
 
                "ExtendedTimeout": 900000,
1543
 
                "Expires": "2019-02-05T00:00:00",
1544
 
                "LastCheckerStatus": -2,
1545
 
            },
1546
 
        }
1547
 
        return super(TestDumpJSONCmd, self).setUp()
1548
 
 
1549
 
    def test_normal(self):
1550
 
        output = DumpJSONCmd().output(self.clients.values())
 
1512
    expected_json = {
 
1513
        "foo": {
 
1514
            "Name": "foo",
 
1515
            "KeyID": ("92ed150794387c03ce684574b1139a65"
 
1516
                      "94a34f895daaaf09fd8ea90a27cddb12"),
 
1517
            "Host": "foo.example.org",
 
1518
            "Enabled": True,
 
1519
            "Timeout": 300000,
 
1520
            "LastCheckedOK": "2019-02-03T00:00:00",
 
1521
            "Created": "2019-01-02T00:00:00",
 
1522
            "Interval": 120000,
 
1523
            "Fingerprint": ("778827225BA7DE539C5A"
 
1524
                            "7CFA59CFF7CDBD9A5920"),
 
1525
            "CheckerRunning": False,
 
1526
            "LastEnabled": "2019-01-03T00:00:00",
 
1527
            "ApprovalPending": False,
 
1528
            "ApprovedByDefault": True,
 
1529
            "LastApprovalRequest": "",
 
1530
            "ApprovalDelay": 0,
 
1531
            "ApprovalDuration": 1000,
 
1532
            "Checker": "fping -q -- %(host)s",
 
1533
            "ExtendedTimeout": 900000,
 
1534
            "Expires": "2019-02-04T00:00:00",
 
1535
            "LastCheckerStatus": 0,
 
1536
        },
 
1537
        "barbar": {
 
1538
            "Name": "barbar",
 
1539
            "KeyID": ("0558568eedd67d622f5c83b35a115f79"
 
1540
                      "6ab612cff5ad227247e46c2b020f441c"),
 
1541
            "Host": "192.0.2.3",
 
1542
            "Enabled": True,
 
1543
            "Timeout": 300000,
 
1544
            "LastCheckedOK": "2019-02-04T00:00:00",
 
1545
            "Created": "2019-01-03T00:00:00",
 
1546
            "Interval": 120000,
 
1547
            "Fingerprint": ("3E393AEAEFB84C7E89E2"
 
1548
                            "F547B3A107558FCA3A27"),
 
1549
            "CheckerRunning": True,
 
1550
            "LastEnabled": "2019-01-04T00:00:00",
 
1551
            "ApprovalPending": False,
 
1552
            "ApprovedByDefault": False,
 
1553
            "LastApprovalRequest": "2019-01-03T00:00:00",
 
1554
            "ApprovalDelay": 30000,
 
1555
            "ApprovalDuration": 93785000,
 
1556
            "Checker": ":",
 
1557
            "ExtendedTimeout": 900000,
 
1558
            "Expires": "2019-02-05T00:00:00",
 
1559
            "LastCheckerStatus": -2,
 
1560
        },
 
1561
    }
 
1562
 
 
1563
    def test_DumpJSON_normal(self):
 
1564
        output = command.DumpJSON().output(self.clients.values())
1551
1565
        json_data = json.loads(output)
1552
1566
        self.assertDictEqual(json_data, self.expected_json)
1553
1567
 
1554
 
    def test_one_client(self):
1555
 
        output = DumpJSONCmd().output(self.one_client.values())
 
1568
    def test_DumpJSON_one_client(self):
 
1569
        output = command.DumpJSON().output(self.one_client.values())
1556
1570
        json_data = json.loads(output)
1557
1571
        expected_json = {"foo": self.expected_json["foo"]}
1558
1572
        self.assertDictEqual(json_data, expected_json)
1559
1573
 
1560
 
 
1561
 
class TestPrintTableCmd(TestCmd):
1562
 
    def test_normal(self):
1563
 
        output = PrintTableCmd().output(self.clients.values())
 
1574
    def test_PrintTable_normal(self):
 
1575
        output = command.PrintTable().output(self.clients.values())
1564
1576
        expected_output = "\n".join((
1565
1577
            "Name   Enabled Timeout  Last Successful Check",
1566
1578
            "foo    Yes     00:05:00 2019-02-03T00:00:00  ",
1568
1580
        ))
1569
1581
        self.assertEqual(output, expected_output)
1570
1582
 
1571
 
    def test_verbose(self):
1572
 
        output = PrintTableCmd(verbose=True).output(
 
1583
    def test_PrintTable_verbose(self):
 
1584
        output = command.PrintTable(verbose=True).output(
1573
1585
            self.clients.values())
1574
1586
        columns = (
1575
1587
            (
1663
1675
                                    for line in range(num_lines))
1664
1676
        self.assertEqual(output, expected_output)
1665
1677
 
1666
 
    def test_one_client(self):
1667
 
        output = PrintTableCmd().output(self.one_client.values())
 
1678
    def test_PrintTable_one_client(self):
 
1679
        output = command.PrintTable().output(self.one_client.values())
1668
1680
        expected_output = "\n".join((
1669
1681
            "Name Enabled Timeout  Last Successful Check",
1670
1682
            "foo  Yes     00:05:00 2019-02-03T00:00:00  ",
1672
1684
        self.assertEqual(output, expected_output)
1673
1685
 
1674
1686
 
1675
 
class TestPropertyCmd(TestCmd):
1676
 
    """Abstract class for tests of PropertyCmd classes"""
 
1687
class TestPropertyCmd(TestCommand):
 
1688
    """Abstract class for tests of command.Property classes"""
1677
1689
    def runTest(self):
1678
1690
        if not hasattr(self, "command"):
1679
1691
            return
1702
1714
 
1703
1715
 
1704
1716
class TestEnableCmd(TestPropertyCmd):
1705
 
    command = EnableCmd
 
1717
    command = command.Enable
1706
1718
    propname = "Enabled"
1707
1719
    values_to_set = [dbus.Boolean(True)]
1708
1720
 
1709
1721
 
1710
1722
class TestDisableCmd(TestPropertyCmd):
1711
 
    command = DisableCmd
 
1723
    command = command.Disable
1712
1724
    propname = "Enabled"
1713
1725
    values_to_set = [dbus.Boolean(False)]
1714
1726
 
1715
1727
 
1716
1728
class TestBumpTimeoutCmd(TestPropertyCmd):
1717
 
    command = BumpTimeoutCmd
 
1729
    command = command.BumpTimeout
1718
1730
    propname = "LastCheckedOK"
1719
1731
    values_to_set = [""]
1720
1732
 
1721
1733
 
1722
1734
class TestStartCheckerCmd(TestPropertyCmd):
1723
 
    command = StartCheckerCmd
 
1735
    command = command.StartChecker
1724
1736
    propname = "CheckerRunning"
1725
1737
    values_to_set = [dbus.Boolean(True)]
1726
1738
 
1727
1739
 
1728
1740
class TestStopCheckerCmd(TestPropertyCmd):
1729
 
    command = StopCheckerCmd
 
1741
    command = command.StopChecker
1730
1742
    propname = "CheckerRunning"
1731
1743
    values_to_set = [dbus.Boolean(False)]
1732
1744
 
1733
1745
 
1734
1746
class TestApproveByDefaultCmd(TestPropertyCmd):
1735
 
    command = ApproveByDefaultCmd
 
1747
    command = command.ApproveByDefault
1736
1748
    propname = "ApprovedByDefault"
1737
1749
    values_to_set = [dbus.Boolean(True)]
1738
1750
 
1739
1751
 
1740
1752
class TestDenyByDefaultCmd(TestPropertyCmd):
1741
 
    command = DenyByDefaultCmd
 
1753
    command = command.DenyByDefault
1742
1754
    propname = "ApprovedByDefault"
1743
1755
    values_to_set = [dbus.Boolean(False)]
1744
1756
 
1756
1768
 
1757
1769
 
1758
1770
class TestSetCheckerCmd(TestPropertyValueCmd):
1759
 
    command = SetCheckerCmd
 
1771
    command = command.SetChecker
1760
1772
    propname = "Checker"
1761
1773
    values_to_set = ["", ":", "fping -q -- %s"]
1762
1774
 
1763
1775
 
1764
1776
class TestSetHostCmd(TestPropertyValueCmd):
1765
 
    command = SetHostCmd
 
1777
    command = command.SetHost
1766
1778
    propname = "Host"
1767
1779
    values_to_set = ["192.0.2.3", "foo.example.org"]
1768
1780
 
1769
1781
 
1770
1782
class TestSetSecretCmd(TestPropertyValueCmd):
1771
 
    command = SetSecretCmd
 
1783
    command = command.SetSecret
1772
1784
    propname = "Secret"
1773
1785
    values_to_set = [io.BytesIO(b""),
1774
1786
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1776
1788
 
1777
1789
 
1778
1790
class TestSetTimeoutCmd(TestPropertyValueCmd):
1779
 
    command = SetTimeoutCmd
 
1791
    command = command.SetTimeout
1780
1792
    propname = "Timeout"
1781
1793
    values_to_set = [datetime.timedelta(),
1782
1794
                     datetime.timedelta(minutes=5),
1787
1799
 
1788
1800
 
1789
1801
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1790
 
    command = SetExtendedTimeoutCmd
 
1802
    command = command.SetExtendedTimeout
1791
1803
    propname = "ExtendedTimeout"
1792
1804
    values_to_set = [datetime.timedelta(),
1793
1805
                     datetime.timedelta(minutes=5),
1798
1810
 
1799
1811
 
1800
1812
class TestSetIntervalCmd(TestPropertyValueCmd):
1801
 
    command = SetIntervalCmd
 
1813
    command = command.SetInterval
1802
1814
    propname = "Interval"
1803
1815
    values_to_set = [datetime.timedelta(),
1804
1816
                     datetime.timedelta(minutes=5),
1809
1821
 
1810
1822
 
1811
1823
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1812
 
    command = SetApprovalDelayCmd
 
1824
    command = command.SetApprovalDelay
1813
1825
    propname = "ApprovalDelay"
1814
1826
    values_to_set = [datetime.timedelta(),
1815
1827
                     datetime.timedelta(minutes=5),
1820
1832
 
1821
1833
 
1822
1834
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1823
 
    command = SetApprovalDurationCmd
 
1835
    command = command.SetApprovalDuration
1824
1836
    propname = "ApprovalDuration"
1825
1837
    values_to_set = [datetime.timedelta(),
1826
1838
                     datetime.timedelta(minutes=5),