/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 16:48:56 UTC
  • Revision ID: teddy@recompile.se-20190317164856-de11glvsfwhnj34w
mandos-ctl: Refactor tests

* mandos-ctl (Test_string_to_delta.test_handles_basic_rfc3339): Split
                                                  into multiple tests.
  (Test_string_to_delta.test_rfc3339_zero_seconds): New.
  (Test_string_to_delta.test_rfc3339_zero_days): - '' -
  (Test_string_to_delta.test_rfc3339_one_second): - '' -
  (Test_string_to_delta.test_rfc3339_two_hours): - '' -
  (TestCommand.setUp.MockClient.Get): Remove; unused.
  (TestBaseCommands.test_Remove): Remove unnecessary assertion.
  (TestPropertyCmd.runTest): - '' -

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