/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-30 07:03:04 UTC
  • Revision ID: teddy@recompile.se-20190330070304-dqgch62lsaaygg46
mandos-ctl: Refactor D-Bus operations

* mandos-ctl (dbus): Rename imported module to "dbus_python".
  (main): Only create a bus object and do everything via that object.
  (get_mandos_dbus_object): Remove and move code into dbus or
                            dbus_python_adapter namespaces.
  (if_dbus_exception_log_with_exception_and_exit): - '' -
  (SilenceLogger): - '' -
  (dbus): New; move everything dbus-specific into this module-like
          namespace.
  (dbus_python_adapter): New; move everything specific to the
                         dbus-python D-Bus module into this
                         module-like namespace.
  (command.Base.run): Take only a bus argument; use only that.  Pass
                      "client" argument as a D-Bus object path string,
                      not a dbus-python proxy object.  All derivatives
                      adjusted.
  (command.IsEnabled.is_enabled): Remove.
  (command.Approve, command.Deny, command.Remove,
  command.PropertySetter): Do no logging of D-Bus commands, and use
  only bus, not client, to do D-Bus calls.
  (command.DumpJSON.dbus_boolean_to_bool): Remove; move filtering to
                                           dbus_python_adapter.
  (command.Enable, command.Disable, command.StopChecker,
  command.ApproveByDefault): Use normal Python booleans instead of
  dbus-python's special Boolean types.
  (Unique): New; move here out from inside TestPropertySetterCmd.
  (Test_get_mandos_dbus_object): Remove.
  (Test_get_managed_objects): - '' -
  (Test_dbus_exceptions): New.
  (Test_dbus_MandosBus): - '' -
  (Test_dbus_python_adapter_SystemBus): - '' -
  (Test_dbus_python_adapter_CachingBus): - '' -
  (Test_commands_from_options): Don't create mock client proxy
  objects, define dict of client properties and use a mock dbus to
  verify that the correct D-Bus calls are made.  Also remove any types
  specific to dbus-python.
  (TestEnableCmd, TestDisableCmd, TestStartCheckerCmd,
  TestStopCheckerCmd, TestApproveByDefaultCmd, TestDenyByDefaultCmd):
  Use normal Python booleans instead of dbus-python's special Boolean
  types.
  (TestPropertySetterValueCmd.runTest): Remove; unnecessary.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
2
 
# -*- after-save-hook: (lambda () (let ((command (if (fboundp 'file-local-name) (file-local-name (buffer-file-name)) (or (file-remote-p (buffer-file-name) 'localname) (buffer-file-name))))) (if (= (progn (if (get-buffer "*Test*") (kill-buffer "*Test*")) (process-file-shell-command (format "%s --check" (shell-quote-argument command)) nil "*Test*")) 0) (let ((w (get-buffer-window "*Test*"))) (if w (delete-window w))) (progn (with-current-buffer "*Test*" (compilation-mode)) (display-buffer "*Test*" '(display-buffer-in-side-window)))))); coding: utf-8 -*-
 
2
# -*- 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*")))); -*-
3
3
#
4
4
# Mandos Monitor - Control and monitor the Mandos server
5
5
#
45
45
import io
46
46
import tempfile
47
47
import contextlib
 
48
import abc
48
49
 
49
 
try:
50
 
    import pydbus
51
 
    import gi
52
 
    dbus_python = None
53
 
except ImportError:
54
 
    import dbus as dbus_python
55
 
    pydbus = None
56
 
    class gi(object):
57
 
        """Dummy gi module, for the tests"""
58
 
        class repository(object):
59
 
            class GLib(object):
60
 
                class Error(Exception):
61
 
                    pass
 
50
import dbus as dbus_python
62
51
 
63
52
# Show warnings by default
64
53
if not sys.warnoptions:
78
67
 
79
68
locale.setlocale(locale.LC_ALL, "")
80
69
 
81
 
version = "1.8.4"
 
70
version = "1.8.3"
82
71
 
83
72
 
84
73
def main():
93
82
    if options.debug:
94
83
        log.setLevel(logging.DEBUG)
95
84
 
96
 
    if pydbus is not None:
97
 
        bus = pydbus_adapter.CachingBus(pydbus)
98
 
    else:
99
 
        bus = dbus_python_adapter.CachingBus(dbus_python)
 
85
    bus = dbus_python_adapter.CachingBus(dbus_python)
100
86
 
101
87
    try:
102
88
        all_clients = bus.get_clients_and_properties()
136
122
                        help="Select all clients")
137
123
    parser.add_argument("-v", "--verbose", action="store_true",
138
124
                        help="Print all fields")
139
 
    parser.add_argument("-j", "--dump-json", dest="commands",
140
 
                        action="append_const", default=[],
141
 
                        const=command.DumpJSON(),
 
125
    parser.add_argument("-j", "--dump-json", action="store_true",
142
126
                        help="Dump client data in JSON format")
143
127
    enable_disable = parser.add_mutually_exclusive_group()
144
 
    enable_disable.add_argument("-e", "--enable", dest="commands",
145
 
                                action="append_const", default=[],
146
 
                                const=command.Enable(),
 
128
    enable_disable.add_argument("-e", "--enable", action="store_true",
147
129
                                help="Enable client")
148
 
    enable_disable.add_argument("-d", "--disable", dest="commands",
149
 
                                action="append_const", default=[],
150
 
                                const=command.Disable(),
 
130
    enable_disable.add_argument("-d", "--disable",
 
131
                                action="store_true",
151
132
                                help="disable client")
152
 
    parser.add_argument("-b", "--bump-timeout", dest="commands",
153
 
                        action="append_const", default=[],
154
 
                        const=command.BumpTimeout(),
 
133
    parser.add_argument("-b", "--bump-timeout", action="store_true",
155
134
                        help="Bump timeout for client")
156
135
    start_stop_checker = parser.add_mutually_exclusive_group()
157
136
    start_stop_checker.add_argument("--start-checker",
158
 
                                    dest="commands",
159
 
                                    action="append_const", default=[],
160
 
                                    const=command.StartChecker(),
 
137
                                    action="store_true",
161
138
                                    help="Start checker for client")
162
 
    start_stop_checker.add_argument("--stop-checker", dest="commands",
163
 
                                    action="append_const", default=[],
164
 
                                    const=command.StopChecker(),
 
139
    start_stop_checker.add_argument("--stop-checker",
 
140
                                    action="store_true",
165
141
                                    help="Stop checker for client")
166
 
    parser.add_argument("-V", "--is-enabled", dest="commands",
167
 
                        action="append_const", default=[],
168
 
                        const=command.IsEnabled(),
 
142
    parser.add_argument("-V", "--is-enabled", action="store_true",
169
143
                        help="Check if client is enabled")
170
 
    parser.add_argument("-r", "--remove", dest="commands",
171
 
                        action="append_const", default=[],
172
 
                        const=command.Remove(),
 
144
    parser.add_argument("-r", "--remove", action="store_true",
173
145
                        help="Remove client")
174
 
    parser.add_argument("-c", "--checker", dest="commands",
175
 
                        action="append", default=[],
176
 
                        metavar="COMMAND", type=command.SetChecker,
 
146
    parser.add_argument("-c", "--checker",
177
147
                        help="Set checker command for client")
178
 
    parser.add_argument(
179
 
        "-t", "--timeout", dest="commands", action="append",
180
 
        default=[], metavar="TIME",
181
 
        type=command.SetTimeout.argparse(string_to_delta),
182
 
        help="Set timeout for client")
183
 
    parser.add_argument(
184
 
        "--extended-timeout", dest="commands", action="append",
185
 
        default=[], metavar="TIME",
186
 
        type=command.SetExtendedTimeout.argparse(string_to_delta),
187
 
        help="Set extended timeout for client")
188
 
    parser.add_argument(
189
 
        "-i", "--interval", dest="commands", action="append",
190
 
        default=[], metavar="TIME",
191
 
        type=command.SetInterval.argparse(string_to_delta),
192
 
        help="Set checker interval for client")
 
148
    parser.add_argument("-t", "--timeout", type=string_to_delta,
 
149
                        help="Set timeout for client")
 
150
    parser.add_argument("--extended-timeout", type=string_to_delta,
 
151
                        help="Set extended timeout for client")
 
152
    parser.add_argument("-i", "--interval", type=string_to_delta,
 
153
                        help="Set checker interval for client")
193
154
    approve_deny_default = parser.add_mutually_exclusive_group()
194
155
    approve_deny_default.add_argument(
195
 
        "--approve-by-default", dest="commands",
196
 
        action="append_const", default=[],
197
 
        const=command.ApproveByDefault(),
 
156
        "--approve-by-default", action="store_true",
 
157
        default=None, dest="approved_by_default",
198
158
        help="Set client to be approved by default")
199
159
    approve_deny_default.add_argument(
200
 
        "--deny-by-default", dest="commands",
201
 
        action="append_const", default=[],
202
 
        const=command.DenyByDefault(),
 
160
        "--deny-by-default", action="store_false",
 
161
        dest="approved_by_default",
203
162
        help="Set client to be denied by default")
204
 
    parser.add_argument(
205
 
        "--approval-delay", dest="commands", action="append",
206
 
        default=[], metavar="TIME",
207
 
        type=command.SetApprovalDelay.argparse(string_to_delta),
208
 
        help="Set delay before client approve/deny")
209
 
    parser.add_argument(
210
 
        "--approval-duration", dest="commands", action="append",
211
 
        default=[], metavar="TIME",
212
 
        type=command.SetApprovalDuration.argparse(string_to_delta),
213
 
        help="Set duration of one client approval")
214
 
    parser.add_argument("-H", "--host", dest="commands",
215
 
                        action="append", default=[], metavar="STRING",
216
 
                        type=command.SetHost,
217
 
                        help="Set host for client")
218
 
    parser.add_argument(
219
 
        "-s", "--secret", dest="commands", action="append",
220
 
        default=[], metavar="FILENAME",
221
 
        type=command.SetSecret.argparse(argparse.FileType(mode="rb")),
222
 
        help="Set password blob (file) for client")
 
163
    parser.add_argument("--approval-delay", type=string_to_delta,
 
164
                        help="Set delay before client approve/deny")
 
165
    parser.add_argument("--approval-duration", type=string_to_delta,
 
166
                        help="Set duration of one client approval")
 
167
    parser.add_argument("-H", "--host", help="Set host for client")
 
168
    parser.add_argument("-s", "--secret",
 
169
                        type=argparse.FileType(mode="rb"),
 
170
                        help="Set password blob (file) for client")
223
171
    approve_deny = parser.add_mutually_exclusive_group()
224
172
    approve_deny.add_argument(
225
 
        "-A", "--approve", dest="commands", action="append_const",
226
 
        default=[], const=command.Approve(),
 
173
        "-A", "--approve", action="store_true",
227
174
        help="Approve any current client request")
228
 
    approve_deny.add_argument("-D", "--deny", dest="commands",
229
 
                              action="append_const", default=[],
230
 
                              const=command.Deny(),
 
175
    approve_deny.add_argument("-D", "--deny", action="store_true",
231
176
                              help="Deny any current client request")
232
177
    parser.add_argument("--debug", action="store_true",
233
178
                        help="Debug mode (show D-Bus commands)")
250
195
def rfc3339_duration_to_delta(duration):
251
196
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
252
197
 
253
 
    >>> rfc3339_duration_to_delta("P7D") == datetime.timedelta(7)
254
 
    True
255
 
    >>> rfc3339_duration_to_delta("PT60S") == datetime.timedelta(0, 60)
256
 
    True
257
 
    >>> rfc3339_duration_to_delta("PT60M") == datetime.timedelta(hours=1)
258
 
    True
259
 
    >>> # 60 months
260
 
    >>> rfc3339_duration_to_delta("P60M") == datetime.timedelta(1680)
261
 
    True
262
 
    >>> rfc3339_duration_to_delta("PT24H") == datetime.timedelta(1)
263
 
    True
264
 
    >>> rfc3339_duration_to_delta("P1W") == datetime.timedelta(7)
265
 
    True
266
 
    >>> rfc3339_duration_to_delta("PT5M30S") == datetime.timedelta(0, 330)
267
 
    True
268
 
    >>> rfc3339_duration_to_delta("P1DT3M20S") == datetime.timedelta(1, 200)
269
 
    True
 
198
    >>> rfc3339_duration_to_delta("P7D")
 
199
    datetime.timedelta(7)
 
200
    >>> rfc3339_duration_to_delta("PT60S")
 
201
    datetime.timedelta(0, 60)
 
202
    >>> rfc3339_duration_to_delta("PT60M")
 
203
    datetime.timedelta(0, 3600)
 
204
    >>> rfc3339_duration_to_delta("P60M")
 
205
    datetime.timedelta(1680)
 
206
    >>> rfc3339_duration_to_delta("PT24H")
 
207
    datetime.timedelta(1)
 
208
    >>> rfc3339_duration_to_delta("P1W")
 
209
    datetime.timedelta(7)
 
210
    >>> rfc3339_duration_to_delta("PT5M30S")
 
211
    datetime.timedelta(0, 330)
 
212
    >>> rfc3339_duration_to_delta("P1DT3M20S")
 
213
    datetime.timedelta(1, 200)
270
214
    >>> # Can not be empty:
271
215
    >>> rfc3339_duration_to_delta("")
272
216
    Traceback (most recent call last):
382
326
    """Parse an interval string as documented by Mandos before 1.6.1,
383
327
    and return a datetime.timedelta
384
328
 
385
 
    >>> parse_pre_1_6_1_interval('7d') == datetime.timedelta(days=7)
386
 
    True
387
 
    >>> parse_pre_1_6_1_interval('60s') == datetime.timedelta(0, 60)
388
 
    True
389
 
    >>> parse_pre_1_6_1_interval('60m') == datetime.timedelta(hours=1)
390
 
    True
391
 
    >>> parse_pre_1_6_1_interval('24h') == datetime.timedelta(days=1)
392
 
    True
393
 
    >>> parse_pre_1_6_1_interval('1w') == datetime.timedelta(days=7)
394
 
    True
395
 
    >>> parse_pre_1_6_1_interval('5m 30s') == datetime.timedelta(0, 330)
396
 
    True
397
 
    >>> parse_pre_1_6_1_interval('') == datetime.timedelta(0)
398
 
    True
 
329
    >>> parse_pre_1_6_1_interval('7d')
 
330
    datetime.timedelta(7)
 
331
    >>> parse_pre_1_6_1_interval('60s')
 
332
    datetime.timedelta(0, 60)
 
333
    >>> parse_pre_1_6_1_interval('60m')
 
334
    datetime.timedelta(0, 3600)
 
335
    >>> parse_pre_1_6_1_interval('24h')
 
336
    datetime.timedelta(1)
 
337
    >>> parse_pre_1_6_1_interval('1w')
 
338
    datetime.timedelta(7)
 
339
    >>> parse_pre_1_6_1_interval('5m 30s')
 
340
    datetime.timedelta(0, 330)
 
341
    >>> parse_pre_1_6_1_interval('')
 
342
    datetime.timedelta(0)
399
343
    >>> # Ignore unknown characters, allow any order and repetitions
400
 
    >>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m') == datetime.timedelta(2, 480, 18000)
401
 
    True
 
344
    >>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m')
 
345
    datetime.timedelta(2, 480, 18000)
402
346
 
403
347
    """
404
348
 
425
369
    """Apply additional restrictions on options, not expressible in
426
370
argparse"""
427
371
 
428
 
    def has_commands(options, commands=None):
429
 
        if commands is None:
430
 
            commands = (command.Enable,
431
 
                        command.Disable,
432
 
                        command.BumpTimeout,
433
 
                        command.StartChecker,
434
 
                        command.StopChecker,
435
 
                        command.IsEnabled,
436
 
                        command.Remove,
437
 
                        command.SetChecker,
438
 
                        command.SetTimeout,
439
 
                        command.SetExtendedTimeout,
440
 
                        command.SetInterval,
441
 
                        command.ApproveByDefault,
442
 
                        command.DenyByDefault,
443
 
                        command.SetApprovalDelay,
444
 
                        command.SetApprovalDuration,
445
 
                        command.SetHost,
446
 
                        command.SetSecret,
447
 
                        command.Approve,
448
 
                        command.Deny)
449
 
        return any(isinstance(cmd, commands)
450
 
                   for cmd in options.commands)
 
372
    def has_actions(options):
 
373
        return any((options.enable,
 
374
                    options.disable,
 
375
                    options.bump_timeout,
 
376
                    options.start_checker,
 
377
                    options.stop_checker,
 
378
                    options.is_enabled,
 
379
                    options.remove,
 
380
                    options.checker is not None,
 
381
                    options.timeout is not None,
 
382
                    options.extended_timeout is not None,
 
383
                    options.interval is not None,
 
384
                    options.approved_by_default is not None,
 
385
                    options.approval_delay is not None,
 
386
                    options.approval_duration is not None,
 
387
                    options.host is not None,
 
388
                    options.secret is not None,
 
389
                    options.approve,
 
390
                    options.deny))
451
391
 
452
 
    if has_commands(options) and not (options.client or options.all):
 
392
    if has_actions(options) and not (options.client or options.all):
453
393
        parser.error("Options require clients names or --all.")
454
 
    if options.verbose and has_commands(options):
 
394
    if options.verbose and has_actions(options):
455
395
        parser.error("--verbose can only be used alone.")
456
 
    if (has_commands(options, (command.DumpJSON,))
457
 
        and (options.verbose or len(options.commands) > 1)):
 
396
    if options.dump_json and (options.verbose
 
397
                              or has_actions(options)):
458
398
        parser.error("--dump-json can only be used alone.")
459
 
    if options.all and not has_commands(options):
 
399
    if options.all and not has_actions(options):
460
400
        parser.error("--all requires an action.")
461
 
    if (has_commands(options, (command.IsEnabled,))
462
 
        and len(options.client) > 1):
 
401
    if options.is_enabled and len(options.client) > 1:
463
402
        parser.error("--is-enabled requires exactly one client")
464
 
    if (len(options.commands) > 1
465
 
        and has_commands(options, (command.Remove,))
466
 
        and not has_commands(options, (command.Deny,))):
467
 
        parser.error("--remove can only be combined with --deny")
 
403
    if options.remove:
 
404
        options.remove = False
 
405
        if has_actions(options) and not options.deny:
 
406
            parser.error("--remove can only be combined with --deny")
 
407
        options.remove = True
 
408
 
468
409
 
469
410
 
470
411
class dbus(object):
572
513
                        for key, subval in value.items()}
573
514
            return value
574
515
 
575
 
        def set_client_property(self, objectpath, key, value):
576
 
            if key == "Secret":
577
 
                if not isinstance(value, bytes):
578
 
                    value = value.encode("utf-8")
579
 
                value = self.dbus_python.ByteArray(value)
580
 
            return self.set_property(self.busname, objectpath,
581
 
                                     self.client_interface, key,
582
 
                                     value)
583
516
 
584
517
    class SilenceLogger(object):
585
518
        "Simple context manager to silence a particular logger"
616
549
                return new_object
617
550
 
618
551
 
619
 
class pydbus_adapter(object):
620
 
    class SystemBus(dbus.MandosBus):
621
 
        def __init__(self, module=pydbus):
622
 
            self.pydbus = module
623
 
            self.bus = self.pydbus.SystemBus()
624
 
 
625
 
        @contextlib.contextmanager
626
 
        def convert_exception(self, exception_class=dbus.Error):
627
 
            try:
628
 
                yield
629
 
            except gi.repository.GLib.Error as e:
630
 
                # This does what "raise from" would do
631
 
                exc = exception_class(*e.args)
632
 
                exc.__cause__ = e
633
 
                raise exc
634
 
 
635
 
        def call_method(self, methodname, busname, objectpath,
636
 
                        interface, *args):
637
 
            proxy_object = self.get(busname, objectpath)
638
 
            log.debug("D-Bus: %s:%s:%s.%s(%s)", busname, objectpath,
639
 
                      interface, methodname,
640
 
                      ", ".join(repr(a) for a in args))
641
 
            method = getattr(proxy_object[interface], methodname)
642
 
            with self.convert_exception():
643
 
                return method(*args)
644
 
 
645
 
        def get(self, busname, objectpath):
646
 
            log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
647
 
                      busname, objectpath)
648
 
            with self.convert_exception(dbus.ConnectFailed):
649
 
                if sys.version_info.major <= 2:
650
 
                    with warnings.catch_warnings():
651
 
                        warnings.filterwarnings(
652
 
                            "ignore", "", DeprecationWarning,
653
 
                            r"^xml\.etree\.ElementTree$")
654
 
                        return self.bus.get(busname, objectpath)
655
 
                else:
656
 
                    return self.bus.get(busname, objectpath)
657
 
 
658
 
        def set_property(self, busname, objectpath, interface, key,
659
 
                         value):
660
 
            proxy_object = self.get(busname, objectpath)
661
 
            log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", busname,
662
 
                      objectpath, self.properties_iface, interface,
663
 
                      key, value)
664
 
            setattr(proxy_object[interface], key, value)
665
 
 
666
 
    class CachingBus(SystemBus):
667
 
        """A caching layer for pydbus_adapter.SystemBus"""
668
 
        def __init__(self, *args, **kwargs):
669
 
            self.object_cache = {}
670
 
            super(pydbus_adapter.CachingBus,
671
 
                  self).__init__(*args, **kwargs)
672
 
        def get(self, busname, objectpath):
673
 
            try:
674
 
                return self.object_cache[(busname, objectpath)]
675
 
            except KeyError:
676
 
                new_object = (super(pydbus_adapter.CachingBus, self)
677
 
                              .get(busname, objectpath))
678
 
                self.object_cache[(busname, objectpath)]  = new_object
679
 
                return new_object
680
 
 
681
 
 
682
552
def commands_from_options(options):
683
553
 
684
 
    commands = list(options.commands)
685
 
 
686
 
    def find_cmd(cmd, commands):
687
 
        i = 0
688
 
        for i, c in enumerate(commands):
689
 
            if isinstance(c, cmd):
690
 
                return i
691
 
        return i+1
692
 
 
693
 
    # If command.Remove is present, move any instances of command.Deny
694
 
    # to occur ahead of command.Remove.
695
 
    index_of_remove = find_cmd(command.Remove, commands)
696
 
    before_remove = commands[:index_of_remove]
697
 
    after_remove = commands[index_of_remove:]
698
 
    cleaned_after = []
699
 
    for cmd in after_remove:
700
 
        if isinstance(cmd, command.Deny):
701
 
            before_remove.append(cmd)
 
554
    commands = []
 
555
 
 
556
    if options.is_enabled:
 
557
        commands.append(command.IsEnabled())
 
558
 
 
559
    if options.approve:
 
560
        commands.append(command.Approve())
 
561
 
 
562
    if options.deny:
 
563
        commands.append(command.Deny())
 
564
 
 
565
    if options.remove:
 
566
        commands.append(command.Remove())
 
567
 
 
568
    if options.dump_json:
 
569
        commands.append(command.DumpJSON())
 
570
 
 
571
    if options.enable:
 
572
        commands.append(command.Enable())
 
573
 
 
574
    if options.disable:
 
575
        commands.append(command.Disable())
 
576
 
 
577
    if options.bump_timeout:
 
578
        commands.append(command.BumpTimeout())
 
579
 
 
580
    if options.start_checker:
 
581
        commands.append(command.StartChecker())
 
582
 
 
583
    if options.stop_checker:
 
584
        commands.append(command.StopChecker())
 
585
 
 
586
    if options.approved_by_default is not None:
 
587
        if options.approved_by_default:
 
588
            commands.append(command.ApproveByDefault())
702
589
        else:
703
 
            cleaned_after.append(cmd)
704
 
    if cleaned_after != after_remove:
705
 
        commands = before_remove + cleaned_after
 
590
            commands.append(command.DenyByDefault())
 
591
 
 
592
    if options.checker is not None:
 
593
        commands.append(command.SetChecker(options.checker))
 
594
 
 
595
    if options.host is not None:
 
596
        commands.append(command.SetHost(options.host))
 
597
 
 
598
    if options.secret is not None:
 
599
        commands.append(command.SetSecret(options.secret))
 
600
 
 
601
    if options.timeout is not None:
 
602
        commands.append(command.SetTimeout(options.timeout))
 
603
 
 
604
    if options.extended_timeout:
 
605
        commands.append(
 
606
            command.SetExtendedTimeout(options.extended_timeout))
 
607
 
 
608
    if options.interval is not None:
 
609
        commands.append(command.SetInterval(options.interval))
 
610
 
 
611
    if options.approval_delay is not None:
 
612
        commands.append(
 
613
            command.SetApprovalDelay(options.approval_delay))
 
614
 
 
615
    if options.approval_duration is not None:
 
616
        commands.append(
 
617
            command.SetApprovalDuration(options.approval_duration))
706
618
 
707
619
    # If no command option has been given, show table of clients,
708
620
    # optionally verbosely
923
835
        def __init__(self, value):
924
836
            self.value_to_set = value
925
837
 
926
 
        @classmethod
927
 
        def argparse(cls, argtype):
928
 
            def cmdtype(arg):
929
 
                return cls(argtype(arg))
930
 
            return cmdtype
931
838
 
932
839
    class SetChecker(PropertySetterValue):
933
840
        propname = "Checker"
1029
936
class Test_string_to_delta(TestCaseWithAssertLogs):
1030
937
    # Just test basic RFC 3339 functionality here, the doc string for
1031
938
    # rfc3339_duration_to_delta() already has more comprehensive
1032
 
    # tests, which are run by doctest.
 
939
    # tests, which is run by doctest.
1033
940
 
1034
941
    def test_rfc3339_zero_seconds(self):
1035
942
        self.assertEqual(datetime.timedelta(),
1059
966
 
1060
967
    def test_actions_requires_client_or_all(self):
1061
968
        for action, value in self.actions.items():
1062
 
            args = self.actionargs(action, value)
 
969
            options = self.parser.parse_args()
 
970
            setattr(options, action, value)
1063
971
            with self.assertParseError():
1064
 
                self.parse_args(args)
 
972
                self.check_option_syntax(options)
1065
973
 
1066
 
    # This mostly corresponds to the definition from has_commands() in
 
974
    # This mostly corresponds to the definition from has_actions() in
1067
975
    # check_option_syntax()
1068
976
    actions = {
1069
 
        "--enable": None,
1070
 
        "--disable": None,
1071
 
        "--bump-timeout": None,
1072
 
        "--start-checker": None,
1073
 
        "--stop-checker": None,
1074
 
        "--is-enabled": None,
1075
 
        "--remove": None,
1076
 
        "--checker": "x",
1077
 
        "--timeout": "PT0S",
1078
 
        "--extended-timeout": "PT0S",
1079
 
        "--interval": "PT0S",
1080
 
        "--approve-by-default": None,
1081
 
        "--deny-by-default": None,
1082
 
        "--approval-delay": "PT0S",
1083
 
        "--approval-duration": "PT0S",
1084
 
        "--host": "hostname",
1085
 
        "--secret": "/dev/null",
1086
 
        "--approve": None,
1087
 
        "--deny": None,
 
977
        # The actual values set here are not that important, but we do
 
978
        # at least stick to the correct types, even though they are
 
979
        # never used
 
980
        "enable": True,
 
981
        "disable": True,
 
982
        "bump_timeout": True,
 
983
        "start_checker": True,
 
984
        "stop_checker": True,
 
985
        "is_enabled": True,
 
986
        "remove": True,
 
987
        "checker": "x",
 
988
        "timeout": datetime.timedelta(),
 
989
        "extended_timeout": datetime.timedelta(),
 
990
        "interval": datetime.timedelta(),
 
991
        "approved_by_default": True,
 
992
        "approval_delay": datetime.timedelta(),
 
993
        "approval_duration": datetime.timedelta(),
 
994
        "host": "x",
 
995
        "secret": io.BytesIO(b"x"),
 
996
        "approve": True,
 
997
        "deny": True,
1088
998
    }
1089
999
 
1090
 
    @staticmethod
1091
 
    def actionargs(action, value, *args):
1092
 
        if value is not None:
1093
 
            return [action, value] + list(args)
1094
 
        else:
1095
 
            return [action] + list(args)
1096
 
 
1097
1000
    @contextlib.contextmanager
1098
1001
    def assertParseError(self):
1099
1002
        with self.assertRaises(SystemExit) as e:
1104
1007
        # /argparse.html#exiting-methods
1105
1008
        self.assertEqual(2, e.exception.code)
1106
1009
 
1107
 
    def parse_args(self, args):
1108
 
        options = self.parser.parse_args(args)
1109
 
        check_option_syntax(self.parser, options)
1110
 
 
1111
1010
    @staticmethod
1112
1011
    @contextlib.contextmanager
1113
1012
    def redirect_stderr_to_devnull():
1124
1023
 
1125
1024
    def test_actions_all_conflicts_with_verbose(self):
1126
1025
        for action, value in self.actions.items():
1127
 
            args = self.actionargs(action, value, "--all",
1128
 
                                   "--verbose")
 
1026
            options = self.parser.parse_args()
 
1027
            setattr(options, action, value)
 
1028
            options.all = True
 
1029
            options.verbose = True
1129
1030
            with self.assertParseError():
1130
 
                self.parse_args(args)
 
1031
                self.check_option_syntax(options)
1131
1032
 
1132
1033
    def test_actions_with_client_conflicts_with_verbose(self):
1133
1034
        for action, value in self.actions.items():
1134
 
            args = self.actionargs(action, value, "--verbose",
1135
 
                                   "client")
 
1035
            options = self.parser.parse_args()
 
1036
            setattr(options, action, value)
 
1037
            options.verbose = True
 
1038
            options.client = ["client"]
1136
1039
            with self.assertParseError():
1137
 
                self.parse_args(args)
 
1040
                self.check_option_syntax(options)
1138
1041
 
1139
1042
    def test_dump_json_conflicts_with_verbose(self):
1140
 
        args = ["--dump-json", "--verbose"]
 
1043
        options = self.parser.parse_args()
 
1044
        options.dump_json = True
 
1045
        options.verbose = True
1141
1046
        with self.assertParseError():
1142
 
            self.parse_args(args)
 
1047
            self.check_option_syntax(options)
1143
1048
 
1144
1049
    def test_dump_json_conflicts_with_action(self):
1145
1050
        for action, value in self.actions.items():
1146
 
            args = self.actionargs(action, value, "--dump-json")
 
1051
            options = self.parser.parse_args()
 
1052
            setattr(options, action, value)
 
1053
            options.dump_json = True
1147
1054
            with self.assertParseError():
1148
 
                self.parse_args(args)
 
1055
                self.check_option_syntax(options)
1149
1056
 
1150
1057
    def test_all_can_not_be_alone(self):
1151
 
        args = ["--all"]
 
1058
        options = self.parser.parse_args()
 
1059
        options.all = True
1152
1060
        with self.assertParseError():
1153
 
            self.parse_args(args)
 
1061
            self.check_option_syntax(options)
1154
1062
 
1155
1063
    def test_all_is_ok_with_any_action(self):
1156
1064
        for action, value in self.actions.items():
1157
 
            args = self.actionargs(action, value, "--all")
1158
 
            self.parse_args(args)
 
1065
            options = self.parser.parse_args()
 
1066
            setattr(options, action, value)
 
1067
            options.all = True
 
1068
            self.check_option_syntax(options)
1159
1069
 
1160
1070
    def test_any_action_is_ok_with_one_client(self):
1161
1071
        for action, value in self.actions.items():
1162
 
            args = self.actionargs(action, value, "client")
1163
 
            self.parse_args(args)
 
1072
            options = self.parser.parse_args()
 
1073
            setattr(options, action, value)
 
1074
            options.client = ["client"]
 
1075
            self.check_option_syntax(options)
1164
1076
 
1165
1077
    def test_one_client_with_all_actions_except_is_enabled(self):
 
1078
        options = self.parser.parse_args()
1166
1079
        for action, value in self.actions.items():
1167
 
            if action == "--is-enabled":
 
1080
            if action == "is_enabled":
1168
1081
                continue
1169
 
            args = self.actionargs(action, value, "client")
1170
 
            self.parse_args(args)
 
1082
            setattr(options, action, value)
 
1083
        options.client = ["client"]
 
1084
        self.check_option_syntax(options)
1171
1085
 
1172
1086
    def test_two_clients_with_all_actions_except_is_enabled(self):
 
1087
        options = self.parser.parse_args()
1173
1088
        for action, value in self.actions.items():
1174
 
            if action == "--is-enabled":
 
1089
            if action == "is_enabled":
1175
1090
                continue
1176
 
            args = self.actionargs(action, value, "client1",
1177
 
                                   "client2")
1178
 
            self.parse_args(args)
 
1091
            setattr(options, action, value)
 
1092
        options.client = ["client1", "client2"]
 
1093
        self.check_option_syntax(options)
1179
1094
 
1180
1095
    def test_two_clients_are_ok_with_actions_except_is_enabled(self):
1181
1096
        for action, value in self.actions.items():
1182
 
            if action == "--is-enabled":
 
1097
            if action == "is_enabled":
1183
1098
                continue
1184
 
            args = self.actionargs(action, value, "client1",
1185
 
                                   "client2")
1186
 
            self.parse_args(args)
 
1099
            options = self.parser.parse_args()
 
1100
            setattr(options, action, value)
 
1101
            options.client = ["client1", "client2"]
 
1102
            self.check_option_syntax(options)
1187
1103
 
1188
1104
    def test_is_enabled_fails_without_client(self):
1189
 
        args = ["--is-enabled"]
 
1105
        options = self.parser.parse_args()
 
1106
        options.is_enabled = True
1190
1107
        with self.assertParseError():
1191
 
            self.parse_args(args)
 
1108
            self.check_option_syntax(options)
1192
1109
 
1193
1110
    def test_is_enabled_fails_with_two_clients(self):
1194
 
        args = ["--is-enabled", "client1", "client2"]
 
1111
        options = self.parser.parse_args()
 
1112
        options.is_enabled = True
 
1113
        options.client = ["client1", "client2"]
1195
1114
        with self.assertParseError():
1196
 
            self.parse_args(args)
 
1115
            self.check_option_syntax(options)
1197
1116
 
1198
1117
    def test_remove_can_only_be_combined_with_action_deny(self):
1199
1118
        for action, value in self.actions.items():
1200
 
            if action in {"--remove", "--deny"}:
 
1119
            if action in {"remove", "deny"}:
1201
1120
                continue
1202
 
            args = self.actionargs(action, value, "--all",
1203
 
                                   "--remove")
 
1121
            options = self.parser.parse_args()
 
1122
            setattr(options, action, value)
 
1123
            options.all = True
 
1124
            options.remove = True
1204
1125
            with self.assertParseError():
1205
 
                self.parse_args(args)
 
1126
                self.check_option_syntax(options)
1206
1127
 
1207
1128
 
1208
1129
class Test_dbus_exceptions(unittest.TestCase):
1321
1242
                @staticmethod
1322
1243
                def get_object(busname, objectpath):
1323
1244
                    DBusObject = collections.namedtuple(
1324
 
                        "DBusObject", ("methodname", "Set"))
 
1245
                        "DBusObject", ("methodname",))
1325
1246
                    def method(*args, **kwargs):
1326
1247
                        self.assertEqual({"dbus_interface":
1327
1248
                                          "interface"},
1328
1249
                                         kwargs)
1329
1250
                        return func(*args)
1330
 
                    def set_property(interface, key, value,
1331
 
                                     dbus_interface=None):
1332
 
                        self.assertEqual(
1333
 
                            "org.freedesktop.DBus.Properties",
1334
 
                            dbus_interface)
1335
 
                        self.assertEqual("Secret", key)
1336
 
                        return func(interface, key, value,
1337
 
                                    dbus_interface=dbus_interface)
1338
 
                    return DBusObject(methodname=method,
1339
 
                                      Set=set_property)
 
1251
                    return DBusObject(methodname=method)
1340
1252
            class Boolean(object):
1341
1253
                def __init__(self, value):
1342
1254
                    self.value = bool(value)
1348
1260
                pass
1349
1261
            class Dictionary(dict):
1350
1262
                pass
1351
 
            class ByteArray(bytes):
1352
 
                pass
1353
1263
        return mock_dbus_python
1354
1264
 
1355
1265
    def call_method(self, bus, methodname, busname, objectpath,
1532
1442
        # Make sure the dbus logger was suppressed
1533
1443
        self.assertEqual(0, counting_handler.count)
1534
1444
 
1535
 
    def test_Set_Secret_sends_bytearray(self):
1536
 
        ret = [None]
1537
 
        def func(*args, **kwargs):
1538
 
            ret[0] = (args, kwargs)
1539
 
        mock_dbus_python = self.MockDBusPython_func(func)
1540
 
        bus = dbus_python_adapter.SystemBus(mock_dbus_python)
1541
 
        bus.set_client_property("objectpath", "Secret", "value")
1542
 
        expected_call = (("se.recompile.Mandos.Client", "Secret",
1543
 
                          mock_dbus_python.ByteArray(b"value")),
1544
 
                         {"dbus_interface":
1545
 
                          "org.freedesktop.DBus.Properties"})
1546
 
        self.assertEqual(expected_call, ret[0])
1547
 
        if sys.version_info.major == 2:
1548
 
            self.assertIsInstance(ret[0][0][-1],
1549
 
                                  mock_dbus_python.ByteArray)
1550
 
 
1551
1445
    def test_get_object_converts_to_correct_exception(self):
1552
1446
        bus = dbus_python_adapter.SystemBus(
1553
1447
            self.fake_dbus_python_raises_exception_on_connect)
1622
1516
        self.assertIs(obj1, obj1b)
1623
1517
 
1624
1518
 
1625
 
class Test_pydbus_adapter_SystemBus(TestCaseWithAssertLogs):
1626
 
 
1627
 
    def Stub_pydbus_func(self, func):
1628
 
        class stub_pydbus(object):
1629
 
            """stub pydbus module"""
1630
 
            class SystemBus(object):
1631
 
                @staticmethod
1632
 
                def get(busname, objectpath):
1633
 
                    DBusObject = collections.namedtuple(
1634
 
                        "DBusObject", ("methodname",))
1635
 
                    return {"interface":
1636
 
                            DBusObject(methodname=func)}
1637
 
        return stub_pydbus
1638
 
 
1639
 
    def call_method(self, bus, methodname, busname, objectpath,
1640
 
                    interface, *args):
1641
 
        with self.assertLogs(log, logging.DEBUG):
1642
 
            return bus.call_method(methodname, busname, objectpath,
1643
 
                                   interface, *args)
1644
 
 
1645
 
    def test_call_method_returns(self):
1646
 
        expected_method_return = Unique()
1647
 
        method_args = (Unique(), Unique())
1648
 
        def func(*args):
1649
 
            self.assertEqual(len(method_args), len(args))
1650
 
            for marg, arg in zip(method_args, args):
1651
 
                self.assertIs(marg, arg)
1652
 
            return expected_method_return
1653
 
        stub_pydbus = self.Stub_pydbus_func(func)
1654
 
        bus = pydbus_adapter.SystemBus(stub_pydbus)
1655
 
        ret = self.call_method(bus, "methodname", "busname",
1656
 
                               "objectpath", "interface",
1657
 
                               *method_args)
1658
 
        self.assertIs(ret, expected_method_return)
1659
 
 
1660
 
    def test_call_method_handles_exception(self):
1661
 
        dbus_logger = logging.getLogger("dbus.proxies")
1662
 
 
1663
 
        def func():
1664
 
            raise gi.repository.GLib.Error()
1665
 
 
1666
 
        stub_pydbus = self.Stub_pydbus_func(func)
1667
 
        bus = pydbus_adapter.SystemBus(stub_pydbus)
1668
 
 
1669
 
        with self.assertRaises(dbus.Error) as e:
1670
 
            self.call_method(bus, "methodname", "busname",
1671
 
                             "objectpath", "interface")
1672
 
 
1673
 
        self.assertNotIsInstance(e, dbus.ConnectFailed)
1674
 
 
1675
 
    def test_get_converts_to_correct_exception(self):
1676
 
        bus = pydbus_adapter.SystemBus(
1677
 
            self.fake_pydbus_raises_exception_on_connect)
1678
 
        with self.assertRaises(dbus.ConnectFailed):
1679
 
            self.call_method(bus, "methodname", "busname",
1680
 
                             "objectpath", "interface")
1681
 
 
1682
 
    class fake_pydbus_raises_exception_on_connect(object):
1683
 
        """fake dbus-python module"""
1684
 
        @classmethod
1685
 
        def SystemBus(cls):
1686
 
            def get(busname, objectpath):
1687
 
                raise gi.repository.GLib.Error()
1688
 
            Bus = collections.namedtuple("Bus", ["get"])
1689
 
            return Bus(get=get)
1690
 
 
1691
 
    def test_set_property_uses_setattr(self):
1692
 
        class Object(object):
1693
 
            pass
1694
 
        obj = Object()
1695
 
        class pydbus_spy(object):
1696
 
            class SystemBus(object):
1697
 
                @staticmethod
1698
 
                def get(busname, objectpath):
1699
 
                    return {"interface": obj}
1700
 
        bus = pydbus_adapter.SystemBus(pydbus_spy)
1701
 
        value = Unique()
1702
 
        bus.set_property("busname", "objectpath", "interface", "key",
1703
 
                         value)
1704
 
        self.assertIs(value, obj.key)
1705
 
 
1706
 
    def test_get_suppresses_xml_deprecation_warning(self):
1707
 
        if sys.version_info.major >= 3:
1708
 
            return
1709
 
        class stub_pydbus_get(object):
1710
 
            class SystemBus(object):
1711
 
                @staticmethod
1712
 
                def get(busname, objectpath):
1713
 
                    warnings.warn_explicit(
1714
 
                        "deprecated", DeprecationWarning,
1715
 
                        "xml.etree.ElementTree", 0)
1716
 
        bus = pydbus_adapter.SystemBus(stub_pydbus_get)
1717
 
        with warnings.catch_warnings(record=True) as w:
1718
 
            warnings.simplefilter("always")
1719
 
            bus.get("busname", "objectpath")
1720
 
            self.assertEqual(0, len(w))
1721
 
 
1722
 
 
1723
 
class Test_pydbus_adapter_CachingBus(unittest.TestCase):
1724
 
    class stub_pydbus(object):
1725
 
        """stub pydbus module"""
1726
 
        class SystemBus(object):
1727
 
            @staticmethod
1728
 
            def get(busname, objectpath):
1729
 
                return Unique()
1730
 
 
1731
 
    def setUp(self):
1732
 
        self.bus = pydbus_adapter.CachingBus(self.stub_pydbus)
1733
 
 
1734
 
    def test_returns_distinct_objectpaths(self):
1735
 
        obj1 = self.bus.get("busname", "objectpath1")
1736
 
        self.assertIsInstance(obj1, Unique)
1737
 
        obj2 = self.bus.get("busname", "objectpath2")
1738
 
        self.assertIsInstance(obj2, Unique)
1739
 
        self.assertIsNot(obj1, obj2)
1740
 
 
1741
 
    def test_returns_distinct_busnames(self):
1742
 
        obj1 = self.bus.get("busname1", "objectpath")
1743
 
        self.assertIsInstance(obj1, Unique)
1744
 
        obj2 = self.bus.get("busname2", "objectpath")
1745
 
        self.assertIsInstance(obj2, Unique)
1746
 
        self.assertIsNot(obj1, obj2)
1747
 
 
1748
 
    def test_returns_distinct_both(self):
1749
 
        obj1 = self.bus.get("busname1", "objectpath")
1750
 
        self.assertIsInstance(obj1, Unique)
1751
 
        obj2 = self.bus.get("busname2", "objectpath")
1752
 
        self.assertIsInstance(obj2, Unique)
1753
 
        self.assertIsNot(obj1, obj2)
1754
 
 
1755
 
    def test_returns_same(self):
1756
 
        obj1 = self.bus.get("busname", "objectpath")
1757
 
        self.assertIsInstance(obj1, Unique)
1758
 
        obj2 = self.bus.get("busname", "objectpath")
1759
 
        self.assertIsInstance(obj2, Unique)
1760
 
        self.assertIs(obj1, obj2)
1761
 
 
1762
 
    def test_returns_same_old(self):
1763
 
        obj1 = self.bus.get("busname1", "objectpath1")
1764
 
        self.assertIsInstance(obj1, Unique)
1765
 
        obj2 = self.bus.get("busname2", "objectpath2")
1766
 
        self.assertIsInstance(obj2, Unique)
1767
 
        obj1b = self.bus.get("busname1", "objectpath1")
1768
 
        self.assertIsInstance(obj1b, Unique)
1769
 
        self.assertIsNot(obj1, obj2)
1770
 
        self.assertIsNot(obj2, obj1b)
1771
 
        self.assertIs(obj1, obj1b)
1772
 
 
1773
 
 
1774
1519
class Test_commands_from_options(unittest.TestCase):
1775
1520
 
1776
1521
    def setUp(self):
1781
1526
        self.assert_command_from_args(["--is-enabled", "client"],
1782
1527
                                      command.IsEnabled)
1783
1528
 
1784
 
    def assert_command_from_args(self, args, command_cls, length=1,
1785
 
                                 clients=None, **cmd_attrs):
 
1529
    def assert_command_from_args(self, args, command_cls,
 
1530
                                 **cmd_attrs):
1786
1531
        """Assert that parsing ARGS should result in an instance of
1787
1532
COMMAND_CLS with (optionally) all supplied attributes (CMD_ATTRS)."""
1788
1533
        options = self.parser.parse_args(args)
1789
1534
        check_option_syntax(self.parser, options)
1790
1535
        commands = commands_from_options(options)
1791
 
        self.assertEqual(length, len(commands))
1792
 
        for command in commands:
1793
 
            if isinstance(command, command_cls):
1794
 
                break
1795
 
        else:
1796
 
            self.assertIsInstance(command, command_cls)
1797
 
        if clients is not None:
1798
 
            self.assertEqual(clients, options.client)
 
1536
        self.assertEqual(1, len(commands))
 
1537
        command = commands[0]
 
1538
        self.assertIsInstance(command, command_cls)
1799
1539
        for key, value in cmd_attrs.items():
1800
1540
            self.assertEqual(value, getattr(command, key))
1801
1541
 
1802
 
    def assert_commands_from_args(self, args, commands, clients=None):
1803
 
        for cmd in commands:
1804
 
            self.assert_command_from_args(args, cmd,
1805
 
                                          length=len(commands),
1806
 
                                          clients=clients)
1807
 
 
1808
1542
    def test_is_enabled_short(self):
1809
1543
        self.assert_command_from_args(["-V", "client"],
1810
1544
                                      command.IsEnabled)
2001
1735
                                      verbose=True)
2002
1736
 
2003
1737
 
2004
 
    def test_manual_page_example_1(self):
2005
 
        self.assert_command_from_args("",
2006
 
                                      command.PrintTable,
2007
 
                                      clients=[],
2008
 
                                      verbose=False)
2009
 
 
2010
 
    def test_manual_page_example_2(self):
2011
 
        self.assert_command_from_args(
2012
 
            "--verbose foo1.example.org foo2.example.org".split(),
2013
 
            command.PrintTable, clients=["foo1.example.org",
2014
 
                                         "foo2.example.org"],
2015
 
            verbose=True)
2016
 
 
2017
 
    def test_manual_page_example_3(self):
2018
 
        self.assert_command_from_args("--enable --all".split(),
2019
 
                                      command.Enable,
2020
 
                                      clients=[])
2021
 
 
2022
 
    def test_manual_page_example_4(self):
2023
 
        self.assert_commands_from_args(
2024
 
            ("--timeout=PT5M --interval=PT1M foo1.example.org"
2025
 
             " foo2.example.org").split(),
2026
 
            [command.SetTimeout, command.SetInterval],
2027
 
            clients=["foo1.example.org", "foo2.example.org"])
2028
 
 
2029
 
    def test_manual_page_example_5(self):
2030
 
        self.assert_command_from_args("--approve --all".split(),
2031
 
                                      command.Approve,
2032
 
                                      clients=[])
2033
 
 
2034
 
 
2035
1738
class TestCommand(unittest.TestCase):
2036
1739
    """Abstract class for tests of command classes"""
2037
1740
 
2367
2070
    def runTest(self):
2368
2071
        if not hasattr(self, "command"):
2369
2072
            return              # Abstract TestCase class
2370
 
 
2371
 
        if hasattr(self, "values_to_set"):
2372
 
            cmd_args = [(value,) for value in self.values_to_set]
2373
 
            values_to_get = getattr(self, "values_to_get",
2374
 
                                    self.values_to_set)
2375
 
        else:
2376
 
            cmd_args = [() for x in range(len(self.values_to_get))]
2377
 
            values_to_get = self.values_to_get
2378
 
        for value_to_get, cmd_arg in zip(values_to_get, cmd_args):
2379
 
            for clientpath in self.bus.clients:
2380
 
                self.bus.clients[clientpath][self.propname] = (
2381
 
                    Unique())
2382
 
            self.command(*cmd_arg).run(self.bus.clients, self.bus)
2383
 
            for clientpath in self.bus.clients:
2384
 
                value = (self.bus.clients[clientpath]
2385
 
                         [self.propname])
 
2073
        values_to_get = getattr(self, "values_to_get",
 
2074
                                self.values_to_set)
 
2075
        for value_to_set, value_to_get in zip(self.values_to_set,
 
2076
                                              values_to_get):
 
2077
            for clientpath in self.bus.clients:
 
2078
                self.bus.clients[clientpath][self.propname] = Unique()
 
2079
            self.run_command(value_to_set, self.bus.clients)
 
2080
            for clientpath in self.bus.clients:
 
2081
                value = self.bus.clients[clientpath][self.propname]
2386
2082
                self.assertNotIsInstance(value, Unique)
2387
2083
                self.assertEqual(value_to_get, value)
2388
2084
 
 
2085
    def run_command(self, value, clients):
 
2086
        self.command().run(clients, self.bus)
 
2087
 
2389
2088
 
2390
2089
class TestEnableCmd(TestPropertySetterCmd):
2391
2090
    command = command.Enable
2392
2091
    propname = "Enabled"
2393
 
    values_to_get = [True]
 
2092
    values_to_set = [True]
2394
2093
 
2395
2094
 
2396
2095
class TestDisableCmd(TestPropertySetterCmd):
2397
2096
    command = command.Disable
2398
2097
    propname = "Enabled"
2399
 
    values_to_get = [False]
 
2098
    values_to_set = [False]
2400
2099
 
2401
2100
 
2402
2101
class TestBumpTimeoutCmd(TestPropertySetterCmd):
2403
2102
    command = command.BumpTimeout
2404
2103
    propname = "LastCheckedOK"
2405
 
    values_to_get = [""]
 
2104
    values_to_set = [""]
2406
2105
 
2407
2106
 
2408
2107
class TestStartCheckerCmd(TestPropertySetterCmd):
2409
2108
    command = command.StartChecker
2410
2109
    propname = "CheckerRunning"
2411
 
    values_to_get = [True]
 
2110
    values_to_set = [True]
2412
2111
 
2413
2112
 
2414
2113
class TestStopCheckerCmd(TestPropertySetterCmd):
2415
2114
    command = command.StopChecker
2416
2115
    propname = "CheckerRunning"
2417
 
    values_to_get = [False]
 
2116
    values_to_set = [False]
2418
2117
 
2419
2118
 
2420
2119
class TestApproveByDefaultCmd(TestPropertySetterCmd):
2421
2120
    command = command.ApproveByDefault
2422
2121
    propname = "ApprovedByDefault"
2423
 
    values_to_get = [True]
 
2122
    values_to_set = [True]
2424
2123
 
2425
2124
 
2426
2125
class TestDenyByDefaultCmd(TestPropertySetterCmd):
2427
2126
    command = command.DenyByDefault
2428
2127
    propname = "ApprovedByDefault"
2429
 
    values_to_get = [False]
2430
 
 
2431
 
 
2432
 
class TestSetCheckerCmd(TestPropertySetterCmd):
 
2128
    values_to_set = [False]
 
2129
 
 
2130
 
 
2131
class TestPropertySetterValueCmd(TestPropertySetterCmd):
 
2132
    """Abstract class for tests of PropertySetterValueCmd classes"""
 
2133
 
 
2134
    def run_command(self, value, clients):
 
2135
        self.command(value).run(clients, self.bus)
 
2136
 
 
2137
 
 
2138
class TestSetCheckerCmd(TestPropertySetterValueCmd):
2433
2139
    command = command.SetChecker
2434
2140
    propname = "Checker"
2435
2141
    values_to_set = ["", ":", "fping -q -- %s"]
2436
2142
 
2437
2143
 
2438
 
class TestSetHostCmd(TestPropertySetterCmd):
 
2144
class TestSetHostCmd(TestPropertySetterValueCmd):
2439
2145
    command = command.SetHost
2440
2146
    propname = "Host"
2441
2147
    values_to_set = ["192.0.2.3", "client.example.org"]
2442
2148
 
2443
2149
 
2444
 
class TestSetSecretCmd(TestPropertySetterCmd):
 
2150
class TestSetSecretCmd(TestPropertySetterValueCmd):
2445
2151
    command = command.SetSecret
2446
2152
    propname = "Secret"
2447
2153
    values_to_set = [io.BytesIO(b""),
2449
2155
    values_to_get = [f.getvalue() for f in values_to_set]
2450
2156
 
2451
2157
 
2452
 
class TestSetTimeoutCmd(TestPropertySetterCmd):
 
2158
class TestSetTimeoutCmd(TestPropertySetterValueCmd):
2453
2159
    command = command.SetTimeout
2454
2160
    propname = "Timeout"
2455
2161
    values_to_set = [datetime.timedelta(),
2460
2166
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
2461
2167
 
2462
2168
 
2463
 
class TestSetExtendedTimeoutCmd(TestPropertySetterCmd):
 
2169
class TestSetExtendedTimeoutCmd(TestPropertySetterValueCmd):
2464
2170
    command = command.SetExtendedTimeout
2465
2171
    propname = "ExtendedTimeout"
2466
2172
    values_to_set = [datetime.timedelta(),
2471
2177
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
2472
2178
 
2473
2179
 
2474
 
class TestSetIntervalCmd(TestPropertySetterCmd):
 
2180
class TestSetIntervalCmd(TestPropertySetterValueCmd):
2475
2181
    command = command.SetInterval
2476
2182
    propname = "Interval"
2477
2183
    values_to_set = [datetime.timedelta(),
2482
2188
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
2483
2189
 
2484
2190
 
2485
 
class TestSetApprovalDelayCmd(TestPropertySetterCmd):
 
2191
class TestSetApprovalDelayCmd(TestPropertySetterValueCmd):
2486
2192
    command = command.SetApprovalDelay
2487
2193
    propname = "ApprovalDelay"
2488
2194
    values_to_set = [datetime.timedelta(),
2493
2199
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
2494
2200
 
2495
2201
 
2496
 
class TestSetApprovalDurationCmd(TestPropertySetterCmd):
 
2202
class TestSetApprovalDurationCmd(TestPropertySetterValueCmd):
2497
2203
    command = command.SetApprovalDuration
2498
2204
    propname = "ApprovalDuration"
2499
2205
    values_to_set = [datetime.timedelta(),