/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 17:34:07 UTC
  • Revision ID: teddy@recompile.se-20190317173407-itlj1a7mzfwb3yz3
mandos-ctl: Refactor tests

* mandos-ctl: Change all calls to assertEqual (and related functions
              assertNotEqual and assertDictEqual) to always pass
              arguments in (expected, actual) order, for consistency.

Show diffs side-by-side

added added

removed removed

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