/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
#!/usr/bin/python
# -*- mode: python; coding: utf-8; after-save-hook: (lambda () (let ((command (if (and (boundp 'tramp-file-name-structure) (string-match (car tramp-file-name-structure) (buffer-file-name))) (tramp-file-name-localname (tramp-dissect-file-name (buffer-file-name))) (buffer-file-name)))) (if (= (shell-command (format "%s --check" (shell-quote-argument command)) "*Test*") 0) (let ((w (get-buffer-window "*Test*"))) (if w (delete-window w)) (kill-buffer "*Test*")) (display-buffer "*Test*")))); -*-
#
# Mandos Monitor - Control and monitor the Mandos server
#
# Copyright © 2008-2019 Teddy Hogeborn
# Copyright © 2008-2019 Björn Påhlsson
#
# This file is part of Mandos.
#
# Mandos is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#     Mandos is distributed in the hope that it will be useful, but
#     WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact the authors at <mandos@recompile.se>.
#

from __future__ import (division, absolute_import, print_function,
                        unicode_literals)

try:
    from future_builtins import *
except ImportError:
    pass

import sys
import argparse
import locale
import datetime
import re
import os
import collections
import json
import unittest
import logging

import dbus

# Show warnings by default
if not sys.warnoptions:
    import warnings
    warnings.simplefilter("default")

log = logging.getLogger(sys.argv[0])
logging.basicConfig(level="INFO", # Show info level messages
                    format="%(message)s") # Show basic log messages

logging.captureWarnings(True)   # Show warnings via the logging system

if sys.version_info.major == 2:
    str = unicode

locale.setlocale(locale.LC_ALL, "")

defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
domain = "se.recompile"
busname = domain + ".Mandos"
server_path = "/"
server_interface = domain + ".Mandos"
client_interface = domain + ".Mandos.Client"
version = "1.8.3"


try:
    dbus.OBJECT_MANAGER_IFACE
except AttributeError:
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"


def milliseconds_to_string(ms):
    td = datetime.timedelta(0, 0, 0, ms)
    return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
            .format(days="{}T".format(td.days) if td.days else "",
                    hours=td.seconds // 3600,
                    minutes=(td.seconds % 3600) // 60,
                    seconds=td.seconds % 60))


def rfc3339_duration_to_delta(duration):
    """Parse an RFC 3339 "duration" and return a datetime.timedelta

    >>> rfc3339_duration_to_delta("P7D")
    datetime.timedelta(7)
    >>> rfc3339_duration_to_delta("PT60S")
    datetime.timedelta(0, 60)
    >>> rfc3339_duration_to_delta("PT60M")
    datetime.timedelta(0, 3600)
    >>> rfc3339_duration_to_delta("P60M")
    datetime.timedelta(1680)
    >>> rfc3339_duration_to_delta("PT24H")
    datetime.timedelta(1)
    >>> rfc3339_duration_to_delta("P1W")
    datetime.timedelta(7)
    >>> rfc3339_duration_to_delta("PT5M30S")
    datetime.timedelta(0, 330)
    >>> rfc3339_duration_to_delta("P1DT3M20S")
    datetime.timedelta(1, 200)
    >>> # Can not be empty:
    >>> rfc3339_duration_to_delta("")
    Traceback (most recent call last):
    ...
    ValueError: Invalid RFC 3339 duration: u''
    >>> # Must start with "P":
    >>> rfc3339_duration_to_delta("1D")
    Traceback (most recent call last):
    ...
    ValueError: Invalid RFC 3339 duration: u'1D'
    >>> # Must use correct order
    >>> rfc3339_duration_to_delta("PT1S2M")
    Traceback (most recent call last):
    ...
    ValueError: Invalid RFC 3339 duration: u'PT1S2M'
    >>> # Time needs time marker
    >>> rfc3339_duration_to_delta("P1H2S")
    Traceback (most recent call last):
    ...
    ValueError: Invalid RFC 3339 duration: u'P1H2S'
    >>> # Weeks can not be combined with anything else
    >>> rfc3339_duration_to_delta("P1D2W")
    Traceback (most recent call last):
    ...
    ValueError: Invalid RFC 3339 duration: u'P1D2W'
    >>> rfc3339_duration_to_delta("P2W2H")
    Traceback (most recent call last):
    ...
    ValueError: Invalid RFC 3339 duration: u'P2W2H'
    """

    # Parsing an RFC 3339 duration with regular expressions is not
    # possible - there would have to be multiple places for the same
    # values, like seconds.  The current code, while more esoteric, is
    # cleaner without depending on a parsing library.  If Python had a
    # built-in library for parsing we would use it, but we'd like to
    # avoid excessive use of external libraries.

    # New type for defining tokens, syntax, and semantics all-in-one
    Token = collections.namedtuple("Token", (
        "regexp",  # To match token; if "value" is not None, must have
                   # a "group" containing digits
        "value",   # datetime.timedelta or None
        "followers"))           # Tokens valid after this token
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
    # the "duration" ABNF definition in RFC 3339, Appendix A.
    token_end = Token(re.compile(r"$"), None, frozenset())
    token_second = Token(re.compile(r"(\d+)S"),
                         datetime.timedelta(seconds=1),
                         frozenset((token_end, )))
    token_minute = Token(re.compile(r"(\d+)M"),
                         datetime.timedelta(minutes=1),
                         frozenset((token_second, token_end)))
    token_hour = Token(re.compile(r"(\d+)H"),
                       datetime.timedelta(hours=1),
                       frozenset((token_minute, token_end)))
    token_time = Token(re.compile(r"T"),
                       None,
                       frozenset((token_hour, token_minute,
                                  token_second)))
    token_day = Token(re.compile(r"(\d+)D"),
                      datetime.timedelta(days=1),
                      frozenset((token_time, token_end)))
    token_month = Token(re.compile(r"(\d+)M"),
                        datetime.timedelta(weeks=4),
                        frozenset((token_day, token_end)))
    token_year = Token(re.compile(r"(\d+)Y"),
                       datetime.timedelta(weeks=52),
                       frozenset((token_month, token_end)))
    token_week = Token(re.compile(r"(\d+)W"),
                       datetime.timedelta(weeks=1),
                       frozenset((token_end, )))
    token_duration = Token(re.compile(r"P"), None,
                           frozenset((token_year, token_month,
                                      token_day, token_time,
                                      token_week)))
    # Define starting values:
    # Value so far
    value = datetime.timedelta()
    found_token = None
    # Following valid tokens
    followers = frozenset((token_duration, ))
    # String left to parse
    s = duration
    # Loop until end token is found
    while found_token is not token_end:
        # Search for any currently valid tokens
        for token in followers:
            match = token.regexp.match(s)
            if match is not None:
                # Token found
                if token.value is not None:
                    # Value found, parse digits
                    factor = int(match.group(1), 10)
                    # Add to value so far
                    value += factor * token.value
                # Strip token from string
                s = token.regexp.sub("", s, 1)
                # Go to found token
                found_token = token
                # Set valid next tokens
                followers = found_token.followers
                break
        else:
            # No currently valid tokens were found
            raise ValueError("Invalid RFC 3339 duration: {!r}"
                             .format(duration))
    # End token found
    return value


def string_to_delta(interval):
    """Parse a string and return a datetime.timedelta"""

    try:
        return rfc3339_duration_to_delta(interval)
    except ValueError as e:
        log.warning("%s - Parsing as pre-1.6.1 interval instead",
                    ' '.join(e.args))
    return parse_pre_1_6_1_interval(interval)


def parse_pre_1_6_1_interval(interval):
    """Parse an interval string as documented by Mandos before 1.6.1,
    and return a datetime.timedelta

    >>> parse_pre_1_6_1_interval('7d')
    datetime.timedelta(7)
    >>> parse_pre_1_6_1_interval('60s')
    datetime.timedelta(0, 60)
    >>> parse_pre_1_6_1_interval('60m')
    datetime.timedelta(0, 3600)
    >>> parse_pre_1_6_1_interval('24h')
    datetime.timedelta(1)
    >>> parse_pre_1_6_1_interval('1w')
    datetime.timedelta(7)
    >>> parse_pre_1_6_1_interval('5m 30s')
    datetime.timedelta(0, 330)
    >>> parse_pre_1_6_1_interval('')
    datetime.timedelta(0)
    >>> # Ignore unknown characters, allow any order and repetitions
    >>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m')
    datetime.timedelta(2, 480, 18000)

    """

    value = datetime.timedelta(0)
    regexp = re.compile(r"(\d+)([dsmhw]?)")

    for num, suffix in regexp.findall(interval):
        if suffix == "d":
            value += datetime.timedelta(int(num))
        elif suffix == "s":
            value += datetime.timedelta(0, int(num))
        elif suffix == "m":
            value += datetime.timedelta(0, 0, 0, 0, int(num))
        elif suffix == "h":
            value += datetime.timedelta(0, 0, 0, 0, 0, int(num))
        elif suffix == "w":
            value += datetime.timedelta(0, 0, 0, 0, 0, 0, int(num))
        elif suffix == "":
            value += datetime.timedelta(0, 0, 0, int(num))
    return value


class TableOfClients(object):
    tablewords = {
        "Name": "Name",
        "Enabled": "Enabled",
        "Timeout": "Timeout",
        "LastCheckedOK": "Last Successful Check",
        "LastApprovalRequest": "Last Approval Request",
        "Created": "Created",
        "Interval": "Interval",
        "Host": "Host",
        "Fingerprint": "Fingerprint",
        "KeyID": "Key ID",
        "CheckerRunning": "Check Is Running",
        "LastEnabled": "Last Enabled",
        "ApprovalPending": "Approval Is Pending",
        "ApprovedByDefault": "Approved By Default",
        "ApprovalDelay": "Approval Delay",
        "ApprovalDuration": "Approval Duration",
        "Checker": "Checker",
        "ExtendedTimeout": "Extended Timeout",
        "Expires": "Expires",
        "LastCheckerStatus": "Last Checker Status",
    }

    def __init__(self, clients, keywords, tablewords=None):
        self.clients = clients
        self.keywords = keywords
        if tablewords is not None:
            self.tablewords = tablewords

    def __str__(self):
        return "\n".join(self.rows())

    if sys.version_info.major == 2:
        __unicode__ = __str__
        def __str__(self):
            return str(self).encode(locale.getpreferredencoding())

    def rows(self):
        format_string = self.row_formatting_string()
        rows = [self.header_line(format_string)]
        rows.extend(self.client_line(client, format_string)
                    for client in self.clients)
        return rows

    def row_formatting_string(self):
        "Format string used to format table rows"
        return " ".join("{{{key}:{width}}}".format(
            width=max(len(self.tablewords[key]),
                      *(len(self.string_from_client(client, key))
                        for client in self.clients)),
            key=key)
                        for key in self.keywords)

    def string_from_client(self, client, key):
        return self.valuetostring(client[key], key)

    @staticmethod
    def valuetostring(value, keyword):
        if isinstance(value, dbus.Boolean):
            return "Yes" if value else "No"
        if keyword in ("Timeout", "Interval", "ApprovalDelay",
                       "ApprovalDuration", "ExtendedTimeout"):
            return milliseconds_to_string(value)
        return str(value)

    def header_line(self, format_string):
        return format_string.format(**self.tablewords)

    def client_line(self, client, format_string):
        return format_string.format(
            **{key: self.string_from_client(client, key)
               for key in self.keywords})


def has_actions(options):
    return any((options.enable,
                options.disable,
                options.bump_timeout,
                options.start_checker,
                options.stop_checker,
                options.is_enabled,
                options.remove,
                options.checker is not None,
                options.timeout is not None,
                options.extended_timeout is not None,
                options.interval is not None,
                options.approved_by_default is not None,
                options.approval_delay is not None,
                options.approval_duration is not None,
                options.host is not None,
                options.secret is not None,
                options.approve,
                options.deny))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--version", action="version",
                        version="%(prog)s {}".format(version),
                        help="show version number and exit")
    parser.add_argument("-a", "--all", action="store_true",
                        help="Select all clients")
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="Print all fields")
    parser.add_argument("-j", "--dump-json", action="store_true",
                        help="Dump client data in JSON format")
    enable_disable = parser.add_mutually_exclusive_group()
    enable_disable.add_argument("-e", "--enable", action="store_true",
                                help="Enable client")
    enable_disable.add_argument("-d", "--disable",
                                action="store_true",
                                help="disable client")
    parser.add_argument("-b", "--bump-timeout", action="store_true",
                        help="Bump timeout for client")
    start_stop_checker = parser.add_mutually_exclusive_group()
    start_stop_checker.add_argument("--start-checker",
                                    action="store_true",
                                    help="Start checker for client")
    start_stop_checker.add_argument("--stop-checker",
                                    action="store_true",
                                    help="Stop checker for client")
    parser.add_argument("-V", "--is-enabled", action="store_true",
                        help="Check if client is enabled")
    parser.add_argument("-r", "--remove", action="store_true",
                        help="Remove client")
    parser.add_argument("-c", "--checker",
                        help="Set checker command for client")
    parser.add_argument("-t", "--timeout",
                        help="Set timeout for client")
    parser.add_argument("--extended-timeout",
                        help="Set extended timeout for client")
    parser.add_argument("-i", "--interval",
                        help="Set checker interval for client")
    approve_deny_default = parser.add_mutually_exclusive_group()
    approve_deny_default.add_argument(
        "--approve-by-default", action="store_true",
        default=None, dest="approved_by_default",
        help="Set client to be approved by default")
    approve_deny_default.add_argument(
        "--deny-by-default", action="store_false",
        dest="approved_by_default",
        help="Set client to be denied by default")
    parser.add_argument("--approval-delay",
                        help="Set delay before client approve/deny")
    parser.add_argument("--approval-duration",
                        help="Set duration of one client approval")
    parser.add_argument("-H", "--host", help="Set host for client")
    parser.add_argument("-s", "--secret",
                        type=argparse.FileType(mode="rb"),
                        help="Set password blob (file) for client")
    approve_deny = parser.add_mutually_exclusive_group()
    approve_deny.add_argument(
        "-A", "--approve", action="store_true",
        help="Approve any current client request")
    approve_deny.add_argument("-D", "--deny", action="store_true",
                              help="Deny any current client request")
    parser.add_argument("--check", action="store_true",
                        help="Run self-test")
    parser.add_argument("client", nargs="*", help="Client name")
    options = parser.parse_args()

    if has_actions(options) and not (options.client or options.all):
        parser.error("Options require clients names or --all.")
    if options.verbose and has_actions(options):
        parser.error("--verbose can only be used alone.")
    if options.dump_json and (options.verbose
                              or has_actions(options)):
        parser.error("--dump-json can only be used alone.")
    if options.all and not has_actions(options):
        parser.error("--all requires an action.")
    if options.is_enabled and len(options.client) > 1:
            parser.error("--is-enabled requires exactly one client")

    try:
        bus = dbus.SystemBus()
        mandos_dbus_objc = bus.get_object(busname, server_path)
    except dbus.exceptions.DBusException:
        log.critical("Could not connect to Mandos server")
        sys.exit(1)

    mandos_serv = dbus.Interface(mandos_dbus_objc,
                                 dbus_interface=server_interface)
    mandos_serv_object_manager = dbus.Interface(
        mandos_dbus_objc, dbus_interface=dbus.OBJECT_MANAGER_IFACE)

    # block stderr since dbus library prints to stderr
    null = os.open(os.path.devnull, os.O_RDWR)
    stderrcopy = os.dup(sys.stderr.fileno())
    os.dup2(null, sys.stderr.fileno())
    os.close(null)
    try:
        try:
            mandos_clients = {path: ifs_and_props[client_interface]
                              for path, ifs_and_props in
                              mandos_serv_object_manager
                              .GetManagedObjects().items()
                              if client_interface in ifs_and_props}
        finally:
            # restore stderr
            os.dup2(stderrcopy, sys.stderr.fileno())
            os.close(stderrcopy)
    except dbus.exceptions.DBusException as e:
        log.critical("Failed to access Mandos server through D-Bus:"
                     "\n%s", e)
        sys.exit(1)

    # Compile dict of (clients: properties) to process
    clients = {}

    if options.all or not options.client:
        clients = {bus.get_object(busname, path): properties
                   for path, properties in mandos_clients.items()}
    else:
        for name in options.client:
            for path, client in mandos_clients.items():
                if client["Name"] == name:
                    client_objc = bus.get_object(busname, path)
                    clients[client_objc] = client
                    break
            else:
                log.critical("Client not found on server: %r", name)
                sys.exit(1)

    if not has_actions(options) and clients:
        if options.verbose or options.dump_json:
            keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
                        "Created", "Interval", "Host", "KeyID",
                        "Fingerprint", "CheckerRunning",
                        "LastEnabled", "ApprovalPending",
                        "ApprovedByDefault", "LastApprovalRequest",
                        "ApprovalDelay", "ApprovalDuration",
                        "Checker", "ExtendedTimeout", "Expires",
                        "LastCheckerStatus")
        else:
            keywords = defaultkeywords

        if options.dump_json:
            json.dump({client["Name"]: {key:
                                        bool(client[key])
                                        if isinstance(client[key],
                                                      dbus.Boolean)
                                        else client[key]
                                        for key in keywords}
                       for client in clients.values()},
                      fp=sys.stdout, indent=4,
                      separators=(',', ': '))
            print()
        else:
            print(TableOfClients(clients.values(), keywords))
    else:
        # Process each client in the list by all selected options
        for client in clients:

            def set_client_prop(prop, value):
                """Set a Client D-Bus property"""
                client.Set(client_interface, prop, value,
                           dbus_interface=dbus.PROPERTIES_IFACE)

            def set_client_prop_ms(prop, value):
                """Set a Client D-Bus property, converted
                from a string to milliseconds."""
                set_client_prop(prop,
                                string_to_delta(value).total_seconds()
                                * 1000)

            if options.remove:
                mandos_serv.RemoveClient(client.__dbus_object_path__)
            if options.enable:
                set_client_prop("Enabled", dbus.Boolean(True))
            if options.disable:
                set_client_prop("Enabled", dbus.Boolean(False))
            if options.bump_timeout:
                set_client_prop("LastCheckedOK", "")
            if options.start_checker:
                set_client_prop("CheckerRunning", dbus.Boolean(True))
            if options.stop_checker:
                set_client_prop("CheckerRunning", dbus.Boolean(False))
            if options.is_enabled:
                if client.Get(client_interface, "Enabled",
                              dbus_interface=dbus.PROPERTIES_IFACE):
                    sys.exit(0)
                else:
                    sys.exit(1)
            if options.checker is not None:
                set_client_prop("Checker", options.checker)
            if options.host is not None:
                set_client_prop("Host", options.host)
            if options.interval is not None:
                set_client_prop_ms("Interval", options.interval)
            if options.approval_delay is not None:
                set_client_prop_ms("ApprovalDelay",
                                   options.approval_delay)
            if options.approval_duration is not None:
                set_client_prop_ms("ApprovalDuration",
                                   options.approval_duration)
            if options.timeout is not None:
                set_client_prop_ms("Timeout", options.timeout)
            if options.extended_timeout is not None:
                set_client_prop_ms("ExtendedTimeout",
                                   options.extended_timeout)
            if options.secret is not None:
                set_client_prop("Secret",
                                dbus.ByteArray(options.secret.read()))
            if options.approved_by_default is not None:
                set_client_prop("ApprovedByDefault",
                                dbus.Boolean(options
                                             .approved_by_default))
            if options.approve:
                client.Approve(dbus.Boolean(True),
                               dbus_interface=client_interface)
            elif options.deny:
                client.Approve(dbus.Boolean(False),
                               dbus_interface=client_interface)


class Test_milliseconds_to_string(unittest.TestCase):
    def test_all(self):
        self.assertEqual(milliseconds_to_string(93785000),
                         "1T02:03:05")
    def test_no_days(self):
        self.assertEqual(milliseconds_to_string(7385000), "02:03:05")
    def test_all_zero(self):
        self.assertEqual(milliseconds_to_string(0), "00:00:00")
    def test_no_fractional_seconds(self):
        self.assertEqual(milliseconds_to_string(400), "00:00:00")
        self.assertEqual(milliseconds_to_string(900), "00:00:00")
        self.assertEqual(milliseconds_to_string(1900), "00:00:01")

class Test_string_to_delta(unittest.TestCase):
    def test_handles_basic_rfc3339(self):
        self.assertEqual(string_to_delta("PT2H"),
                         datetime.timedelta(0, 7200))
    def test_falls_back_to_pre_1_6_1_with_warning(self):
        # assertLogs only exists in Python 3.4
        if hasattr(self, "assertLogs"):
            with self.assertLogs(log, logging.WARNING):
                value = string_to_delta("2h")
        else:
            value = string_to_delta("2h")
        self.assertEqual(value, datetime.timedelta(0, 7200))

class Test_TableOfClients(unittest.TestCase):
    def setUp(self):
        self.tablewords = {
            "Attr1": "X",
            "AttrTwo": "Yy",
            "AttrThree": "Zzz",
            "Bool": "A D-BUS Boolean",
            "NonDbusBoolean": "A Non-D-BUS Boolean",
            "Integer": "An Integer",
            "Timeout": "Timedelta 1",
            "Interval": "Timedelta 2",
            "ApprovalDelay": "Timedelta 3",
            "ApprovalDuration": "Timedelta 4",
            "ExtendedTimeout": "Timedelta 5",
            "String": "A String",
        }
        self.keywords = ["Attr1", "AttrTwo"]
        self.clients = [
            {
                "Attr1": "x1",
                "AttrTwo": "y1",
                "AttrThree": "z1",
                "Bool": dbus.Boolean(False),
                "NonDbusBoolean": False,
                "Integer": 0,
                "Timeout": 0,
                "Interval": 1000,
                "ApprovalDelay": 2000,
                "ApprovalDuration": 3000,
                "ExtendedTimeout": 4000,
                "String": "",
            },
            {
                "Attr1": "x2",
                "AttrTwo": "y2",
                "AttrThree": "z2",
                "Bool": dbus.Boolean(True),
                "NonDbusBoolean": True,
                "Integer": 1,
                "Timeout": 93785000,
                "Interval": 93786000,
                "ApprovalDelay": 93787000,
                "ApprovalDuration": 93788000,
                "ExtendedTimeout": 93789000,
                "String": "A huge string which will not fit," * 10,
            },
        ]
    def test_short_header(self):
        text = str(TableOfClients(self.clients, self.keywords,
                                  self.tablewords))
        expected_text = """
X  Yy
x1 y1
x2 y2
"""[1:-1]
        self.assertEqual(text, expected_text)
    def test_booleans(self):
        keywords = ["Bool", "NonDbusBoolean"]
        text = str(TableOfClients(self.clients, keywords,
                                  self.tablewords))
        expected_text = """
A D-BUS Boolean A Non-D-BUS Boolean
No              False              
Yes             True               
"""[1:-1]
        self.assertEqual(text, expected_text)
    def test_milliseconds_detection(self):
        keywords = ["Integer", "Timeout", "Interval", "ApprovalDelay",
                    "ApprovalDuration", "ExtendedTimeout"]
        text = str(TableOfClients(self.clients, keywords,
                                  self.tablewords))
        expected_text = """
An Integer Timedelta 1 Timedelta 2 Timedelta 3 Timedelta 4 Timedelta 5
0          00:00:00    00:00:01    00:00:02    00:00:03    00:00:04   
1          1T02:03:05  1T02:03:06  1T02:03:07  1T02:03:08  1T02:03:09 
"""[1:-1]
        self.assertEqual(text, expected_text)
    def test_empty_and_long_string_values(self):
        keywords = ["String"]
        text = str(TableOfClients(self.clients, keywords,
                                  self.tablewords))
        expected_text = """
A String                                                                                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                                                                                          
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,
"""[1:-1]
        self.assertEqual(text, expected_text)



def should_only_run_tests():
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("--check", action='store_true')
    args, unknown_args = parser.parse_known_args()
    run_tests = args.check
    if run_tests:
        # Remove --check argument from sys.argv
        sys.argv[1:] = unknown_args
    return run_tests

# Add all tests from doctest strings
def load_tests(loader, tests, none):
    import doctest
    tests.addTests(doctest.DocTestSuite())
    return tests

if __name__ == "__main__":
    if should_only_run_tests():
        # Call using ./tdd-python-script --check [--verbose]
        unittest.main()
    else:
        main()