/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: 2022-04-24 11:45:13 UTC
  • Revision ID: teddy@recompile.se-20220424114513-0rvlunnjhgs3deus
mandos-monitor: Update boilerplate code

* mandos-monitor: Show warnings by default.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python3 -bbI
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
# -*- coding: utf-8; lexical-binding: t -*-
3
3
#
4
4
# Mandos Control - Control or query the Mandos server
5
5
#
23
23
#
24
24
# Contact the authors at <mandos@recompile.se>.
25
25
#
26
 
 
27
26
from __future__ import (division, absolute_import, print_function,
28
27
                        unicode_literals)
29
28
 
33
32
    pass
34
33
 
35
34
import sys
 
35
import unittest
36
36
import argparse
 
37
import logging
 
38
import os
37
39
import locale
38
40
import datetime
39
41
import re
40
 
import os
41
42
import collections
42
43
import json
43
 
import unittest
44
 
import logging
45
44
import io
46
45
import tempfile
47
46
import contextlib
49
48
if sys.version_info.major == 2:
50
49
    __metaclass__ = type
51
50
    str = unicode
 
51
    input = raw_input
52
52
 
53
53
class gi:
54
54
    """Dummy gi module, for the tests"""
77
77
    import warnings
78
78
    warnings.simplefilter("default")
79
79
 
80
 
log = logging.getLogger(sys.argv[0])
 
80
log = logging.getLogger(os.path.basename(sys.argv[0]))
81
81
logging.basicConfig(level="INFO", # Show info level messages
82
82
                    format="%(message)s") # Show basic log messages
83
83
 
102
102
    clientnames = options.client
103
103
 
104
104
    if options.debug:
105
 
        log.setLevel(logging.DEBUG)
 
105
        logging.getLogger("").setLevel(logging.DEBUG)
106
106
 
107
107
    if dbussy is not None and ravel is not None:
108
108
        bus = dbussy_adapter.CachingBus(dbussy, ravel)
256
256
        return rfc3339_duration_to_delta(interval)
257
257
    except ValueError as e:
258
258
        log.warning("%s - Parsing as pre-1.6.1 interval instead",
259
 
                    ' '.join(e.args))
 
259
                    " ".join(e.args))
260
260
    return parse_pre_1_6_1_interval(interval)
261
261
 
262
262
 
395
395
    """Parse an interval string as documented by Mandos before 1.6.1,
396
396
    and return a datetime.timedelta
397
397
 
398
 
    >>> parse_pre_1_6_1_interval('7d') == datetime.timedelta(days=7)
399
 
    True
400
 
    >>> parse_pre_1_6_1_interval('60s') == datetime.timedelta(0, 60)
401
 
    True
402
 
    >>> parse_pre_1_6_1_interval('60m') == datetime.timedelta(hours=1)
403
 
    True
404
 
    >>> parse_pre_1_6_1_interval('24h') == datetime.timedelta(days=1)
405
 
    True
406
 
    >>> parse_pre_1_6_1_interval('1w') == datetime.timedelta(days=7)
407
 
    True
408
 
    >>> parse_pre_1_6_1_interval('5m 30s') == datetime.timedelta(0, 330)
409
 
    True
410
 
    >>> parse_pre_1_6_1_interval('') == datetime.timedelta(0)
 
398
    >>> parse_pre_1_6_1_interval("7d") == datetime.timedelta(days=7)
 
399
    True
 
400
    >>> parse_pre_1_6_1_interval("60s") == datetime.timedelta(0, 60)
 
401
    True
 
402
    >>> parse_pre_1_6_1_interval("60m") == datetime.timedelta(hours=1)
 
403
    True
 
404
    >>> parse_pre_1_6_1_interval("24h") == datetime.timedelta(days=1)
 
405
    True
 
406
    >>> parse_pre_1_6_1_interval("1w") == datetime.timedelta(days=7)
 
407
    True
 
408
    >>> parse_pre_1_6_1_interval("5m 30s") == datetime.timedelta(0, 330)
 
409
    True
 
410
    >>> parse_pre_1_6_1_interval("") == datetime.timedelta(0)
411
411
    True
412
412
    >>> # Ignore unknown characters, allow any order and repetitions
413
 
    >>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m') == datetime.timedelta(2, 480, 18000)
 
413
    >>> parse_pre_1_6_1_interval("2dxy7zz11y3m5m") == datetime.timedelta(2, 480, 18000)
414
414
    True
415
415
 
416
416
    """
876
876
                    {key: properties[key]
877
877
                     for key in self.all_keywords}
878
878
                    for properties in clients.values()}
879
 
            print(json.dumps(data, indent=4, separators=(',', ': ')))
 
879
            print(json.dumps(data, indent=4, separators=(",", ": ")))
880
880
 
881
881
 
882
882
    class PrintTable(Output):
2742
2742
class TestSetSecretCmd(TestPropertySetterCmd):
2743
2743
    command = command.SetSecret
2744
2744
    propname = "Secret"
2745
 
    values_to_set = [io.BytesIO(b""),
2746
 
                     io.BytesIO(b"secret\0xyzzy\nbar")]
2747
 
    values_to_get = [f.getvalue() for f in values_to_set]
 
2745
    def __init__(self, *args, **kwargs):
 
2746
        self.values_to_set = [io.BytesIO(b""),
 
2747
                              io.BytesIO(b"secret\0xyzzy\nbar")]
 
2748
        self.values_to_get = [f.getvalue() for f in
 
2749
                              self.values_to_set]
 
2750
        super(TestSetSecretCmd, self).__init__(*args, **kwargs)
2748
2751
 
2749
2752
 
2750
2753
class TestSetTimeoutCmd(TestPropertySetterCmd):
2803
2806
 
2804
2807
 
2805
2808
 
2806
 
def should_only_run_tests():
 
2809
def parse_test_args():
 
2810
    # type: () -> argparse.Namespace
2807
2811
    parser = argparse.ArgumentParser(add_help=False)
2808
 
    parser.add_argument("--check", action='store_true')
 
2812
    parser.add_argument("--check", action="store_true")
 
2813
    parser.add_argument("--prefix", )
2809
2814
    args, unknown_args = parser.parse_known_args()
2810
 
    run_tests = args.check
2811
 
    if run_tests:
2812
 
        # Remove --check argument from sys.argv
 
2815
    if args.check:
 
2816
        # Remove test options from sys.argv
2813
2817
        sys.argv[1:] = unknown_args
2814
 
    return run_tests
 
2818
    return args
2815
2819
 
2816
2820
# Add all tests from doctest strings
2817
2821
def load_tests(loader, tests, none):
2820
2824
    return tests
2821
2825
 
2822
2826
if __name__ == "__main__":
 
2827
    options = parse_test_args()
2823
2828
    try:
2824
 
        if should_only_run_tests():
2825
 
            # Call using ./tdd-python-script --check [--verbose]
2826
 
            unittest.main()
 
2829
        if options.check:
 
2830
            extra_test_prefix = options.prefix
 
2831
            if extra_test_prefix is not None:
 
2832
                if not (unittest.main(argv=[""], exit=False)
 
2833
                        .result.wasSuccessful()):
 
2834
                    sys.exit(1)
 
2835
                class ExtraTestLoader(unittest.TestLoader):
 
2836
                    testMethodPrefix = extra_test_prefix
 
2837
                # Call using ./scriptname --check [--verbose]
 
2838
                unittest.main(argv=[""], testLoader=ExtraTestLoader())
 
2839
            else:
 
2840
                unittest.main(argv=[""])
2827
2841
        else:
2828
2842
            main()
2829
2843
    finally:
2830
2844
        logging.shutdown()
 
2845
 
 
2846
# Local Variables:
 
2847
# run-tests:
 
2848
# (lambda (&optional extra)
 
2849
#   (if (not (funcall run-tests-in-test-buffer default-directory
 
2850
#             extra))
 
2851
#       (funcall show-test-buffer-in-test-window)
 
2852
#     (funcall remove-test-window)
 
2853
#     (if extra (message "Extra tests run successfully!"))))
 
2854
# run-tests-in-test-buffer:
 
2855
# (lambda (dir &optional extra)
 
2856
#   (with-current-buffer (get-buffer-create "*Test*")
 
2857
#     (setq buffer-read-only nil
 
2858
#           default-directory dir)
 
2859
#     (erase-buffer)
 
2860
#     (compilation-mode))
 
2861
#   (let ((inhibit-read-only t))
 
2862
#     (= (process-file-shell-command
 
2863
#         (funcall get-command-line extra)
 
2864
#         nil "*Test*") 0)))
 
2865
# get-command-line:
 
2866
# (lambda (&optional extra)
 
2867
#   (let ((quoted-script
 
2868
#          (shell-quote-argument (funcall get-script-name))))
 
2869
#     (format
 
2870
#      (concat "%s --check" (if extra " --prefix=atest" ""))
 
2871
#      quoted-script)))
 
2872
# get-script-name:
 
2873
# (lambda ()
 
2874
#   (if (fboundp 'file-local-name)
 
2875
#       (file-local-name (buffer-file-name))
 
2876
#     (or (file-remote-p (buffer-file-name) 'localname)
 
2877
#         (buffer-file-name))))
 
2878
# remove-test-window:
 
2879
# (lambda ()
 
2880
#   (let ((test-window (get-buffer-window "*Test*")))
 
2881
#     (if test-window (delete-window test-window))))
 
2882
# show-test-buffer-in-test-window:
 
2883
# (lambda ()
 
2884
#   (when (not (get-buffer-window-list "*Test*"))
 
2885
#     (setq next-error-last-buffer (get-buffer "*Test*"))
 
2886
#     (let* ((side (if (>= (window-width) 146) 'right 'bottom))
 
2887
#            (display-buffer-overriding-action
 
2888
#             `((display-buffer-in-side-window) (side . ,side)
 
2889
#               (window-height . fit-window-to-buffer)
 
2890
#               (window-width . fit-window-to-buffer))))
 
2891
#       (display-buffer "*Test*"))))
 
2892
# eval:
 
2893
# (progn
 
2894
#   (let* ((run-extra-tests (lambda () (interactive)
 
2895
#                             (funcall run-tests t)))
 
2896
#          (inner-keymap `(keymap (116 . ,run-extra-tests))) ; t
 
2897
#          (outer-keymap `(keymap (3 . ,inner-keymap))))     ; C-c
 
2898
#     (setq minor-mode-overriding-map-alist
 
2899
#           (cons `(run-tests . ,outer-keymap)
 
2900
#                 minor-mode-overriding-map-alist)))
 
2901
#   (add-hook 'after-save-hook run-tests 90 t))
 
2902
# End: