/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-16 04:38:35 UTC
  • Revision ID: teddy@recompile.se-20190316043835-xlmz9xse3bh1u5u6
mandos-ctl: Refactor tests

* mandos-ctl (Test_get_managed_objects): Remove some useless
                                         "@staticmethod"s.

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
477
477
    commands = []
478
478
 
479
479
    if options.is_enabled:
480
 
        commands.append(command.IsEnabled())
 
480
        commands.append(IsEnabledCmd())
481
481
 
482
482
    if options.approve:
483
 
        commands.append(command.Approve())
 
483
        commands.append(ApproveCmd())
484
484
 
485
485
    if options.deny:
486
 
        commands.append(command.Deny())
 
486
        commands.append(DenyCmd())
487
487
 
488
488
    if options.remove:
489
 
        commands.append(command.Remove())
 
489
        commands.append(RemoveCmd())
490
490
 
491
491
    if options.dump_json:
492
 
        commands.append(command.DumpJSON())
 
492
        commands.append(DumpJSONCmd())
493
493
 
494
494
    if options.enable:
495
 
        commands.append(command.Enable())
 
495
        commands.append(EnableCmd())
496
496
 
497
497
    if options.disable:
498
 
        commands.append(command.Disable())
 
498
        commands.append(DisableCmd())
499
499
 
500
500
    if options.bump_timeout:
501
 
        commands.append(command.BumpTimeout())
 
501
        commands.append(BumpTimeoutCmd())
502
502
 
503
503
    if options.start_checker:
504
 
        commands.append(command.StartChecker())
 
504
        commands.append(StartCheckerCmd())
505
505
 
506
506
    if options.stop_checker:
507
 
        commands.append(command.StopChecker())
 
507
        commands.append(StopCheckerCmd())
508
508
 
509
509
    if options.approved_by_default is not None:
510
510
        if options.approved_by_default:
511
 
            commands.append(command.ApproveByDefault())
 
511
            commands.append(ApproveByDefaultCmd())
512
512
        else:
513
 
            commands.append(command.DenyByDefault())
 
513
            commands.append(DenyByDefaultCmd())
514
514
 
515
515
    if options.checker is not None:
516
 
        commands.append(command.SetChecker(options.checker))
 
516
        commands.append(SetCheckerCmd(options.checker))
517
517
 
518
518
    if options.host is not None:
519
 
        commands.append(command.SetHost(options.host))
 
519
        commands.append(SetHostCmd(options.host))
520
520
 
521
521
    if options.secret is not None:
522
 
        commands.append(command.SetSecret(options.secret))
 
522
        commands.append(SetSecretCmd(options.secret))
523
523
 
524
524
    if options.timeout is not None:
525
 
        commands.append(command.SetTimeout(options.timeout))
 
525
        commands.append(SetTimeoutCmd(options.timeout))
526
526
 
527
527
    if options.extended_timeout:
528
528
        commands.append(
529
 
            command.SetExtendedTimeout(options.extended_timeout))
 
529
            SetExtendedTimeoutCmd(options.extended_timeout))
530
530
 
531
531
    if options.interval is not None:
532
 
        commands.append(command.SetInterval(options.interval))
 
532
        commands.append(SetIntervalCmd(options.interval))
533
533
 
534
534
    if options.approval_delay is not None:
535
 
        commands.append(
536
 
            command.SetApprovalDelay(options.approval_delay))
 
535
        commands.append(SetApprovalDelayCmd(options.approval_delay))
537
536
 
538
537
    if options.approval_duration is not None:
539
538
        commands.append(
540
 
            command.SetApprovalDuration(options.approval_duration))
 
539
            SetApprovalDurationCmd(options.approval_duration))
541
540
 
542
541
    # If no command option has been given, show table of clients,
543
542
    # optionally verbosely
544
543
    if not commands:
545
 
        commands.append(command.PrintTable(verbose=options.verbose))
 
544
        commands.append(PrintTableCmd(verbose=options.verbose))
546
545
 
547
546
    return commands
548
547
 
549
548
 
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=(',', ': '))
 
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__
 
674
            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})
630
712
 
631
713
        @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
 
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
821
809
a datetime.timedelta() but should store it as milliseconds."""
822
810
 
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"
 
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"
851
839
 
852
840
 
853
841
 
884
872
                                                    ("records",
885
873
                                                     "output"))
886
874
 
887
 
 
888
875
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):
 
876
    def test_handles_basic_rfc3339(self):
894
877
        self.assertEqual(string_to_delta("PT0S"),
895
878
                         datetime.timedelta())
896
 
 
897
 
    def test_rfc3339_zero_days(self):
898
879
        self.assertEqual(string_to_delta("P0D"),
899
880
                         datetime.timedelta())
900
 
 
901
 
    def test_rfc3339_one_second(self):
902
881
        self.assertEqual(string_to_delta("PT1S"),
903
882
                         datetime.timedelta(0, 1))
904
 
 
905
 
    def test_rfc3339_two_hours(self):
906
883
        self.assertEqual(string_to_delta("PT2H"),
907
884
                         datetime.timedelta(0, 7200))
908
885
 
953
930
    @contextlib.contextmanager
954
931
    def assertParseError(self):
955
932
        with self.assertRaises(SystemExit) as e:
956
 
            with self.redirect_stderr_to_devnull():
 
933
            with self.temporarily_suppress_stderr():
957
934
                yield
958
935
        # Exit code from argparse is guaranteed to be "2".  Reference:
959
936
        # https://docs.python.org/3/library
962
939
 
963
940
    @staticmethod
964
941
    @contextlib.contextmanager
965
 
    def redirect_stderr_to_devnull():
 
942
    def temporarily_suppress_stderr():
966
943
        null = os.open(os.path.devnull, os.O_RDWR)
967
944
        stderrcopy = os.dup(sys.stderr.fileno())
968
945
        os.dup2(null, sys.stderr.fileno())
977
954
    def check_option_syntax(self, options):
978
955
        check_option_syntax(self.parser, options)
979
956
 
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"]
 
957
    def test_actions_conflicts_with_verbose(self):
 
958
        for action, value in self.actions.items():
 
959
            options = self.parser.parse_args()
 
960
            setattr(options, action, value)
 
961
            options.verbose = True
995
962
            with self.assertParseError():
996
963
                self.check_option_syntax(options)
997
964
 
1023
990
            options.all = True
1024
991
            self.check_option_syntax(options)
1025
992
 
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"]
 
993
    def test_is_enabled_fails_without_client(self):
 
994
        options = self.parser.parse_args()
 
995
        options.is_enabled = True
 
996
        with self.assertParseError():
1031
997
            self.check_option_syntax(options)
1032
998
 
1033
 
    def test_one_client_with_all_actions_except_is_enabled(self):
 
999
    def test_is_enabled_works_with_one_client(self):
1034
1000
        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)
 
1001
        options.is_enabled = True
1039
1002
        options.client = ["foo"]
1040
1003
        self.check_option_syntax(options)
1041
1004
 
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
1005
    def test_is_enabled_fails_with_two_clients(self):
1067
1006
        options = self.parser.parse_args()
1068
1007
        options.is_enabled = True
1145
1084
                    get_managed_objects(MockObjectManagerFailing())
1146
1085
        finally:
1147
1086
            dbus_logger.removeFilter(counting_handler)
1148
 
 
1149
 
        # Make sure the dbus logger was suppressed
1150
1087
        self.assertEqual(counting_handler.count, 0)
1151
1088
 
1152
1089
        # Test that the dbus_logger still works
1166
1103
 
1167
1104
    def test_is_enabled(self):
1168
1105
        self.assert_command_from_args(["--is-enabled", "foo"],
1169
 
                                      command.IsEnabled)
 
1106
                                      IsEnabledCmd)
1170
1107
 
1171
1108
    def assert_command_from_args(self, args, command_cls,
1172
1109
                                 **cmd_attrs):
1182
1119
            self.assertEqual(getattr(command, key), value)
1183
1120
 
1184
1121
    def test_is_enabled_short(self):
1185
 
        self.assert_command_from_args(["-V", "foo"],
1186
 
                                      command.IsEnabled)
 
1122
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1187
1123
 
1188
1124
    def test_approve(self):
1189
1125
        self.assert_command_from_args(["--approve", "foo"],
1190
 
                                      command.Approve)
 
1126
                                      ApproveCmd)
1191
1127
 
1192
1128
    def test_approve_short(self):
1193
 
        self.assert_command_from_args(["-A", "foo"], command.Approve)
 
1129
        self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1194
1130
 
1195
1131
    def test_deny(self):
1196
 
        self.assert_command_from_args(["--deny", "foo"], command.Deny)
 
1132
        self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1197
1133
 
1198
1134
    def test_deny_short(self):
1199
 
        self.assert_command_from_args(["-D", "foo"], command.Deny)
 
1135
        self.assert_command_from_args(["-D", "foo"], DenyCmd)
1200
1136
 
1201
1137
    def test_remove(self):
1202
1138
        self.assert_command_from_args(["--remove", "foo"],
1203
 
                                      command.Remove)
 
1139
                                      RemoveCmd)
1204
1140
 
1205
1141
    def test_deny_before_remove(self):
1206
1142
        options = self.parser.parse_args(["--deny", "--remove",
1208
1144
        check_option_syntax(self.parser, options)
1209
1145
        commands = commands_from_options(options)
1210
1146
        self.assertEqual(len(commands), 2)
1211
 
        self.assertIsInstance(commands[0], command.Deny)
1212
 
        self.assertIsInstance(commands[1], command.Remove)
 
1147
        self.assertIsInstance(commands[0], DenyCmd)
 
1148
        self.assertIsInstance(commands[1], RemoveCmd)
1213
1149
 
1214
1150
    def test_deny_before_remove_reversed(self):
1215
1151
        options = self.parser.parse_args(["--remove", "--deny",
1217
1153
        check_option_syntax(self.parser, options)
1218
1154
        commands = commands_from_options(options)
1219
1155
        self.assertEqual(len(commands), 2)
1220
 
        self.assertIsInstance(commands[0], command.Deny)
1221
 
        self.assertIsInstance(commands[1], command.Remove)
 
1156
        self.assertIsInstance(commands[0], DenyCmd)
 
1157
        self.assertIsInstance(commands[1], RemoveCmd)
1222
1158
 
1223
1159
    def test_remove_short(self):
1224
 
        self.assert_command_from_args(["-r", "foo"], command.Remove)
 
1160
        self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1225
1161
 
1226
1162
    def test_dump_json(self):
1227
 
        self.assert_command_from_args(["--dump-json"],
1228
 
                                      command.DumpJSON)
 
1163
        self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1229
1164
 
1230
1165
    def test_enable(self):
1231
 
        self.assert_command_from_args(["--enable", "foo"],
1232
 
                                      command.Enable)
 
1166
        self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1233
1167
 
1234
1168
    def test_enable_short(self):
1235
 
        self.assert_command_from_args(["-e", "foo"], command.Enable)
 
1169
        self.assert_command_from_args(["-e", "foo"], EnableCmd)
1236
1170
 
1237
1171
    def test_disable(self):
1238
1172
        self.assert_command_from_args(["--disable", "foo"],
1239
 
                                      command.Disable)
 
1173
                                      DisableCmd)
1240
1174
 
1241
1175
    def test_disable_short(self):
1242
 
        self.assert_command_from_args(["-d", "foo"], command.Disable)
 
1176
        self.assert_command_from_args(["-d", "foo"], DisableCmd)
1243
1177
 
1244
1178
    def test_bump_timeout(self):
1245
1179
        self.assert_command_from_args(["--bump-timeout", "foo"],
1246
 
                                      command.BumpTimeout)
 
1180
                                      BumpTimeoutCmd)
1247
1181
 
1248
1182
    def test_bump_timeout_short(self):
1249
 
        self.assert_command_from_args(["-b", "foo"],
1250
 
                                      command.BumpTimeout)
 
1183
        self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1251
1184
 
1252
1185
    def test_start_checker(self):
1253
1186
        self.assert_command_from_args(["--start-checker", "foo"],
1254
 
                                      command.StartChecker)
 
1187
                                      StartCheckerCmd)
1255
1188
 
1256
1189
    def test_stop_checker(self):
1257
1190
        self.assert_command_from_args(["--stop-checker", "foo"],
1258
 
                                      command.StopChecker)
 
1191
                                      StopCheckerCmd)
1259
1192
 
1260
1193
    def test_approve_by_default(self):
1261
1194
        self.assert_command_from_args(["--approve-by-default", "foo"],
1262
 
                                      command.ApproveByDefault)
 
1195
                                      ApproveByDefaultCmd)
1263
1196
 
1264
1197
    def test_deny_by_default(self):
1265
1198
        self.assert_command_from_args(["--deny-by-default", "foo"],
1266
 
                                      command.DenyByDefault)
 
1199
                                      DenyByDefaultCmd)
1267
1200
 
1268
1201
    def test_checker(self):
1269
1202
        self.assert_command_from_args(["--checker", ":", "foo"],
1270
 
                                      command.SetChecker,
1271
 
                                      value_to_set=":")
 
1203
                                      SetCheckerCmd, value_to_set=":")
1272
1204
 
1273
1205
    def test_checker_empty(self):
1274
1206
        self.assert_command_from_args(["--checker", "", "foo"],
1275
 
                                      command.SetChecker,
1276
 
                                      value_to_set="")
 
1207
                                      SetCheckerCmd, value_to_set="")
1277
1208
 
1278
1209
    def test_checker_short(self):
1279
1210
        self.assert_command_from_args(["-c", ":", "foo"],
1280
 
                                      command.SetChecker,
1281
 
                                      value_to_set=":")
 
1211
                                      SetCheckerCmd, value_to_set=":")
1282
1212
 
1283
1213
    def test_host(self):
1284
1214
        self.assert_command_from_args(["--host", "foo.example.org",
1285
 
                                       "foo"], command.SetHost,
 
1215
                                       "foo"], SetHostCmd,
1286
1216
                                      value_to_set="foo.example.org")
1287
1217
 
1288
1218
    def test_host_short(self):
1289
1219
        self.assert_command_from_args(["-H", "foo.example.org",
1290
 
                                       "foo"], command.SetHost,
 
1220
                                       "foo"], SetHostCmd,
1291
1221
                                      value_to_set="foo.example.org")
1292
1222
 
1293
1223
    def test_secret_devnull(self):
1294
1224
        self.assert_command_from_args(["--secret", os.path.devnull,
1295
 
                                       "foo"], command.SetSecret,
 
1225
                                       "foo"], SetSecretCmd,
1296
1226
                                      value_to_set=b"")
1297
1227
 
1298
1228
    def test_secret_tempfile(self):
1301
1231
            f.write(value)
1302
1232
            f.seek(0)
1303
1233
            self.assert_command_from_args(["--secret", f.name,
1304
 
                                           "foo"], command.SetSecret,
 
1234
                                           "foo"], SetSecretCmd,
1305
1235
                                          value_to_set=value)
1306
1236
 
1307
1237
    def test_secret_devnull_short(self):
1308
1238
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
1309
 
                                      command.SetSecret,
1310
 
                                      value_to_set=b"")
 
1239
                                      SetSecretCmd, value_to_set=b"")
1311
1240
 
1312
1241
    def test_secret_tempfile_short(self):
1313
1242
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
1315
1244
            f.write(value)
1316
1245
            f.seek(0)
1317
1246
            self.assert_command_from_args(["-s", f.name, "foo"],
1318
 
                                          command.SetSecret,
 
1247
                                          SetSecretCmd,
1319
1248
                                          value_to_set=value)
1320
1249
 
1321
1250
    def test_timeout(self):
1322
1251
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
1323
 
                                      command.SetTimeout,
 
1252
                                      SetTimeoutCmd,
1324
1253
                                      value_to_set=300000)
1325
1254
 
1326
1255
    def test_timeout_short(self):
1327
1256
        self.assert_command_from_args(["-t", "PT5M", "foo"],
1328
 
                                      command.SetTimeout,
 
1257
                                      SetTimeoutCmd,
1329
1258
                                      value_to_set=300000)
1330
1259
 
1331
1260
    def test_extended_timeout(self):
1332
1261
        self.assert_command_from_args(["--extended-timeout", "PT15M",
1333
1262
                                       "foo"],
1334
 
                                      command.SetExtendedTimeout,
 
1263
                                      SetExtendedTimeoutCmd,
1335
1264
                                      value_to_set=900000)
1336
1265
 
1337
1266
    def test_interval(self):
1338
1267
        self.assert_command_from_args(["--interval", "PT2M", "foo"],
1339
 
                                      command.SetInterval,
 
1268
                                      SetIntervalCmd,
1340
1269
                                      value_to_set=120000)
1341
1270
 
1342
1271
    def test_interval_short(self):
1343
1272
        self.assert_command_from_args(["-i", "PT2M", "foo"],
1344
 
                                      command.SetInterval,
 
1273
                                      SetIntervalCmd,
1345
1274
                                      value_to_set=120000)
1346
1275
 
1347
1276
    def test_approval_delay(self):
1348
1277
        self.assert_command_from_args(["--approval-delay", "PT30S",
1349
 
                                       "foo"],
1350
 
                                      command.SetApprovalDelay,
 
1278
                                       "foo"], SetApprovalDelayCmd,
1351
1279
                                      value_to_set=30000)
1352
1280
 
1353
1281
    def test_approval_duration(self):
1354
1282
        self.assert_command_from_args(["--approval-duration", "PT1S",
1355
 
                                       "foo"],
1356
 
                                      command.SetApprovalDuration,
 
1283
                                       "foo"], SetApprovalDurationCmd,
1357
1284
                                      value_to_set=1000)
1358
1285
 
1359
1286
    def test_print_table(self):
1360
 
        self.assert_command_from_args([], command.PrintTable,
 
1287
        self.assert_command_from_args([], PrintTableCmd,
1361
1288
                                      verbose=False)
1362
1289
 
1363
1290
    def test_print_table_verbose(self):
1364
 
        self.assert_command_from_args(["--verbose"],
1365
 
                                      command.PrintTable,
 
1291
        self.assert_command_from_args(["--verbose"], PrintTableCmd,
1366
1292
                                      verbose=True)
1367
1293
 
1368
1294
    def test_print_table_verbose_short(self):
1369
 
        self.assert_command_from_args(["-v"], command.PrintTable,
 
1295
        self.assert_command_from_args(["-v"], PrintTableCmd,
1370
1296
                                      verbose=True)
1371
1297
 
1372
1298
 
1373
 
class TestCommand(unittest.TestCase):
 
1299
class TestCmd(unittest.TestCase):
1374
1300
    """Abstract class for tests of command classes"""
1375
1301
 
1376
1302
    def setUp(self):
1386
1312
                testcase.assertEqual(dbus_interface,
1387
1313
                                     dbus.PROPERTIES_IFACE)
1388
1314
                self.attributes[propname] = value
 
1315
            def Get(self, interface, propname, dbus_interface):
 
1316
                testcase.assertEqual(interface, client_dbus_interface)
 
1317
                testcase.assertEqual(dbus_interface,
 
1318
                                     dbus.PROPERTIES_IFACE)
 
1319
                return self.attributes[propname]
1389
1320
            def Approve(self, approve, dbus_interface):
1390
1321
                testcase.assertEqual(dbus_interface,
1391
1322
                                     client_dbus_interface)
1461
1392
        return Bus()
1462
1393
 
1463
1394
 
1464
 
class TestBaseCommands(TestCommand):
 
1395
class TestIsEnabledCmd(TestCmd):
 
1396
    def test_is_enabled(self):
 
1397
        self.assertTrue(all(IsEnabledCmd().is_enabled(client,
 
1398
                                                      properties)
 
1399
                            for client, properties
 
1400
                            in self.clients.items()))
1465
1401
 
1466
 
    def test_IsEnabled_exits_successfully(self):
 
1402
    def test_is_enabled_run_exits_successfully(self):
1467
1403
        with self.assertRaises(SystemExit) as e:
1468
 
            command.IsEnabled().run(self.one_client)
 
1404
            IsEnabledCmd().run(self.one_client)
1469
1405
        if e.exception.code is not None:
1470
1406
            self.assertEqual(e.exception.code, 0)
1471
1407
        else:
1472
1408
            self.assertIsNone(e.exception.code)
1473
1409
 
1474
 
    def test_IsEnabled_exits_with_failure(self):
 
1410
    def test_is_enabled_run_exits_with_failure(self):
1475
1411
        self.client.attributes["Enabled"] = dbus.Boolean(False)
1476
1412
        with self.assertRaises(SystemExit) as e:
1477
 
            command.IsEnabled().run(self.one_client)
 
1413
            IsEnabledCmd().run(self.one_client)
1478
1414
        if isinstance(e.exception.code, int):
1479
1415
            self.assertNotEqual(e.exception.code, 0)
1480
1416
        else:
1481
1417
            self.assertIsNotNone(e.exception.code)
1482
1418
 
1483
 
    def test_Approve(self):
1484
 
        command.Approve().run(self.clients, self.bus)
 
1419
 
 
1420
class TestApproveCmd(TestCmd):
 
1421
    def test_approve(self):
 
1422
        ApproveCmd().run(self.clients, self.bus)
1485
1423
        for clientpath in self.clients:
1486
1424
            client = self.bus.get_object(dbus_busname, clientpath)
1487
1425
            self.assertIn(("Approve", (True, client_dbus_interface)),
1488
1426
                          client.calls)
1489
1427
 
1490
 
    def test_Deny(self):
1491
 
        command.Deny().run(self.clients, self.bus)
 
1428
 
 
1429
class TestDenyCmd(TestCmd):
 
1430
    def test_deny(self):
 
1431
        DenyCmd().run(self.clients, self.bus)
1492
1432
        for clientpath in self.clients:
1493
1433
            client = self.bus.get_object(dbus_busname, clientpath)
1494
1434
            self.assertIn(("Approve", (False, client_dbus_interface)),
1495
1435
                          client.calls)
1496
1436
 
1497
 
    def test_Remove(self):
 
1437
 
 
1438
class TestRemoveCmd(TestCmd):
 
1439
    def test_remove(self):
1498
1440
        class MockMandos(object):
1499
1441
            def __init__(self):
1500
1442
                self.calls = []
1501
1443
            def RemoveClient(self, dbus_path):
1502
1444
                self.calls.append(("RemoveClient", (dbus_path,)))
1503
1445
        mandos = MockMandos()
1504
 
        command.Remove().run(self.clients, self.bus, mandos)
 
1446
        super(TestRemoveCmd, self).setUp()
 
1447
        RemoveCmd().run(self.clients, self.bus, mandos)
 
1448
        self.assertEqual(len(mandos.calls), 2)
1505
1449
        for clientpath in self.clients:
1506
1450
            self.assertIn(("RemoveClient", (clientpath,)),
1507
1451
                          mandos.calls)
1508
1452
 
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())
 
1453
 
 
1454
class TestDumpJSONCmd(TestCmd):
 
1455
    def setUp(self):
 
1456
        self.expected_json = {
 
1457
            "foo": {
 
1458
                "Name": "foo",
 
1459
                "KeyID": ("92ed150794387c03ce684574b1139a65"
 
1460
                          "94a34f895daaaf09fd8ea90a27cddb12"),
 
1461
                "Host": "foo.example.org",
 
1462
                "Enabled": True,
 
1463
                "Timeout": 300000,
 
1464
                "LastCheckedOK": "2019-02-03T00:00:00",
 
1465
                "Created": "2019-01-02T00:00:00",
 
1466
                "Interval": 120000,
 
1467
                "Fingerprint": ("778827225BA7DE539C5A"
 
1468
                                "7CFA59CFF7CDBD9A5920"),
 
1469
                "CheckerRunning": False,
 
1470
                "LastEnabled": "2019-01-03T00:00:00",
 
1471
                "ApprovalPending": False,
 
1472
                "ApprovedByDefault": True,
 
1473
                "LastApprovalRequest": "",
 
1474
                "ApprovalDelay": 0,
 
1475
                "ApprovalDuration": 1000,
 
1476
                "Checker": "fping -q -- %(host)s",
 
1477
                "ExtendedTimeout": 900000,
 
1478
                "Expires": "2019-02-04T00:00:00",
 
1479
                "LastCheckerStatus": 0,
 
1480
            },
 
1481
            "barbar": {
 
1482
                "Name": "barbar",
 
1483
                "KeyID": ("0558568eedd67d622f5c83b35a115f79"
 
1484
                          "6ab612cff5ad227247e46c2b020f441c"),
 
1485
                "Host": "192.0.2.3",
 
1486
                "Enabled": True,
 
1487
                "Timeout": 300000,
 
1488
                "LastCheckedOK": "2019-02-04T00:00:00",
 
1489
                "Created": "2019-01-03T00:00:00",
 
1490
                "Interval": 120000,
 
1491
                "Fingerprint": ("3E393AEAEFB84C7E89E2"
 
1492
                                "F547B3A107558FCA3A27"),
 
1493
                "CheckerRunning": True,
 
1494
                "LastEnabled": "2019-01-04T00:00:00",
 
1495
                "ApprovalPending": False,
 
1496
                "ApprovedByDefault": False,
 
1497
                "LastApprovalRequest": "2019-01-03T00:00:00",
 
1498
                "ApprovalDelay": 30000,
 
1499
                "ApprovalDuration": 93785000,
 
1500
                "Checker": ":",
 
1501
                "ExtendedTimeout": 900000,
 
1502
                "Expires": "2019-02-05T00:00:00",
 
1503
                "LastCheckerStatus": -2,
 
1504
            },
 
1505
        }
 
1506
        return super(TestDumpJSONCmd, self).setUp()
 
1507
 
 
1508
    def test_normal(self):
 
1509
        output = DumpJSONCmd().output(self.clients.values())
1562
1510
        json_data = json.loads(output)
1563
1511
        self.assertDictEqual(json_data, self.expected_json)
1564
1512
 
1565
 
    def test_DumpJSON_one_client(self):
1566
 
        output = command.DumpJSON().output(self.one_client.values())
 
1513
    def test_one_client(self):
 
1514
        output = DumpJSONCmd().output(self.one_client.values())
1567
1515
        json_data = json.loads(output)
1568
1516
        expected_json = {"foo": self.expected_json["foo"]}
1569
1517
        self.assertDictEqual(json_data, expected_json)
1570
1518
 
1571
 
    def test_PrintTable_normal(self):
1572
 
        output = command.PrintTable().output(self.clients.values())
 
1519
 
 
1520
class TestPrintTableCmd(TestCmd):
 
1521
    def test_normal(self):
 
1522
        output = PrintTableCmd().output(self.clients.values())
1573
1523
        expected_output = "\n".join((
1574
1524
            "Name   Enabled Timeout  Last Successful Check",
1575
1525
            "foo    Yes     00:05:00 2019-02-03T00:00:00  ",
1577
1527
        ))
1578
1528
        self.assertEqual(output, expected_output)
1579
1529
 
1580
 
    def test_PrintTable_verbose(self):
1581
 
        output = command.PrintTable(verbose=True).output(
 
1530
    def test_verbose(self):
 
1531
        output = PrintTableCmd(verbose=True).output(
1582
1532
            self.clients.values())
1583
1533
        columns = (
1584
1534
            (
1672
1622
                                    for line in range(num_lines))
1673
1623
        self.assertEqual(output, expected_output)
1674
1624
 
1675
 
    def test_PrintTable_one_client(self):
1676
 
        output = command.PrintTable().output(self.one_client.values())
 
1625
    def test_one_client(self):
 
1626
        output = PrintTableCmd().output(self.one_client.values())
1677
1627
        expected_output = "\n".join((
1678
1628
            "Name Enabled Timeout  Last Successful Check",
1679
1629
            "foo  Yes     00:05:00 2019-02-03T00:00:00  ",
1681
1631
        self.assertEqual(output, expected_output)
1682
1632
 
1683
1633
 
1684
 
class TestPropertyCmd(TestCommand):
1685
 
    """Abstract class for tests of command.Property classes"""
 
1634
class TestPropertyCmd(TestCmd):
 
1635
    """Abstract class for tests of PropertyCmd classes"""
1686
1636
    def runTest(self):
1687
1637
        if not hasattr(self, "command"):
1688
1638
            return
1693
1643
            for clientpath in self.clients:
1694
1644
                client = self.bus.get_object(dbus_busname, clientpath)
1695
1645
                old_value = client.attributes[self.propname]
 
1646
                self.assertNotIsInstance(old_value, self.Unique)
1696
1647
                client.attributes[self.propname] = self.Unique()
1697
1648
            self.run_command(value_to_set, self.clients)
1698
1649
            for clientpath in self.clients:
1710
1661
 
1711
1662
 
1712
1663
class TestEnableCmd(TestPropertyCmd):
1713
 
    command = command.Enable
 
1664
    command = EnableCmd
1714
1665
    propname = "Enabled"
1715
1666
    values_to_set = [dbus.Boolean(True)]
1716
1667
 
1717
1668
 
1718
1669
class TestDisableCmd(TestPropertyCmd):
1719
 
    command = command.Disable
 
1670
    command = DisableCmd
1720
1671
    propname = "Enabled"
1721
1672
    values_to_set = [dbus.Boolean(False)]
1722
1673
 
1723
1674
 
1724
1675
class TestBumpTimeoutCmd(TestPropertyCmd):
1725
 
    command = command.BumpTimeout
 
1676
    command = BumpTimeoutCmd
1726
1677
    propname = "LastCheckedOK"
1727
1678
    values_to_set = [""]
1728
1679
 
1729
1680
 
1730
1681
class TestStartCheckerCmd(TestPropertyCmd):
1731
 
    command = command.StartChecker
 
1682
    command = StartCheckerCmd
1732
1683
    propname = "CheckerRunning"
1733
1684
    values_to_set = [dbus.Boolean(True)]
1734
1685
 
1735
1686
 
1736
1687
class TestStopCheckerCmd(TestPropertyCmd):
1737
 
    command = command.StopChecker
 
1688
    command = StopCheckerCmd
1738
1689
    propname = "CheckerRunning"
1739
1690
    values_to_set = [dbus.Boolean(False)]
1740
1691
 
1741
1692
 
1742
1693
class TestApproveByDefaultCmd(TestPropertyCmd):
1743
 
    command = command.ApproveByDefault
 
1694
    command = ApproveByDefaultCmd
1744
1695
    propname = "ApprovedByDefault"
1745
1696
    values_to_set = [dbus.Boolean(True)]
1746
1697
 
1747
1698
 
1748
1699
class TestDenyByDefaultCmd(TestPropertyCmd):
1749
 
    command = command.DenyByDefault
 
1700
    command = DenyByDefaultCmd
1750
1701
    propname = "ApprovedByDefault"
1751
1702
    values_to_set = [dbus.Boolean(False)]
1752
1703
 
1764
1715
 
1765
1716
 
1766
1717
class TestSetCheckerCmd(TestPropertyValueCmd):
1767
 
    command = command.SetChecker
 
1718
    command = SetCheckerCmd
1768
1719
    propname = "Checker"
1769
1720
    values_to_set = ["", ":", "fping -q -- %s"]
1770
1721
 
1771
1722
 
1772
1723
class TestSetHostCmd(TestPropertyValueCmd):
1773
 
    command = command.SetHost
 
1724
    command = SetHostCmd
1774
1725
    propname = "Host"
1775
1726
    values_to_set = ["192.0.2.3", "foo.example.org"]
1776
1727
 
1777
1728
 
1778
1729
class TestSetSecretCmd(TestPropertyValueCmd):
1779
 
    command = command.SetSecret
 
1730
    command = SetSecretCmd
1780
1731
    propname = "Secret"
1781
1732
    values_to_set = [io.BytesIO(b""),
1782
1733
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1784
1735
 
1785
1736
 
1786
1737
class TestSetTimeoutCmd(TestPropertyValueCmd):
1787
 
    command = command.SetTimeout
 
1738
    command = SetTimeoutCmd
1788
1739
    propname = "Timeout"
1789
1740
    values_to_set = [datetime.timedelta(),
1790
1741
                     datetime.timedelta(minutes=5),
1795
1746
 
1796
1747
 
1797
1748
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1798
 
    command = command.SetExtendedTimeout
 
1749
    command = SetExtendedTimeoutCmd
1799
1750
    propname = "ExtendedTimeout"
1800
1751
    values_to_set = [datetime.timedelta(),
1801
1752
                     datetime.timedelta(minutes=5),
1806
1757
 
1807
1758
 
1808
1759
class TestSetIntervalCmd(TestPropertyValueCmd):
1809
 
    command = command.SetInterval
 
1760
    command = SetIntervalCmd
1810
1761
    propname = "Interval"
1811
1762
    values_to_set = [datetime.timedelta(),
1812
1763
                     datetime.timedelta(minutes=5),
1817
1768
 
1818
1769
 
1819
1770
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1820
 
    command = command.SetApprovalDelay
 
1771
    command = SetApprovalDelayCmd
1821
1772
    propname = "ApprovalDelay"
1822
1773
    values_to_set = [datetime.timedelta(),
1823
1774
                     datetime.timedelta(minutes=5),
1828
1779
 
1829
1780
 
1830
1781
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1831
 
    command = command.SetApprovalDuration
 
1782
    command = SetApprovalDurationCmd
1832
1783
    propname = "ApprovalDuration"
1833
1784
    values_to_set = [datetime.timedelta(),
1834
1785
                     datetime.timedelta(minutes=5),