/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 05:49:56 UTC
  • Revision ID: teddy@recompile.se-20190316054956-ikjmjulma6jea5fa
mandos-ctl: Refactor and fix bug in tests.

* mandos-ctl (Test_check_option_syntax): Refactor and add more tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
61
61
 
62
62
if sys.version_info.major == 2:
63
63
    str = unicode
64
 
    import StringIO
65
 
    io.StringIO = StringIO.StringIO
66
64
 
67
65
locale.setlocale(locale.LC_ALL, "")
68
66
 
83
81
 
84
82
def main():
85
83
    parser = argparse.ArgumentParser()
 
84
 
86
85
    add_command_line_options(parser)
87
86
 
88
87
    options = parser.parse_args()
 
88
 
89
89
    check_option_syntax(parser, options)
90
90
 
91
91
    clientnames = options.client
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
460
460
 
461
461
    def __enter__(self):
462
462
        self.logger.addFilter(self.nullfilter)
 
463
        return self
463
464
 
464
465
    class NullFilter(logging.Filter):
465
466
        def filter(self, record):
476
477
    commands = []
477
478
 
478
479
    if options.is_enabled:
479
 
        commands.append(command.IsEnabled())
 
480
        commands.append(IsEnabledCmd())
480
481
 
481
482
    if options.approve:
482
 
        commands.append(command.Approve())
 
483
        commands.append(ApproveCmd())
483
484
 
484
485
    if options.deny:
485
 
        commands.append(command.Deny())
 
486
        commands.append(DenyCmd())
486
487
 
487
488
    if options.remove:
488
 
        commands.append(command.Remove())
 
489
        commands.append(RemoveCmd())
489
490
 
490
491
    if options.dump_json:
491
 
        commands.append(command.DumpJSON())
 
492
        commands.append(DumpJSONCmd())
492
493
 
493
494
    if options.enable:
494
 
        commands.append(command.Enable())
 
495
        commands.append(EnableCmd())
495
496
 
496
497
    if options.disable:
497
 
        commands.append(command.Disable())
 
498
        commands.append(DisableCmd())
498
499
 
499
500
    if options.bump_timeout:
500
 
        commands.append(command.BumpTimeout())
 
501
        commands.append(BumpTimeoutCmd())
501
502
 
502
503
    if options.start_checker:
503
 
        commands.append(command.StartChecker())
 
504
        commands.append(StartCheckerCmd())
504
505
 
505
506
    if options.stop_checker:
506
 
        commands.append(command.StopChecker())
 
507
        commands.append(StopCheckerCmd())
507
508
 
508
509
    if options.approved_by_default is not None:
509
510
        if options.approved_by_default:
510
 
            commands.append(command.ApproveByDefault())
 
511
            commands.append(ApproveByDefaultCmd())
511
512
        else:
512
 
            commands.append(command.DenyByDefault())
 
513
            commands.append(DenyByDefaultCmd())
513
514
 
514
515
    if options.checker is not None:
515
 
        commands.append(command.SetChecker(options.checker))
 
516
        commands.append(SetCheckerCmd(options.checker))
516
517
 
517
518
    if options.host is not None:
518
 
        commands.append(command.SetHost(options.host))
 
519
        commands.append(SetHostCmd(options.host))
519
520
 
520
521
    if options.secret is not None:
521
 
        commands.append(command.SetSecret(options.secret))
 
522
        commands.append(SetSecretCmd(options.secret))
522
523
 
523
524
    if options.timeout is not None:
524
 
        commands.append(command.SetTimeout(options.timeout))
 
525
        commands.append(SetTimeoutCmd(options.timeout))
525
526
 
526
527
    if options.extended_timeout:
527
528
        commands.append(
528
 
            command.SetExtendedTimeout(options.extended_timeout))
 
529
            SetExtendedTimeoutCmd(options.extended_timeout))
529
530
 
530
531
    if options.interval is not None:
531
 
        commands.append(command.SetInterval(options.interval))
 
532
        commands.append(SetIntervalCmd(options.interval))
532
533
 
533
534
    if options.approval_delay is not None:
534
 
        commands.append(
535
 
            command.SetApprovalDelay(options.approval_delay))
 
535
        commands.append(SetApprovalDelayCmd(options.approval_delay))
536
536
 
537
537
    if options.approval_duration is not None:
538
538
        commands.append(
539
 
            command.SetApprovalDuration(options.approval_duration))
 
539
            SetApprovalDurationCmd(options.approval_duration))
540
540
 
541
541
    # If no command option has been given, show table of clients,
542
542
    # optionally verbosely
543
543
    if not commands:
544
 
        commands.append(command.PrintTable(verbose=options.verbose))
 
544
        commands.append(PrintTableCmd(verbose=options.verbose))
545
545
 
546
546
    return commands
547
547
 
548
548
 
549
 
class command(object):
550
 
    """A namespace for command classes"""
551
 
 
552
 
    class Base(object):
553
 
        """Abstract base class for commands"""
554
 
        def run(self, clients, bus=None, mandos=None):
555
 
            """Normal commands should implement run_on_one_client(),
556
 
but commands which want to operate on all clients at the same time can
557
 
override this run() method instead.
558
 
"""
559
 
            for clientpath, properties in clients.items():
560
 
                log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
561
 
                          dbus_busname, str(clientpath))
562
 
                client = bus.get_object(dbus_busname, clientpath)
563
 
                self.run_on_one_client(client, properties)
564
 
 
565
 
 
566
 
    class IsEnabled(Base):
567
 
        def run(self, clients, bus=None, mandos=None):
568
 
            client, properties = next(iter(clients.items()))
569
 
            if self.is_enabled(client, properties):
570
 
                sys.exit(0)
571
 
            sys.exit(1)
572
 
        def is_enabled(self, client, properties):
573
 
            return properties["Enabled"]
574
 
 
575
 
 
576
 
    class Approve(Base):
577
 
        def run_on_one_client(self, client, properties):
578
 
            log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
579
 
                      client.__dbus_object_path__,
580
 
                      client_dbus_interface)
581
 
            client.Approve(dbus.Boolean(True),
582
 
                           dbus_interface=client_dbus_interface)
583
 
 
584
 
 
585
 
    class Deny(Base):
586
 
        def run_on_one_client(self, client, properties):
587
 
            log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
588
 
                      client.__dbus_object_path__,
589
 
                      client_dbus_interface)
590
 
            client.Approve(dbus.Boolean(False),
591
 
                           dbus_interface=client_dbus_interface)
592
 
 
593
 
 
594
 
    class Remove(Base):
595
 
        def run(self, clients, bus, mandos):
596
 
            for clientpath in clients.keys():
597
 
                log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)",
598
 
                          dbus_busname, server_dbus_path,
599
 
                          server_dbus_interface, clientpath)
600
 
                mandos.RemoveClient(clientpath)
601
 
 
602
 
 
603
 
    class Output(Base):
604
 
        """Abstract class for commands outputting client details"""
605
 
        all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
606
 
                        "Created", "Interval", "Host", "KeyID",
607
 
                        "Fingerprint", "CheckerRunning",
608
 
                        "LastEnabled", "ApprovalPending",
609
 
                        "ApprovedByDefault", "LastApprovalRequest",
610
 
                        "ApprovalDelay", "ApprovalDuration",
611
 
                        "Checker", "ExtendedTimeout", "Expires",
612
 
                        "LastCheckerStatus")
613
 
 
614
 
 
615
 
    class DumpJSON(Output):
616
 
        def run(self, clients, bus=None, mandos=None):
617
 
            data = {client["Name"]:
618
 
                    {key: self.dbus_boolean_to_bool(client[key])
619
 
                     for key in self.all_keywords}
620
 
                    for client in clients.values()}
621
 
            print(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})
622
712
 
623
713
        @staticmethod
624
 
        def dbus_boolean_to_bool(value):
625
 
            if isinstance(value, dbus.Boolean):
626
 
                value = bool(value)
627
 
            return value
628
 
 
629
 
 
630
 
    class PrintTable(Output):
631
 
        def __init__(self, verbose=False):
632
 
            self.verbose = verbose
633
 
 
634
 
        def run(self, clients, bus=None, mandos=None):
635
 
            default_keywords = ("Name", "Enabled", "Timeout",
636
 
                                "LastCheckedOK")
637
 
            keywords = default_keywords
638
 
            if self.verbose:
639
 
                keywords = self.all_keywords
640
 
            print(self.TableOfClients(clients.values(), keywords))
641
 
 
642
 
        class TableOfClients(object):
643
 
            tableheaders = {
644
 
                "Name": "Name",
645
 
                "Enabled": "Enabled",
646
 
                "Timeout": "Timeout",
647
 
                "LastCheckedOK": "Last Successful Check",
648
 
                "LastApprovalRequest": "Last Approval Request",
649
 
                "Created": "Created",
650
 
                "Interval": "Interval",
651
 
                "Host": "Host",
652
 
                "Fingerprint": "Fingerprint",
653
 
                "KeyID": "Key ID",
654
 
                "CheckerRunning": "Check Is Running",
655
 
                "LastEnabled": "Last Enabled",
656
 
                "ApprovalPending": "Approval Is Pending",
657
 
                "ApprovedByDefault": "Approved By Default",
658
 
                "ApprovalDelay": "Approval Delay",
659
 
                "ApprovalDuration": "Approval Duration",
660
 
                "Checker": "Checker",
661
 
                "ExtendedTimeout": "Extended Timeout",
662
 
                "Expires": "Expires",
663
 
                "LastCheckerStatus": "Last Checker Status",
664
 
            }
665
 
 
666
 
            def __init__(self, clients, keywords):
667
 
                self.clients = clients
668
 
                self.keywords = keywords
669
 
 
670
 
            def __str__(self):
671
 
                return "\n".join(self.rows())
672
 
 
673
 
            if sys.version_info.major == 2:
674
 
                __unicode__ = __str__
675
 
                def __str__(self):
676
 
                    return str(self).encode(
677
 
                        locale.getpreferredencoding())
678
 
 
679
 
            def rows(self):
680
 
                format_string = self.row_formatting_string()
681
 
                rows = [self.header_line(format_string)]
682
 
                rows.extend(self.client_line(client, format_string)
683
 
                            for client in self.clients)
684
 
                return rows
685
 
 
686
 
            def row_formatting_string(self):
687
 
                "Format string used to format table rows"
688
 
                return " ".join("{{{key}:{width}}}".format(
689
 
                    width=max(len(self.tableheaders[key]),
690
 
                              *(len(self.string_from_client(client,
691
 
                                                            key))
692
 
                                for client in self.clients)),
693
 
                    key=key)
694
 
                                for key in self.keywords)
695
 
 
696
 
            def string_from_client(self, client, key):
697
 
                return self.valuetostring(client[key], key)
698
 
 
699
 
            @classmethod
700
 
            def valuetostring(cls, value, keyword):
701
 
                if isinstance(value, dbus.Boolean):
702
 
                    return "Yes" if value else "No"
703
 
                if keyword in ("Timeout", "Interval", "ApprovalDelay",
704
 
                               "ApprovalDuration", "ExtendedTimeout"):
705
 
                    return cls.milliseconds_to_string(value)
706
 
                return str(value)
707
 
 
708
 
            def header_line(self, format_string):
709
 
                return format_string.format(**self.tableheaders)
710
 
 
711
 
            def client_line(self, client, format_string):
712
 
                return format_string.format(
713
 
                    **{key: self.string_from_client(client, key)
714
 
                       for key in self.keywords})
715
 
 
716
 
            @staticmethod
717
 
            def milliseconds_to_string(ms):
718
 
                td = datetime.timedelta(0, 0, 0, ms)
719
 
                return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
720
 
                        .format(days="{}T".format(td.days)
721
 
                                if td.days else "",
722
 
                                hours=td.seconds // 3600,
723
 
                                minutes=(td.seconds % 3600) // 60,
724
 
                                seconds=td.seconds % 60))
725
 
 
726
 
 
727
 
    class PropertySetter(Base):
728
 
        "Abstract class for Actions for setting one client property"
729
 
 
730
 
        def run_on_one_client(self, client, properties):
731
 
            """Set the Client's D-Bus property"""
732
 
            log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
733
 
                      client.__dbus_object_path__,
734
 
                      dbus.PROPERTIES_IFACE, client_dbus_interface,
735
 
                      self.propname, self.value_to_set
736
 
                      if not isinstance(self.value_to_set,
737
 
                                        dbus.Boolean)
738
 
                      else bool(self.value_to_set))
739
 
            client.Set(client_dbus_interface, self.propname,
740
 
                       self.value_to_set,
741
 
                       dbus_interface=dbus.PROPERTIES_IFACE)
742
 
 
743
 
        @property
744
 
        def propname(self):
745
 
            raise NotImplementedError()
746
 
 
747
 
 
748
 
    class Enable(PropertySetter):
749
 
        propname = "Enabled"
750
 
        value_to_set = dbus.Boolean(True)
751
 
 
752
 
 
753
 
    class Disable(PropertySetter):
754
 
        propname = "Enabled"
755
 
        value_to_set = dbus.Boolean(False)
756
 
 
757
 
 
758
 
    class BumpTimeout(PropertySetter):
759
 
        propname = "LastCheckedOK"
760
 
        value_to_set = ""
761
 
 
762
 
 
763
 
    class StartChecker(PropertySetter):
764
 
        propname = "CheckerRunning"
765
 
        value_to_set = dbus.Boolean(True)
766
 
 
767
 
 
768
 
    class StopChecker(PropertySetter):
769
 
        propname = "CheckerRunning"
770
 
        value_to_set = dbus.Boolean(False)
771
 
 
772
 
 
773
 
    class ApproveByDefault(PropertySetter):
774
 
        propname = "ApprovedByDefault"
775
 
        value_to_set = dbus.Boolean(True)
776
 
 
777
 
 
778
 
    class DenyByDefault(PropertySetter):
779
 
        propname = "ApprovedByDefault"
780
 
        value_to_set = dbus.Boolean(False)
781
 
 
782
 
 
783
 
    class PropertySetterValue(PropertySetter):
784
 
        """Abstract class for PropertySetter recieving a value as
785
 
constructor argument instead of a class attribute."""
786
 
        def __init__(self, value):
787
 
            self.value_to_set = value
788
 
 
789
 
 
790
 
    class SetChecker(PropertySetterValue):
791
 
        propname = "Checker"
792
 
 
793
 
 
794
 
    class SetHost(PropertySetterValue):
795
 
        propname = "Host"
796
 
 
797
 
 
798
 
    class SetSecret(PropertySetterValue):
799
 
        propname = "Secret"
800
 
 
801
 
        @property
802
 
        def value_to_set(self):
803
 
            return self._vts
804
 
 
805
 
        @value_to_set.setter
806
 
        def value_to_set(self, value):
807
 
            """When setting, read data from supplied file object"""
808
 
            self._vts = value.read()
809
 
            value.close()
810
 
 
811
 
 
812
 
    class PropertySetterValueMilliseconds(PropertySetterValue):
813
 
        """Abstract class for PropertySetterValue taking a value
814
 
argument as a datetime.timedelta() but should store it as
815
 
milliseconds."""
816
 
 
817
 
        @property
818
 
        def value_to_set(self):
819
 
            return self._vts
820
 
 
821
 
        @value_to_set.setter
822
 
        def value_to_set(self, value):
823
 
            "When setting, convert value from a datetime.timedelta"
824
 
            self._vts = int(round(value.total_seconds() * 1000))
825
 
 
826
 
 
827
 
    class SetTimeout(PropertySetterValueMilliseconds):
828
 
        propname = "Timeout"
829
 
 
830
 
 
831
 
    class SetExtendedTimeout(PropertySetterValueMilliseconds):
832
 
        propname = "ExtendedTimeout"
833
 
 
834
 
 
835
 
    class SetInterval(PropertySetterValueMilliseconds):
836
 
        propname = "Interval"
837
 
 
838
 
 
839
 
    class SetApprovalDelay(PropertySetterValueMilliseconds):
840
 
        propname = "ApprovalDelay"
841
 
 
842
 
 
843
 
    class SetApprovalDuration(PropertySetterValueMilliseconds):
844
 
        propname = "ApprovalDuration"
 
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
 
809
a datetime.timedelta() but should store it as milliseconds."""
 
810
 
 
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"
845
839
 
846
840
 
847
841
 
878
872
                                                    ("records",
879
873
                                                     "output"))
880
874
 
881
 
 
882
875
class Test_string_to_delta(TestCaseWithAssertLogs):
883
 
    # Just test basic RFC 3339 functionality here, the doc string for
884
 
    # rfc3339_duration_to_delta() already has more comprehensive
885
 
    # tests, which is run by doctest.
886
 
 
887
 
    def test_rfc3339_zero_seconds(self):
888
 
        self.assertEqual(datetime.timedelta(),
889
 
                         string_to_delta("PT0S"))
890
 
 
891
 
    def test_rfc3339_zero_days(self):
892
 
        self.assertEqual(datetime.timedelta(), string_to_delta("P0D"))
893
 
 
894
 
    def test_rfc3339_one_second(self):
895
 
        self.assertEqual(datetime.timedelta(0, 1),
896
 
                         string_to_delta("PT1S"))
897
 
 
898
 
    def test_rfc3339_two_hours(self):
899
 
        self.assertEqual(datetime.timedelta(0, 7200),
900
 
                         string_to_delta("PT2H"))
 
876
    def test_handles_basic_rfc3339(self):
 
877
        self.assertEqual(string_to_delta("PT0S"),
 
878
                         datetime.timedelta())
 
879
        self.assertEqual(string_to_delta("P0D"),
 
880
                         datetime.timedelta())
 
881
        self.assertEqual(string_to_delta("PT1S"),
 
882
                         datetime.timedelta(0, 1))
 
883
        self.assertEqual(string_to_delta("PT2H"),
 
884
                         datetime.timedelta(0, 7200))
901
885
 
902
886
    def test_falls_back_to_pre_1_6_1_with_warning(self):
903
887
        with self.assertLogs(log, logging.WARNING):
904
888
            value = string_to_delta("2h")
905
 
        self.assertEqual(datetime.timedelta(0, 7200), value)
 
889
        self.assertEqual(value, datetime.timedelta(0, 7200))
906
890
 
907
891
 
908
892
class Test_check_option_syntax(unittest.TestCase):
946
930
    @contextlib.contextmanager
947
931
    def assertParseError(self):
948
932
        with self.assertRaises(SystemExit) as e:
949
 
            with self.redirect_stderr_to_devnull():
 
933
            with self.temporarily_suppress_stderr():
950
934
                yield
951
935
        # Exit code from argparse is guaranteed to be "2".  Reference:
952
936
        # https://docs.python.org/3/library
953
937
        # /argparse.html#exiting-methods
954
 
        self.assertEqual(2, e.exception.code)
 
938
        self.assertEqual(e.exception.code, 2)
955
939
 
956
940
    @staticmethod
957
941
    @contextlib.contextmanager
958
 
    def redirect_stderr_to_devnull():
959
 
        old_stderr = sys.stderr
960
 
        with contextlib.closing(open(os.devnull, "w")) as null:
961
 
            sys.stderr = null
962
 
            try:
963
 
                yield
964
 
            finally:
965
 
                sys.stderr = old_stderr
 
942
    def temporarily_suppress_stderr():
 
943
        null = os.open(os.path.devnull, os.O_RDWR)
 
944
        stderrcopy = os.dup(sys.stderr.fileno())
 
945
        os.dup2(null, sys.stderr.fileno())
 
946
        os.close(null)
 
947
        try:
 
948
            yield
 
949
        finally:
 
950
            # restore stderr
 
951
            os.dup2(stderrcopy, sys.stderr.fileno())
 
952
            os.close(stderrcopy)
966
953
 
967
954
    def check_option_syntax(self, options):
968
955
        check_option_syntax(self.parser, options)
981
968
            options = self.parser.parse_args()
982
969
            setattr(options, action, value)
983
970
            options.verbose = True
984
 
            options.client = ["client"]
 
971
            options.client = ["foo"]
985
972
            with self.assertParseError():
986
973
                self.check_option_syntax(options)
987
974
 
1017
1004
        for action, value in self.actions.items():
1018
1005
            options = self.parser.parse_args()
1019
1006
            setattr(options, action, value)
1020
 
            options.client = ["client"]
 
1007
            options.client = ["foo"]
1021
1008
            self.check_option_syntax(options)
1022
1009
 
1023
 
    def test_one_client_with_all_actions_except_is_enabled(self):
1024
 
        options = self.parser.parse_args()
1025
 
        for action, value in self.actions.items():
1026
 
            if action == "is_enabled":
1027
 
                continue
1028
 
            setattr(options, action, value)
1029
 
        options.client = ["client"]
1030
 
        self.check_option_syntax(options)
1031
 
 
1032
 
    def test_two_clients_with_all_actions_except_is_enabled(self):
1033
 
        options = self.parser.parse_args()
1034
 
        for action, value in self.actions.items():
1035
 
            if action == "is_enabled":
1036
 
                continue
1037
 
            setattr(options, action, value)
1038
 
        options.client = ["client1", "client2"]
1039
 
        self.check_option_syntax(options)
1040
 
 
1041
 
    def test_two_clients_are_ok_with_actions_except_is_enabled(self):
 
1010
    def test_actions_except_is_enabled_are_ok_with_two_clients(self):
1042
1011
        for action, value in self.actions.items():
1043
1012
            if action == "is_enabled":
1044
1013
                continue
1045
1014
            options = self.parser.parse_args()
1046
1015
            setattr(options, action, value)
1047
 
            options.client = ["client1", "client2"]
 
1016
            options.client = ["foo", "barbar"]
1048
1017
            self.check_option_syntax(options)
1049
1018
 
1050
1019
    def test_is_enabled_fails_without_client(self):
1056
1025
    def test_is_enabled_fails_with_two_clients(self):
1057
1026
        options = self.parser.parse_args()
1058
1027
        options.is_enabled = True
1059
 
        options.client = ["client1", "client2"]
 
1028
        options.client = ["foo", "barbar"]
1060
1029
        with self.assertParseError():
1061
1030
            self.check_option_syntax(options)
1062
1031
 
1079
1048
            def get_object(mockbus_self, busname, dbus_path):
1080
1049
                # Note that "self" is still the testcase instance,
1081
1050
                # this MockBus instance is in "mockbus_self".
1082
 
                self.assertEqual(dbus_busname, busname)
1083
 
                self.assertEqual(server_dbus_path, dbus_path)
 
1051
                self.assertEqual(busname, dbus_busname)
 
1052
                self.assertEqual(dbus_path, server_dbus_path)
1084
1053
                mockbus_self.called = True
1085
1054
                return mockbus_self
1086
1055
 
1089
1058
        self.assertTrue(mockbus.called)
1090
1059
 
1091
1060
    def test_logs_and_exits_on_dbus_error(self):
1092
 
        class FailingBusStub(object):
 
1061
        class MockBusFailing(object):
1093
1062
            def get_object(self, busname, dbus_path):
1094
1063
                raise dbus.exceptions.DBusException("Test")
1095
1064
 
1096
1065
        with self.assertLogs(log, logging.CRITICAL):
1097
1066
            with self.assertRaises(SystemExit) as e:
1098
 
                bus = get_mandos_dbus_object(bus=FailingBusStub())
 
1067
                bus = get_mandos_dbus_object(bus=MockBusFailing())
1099
1068
 
1100
1069
        if isinstance(e.exception.code, int):
1101
 
            self.assertNotEqual(0, e.exception.code)
 
1070
            self.assertNotEqual(e.exception.code, 0)
1102
1071
        else:
1103
1072
            self.assertIsNotNone(e.exception.code)
1104
1073
 
1105
1074
 
1106
1075
class Test_get_managed_objects(TestCaseWithAssertLogs):
1107
1076
    def test_calls_and_returns_GetManagedObjects(self):
1108
 
        managed_objects = {"/clients/client": { "Name": "client"}}
1109
 
        class ObjectManagerStub(object):
 
1077
        managed_objects = {"/clients/foo": { "Name": "foo"}}
 
1078
        class MockObjectManager(object):
1110
1079
            def GetManagedObjects(self):
1111
1080
                return managed_objects
1112
 
        retval = get_managed_objects(ObjectManagerStub())
 
1081
        retval = get_managed_objects(MockObjectManager())
1113
1082
        self.assertDictEqual(managed_objects, retval)
1114
1083
 
1115
1084
    def test_logs_and_exits_on_dbus_error(self):
1116
1085
        dbus_logger = logging.getLogger("dbus.proxies")
1117
1086
 
1118
 
        class ObjectManagerFailingStub(object):
 
1087
        class MockObjectManagerFailing(object):
1119
1088
            def GetManagedObjects(self):
1120
1089
                dbus_logger.error("Test")
1121
1090
                raise dbus.exceptions.DBusException("Test")
1132
1101
        try:
1133
1102
            with self.assertLogs(log, logging.CRITICAL) as watcher:
1134
1103
                with self.assertRaises(SystemExit) as e:
1135
 
                    get_managed_objects(ObjectManagerFailingStub())
 
1104
                    get_managed_objects(MockObjectManagerFailing())
1136
1105
        finally:
1137
1106
            dbus_logger.removeFilter(counting_handler)
1138
1107
 
1139
1108
        # Make sure the dbus logger was suppressed
1140
 
        self.assertEqual(0, counting_handler.count)
 
1109
        self.assertEqual(counting_handler.count, 0)
1141
1110
 
1142
1111
        # Test that the dbus_logger still works
1143
1112
        with self.assertLogs(dbus_logger, logging.ERROR):
1144
1113
            dbus_logger.error("Test")
1145
1114
 
1146
1115
        if isinstance(e.exception.code, int):
1147
 
            self.assertNotEqual(0, e.exception.code)
 
1116
            self.assertNotEqual(e.exception.code, 0)
1148
1117
        else:
1149
1118
            self.assertIsNotNone(e.exception.code)
1150
1119
 
1155
1124
        add_command_line_options(self.parser)
1156
1125
 
1157
1126
    def test_is_enabled(self):
1158
 
        self.assert_command_from_args(["--is-enabled", "client"],
1159
 
                                      command.IsEnabled)
 
1127
        self.assert_command_from_args(["--is-enabled", "foo"],
 
1128
                                      IsEnabledCmd)
1160
1129
 
1161
1130
    def assert_command_from_args(self, args, command_cls,
1162
1131
                                 **cmd_attrs):
1165
1134
        options = self.parser.parse_args(args)
1166
1135
        check_option_syntax(self.parser, options)
1167
1136
        commands = commands_from_options(options)
1168
 
        self.assertEqual(1, len(commands))
 
1137
        self.assertEqual(len(commands), 1)
1169
1138
        command = commands[0]
1170
1139
        self.assertIsInstance(command, command_cls)
1171
1140
        for key, value in cmd_attrs.items():
1172
 
            self.assertEqual(value, getattr(command, key))
 
1141
            self.assertEqual(getattr(command, key), value)
1173
1142
 
1174
1143
    def test_is_enabled_short(self):
1175
 
        self.assert_command_from_args(["-V", "client"],
1176
 
                                      command.IsEnabled)
 
1144
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1177
1145
 
1178
1146
    def test_approve(self):
1179
 
        self.assert_command_from_args(["--approve", "client"],
1180
 
                                      command.Approve)
 
1147
        self.assert_command_from_args(["--approve", "foo"],
 
1148
                                      ApproveCmd)
1181
1149
 
1182
1150
    def test_approve_short(self):
1183
 
        self.assert_command_from_args(["-A", "client"],
1184
 
                                      command.Approve)
 
1151
        self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1185
1152
 
1186
1153
    def test_deny(self):
1187
 
        self.assert_command_from_args(["--deny", "client"],
1188
 
                                      command.Deny)
 
1154
        self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1189
1155
 
1190
1156
    def test_deny_short(self):
1191
 
        self.assert_command_from_args(["-D", "client"], command.Deny)
 
1157
        self.assert_command_from_args(["-D", "foo"], DenyCmd)
1192
1158
 
1193
1159
    def test_remove(self):
1194
 
        self.assert_command_from_args(["--remove", "client"],
1195
 
                                      command.Remove)
 
1160
        self.assert_command_from_args(["--remove", "foo"],
 
1161
                                      RemoveCmd)
1196
1162
 
1197
1163
    def test_deny_before_remove(self):
1198
1164
        options = self.parser.parse_args(["--deny", "--remove",
1199
 
                                          "client"])
 
1165
                                          "foo"])
1200
1166
        check_option_syntax(self.parser, options)
1201
1167
        commands = commands_from_options(options)
1202
 
        self.assertEqual(2, len(commands))
1203
 
        self.assertIsInstance(commands[0], command.Deny)
1204
 
        self.assertIsInstance(commands[1], command.Remove)
 
1168
        self.assertEqual(len(commands), 2)
 
1169
        self.assertIsInstance(commands[0], DenyCmd)
 
1170
        self.assertIsInstance(commands[1], RemoveCmd)
1205
1171
 
1206
1172
    def test_deny_before_remove_reversed(self):
1207
1173
        options = self.parser.parse_args(["--remove", "--deny",
1208
1174
                                          "--all"])
1209
1175
        check_option_syntax(self.parser, options)
1210
1176
        commands = commands_from_options(options)
1211
 
        self.assertEqual(2, len(commands))
1212
 
        self.assertIsInstance(commands[0], command.Deny)
1213
 
        self.assertIsInstance(commands[1], command.Remove)
 
1177
        self.assertEqual(len(commands), 2)
 
1178
        self.assertIsInstance(commands[0], DenyCmd)
 
1179
        self.assertIsInstance(commands[1], RemoveCmd)
1214
1180
 
1215
1181
    def test_remove_short(self):
1216
 
        self.assert_command_from_args(["-r", "client"],
1217
 
                                      command.Remove)
 
1182
        self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1218
1183
 
1219
1184
    def test_dump_json(self):
1220
 
        self.assert_command_from_args(["--dump-json"],
1221
 
                                      command.DumpJSON)
 
1185
        self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1222
1186
 
1223
1187
    def test_enable(self):
1224
 
        self.assert_command_from_args(["--enable", "client"],
1225
 
                                      command.Enable)
 
1188
        self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1226
1189
 
1227
1190
    def test_enable_short(self):
1228
 
        self.assert_command_from_args(["-e", "client"],
1229
 
                                      command.Enable)
 
1191
        self.assert_command_from_args(["-e", "foo"], EnableCmd)
1230
1192
 
1231
1193
    def test_disable(self):
1232
 
        self.assert_command_from_args(["--disable", "client"],
1233
 
                                      command.Disable)
 
1194
        self.assert_command_from_args(["--disable", "foo"],
 
1195
                                      DisableCmd)
1234
1196
 
1235
1197
    def test_disable_short(self):
1236
 
        self.assert_command_from_args(["-d", "client"],
1237
 
                                      command.Disable)
 
1198
        self.assert_command_from_args(["-d", "foo"], DisableCmd)
1238
1199
 
1239
1200
    def test_bump_timeout(self):
1240
 
        self.assert_command_from_args(["--bump-timeout", "client"],
1241
 
                                      command.BumpTimeout)
 
1201
        self.assert_command_from_args(["--bump-timeout", "foo"],
 
1202
                                      BumpTimeoutCmd)
1242
1203
 
1243
1204
    def test_bump_timeout_short(self):
1244
 
        self.assert_command_from_args(["-b", "client"],
1245
 
                                      command.BumpTimeout)
 
1205
        self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1246
1206
 
1247
1207
    def test_start_checker(self):
1248
 
        self.assert_command_from_args(["--start-checker", "client"],
1249
 
                                      command.StartChecker)
 
1208
        self.assert_command_from_args(["--start-checker", "foo"],
 
1209
                                      StartCheckerCmd)
1250
1210
 
1251
1211
    def test_stop_checker(self):
1252
 
        self.assert_command_from_args(["--stop-checker", "client"],
1253
 
                                      command.StopChecker)
 
1212
        self.assert_command_from_args(["--stop-checker", "foo"],
 
1213
                                      StopCheckerCmd)
1254
1214
 
1255
1215
    def test_approve_by_default(self):
1256
 
        self.assert_command_from_args(["--approve-by-default",
1257
 
                                       "client"],
1258
 
                                      command.ApproveByDefault)
 
1216
        self.assert_command_from_args(["--approve-by-default", "foo"],
 
1217
                                      ApproveByDefaultCmd)
1259
1218
 
1260
1219
    def test_deny_by_default(self):
1261
 
        self.assert_command_from_args(["--deny-by-default", "client"],
1262
 
                                      command.DenyByDefault)
 
1220
        self.assert_command_from_args(["--deny-by-default", "foo"],
 
1221
                                      DenyByDefaultCmd)
1263
1222
 
1264
1223
    def test_checker(self):
1265
 
        self.assert_command_from_args(["--checker", ":", "client"],
1266
 
                                      command.SetChecker,
1267
 
                                      value_to_set=":")
 
1224
        self.assert_command_from_args(["--checker", ":", "foo"],
 
1225
                                      SetCheckerCmd, value_to_set=":")
1268
1226
 
1269
1227
    def test_checker_empty(self):
1270
 
        self.assert_command_from_args(["--checker", "", "client"],
1271
 
                                      command.SetChecker,
1272
 
                                      value_to_set="")
 
1228
        self.assert_command_from_args(["--checker", "", "foo"],
 
1229
                                      SetCheckerCmd, value_to_set="")
1273
1230
 
1274
1231
    def test_checker_short(self):
1275
 
        self.assert_command_from_args(["-c", ":", "client"],
1276
 
                                      command.SetChecker,
1277
 
                                      value_to_set=":")
 
1232
        self.assert_command_from_args(["-c", ":", "foo"],
 
1233
                                      SetCheckerCmd, value_to_set=":")
1278
1234
 
1279
1235
    def test_host(self):
1280
 
        self.assert_command_from_args(
1281
 
            ["--host", "client.example.org", "client"],
1282
 
            command.SetHost, value_to_set="client.example.org")
 
1236
        self.assert_command_from_args(["--host", "foo.example.org",
 
1237
                                       "foo"], SetHostCmd,
 
1238
                                      value_to_set="foo.example.org")
1283
1239
 
1284
1240
    def test_host_short(self):
1285
 
        self.assert_command_from_args(
1286
 
            ["-H", "client.example.org", "client"], command.SetHost,
1287
 
            value_to_set="client.example.org")
 
1241
        self.assert_command_from_args(["-H", "foo.example.org",
 
1242
                                       "foo"], SetHostCmd,
 
1243
                                      value_to_set="foo.example.org")
1288
1244
 
1289
1245
    def test_secret_devnull(self):
1290
1246
        self.assert_command_from_args(["--secret", os.path.devnull,
1291
 
                                       "client"], command.SetSecret,
 
1247
                                       "foo"], SetSecretCmd,
1292
1248
                                      value_to_set=b"")
1293
1249
 
1294
1250
    def test_secret_tempfile(self):
1297
1253
            f.write(value)
1298
1254
            f.seek(0)
1299
1255
            self.assert_command_from_args(["--secret", f.name,
1300
 
                                           "client"],
1301
 
                                          command.SetSecret,
 
1256
                                           "foo"], SetSecretCmd,
1302
1257
                                          value_to_set=value)
1303
1258
 
1304
1259
    def test_secret_devnull_short(self):
1305
 
        self.assert_command_from_args(["-s", os.path.devnull,
1306
 
                                       "client"], command.SetSecret,
1307
 
                                      value_to_set=b"")
 
1260
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
 
1261
                                      SetSecretCmd, value_to_set=b"")
1308
1262
 
1309
1263
    def test_secret_tempfile_short(self):
1310
1264
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
1311
1265
            value = b"secret\0xyzzy\nbar"
1312
1266
            f.write(value)
1313
1267
            f.seek(0)
1314
 
            self.assert_command_from_args(["-s", f.name, "client"],
1315
 
                                          command.SetSecret,
 
1268
            self.assert_command_from_args(["-s", f.name, "foo"],
 
1269
                                          SetSecretCmd,
1316
1270
                                          value_to_set=value)
1317
1271
 
1318
1272
    def test_timeout(self):
1319
 
        self.assert_command_from_args(["--timeout", "PT5M", "client"],
1320
 
                                      command.SetTimeout,
 
1273
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
 
1274
                                      SetTimeoutCmd,
1321
1275
                                      value_to_set=300000)
1322
1276
 
1323
1277
    def test_timeout_short(self):
1324
 
        self.assert_command_from_args(["-t", "PT5M", "client"],
1325
 
                                      command.SetTimeout,
 
1278
        self.assert_command_from_args(["-t", "PT5M", "foo"],
 
1279
                                      SetTimeoutCmd,
1326
1280
                                      value_to_set=300000)
1327
1281
 
1328
1282
    def test_extended_timeout(self):
1329
1283
        self.assert_command_from_args(["--extended-timeout", "PT15M",
1330
 
                                       "client"],
1331
 
                                      command.SetExtendedTimeout,
 
1284
                                       "foo"],
 
1285
                                      SetExtendedTimeoutCmd,
1332
1286
                                      value_to_set=900000)
1333
1287
 
1334
1288
    def test_interval(self):
1335
 
        self.assert_command_from_args(["--interval", "PT2M",
1336
 
                                       "client"], command.SetInterval,
 
1289
        self.assert_command_from_args(["--interval", "PT2M", "foo"],
 
1290
                                      SetIntervalCmd,
1337
1291
                                      value_to_set=120000)
1338
1292
 
1339
1293
    def test_interval_short(self):
1340
 
        self.assert_command_from_args(["-i", "PT2M", "client"],
1341
 
                                      command.SetInterval,
 
1294
        self.assert_command_from_args(["-i", "PT2M", "foo"],
 
1295
                                      SetIntervalCmd,
1342
1296
                                      value_to_set=120000)
1343
1297
 
1344
1298
    def test_approval_delay(self):
1345
1299
        self.assert_command_from_args(["--approval-delay", "PT30S",
1346
 
                                       "client"],
1347
 
                                      command.SetApprovalDelay,
 
1300
                                       "foo"], SetApprovalDelayCmd,
1348
1301
                                      value_to_set=30000)
1349
1302
 
1350
1303
    def test_approval_duration(self):
1351
1304
        self.assert_command_from_args(["--approval-duration", "PT1S",
1352
 
                                       "client"],
1353
 
                                      command.SetApprovalDuration,
 
1305
                                       "foo"], SetApprovalDurationCmd,
1354
1306
                                      value_to_set=1000)
1355
1307
 
1356
1308
    def test_print_table(self):
1357
 
        self.assert_command_from_args([], command.PrintTable,
 
1309
        self.assert_command_from_args([], PrintTableCmd,
1358
1310
                                      verbose=False)
1359
1311
 
1360
1312
    def test_print_table_verbose(self):
1361
 
        self.assert_command_from_args(["--verbose"],
1362
 
                                      command.PrintTable,
 
1313
        self.assert_command_from_args(["--verbose"], PrintTableCmd,
1363
1314
                                      verbose=True)
1364
1315
 
1365
1316
    def test_print_table_verbose_short(self):
1366
 
        self.assert_command_from_args(["-v"], command.PrintTable,
 
1317
        self.assert_command_from_args(["-v"], PrintTableCmd,
1367
1318
                                      verbose=True)
1368
1319
 
1369
1320
 
1370
 
class TestCommand(unittest.TestCase):
 
1321
class TestCmd(unittest.TestCase):
1371
1322
    """Abstract class for tests of command classes"""
1372
1323
 
1373
1324
    def setUp(self):
1379
1330
                self.attributes["Name"] = name
1380
1331
                self.calls = []
1381
1332
            def Set(self, interface, propname, value, dbus_interface):
1382
 
                testcase.assertEqual(client_dbus_interface, interface)
1383
 
                testcase.assertEqual(dbus.PROPERTIES_IFACE,
1384
 
                                     dbus_interface)
 
1333
                testcase.assertEqual(interface, client_dbus_interface)
 
1334
                testcase.assertEqual(dbus_interface,
 
1335
                                     dbus.PROPERTIES_IFACE)
1385
1336
                self.attributes[propname] = value
 
1337
            def Get(self, interface, propname, dbus_interface):
 
1338
                testcase.assertEqual(interface, client_dbus_interface)
 
1339
                testcase.assertEqual(dbus_interface,
 
1340
                                     dbus.PROPERTIES_IFACE)
 
1341
                return self.attributes[propname]
1386
1342
            def Approve(self, approve, dbus_interface):
1387
 
                testcase.assertEqual(client_dbus_interface,
1388
 
                                     dbus_interface)
 
1343
                testcase.assertEqual(dbus_interface,
 
1344
                                     client_dbus_interface)
1389
1345
                self.calls.append(("Approve", (approve,
1390
1346
                                               dbus_interface)))
1391
1347
        self.client = MockClient(
1438
1394
            LastCheckerStatus=-2)
1439
1395
        self.clients =  collections.OrderedDict(
1440
1396
            [
1441
 
                (self.client.__dbus_object_path__,
1442
 
                 self.client.attributes),
1443
 
                (self.other_client.__dbus_object_path__,
1444
 
                 self.other_client.attributes),
 
1397
                ("/clients/foo", self.client.attributes),
 
1398
                ("/clients/barbar", self.other_client.attributes),
1445
1399
            ])
1446
 
        self.one_client = {self.client.__dbus_object_path__:
1447
 
                           self.client.attributes}
 
1400
        self.one_client = {"/clients/foo": self.client.attributes}
1448
1401
 
1449
1402
    @property
1450
1403
    def bus(self):
1451
 
        class MockBus(object):
 
1404
        class Bus(object):
1452
1405
            @staticmethod
1453
1406
            def get_object(client_bus_name, path):
1454
 
                self.assertEqual(dbus_busname, client_bus_name)
1455
 
                # Note: "self" here is the TestCmd instance, not the
1456
 
                # MockBus instance, since this is a static method!
1457
 
                if path == self.client.__dbus_object_path__:
1458
 
                    return self.client
1459
 
                elif path == self.other_client.__dbus_object_path__:
1460
 
                    return self.other_client
1461
 
        return MockBus()
1462
 
 
1463
 
 
1464
 
class TestBaseCommands(TestCommand):
1465
 
 
1466
 
    def test_IsEnabled_exits_successfully(self):
 
1407
                self.assertEqual(client_bus_name, dbus_busname)
 
1408
                return {
 
1409
                    # Note: "self" here is the TestCmd instance, not
 
1410
                    # the Bus instance, since this is a static method!
 
1411
                    "/clients/foo": self.client,
 
1412
                    "/clients/barbar": self.other_client,
 
1413
                }[path]
 
1414
        return Bus()
 
1415
 
 
1416
 
 
1417
class TestIsEnabledCmd(TestCmd):
 
1418
    def test_is_enabled(self):
 
1419
        self.assertTrue(all(IsEnabledCmd().is_enabled(client,
 
1420
                                                      properties)
 
1421
                            for client, properties
 
1422
                            in self.clients.items()))
 
1423
 
 
1424
    def test_is_enabled_run_exits_successfully(self):
1467
1425
        with self.assertRaises(SystemExit) as e:
1468
 
            command.IsEnabled().run(self.one_client)
 
1426
            IsEnabledCmd().run(self.one_client)
1469
1427
        if e.exception.code is not None:
1470
 
            self.assertEqual(0, e.exception.code)
 
1428
            self.assertEqual(e.exception.code, 0)
1471
1429
        else:
1472
1430
            self.assertIsNone(e.exception.code)
1473
1431
 
1474
 
    def test_IsEnabled_exits_with_failure(self):
 
1432
    def test_is_enabled_run_exits_with_failure(self):
1475
1433
        self.client.attributes["Enabled"] = dbus.Boolean(False)
1476
1434
        with self.assertRaises(SystemExit) as e:
1477
 
            command.IsEnabled().run(self.one_client)
 
1435
            IsEnabledCmd().run(self.one_client)
1478
1436
        if isinstance(e.exception.code, int):
1479
 
            self.assertNotEqual(0, e.exception.code)
 
1437
            self.assertNotEqual(e.exception.code, 0)
1480
1438
        else:
1481
1439
            self.assertIsNotNone(e.exception.code)
1482
1440
 
1483
 
    def test_Approve(self):
1484
 
        command.Approve().run(self.clients, self.bus)
 
1441
 
 
1442
class TestApproveCmd(TestCmd):
 
1443
    def test_approve(self):
 
1444
        ApproveCmd().run(self.clients, self.bus)
1485
1445
        for clientpath in self.clients:
1486
1446
            client = self.bus.get_object(dbus_busname, clientpath)
1487
1447
            self.assertIn(("Approve", (True, client_dbus_interface)),
1488
1448
                          client.calls)
1489
1449
 
1490
 
    def test_Deny(self):
1491
 
        command.Deny().run(self.clients, self.bus)
 
1450
 
 
1451
class TestDenyCmd(TestCmd):
 
1452
    def test_deny(self):
 
1453
        DenyCmd().run(self.clients, self.bus)
1492
1454
        for clientpath in self.clients:
1493
1455
            client = self.bus.get_object(dbus_busname, clientpath)
1494
1456
            self.assertIn(("Approve", (False, client_dbus_interface)),
1495
1457
                          client.calls)
1496
1458
 
1497
 
    def test_Remove(self):
1498
 
        class MandosSpy(object):
 
1459
 
 
1460
class TestRemoveCmd(TestCmd):
 
1461
    def test_remove(self):
 
1462
        class MockMandos(object):
1499
1463
            def __init__(self):
1500
1464
                self.calls = []
1501
1465
            def RemoveClient(self, dbus_path):
1502
1466
                self.calls.append(("RemoveClient", (dbus_path,)))
1503
 
        mandos = MandosSpy()
1504
 
        command.Remove().run(self.clients, self.bus, mandos)
 
1467
        mandos = MockMandos()
 
1468
        super(TestRemoveCmd, self).setUp()
 
1469
        RemoveCmd().run(self.clients, self.bus, mandos)
 
1470
        self.assertEqual(len(mandos.calls), 2)
1505
1471
        for clientpath in self.clients:
1506
1472
            self.assertIn(("RemoveClient", (clientpath,)),
1507
1473
                          mandos.calls)
1508
1474
 
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
 
        with self.capture_stdout_to_buffer() as buffer:
1562
 
            command.DumpJSON().run(self.clients)
1563
 
        json_data = json.loads(buffer.getvalue())
1564
 
        self.assertDictEqual(self.expected_json, json_data)
1565
 
 
1566
 
    @staticmethod
1567
 
    @contextlib.contextmanager
1568
 
    def capture_stdout_to_buffer():
1569
 
        capture_buffer = io.StringIO()
1570
 
        old_stdout = sys.stdout
1571
 
        sys.stdout = capture_buffer
1572
 
        try:
1573
 
            yield capture_buffer
1574
 
        finally:
1575
 
            sys.stdout = old_stdout
1576
 
 
1577
 
    def test_DumpJSON_one_client(self):
1578
 
        with self.capture_stdout_to_buffer() as buffer:
1579
 
            command.DumpJSON().run(self.one_client)
1580
 
        json_data = json.loads(buffer.getvalue())
 
1475
 
 
1476
class TestDumpJSONCmd(TestCmd):
 
1477
    def setUp(self):
 
1478
        self.expected_json = {
 
1479
            "foo": {
 
1480
                "Name": "foo",
 
1481
                "KeyID": ("92ed150794387c03ce684574b1139a65"
 
1482
                          "94a34f895daaaf09fd8ea90a27cddb12"),
 
1483
                "Host": "foo.example.org",
 
1484
                "Enabled": True,
 
1485
                "Timeout": 300000,
 
1486
                "LastCheckedOK": "2019-02-03T00:00:00",
 
1487
                "Created": "2019-01-02T00:00:00",
 
1488
                "Interval": 120000,
 
1489
                "Fingerprint": ("778827225BA7DE539C5A"
 
1490
                                "7CFA59CFF7CDBD9A5920"),
 
1491
                "CheckerRunning": False,
 
1492
                "LastEnabled": "2019-01-03T00:00:00",
 
1493
                "ApprovalPending": False,
 
1494
                "ApprovedByDefault": True,
 
1495
                "LastApprovalRequest": "",
 
1496
                "ApprovalDelay": 0,
 
1497
                "ApprovalDuration": 1000,
 
1498
                "Checker": "fping -q -- %(host)s",
 
1499
                "ExtendedTimeout": 900000,
 
1500
                "Expires": "2019-02-04T00:00:00",
 
1501
                "LastCheckerStatus": 0,
 
1502
            },
 
1503
            "barbar": {
 
1504
                "Name": "barbar",
 
1505
                "KeyID": ("0558568eedd67d622f5c83b35a115f79"
 
1506
                          "6ab612cff5ad227247e46c2b020f441c"),
 
1507
                "Host": "192.0.2.3",
 
1508
                "Enabled": True,
 
1509
                "Timeout": 300000,
 
1510
                "LastCheckedOK": "2019-02-04T00:00:00",
 
1511
                "Created": "2019-01-03T00:00:00",
 
1512
                "Interval": 120000,
 
1513
                "Fingerprint": ("3E393AEAEFB84C7E89E2"
 
1514
                                "F547B3A107558FCA3A27"),
 
1515
                "CheckerRunning": True,
 
1516
                "LastEnabled": "2019-01-04T00:00:00",
 
1517
                "ApprovalPending": False,
 
1518
                "ApprovedByDefault": False,
 
1519
                "LastApprovalRequest": "2019-01-03T00:00:00",
 
1520
                "ApprovalDelay": 30000,
 
1521
                "ApprovalDuration": 93785000,
 
1522
                "Checker": ":",
 
1523
                "ExtendedTimeout": 900000,
 
1524
                "Expires": "2019-02-05T00:00:00",
 
1525
                "LastCheckerStatus": -2,
 
1526
            },
 
1527
        }
 
1528
        return super(TestDumpJSONCmd, self).setUp()
 
1529
 
 
1530
    def test_normal(self):
 
1531
        output = DumpJSONCmd().output(self.clients.values())
 
1532
        json_data = json.loads(output)
 
1533
        self.assertDictEqual(json_data, self.expected_json)
 
1534
 
 
1535
    def test_one_client(self):
 
1536
        output = DumpJSONCmd().output(self.one_client.values())
 
1537
        json_data = json.loads(output)
1581
1538
        expected_json = {"foo": self.expected_json["foo"]}
1582
 
        self.assertDictEqual(expected_json, json_data)
1583
 
 
1584
 
    def test_PrintTable_normal(self):
1585
 
        with self.capture_stdout_to_buffer() as buffer:
1586
 
            command.PrintTable().run(self.clients)
 
1539
        self.assertDictEqual(json_data, expected_json)
 
1540
 
 
1541
 
 
1542
class TestPrintTableCmd(TestCmd):
 
1543
    def test_normal(self):
 
1544
        output = PrintTableCmd().output(self.clients.values())
1587
1545
        expected_output = "\n".join((
1588
1546
            "Name   Enabled Timeout  Last Successful Check",
1589
1547
            "foo    Yes     00:05:00 2019-02-03T00:00:00  ",
1590
1548
            "barbar Yes     00:05:00 2019-02-04T00:00:00  ",
1591
 
        )) + "\n"
1592
 
        self.assertEqual(expected_output, buffer.getvalue())
 
1549
        ))
 
1550
        self.assertEqual(output, expected_output)
1593
1551
 
1594
 
    def test_PrintTable_verbose(self):
1595
 
        with self.capture_stdout_to_buffer() as buffer:
1596
 
            command.PrintTable(verbose=True).run(self.clients)
 
1552
    def test_verbose(self):
 
1553
        output = PrintTableCmd(verbose=True).output(
 
1554
            self.clients.values())
1597
1555
        columns = (
1598
1556
            (
1599
1557
                "Name   ",
1681
1639
            )
1682
1640
        )
1683
1641
        num_lines = max(len(rows) for rows in columns)
1684
 
        expected_output = ("\n".join("".join(rows[line]
1685
 
                                             for rows in columns)
1686
 
                                     for line in range(num_lines))
1687
 
                           + "\n")
1688
 
        self.assertEqual(expected_output, buffer.getvalue())
 
1642
        expected_output = "\n".join("".join(rows[line]
 
1643
                                            for rows in columns)
 
1644
                                    for line in range(num_lines))
 
1645
        self.assertEqual(output, expected_output)
1689
1646
 
1690
 
    def test_PrintTable_one_client(self):
1691
 
        with self.capture_stdout_to_buffer() as buffer:
1692
 
            command.PrintTable().run(self.one_client)
 
1647
    def test_one_client(self):
 
1648
        output = PrintTableCmd().output(self.one_client.values())
1693
1649
        expected_output = "\n".join((
1694
1650
            "Name Enabled Timeout  Last Successful Check",
1695
1651
            "foo  Yes     00:05:00 2019-02-03T00:00:00  ",
1696
 
        )) + "\n"
1697
 
        self.assertEqual(expected_output, buffer.getvalue())
1698
 
 
1699
 
 
1700
 
class TestPropertySetterCmd(TestCommand):
1701
 
    """Abstract class for tests of command.PropertySetter classes"""
 
1652
        ))
 
1653
        self.assertEqual(output, expected_output)
 
1654
 
 
1655
 
 
1656
class TestPropertyCmd(TestCmd):
 
1657
    """Abstract class for tests of PropertyCmd classes"""
1702
1658
    def runTest(self):
1703
1659
        if not hasattr(self, "command"):
1704
1660
            return
1709
1665
            for clientpath in self.clients:
1710
1666
                client = self.bus.get_object(dbus_busname, clientpath)
1711
1667
                old_value = client.attributes[self.propname]
 
1668
                self.assertNotIsInstance(old_value, self.Unique)
1712
1669
                client.attributes[self.propname] = self.Unique()
1713
1670
            self.run_command(value_to_set, self.clients)
1714
1671
            for clientpath in self.clients:
1715
1672
                client = self.bus.get_object(dbus_busname, clientpath)
1716
1673
                value = client.attributes[self.propname]
1717
1674
                self.assertNotIsInstance(value, self.Unique)
1718
 
                self.assertEqual(value_to_get, value)
 
1675
                self.assertEqual(value, value_to_get)
1719
1676
 
1720
1677
    class Unique(object):
1721
1678
        """Class for objects which exist only to be unique objects,
1725
1682
        self.command().run(clients, self.bus)
1726
1683
 
1727
1684
 
1728
 
class TestEnableCmd(TestPropertySetterCmd):
1729
 
    command = command.Enable
 
1685
class TestEnableCmd(TestPropertyCmd):
 
1686
    command = EnableCmd
1730
1687
    propname = "Enabled"
1731
1688
    values_to_set = [dbus.Boolean(True)]
1732
1689
 
1733
1690
 
1734
 
class TestDisableCmd(TestPropertySetterCmd):
1735
 
    command = command.Disable
 
1691
class TestDisableCmd(TestPropertyCmd):
 
1692
    command = DisableCmd
1736
1693
    propname = "Enabled"
1737
1694
    values_to_set = [dbus.Boolean(False)]
1738
1695
 
1739
1696
 
1740
 
class TestBumpTimeoutCmd(TestPropertySetterCmd):
1741
 
    command = command.BumpTimeout
 
1697
class TestBumpTimeoutCmd(TestPropertyCmd):
 
1698
    command = BumpTimeoutCmd
1742
1699
    propname = "LastCheckedOK"
1743
1700
    values_to_set = [""]
1744
1701
 
1745
1702
 
1746
 
class TestStartCheckerCmd(TestPropertySetterCmd):
1747
 
    command = command.StartChecker
1748
 
    propname = "CheckerRunning"
1749
 
    values_to_set = [dbus.Boolean(True)]
1750
 
 
1751
 
 
1752
 
class TestStopCheckerCmd(TestPropertySetterCmd):
1753
 
    command = command.StopChecker
1754
 
    propname = "CheckerRunning"
1755
 
    values_to_set = [dbus.Boolean(False)]
1756
 
 
1757
 
 
1758
 
class TestApproveByDefaultCmd(TestPropertySetterCmd):
1759
 
    command = command.ApproveByDefault
1760
 
    propname = "ApprovedByDefault"
1761
 
    values_to_set = [dbus.Boolean(True)]
1762
 
 
1763
 
 
1764
 
class TestDenyByDefaultCmd(TestPropertySetterCmd):
1765
 
    command = command.DenyByDefault
1766
 
    propname = "ApprovedByDefault"
1767
 
    values_to_set = [dbus.Boolean(False)]
1768
 
 
1769
 
 
1770
 
class TestPropertySetterValueCmd(TestPropertySetterCmd):
1771
 
    """Abstract class for tests of PropertySetterValueCmd classes"""
 
1703
class TestStartCheckerCmd(TestPropertyCmd):
 
1704
    command = StartCheckerCmd
 
1705
    propname = "CheckerRunning"
 
1706
    values_to_set = [dbus.Boolean(True)]
 
1707
 
 
1708
 
 
1709
class TestStopCheckerCmd(TestPropertyCmd):
 
1710
    command = StopCheckerCmd
 
1711
    propname = "CheckerRunning"
 
1712
    values_to_set = [dbus.Boolean(False)]
 
1713
 
 
1714
 
 
1715
class TestApproveByDefaultCmd(TestPropertyCmd):
 
1716
    command = ApproveByDefaultCmd
 
1717
    propname = "ApprovedByDefault"
 
1718
    values_to_set = [dbus.Boolean(True)]
 
1719
 
 
1720
 
 
1721
class TestDenyByDefaultCmd(TestPropertyCmd):
 
1722
    command = DenyByDefaultCmd
 
1723
    propname = "ApprovedByDefault"
 
1724
    values_to_set = [dbus.Boolean(False)]
 
1725
 
 
1726
 
 
1727
class TestPropertyValueCmd(TestPropertyCmd):
 
1728
    """Abstract class for tests of PropertyValueCmd classes"""
1772
1729
 
1773
1730
    def runTest(self):
1774
 
        if type(self) is TestPropertySetterValueCmd:
 
1731
        if type(self) is TestPropertyValueCmd:
1775
1732
            return
1776
 
        return super(TestPropertySetterValueCmd, self).runTest()
 
1733
        return super(TestPropertyValueCmd, self).runTest()
1777
1734
 
1778
1735
    def run_command(self, value, clients):
1779
1736
        self.command(value).run(clients, self.bus)
1780
1737
 
1781
1738
 
1782
 
class TestSetCheckerCmd(TestPropertySetterValueCmd):
1783
 
    command = command.SetChecker
 
1739
class TestSetCheckerCmd(TestPropertyValueCmd):
 
1740
    command = SetCheckerCmd
1784
1741
    propname = "Checker"
1785
1742
    values_to_set = ["", ":", "fping -q -- %s"]
1786
1743
 
1787
1744
 
1788
 
class TestSetHostCmd(TestPropertySetterValueCmd):
1789
 
    command = command.SetHost
 
1745
class TestSetHostCmd(TestPropertyValueCmd):
 
1746
    command = SetHostCmd
1790
1747
    propname = "Host"
1791
 
    values_to_set = ["192.0.2.3", "client.example.org"]
1792
 
 
1793
 
 
1794
 
class TestSetSecretCmd(TestPropertySetterValueCmd):
1795
 
    command = command.SetSecret
 
1748
    values_to_set = ["192.0.2.3", "foo.example.org"]
 
1749
 
 
1750
 
 
1751
class TestSetSecretCmd(TestPropertyValueCmd):
 
1752
    command = SetSecretCmd
1796
1753
    propname = "Secret"
1797
1754
    values_to_set = [io.BytesIO(b""),
1798
1755
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1799
 
    values_to_get = [f.getvalue() for f in values_to_set]
1800
 
 
1801
 
 
1802
 
class TestSetTimeoutCmd(TestPropertySetterValueCmd):
1803
 
    command = command.SetTimeout
 
1756
    values_to_get = [b"", b"secret\0xyzzy\nbar"]
 
1757
 
 
1758
 
 
1759
class TestSetTimeoutCmd(TestPropertyValueCmd):
 
1760
    command = SetTimeoutCmd
1804
1761
    propname = "Timeout"
1805
1762
    values_to_set = [datetime.timedelta(),
1806
1763
                     datetime.timedelta(minutes=5),
1807
1764
                     datetime.timedelta(seconds=1),
1808
1765
                     datetime.timedelta(weeks=1),
1809
1766
                     datetime.timedelta(weeks=52)]
1810
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1811
 
 
1812
 
 
1813
 
class TestSetExtendedTimeoutCmd(TestPropertySetterValueCmd):
1814
 
    command = command.SetExtendedTimeout
 
1767
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1768
 
 
1769
 
 
1770
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
 
1771
    command = SetExtendedTimeoutCmd
1815
1772
    propname = "ExtendedTimeout"
1816
1773
    values_to_set = [datetime.timedelta(),
1817
1774
                     datetime.timedelta(minutes=5),
1818
1775
                     datetime.timedelta(seconds=1),
1819
1776
                     datetime.timedelta(weeks=1),
1820
1777
                     datetime.timedelta(weeks=52)]
1821
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1822
 
 
1823
 
 
1824
 
class TestSetIntervalCmd(TestPropertySetterValueCmd):
1825
 
    command = command.SetInterval
 
1778
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1779
 
 
1780
 
 
1781
class TestSetIntervalCmd(TestPropertyValueCmd):
 
1782
    command = SetIntervalCmd
1826
1783
    propname = "Interval"
1827
1784
    values_to_set = [datetime.timedelta(),
1828
1785
                     datetime.timedelta(minutes=5),
1829
1786
                     datetime.timedelta(seconds=1),
1830
1787
                     datetime.timedelta(weeks=1),
1831
1788
                     datetime.timedelta(weeks=52)]
1832
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1833
 
 
1834
 
 
1835
 
class TestSetApprovalDelayCmd(TestPropertySetterValueCmd):
1836
 
    command = command.SetApprovalDelay
 
1789
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1790
 
 
1791
 
 
1792
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
 
1793
    command = SetApprovalDelayCmd
1837
1794
    propname = "ApprovalDelay"
1838
1795
    values_to_set = [datetime.timedelta(),
1839
1796
                     datetime.timedelta(minutes=5),
1840
1797
                     datetime.timedelta(seconds=1),
1841
1798
                     datetime.timedelta(weeks=1),
1842
1799
                     datetime.timedelta(weeks=52)]
1843
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1844
 
 
1845
 
 
1846
 
class TestSetApprovalDurationCmd(TestPropertySetterValueCmd):
1847
 
    command = command.SetApprovalDuration
 
1800
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1801
 
 
1802
 
 
1803
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
 
1804
    command = SetApprovalDurationCmd
1848
1805
    propname = "ApprovalDuration"
1849
1806
    values_to_set = [datetime.timedelta(),
1850
1807
                     datetime.timedelta(minutes=5),
1851
1808
                     datetime.timedelta(seconds=1),
1852
1809
                     datetime.timedelta(weeks=1),
1853
1810
                     datetime.timedelta(weeks=52)]
1854
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
 
1811
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1855
1812
 
1856
1813
 
1857
1814