/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-03 14:22:37 UTC
  • Revision ID: teddy@recompile.se-20190303142237-tb8x6rbqms5ku1ws
mandos-ctl: Refactor

* mandos-ctl (commands_and_clients_from_options): Make args to parse
                                                  overrideable.

Show diffs side-by-side

added added

removed removed

Lines of Context:
61
61
 
62
62
locale.setlocale(locale.LC_ALL, "")
63
63
 
64
 
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
65
64
domain = "se.recompile"
66
65
busname = domain + ".Mandos"
67
66
server_path = "/"
216
215
 
217
216
 
218
217
def string_to_delta(interval):
219
 
    """Parse a string and return a datetime.timedelta
220
 
    """
 
218
    """Parse a string and return a datetime.timedelta"""
221
219
 
222
220
    try:
223
221
        return rfc3339_duration_to_delta(interval)
228
226
 
229
227
 
230
228
def parse_pre_1_6_1_interval(interval):
231
 
    """Parse an interval string as documented by Mandos before 1.6.1, and
232
 
    return a datetime.timedelta
 
229
    """Parse an interval string as documented by Mandos before 1.6.1,
 
230
    and return a datetime.timedelta
 
231
 
233
232
    >>> parse_pre_1_6_1_interval('7d')
234
233
    datetime.timedelta(7)
235
234
    >>> parse_pre_1_6_1_interval('60s')
270
269
 
271
270
 
272
271
class TableOfClients(object):
273
 
    tablewords = {
 
272
    tableheaders = {
274
273
        "Name": "Name",
275
274
        "Enabled": "Enabled",
276
275
        "Timeout": "Timeout",
293
292
        "LastCheckerStatus": "Last Checker Status",
294
293
    }
295
294
 
296
 
    def __init__(self, clients, keywords, tablewords=None):
 
295
    def __init__(self, clients, keywords, tableheaders=None):
297
296
        self.clients = clients
298
297
        self.keywords = keywords
299
 
        if tablewords is not None:
300
 
            self.tablewords = tablewords
 
298
        if tableheaders is not None:
 
299
            self.tableheaders = tableheaders
301
300
 
302
301
    def __str__(self):
303
302
        return "\n".join(self.rows())
317
316
    def row_formatting_string(self):
318
317
        "Format string used to format table rows"
319
318
        return " ".join("{{{key}:{width}}}".format(
320
 
            width=max(len(self.tablewords[key]),
321
 
                      max(len(self.string_from_client(client, key))
322
 
                          for client in self.clients)),
 
319
            width=max(len(self.tableheaders[key]),
 
320
                      *(len(self.string_from_client(client, key))
 
321
                        for client in self.clients)),
323
322
            key=key)
324
 
                                 for key in self.keywords)
 
323
                        for key in self.keywords)
325
324
 
326
325
    def string_from_client(self, client, key):
327
326
        return self.valuetostring(client[key], key)
336
335
        return str(value)
337
336
 
338
337
    def header_line(self, format_string):
339
 
        return format_string.format(**self.tablewords)
 
338
        return format_string.format(**self.tableheaders)
340
339
 
341
340
    def client_line(self, client, format_string):
342
341
        return format_string.format(
344
343
               for key in self.keywords})
345
344
 
346
345
 
 
346
## Classes for commands.
 
347
 
 
348
# Abstract classes first
 
349
class Command(object):
 
350
    """Abstract class for commands"""
 
351
    def run(self, mandos, clients):
 
352
        """Normal commands should implement run_on_one_client(), but
 
353
        commands which want to operate on all clients at the same time
 
354
        can override this run() method instead."""
 
355
        self.mandos = mandos
 
356
        for client in clients:
 
357
            self.run_on_one_client(client)
 
358
 
 
359
class PrintCmd(Command):
 
360
    """Abstract class for commands printing client details"""
 
361
    all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
 
362
                    "Created", "Interval", "Host", "KeyID",
 
363
                    "Fingerprint", "CheckerRunning", "LastEnabled",
 
364
                    "ApprovalPending", "ApprovedByDefault",
 
365
                    "LastApprovalRequest", "ApprovalDelay",
 
366
                    "ApprovalDuration", "Checker", "ExtendedTimeout",
 
367
                    "Expires", "LastCheckerStatus")
 
368
    def run(self, mandos, clients):
 
369
        print(self.output(clients))
 
370
 
 
371
class PropertyCmd(Command):
 
372
    """Abstract class for Actions for setting one client property"""
 
373
    def run_on_one_client(self, client):
 
374
        """Set the Client's D-Bus property"""
 
375
        client.Set(client_interface, self.property, self.value_to_set,
 
376
                   dbus_interface=dbus.PROPERTIES_IFACE)
 
377
 
 
378
class ValueArgumentMixIn(object):
 
379
    """Mixin class for commands taking a value as argument"""
 
380
    def __init__(self, value):
 
381
        self.value_to_set = value
 
382
 
 
383
class MillisecondsValueArgumentMixIn(ValueArgumentMixIn):
 
384
    """Mixin class for commands taking a value argument as
 
385
    milliseconds."""
 
386
    @property
 
387
    def value_to_set(self):
 
388
        return self._vts
 
389
    @value_to_set.setter
 
390
    def value_to_set(self, value):
 
391
        """When setting, convert value to a datetime.timedelta"""
 
392
        self._vts = string_to_delta(value).total_seconds() * 1000
 
393
 
 
394
# Actual (non-abstract) command classes
 
395
 
 
396
class PrintTableCmd(PrintCmd):
 
397
    def __init__(self, verbose=False):
 
398
        self.verbose = verbose
 
399
    def output(self, clients):
 
400
        if self.verbose:
 
401
            keywords = self.all_keywords
 
402
        else:
 
403
            keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
 
404
        return str(TableOfClients(clients.values(), keywords))
 
405
 
 
406
class DumpJSONCmd(PrintCmd):
 
407
    def output(self, clients):
 
408
        data = {client["Name"]:
 
409
                {key: self.dbus_boolean_to_bool(client[key])
 
410
                 for key in self.all_keywords}
 
411
                for client in clients.values()}
 
412
        return json.dumps(data, indent=4, separators=(',', ': '))
 
413
    @staticmethod
 
414
    def dbus_boolean_to_bool(value):
 
415
        if isinstance(value, dbus.Boolean):
 
416
            value = bool(value)
 
417
        return value
 
418
 
 
419
class IsEnabledCmd(Command):
 
420
    def run_on_one_client(self, client):
 
421
        if self.is_enabled(client):
 
422
            sys.exit(0)
 
423
        sys.exit(1)
 
424
    def is_enabled(self, client):
 
425
        return client.Get(client_interface, "Enabled",
 
426
                          dbus_interface=dbus.PROPERTIES_IFACE)
 
427
 
 
428
class RemoveCmd(Command):
 
429
    def run_on_one_client(self, client):
 
430
        self.mandos.RemoveClient(client.__dbus_object_path__)
 
431
 
 
432
class ApproveCmd(Command):
 
433
    def run_on_one_client(self, client):
 
434
        client.Approve(dbus.Boolean(True),
 
435
                       dbus_interface=client_interface)
 
436
 
 
437
class DenyCmd(Command):
 
438
    def run_on_one_client(self, client):
 
439
        client.Approve(dbus.Boolean(False),
 
440
                       dbus_interface=client_interface)
 
441
 
 
442
class EnableCmd(PropertyCmd):
 
443
    property = "Enabled"
 
444
    value_to_set = dbus.Boolean(True)
 
445
 
 
446
class DisableCmd(PropertyCmd):
 
447
    property = "Enabled"
 
448
    value_to_set = dbus.Boolean(False)
 
449
 
 
450
class BumpTimeoutCmd(PropertyCmd):
 
451
    property = "LastCheckedOK"
 
452
    value_to_set = ""
 
453
 
 
454
class StartCheckerCmd(PropertyCmd):
 
455
    property = "CheckerRunning"
 
456
    value_to_set = dbus.Boolean(True)
 
457
 
 
458
class StopCheckerCmd(PropertyCmd):
 
459
    property = "CheckerRunning"
 
460
    value_to_set = dbus.Boolean(False)
 
461
 
 
462
class ApproveByDefaultCmd(PropertyCmd):
 
463
    property = "ApprovedByDefault"
 
464
    value_to_set = dbus.Boolean(True)
 
465
 
 
466
class DenyByDefaultCmd(PropertyCmd):
 
467
    property = "ApprovedByDefault"
 
468
    value_to_set = dbus.Boolean(False)
 
469
 
 
470
class SetCheckerCmd(PropertyCmd, ValueArgumentMixIn):
 
471
    property = "Checker"
 
472
 
 
473
class SetHostCmd(PropertyCmd, ValueArgumentMixIn):
 
474
    property = "Host"
 
475
 
 
476
class SetSecretCmd(PropertyCmd, ValueArgumentMixIn):
 
477
    property = "Secret"
 
478
 
 
479
class SetTimeoutCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
 
480
    property = "Timeout"
 
481
 
 
482
class SetExtendedTimeoutCmd(PropertyCmd,
 
483
                            MillisecondsValueArgumentMixIn):
 
484
    property = "ExtendedTimeout"
 
485
 
 
486
class SetIntervalCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
 
487
    property = "Interval"
 
488
 
 
489
class SetApprovalDelayCmd(PropertyCmd,
 
490
                          MillisecondsValueArgumentMixIn):
 
491
    property = "ApprovalDelay"
 
492
 
 
493
class SetApprovalDurationCmd(PropertyCmd,
 
494
                             MillisecondsValueArgumentMixIn):
 
495
    property = "ApprovalDuration"
 
496
 
347
497
def has_actions(options):
348
498
    return any((options.enable,
349
499
                options.disable,
365
515
                options.deny))
366
516
 
367
517
 
368
 
def main():
 
518
def commands_and_clients_from_options(args=None):
 
519
    if args is None:
 
520
        args=sys.argv[1:]
369
521
    parser = argparse.ArgumentParser()
370
522
    parser.add_argument("--version", action="version",
371
523
                        version="%(prog)s {}".format(version),
376
528
                        help="Print all fields")
377
529
    parser.add_argument("-j", "--dump-json", action="store_true",
378
530
                        help="Dump client data in JSON format")
379
 
    parser.add_argument("-e", "--enable", action="store_true",
380
 
                        help="Enable client")
381
 
    parser.add_argument("-d", "--disable", action="store_true",
382
 
                        help="disable client")
 
531
    enable_disable = parser.add_mutually_exclusive_group()
 
532
    enable_disable.add_argument("-e", "--enable", action="store_true",
 
533
                                help="Enable client")
 
534
    enable_disable.add_argument("-d", "--disable",
 
535
                                action="store_true",
 
536
                                help="disable client")
383
537
    parser.add_argument("-b", "--bump-timeout", action="store_true",
384
538
                        help="Bump timeout for client")
385
 
    parser.add_argument("--start-checker", action="store_true",
386
 
                        help="Start checker for client")
387
 
    parser.add_argument("--stop-checker", action="store_true",
388
 
                        help="Stop checker for client")
 
539
    start_stop_checker = parser.add_mutually_exclusive_group()
 
540
    start_stop_checker.add_argument("--start-checker",
 
541
                                    action="store_true",
 
542
                                    help="Start checker for client")
 
543
    start_stop_checker.add_argument("--stop-checker",
 
544
                                    action="store_true",
 
545
                                    help="Stop checker for client")
389
546
    parser.add_argument("-V", "--is-enabled", action="store_true",
390
547
                        help="Check if client is enabled")
391
548
    parser.add_argument("-r", "--remove", action="store_true",
398
555
                        help="Set extended timeout for client")
399
556
    parser.add_argument("-i", "--interval",
400
557
                        help="Set checker interval for client")
401
 
    parser.add_argument("--approve-by-default", action="store_true",
402
 
                        default=None, dest="approved_by_default",
403
 
                        help="Set client to be approved by default")
404
 
    parser.add_argument("--deny-by-default", action="store_false",
405
 
                        dest="approved_by_default",
406
 
                        help="Set client to be denied by default")
 
558
    approve_deny_default = parser.add_mutually_exclusive_group()
 
559
    approve_deny_default.add_argument(
 
560
        "--approve-by-default", action="store_true",
 
561
        default=None, dest="approved_by_default",
 
562
        help="Set client to be approved by default")
 
563
    approve_deny_default.add_argument(
 
564
        "--deny-by-default", action="store_false",
 
565
        dest="approved_by_default",
 
566
        help="Set client to be denied by default")
407
567
    parser.add_argument("--approval-delay",
408
568
                        help="Set delay before client approve/deny")
409
569
    parser.add_argument("--approval-duration",
412
572
    parser.add_argument("-s", "--secret",
413
573
                        type=argparse.FileType(mode="rb"),
414
574
                        help="Set password blob (file) for client")
415
 
    parser.add_argument("-A", "--approve", action="store_true",
416
 
                        help="Approve any current client request")
417
 
    parser.add_argument("-D", "--deny", action="store_true",
418
 
                        help="Deny any current client request")
 
575
    approve_deny = parser.add_mutually_exclusive_group()
 
576
    approve_deny.add_argument(
 
577
        "-A", "--approve", action="store_true",
 
578
        help="Approve any current client request")
 
579
    approve_deny.add_argument("-D", "--deny", action="store_true",
 
580
                              help="Deny any current client request")
419
581
    parser.add_argument("--check", action="store_true",
420
582
                        help="Run self-test")
421
583
    parser.add_argument("client", nargs="*", help="Client name")
422
 
    options = parser.parse_args()
 
584
    options = parser.parse_args(args=args)
423
585
 
424
586
    if has_actions(options) and not (options.client or options.all):
425
587
        parser.error("Options require clients names or --all.")
430
592
        parser.error("--dump-json can only be used alone.")
431
593
    if options.all and not has_actions(options):
432
594
        parser.error("--all requires an action.")
 
595
    if options.is_enabled and len(options.client) > 1:
 
596
            parser.error("--is-enabled requires exactly one client")
 
597
 
 
598
    commands = []
 
599
 
 
600
    if options.dump_json:
 
601
        commands.append(DumpJSONCmd())
 
602
 
 
603
    if options.enable:
 
604
        commands.append(EnableCmd())
 
605
 
 
606
    if options.disable:
 
607
        commands.append(DisableCmd())
 
608
 
 
609
    if options.bump_timeout:
 
610
        commands.append(BumpTimeoutCmd(options.bump_timeout))
 
611
 
 
612
    if options.start_checker:
 
613
        commands.append(StartCheckerCmd())
 
614
 
 
615
    if options.stop_checker:
 
616
        commands.append(StopCheckerCmd())
 
617
 
 
618
    if options.is_enabled:
 
619
        commands.append(IsEnabledCmd())
 
620
 
 
621
    if options.remove:
 
622
        commands.append(RemoveCmd())
 
623
 
 
624
    if options.checker is not None:
 
625
        commands.append(SetCheckerCmd())
 
626
 
 
627
    if options.timeout is not None:
 
628
        commands.append(SetTimeoutCmd(options.timeout))
 
629
 
 
630
    if options.extended_timeout:
 
631
        commands.append(
 
632
            SetExtendedTimeoutCmd(options.extended_timeout))
 
633
 
 
634
    if options.interval is not None:
 
635
        command.append(SetIntervalCmd(options.interval))
 
636
 
 
637
    if options.approved_by_default is not None:
 
638
        if options.approved_by_default:
 
639
            command.append(ApproveByDefaultCmd())
 
640
        else:
 
641
            command.append(DenyByDefaultCmd())
 
642
 
 
643
    if options.approval_delay is not None:
 
644
        command.append(SetApprovalDelayCmd(options.approval_delay))
 
645
 
 
646
    if options.approval_duration is not None:
 
647
        command.append(
 
648
            SetApprovalDurationCmd(options.approval_duration))
 
649
 
 
650
    if options.host is not None:
 
651
        command.append(SetHostCmd(options.host))
 
652
 
 
653
    if options.secret is not None:
 
654
        command.append(SetSecretCmd(options.secret))
 
655
 
 
656
    if options.approve:
 
657
        commands.append(ApproveCmd())
 
658
 
 
659
    if options.deny:
 
660
        commands.append(DenyCmd())
 
661
 
 
662
    # If no command option has been given, show table of clients,
 
663
    # optionally verbosely
 
664
    if not commands:
 
665
        commands.append(PrintTableCmd(verbose=options.verbose))
 
666
 
 
667
    return commands, options.client
 
668
 
 
669
 
 
670
def main():
 
671
    commands, clientnames = commands_and_clients_from_options()
433
672
 
434
673
    try:
435
674
        bus = dbus.SystemBus()
443
682
    mandos_serv_object_manager = dbus.Interface(
444
683
        mandos_dbus_objc, dbus_interface=dbus.OBJECT_MANAGER_IFACE)
445
684
 
446
 
    # block stderr since dbus library prints to stderr
447
 
    null = os.open(os.path.devnull, os.O_RDWR)
448
 
    stderrcopy = os.dup(sys.stderr.fileno())
449
 
    os.dup2(null, sys.stderr.fileno())
450
 
    os.close(null)
 
685
    # Filter out log message from dbus module
 
686
    dbus_logger = logging.getLogger("dbus.proxies")
 
687
    class NullFilter(logging.Filter):
 
688
        def filter(self, record):
 
689
            return False
 
690
    dbus_filter = NullFilter()
 
691
    dbus_logger.addFilter(dbus_filter)
451
692
    try:
452
693
        try:
453
694
            mandos_clients = {path: ifs_and_props[client_interface]
456
697
                              .GetManagedObjects().items()
457
698
                              if client_interface in ifs_and_props}
458
699
        finally:
459
 
            # restore stderr
460
 
            os.dup2(stderrcopy, sys.stderr.fileno())
461
 
            os.close(stderrcopy)
 
700
            # restore dbus logger
 
701
            dbus_logger.removeFilter(dbus_filter)
462
702
    except dbus.exceptions.DBusException as e:
463
703
        log.critical("Failed to access Mandos server through D-Bus:"
464
704
                     "\n%s", e)
467
707
    # Compile dict of (clients: properties) to process
468
708
    clients = {}
469
709
 
470
 
    if options.all or not options.client:
 
710
    if not clientnames:
471
711
        clients = {bus.get_object(busname, path): properties
472
712
                   for path, properties in mandos_clients.items()}
473
713
    else:
474
 
        for name in options.client:
 
714
        for name in clientnames:
475
715
            for path, client in mandos_clients.items():
476
716
                if client["Name"] == name:
477
717
                    client_objc = bus.get_object(busname, path)
481
721
                log.critical("Client not found on server: %r", name)
482
722
                sys.exit(1)
483
723
 
484
 
    if not has_actions(options) and clients:
485
 
        if options.verbose or options.dump_json:
486
 
            keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
487
 
                        "Created", "Interval", "Host", "KeyID",
488
 
                        "Fingerprint", "CheckerRunning",
489
 
                        "LastEnabled", "ApprovalPending",
490
 
                        "ApprovedByDefault", "LastApprovalRequest",
491
 
                        "ApprovalDelay", "ApprovalDuration",
492
 
                        "Checker", "ExtendedTimeout", "Expires",
493
 
                        "LastCheckerStatus")
494
 
        else:
495
 
            keywords = defaultkeywords
496
 
 
497
 
        if options.dump_json:
498
 
            json.dump({client["Name"]: {key:
499
 
                                        bool(client[key])
500
 
                                        if isinstance(client[key],
501
 
                                                      dbus.Boolean)
502
 
                                        else client[key]
503
 
                                        for key in keywords}
504
 
                       for client in clients.values()},
505
 
                      fp=sys.stdout, indent=4,
506
 
                      separators=(',', ': '))
507
 
            print()
508
 
        else:
509
 
            print(TableOfClients(clients.values(), keywords))
510
 
    else:
511
 
        # Process each client in the list by all selected options
512
 
        for client in clients:
513
 
 
514
 
            def set_client_prop(prop, value):
515
 
                """Set a Client D-Bus property"""
516
 
                client.Set(client_interface, prop, value,
517
 
                           dbus_interface=dbus.PROPERTIES_IFACE)
518
 
 
519
 
            def set_client_prop_ms(prop, value):
520
 
                """Set a Client D-Bus property, converted
521
 
                from a string to milliseconds."""
522
 
                set_client_prop(prop,
523
 
                                string_to_delta(value).total_seconds()
524
 
                                * 1000)
525
 
 
526
 
            if options.remove:
527
 
                mandos_serv.RemoveClient(client.__dbus_object_path__)
528
 
            if options.enable:
529
 
                set_client_prop("Enabled", dbus.Boolean(True))
530
 
            if options.disable:
531
 
                set_client_prop("Enabled", dbus.Boolean(False))
532
 
            if options.bump_timeout:
533
 
                set_client_prop("LastCheckedOK", "")
534
 
            if options.start_checker:
535
 
                set_client_prop("CheckerRunning", dbus.Boolean(True))
536
 
            if options.stop_checker:
537
 
                set_client_prop("CheckerRunning", dbus.Boolean(False))
538
 
            if options.is_enabled:
539
 
                if client.Get(client_interface, "Enabled",
540
 
                              dbus_interface=dbus.PROPERTIES_IFACE):
541
 
                    sys.exit(0)
542
 
                else:
543
 
                    sys.exit(1)
544
 
            if options.checker is not None:
545
 
                set_client_prop("Checker", options.checker)
546
 
            if options.host is not None:
547
 
                set_client_prop("Host", options.host)
548
 
            if options.interval is not None:
549
 
                set_client_prop_ms("Interval", options.interval)
550
 
            if options.approval_delay is not None:
551
 
                set_client_prop_ms("ApprovalDelay",
552
 
                                   options.approval_delay)
553
 
            if options.approval_duration is not None:
554
 
                set_client_prop_ms("ApprovalDuration",
555
 
                                   options.approval_duration)
556
 
            if options.timeout is not None:
557
 
                set_client_prop_ms("Timeout", options.timeout)
558
 
            if options.extended_timeout is not None:
559
 
                set_client_prop_ms("ExtendedTimeout",
560
 
                                   options.extended_timeout)
561
 
            if options.secret is not None:
562
 
                set_client_prop("Secret",
563
 
                                dbus.ByteArray(options.secret.read()))
564
 
            if options.approved_by_default is not None:
565
 
                set_client_prop("ApprovedByDefault",
566
 
                                dbus.Boolean(options
567
 
                                             .approved_by_default))
568
 
            if options.approve:
569
 
                client.Approve(dbus.Boolean(True),
570
 
                               dbus_interface=client_interface)
571
 
            elif options.deny:
572
 
                client.Approve(dbus.Boolean(False),
573
 
                               dbus_interface=client_interface)
 
724
    # Run all commands on clients
 
725
    for command in commands:
 
726
        command.run(mandos_serv, clients)
574
727
 
575
728
 
576
729
class Test_milliseconds_to_string(unittest.TestCase):
596
749
            with self.assertLogs(log, logging.WARNING):
597
750
                value = string_to_delta("2h")
598
751
        else:
599
 
            value = string_to_delta("2h")
 
752
            class WarningFilter(logging.Filter):
 
753
                """Don't show, but record the presence of, warnings"""
 
754
                def filter(self, record):
 
755
                    is_warning = record.levelno >= logging.WARNING
 
756
                    self.found = is_warning or getattr(self, "found",
 
757
                                                       False)
 
758
                    return not is_warning
 
759
            warning_filter = WarningFilter()
 
760
            log.addFilter(warning_filter)
 
761
            try:
 
762
                value = string_to_delta("2h")
 
763
            finally:
 
764
                log.removeFilter(warning_filter)
 
765
            self.assertTrue(getattr(warning_filter, "found", False))
600
766
        self.assertEqual(value, datetime.timedelta(0, 7200))
601
767
 
602
768
class Test_TableOfClients(unittest.TestCase):
603
769
    def setUp(self):
604
 
        self.tablewords = {
 
770
        self.tableheaders = {
605
771
            "Attr1": "X",
606
772
            "AttrTwo": "Yy",
607
773
            "AttrThree": "Zzz",
647
813
            },
648
814
        ]
649
815
    def test_short_header(self):
650
 
        rows = TableOfClients(self.clients, self.keywords,
651
 
                              self.tablewords).rows()
652
 
        expected_rows = [
653
 
            "X  Yy",
654
 
            "x1 y1",
655
 
            "x2 y2"]
656
 
        self.assertEqual(rows, expected_rows)
 
816
        text = str(TableOfClients(self.clients, self.keywords,
 
817
                                  self.tableheaders))
 
818
        expected_text = """
 
819
X  Yy
 
820
x1 y1
 
821
x2 y2
 
822
"""[1:-1]
 
823
        self.assertEqual(text, expected_text)
657
824
    def test_booleans(self):
658
825
        keywords = ["Bool", "NonDbusBoolean"]
659
 
        rows = TableOfClients(self.clients, keywords,
660
 
                              self.tablewords).rows()
661
 
        expected_rows = [
662
 
            "A D-BUS Boolean A Non-D-BUS Boolean",
663
 
            "No              False              ",
664
 
            "Yes             True               ",
665
 
        ]
666
 
        self.assertEqual(rows, expected_rows)
 
826
        text = str(TableOfClients(self.clients, keywords,
 
827
                                  self.tableheaders))
 
828
        expected_text = """
 
829
A D-BUS Boolean A Non-D-BUS Boolean
 
830
No              False              
 
831
Yes             True               
 
832
"""[1:-1]
 
833
        self.assertEqual(text, expected_text)
667
834
    def test_milliseconds_detection(self):
668
835
        keywords = ["Integer", "Timeout", "Interval", "ApprovalDelay",
669
836
                    "ApprovalDuration", "ExtendedTimeout"]
670
 
        rows = TableOfClients(self.clients, keywords,
671
 
                              self.tablewords).rows()
672
 
        expected_rows = ("""
 
837
        text = str(TableOfClients(self.clients, keywords,
 
838
                                  self.tableheaders))
 
839
        expected_text = """
673
840
An Integer Timedelta 1 Timedelta 2 Timedelta 3 Timedelta 4 Timedelta 5
674
841
0          00:00:00    00:00:01    00:00:02    00:00:03    00:00:04   
675
842
1          1T02:03:05  1T02:03:06  1T02:03:07  1T02:03:08  1T02:03:09 
676
 
"""
677
 
        ).splitlines()[1:]
678
 
        self.assertEqual(rows, expected_rows)
 
843
"""[1:-1]
 
844
        self.assertEqual(text, expected_text)
679
845
    def test_empty_and_long_string_values(self):
680
846
        keywords = ["String"]
681
 
        rows = TableOfClients(self.clients, keywords,
682
 
                              self.tablewords).rows()
683
 
        expected_rows = ("""
 
847
        text = str(TableOfClients(self.clients, keywords,
 
848
                                  self.tableheaders))
 
849
        expected_text = """
684
850
A String                                                                                                                                                                                                                                                                                                                                  
685
851
                                                                                                                                                                                                                                                                                                                                          
686
852
A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,
687
 
"""
688
 
        ).splitlines()[1:]
689
 
        self.assertEqual(rows, expected_rows)
 
853
"""[1:-1]
 
854
        self.assertEqual(text, expected_text)
690
855
 
691
856
 
692
857