/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos-ctl

  • Committer: Teddy Hogeborn
  • Date: 2019-03-17 11:10:21 UTC
  • Revision ID: teddy@recompile.se-20190317111021-chyektrlb42h6l0j
mandos-ctl: Refactor

* mandos-ctl (TestBaseCommands.test_remove): Remove superfluous
                                             super() call.

Show diffs side-by-side

added added

removed removed

Lines of Context:
61
61
 
62
62
if sys.version_info.major == 2:
63
63
    str = unicode
64
 
    import StringIO
65
 
    io.StringIO = StringIO.StringIO
66
64
 
67
65
locale.setlocale(locale.LC_ALL, "")
68
66
 
83
81
 
84
82
def main():
85
83
    parser = argparse.ArgumentParser()
 
84
 
86
85
    add_command_line_options(parser)
87
86
 
88
87
    options = parser.parse_args()
 
88
 
89
89
    check_option_syntax(parser, options)
90
90
 
91
91
    clientnames = options.client
460
460
 
461
461
    def __enter__(self):
462
462
        self.logger.addFilter(self.nullfilter)
 
463
        return self
463
464
 
464
465
    class NullFilter(logging.Filter):
465
466
        def filter(self, record):
556
557
but commands which want to operate on all clients at the same time can
557
558
override this run() method instead.
558
559
"""
 
560
            self.mandos = mandos
559
561
            for clientpath, properties in clients.items():
560
562
                log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
561
563
                          dbus_busname, str(clientpath))
592
594
 
593
595
 
594
596
    class Remove(Base):
595
 
        def run(self, clients, bus, mandos):
596
 
            for clientpath in clients.keys():
597
 
                log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)",
598
 
                          dbus_busname, server_dbus_path,
599
 
                          server_dbus_interface, clientpath)
600
 
                mandos.RemoveClient(clientpath)
 
597
        def run_on_one_client(self, client, properties):
 
598
            log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)",
 
599
                      dbus_busname, server_dbus_path,
 
600
                      server_dbus_interface,
 
601
                      str(client.__dbus_object_path__))
 
602
            self.mandos.RemoveClient(client.__dbus_object_path__)
601
603
 
602
604
 
603
605
    class Output(Base):
611
613
                        "Checker", "ExtendedTimeout", "Expires",
612
614
                        "LastCheckerStatus")
613
615
 
 
616
        def run(self, clients, bus=None, mandos=None):
 
617
            print(self.output(clients.values()))
 
618
 
 
619
        def output(self, clients):
 
620
            raise NotImplementedError()
 
621
 
614
622
 
615
623
    class DumpJSON(Output):
616
 
        def run(self, clients, bus=None, mandos=None):
 
624
        def output(self, clients):
617
625
            data = {client["Name"]:
618
626
                    {key: self.dbus_boolean_to_bool(client[key])
619
627
                     for key in self.all_keywords}
620
 
                    for client in clients.values()}
621
 
            print(json.dumps(data, indent=4, separators=(',', ': ')))
 
628
                    for client in clients}
 
629
            return json.dumps(data, indent=4, separators=(',', ': '))
622
630
 
623
631
        @staticmethod
624
632
        def dbus_boolean_to_bool(value):
631
639
        def __init__(self, verbose=False):
632
640
            self.verbose = verbose
633
641
 
634
 
        def run(self, clients, bus=None, mandos=None):
 
642
        def output(self, clients):
635
643
            default_keywords = ("Name", "Enabled", "Timeout",
636
644
                                "LastCheckedOK")
637
645
            keywords = default_keywords
638
646
            if self.verbose:
639
647
                keywords = self.all_keywords
640
 
            print(self.TableOfClients(clients.values(), keywords))
 
648
            return str(self.TableOfClients(clients, keywords))
641
649
 
642
650
        class TableOfClients(object):
643
651
            tableheaders = {
724
732
                                seconds=td.seconds % 60))
725
733
 
726
734
 
727
 
    class PropertySetter(Base):
 
735
    class Property(Base):
728
736
        "Abstract class for Actions for setting one client property"
729
737
 
730
738
        def run_on_one_client(self, client, properties):
745
753
            raise NotImplementedError()
746
754
 
747
755
 
748
 
    class Enable(PropertySetter):
 
756
    class Enable(Property):
749
757
        propname = "Enabled"
750
758
        value_to_set = dbus.Boolean(True)
751
759
 
752
760
 
753
 
    class Disable(PropertySetter):
 
761
    class Disable(Property):
754
762
        propname = "Enabled"
755
763
        value_to_set = dbus.Boolean(False)
756
764
 
757
765
 
758
 
    class BumpTimeout(PropertySetter):
 
766
    class BumpTimeout(Property):
759
767
        propname = "LastCheckedOK"
760
768
        value_to_set = ""
761
769
 
762
770
 
763
 
    class StartChecker(PropertySetter):
764
 
        propname = "CheckerRunning"
765
 
        value_to_set = dbus.Boolean(True)
766
 
 
767
 
 
768
 
    class StopChecker(PropertySetter):
769
 
        propname = "CheckerRunning"
770
 
        value_to_set = dbus.Boolean(False)
771
 
 
772
 
 
773
 
    class ApproveByDefault(PropertySetter):
774
 
        propname = "ApprovedByDefault"
775
 
        value_to_set = dbus.Boolean(True)
776
 
 
777
 
 
778
 
    class DenyByDefault(PropertySetter):
779
 
        propname = "ApprovedByDefault"
780
 
        value_to_set = dbus.Boolean(False)
781
 
 
782
 
 
783
 
    class PropertySetterValue(PropertySetter):
784
 
        """Abstract class for PropertySetter recieving a value as
785
 
constructor argument instead of a class attribute."""
 
771
    class StartChecker(Property):
 
772
        propname = "CheckerRunning"
 
773
        value_to_set = dbus.Boolean(True)
 
774
 
 
775
 
 
776
    class StopChecker(Property):
 
777
        propname = "CheckerRunning"
 
778
        value_to_set = dbus.Boolean(False)
 
779
 
 
780
 
 
781
    class ApproveByDefault(Property):
 
782
        propname = "ApprovedByDefault"
 
783
        value_to_set = dbus.Boolean(True)
 
784
 
 
785
 
 
786
    class DenyByDefault(Property):
 
787
        propname = "ApprovedByDefault"
 
788
        value_to_set = dbus.Boolean(False)
 
789
 
 
790
 
 
791
    class PropertyValue(Property):
 
792
        "Abstract class for Property recieving a value as argument"
786
793
        def __init__(self, value):
787
794
            self.value_to_set = value
788
795
 
789
796
 
790
 
    class SetChecker(PropertySetterValue):
 
797
    class SetChecker(PropertyValue):
791
798
        propname = "Checker"
792
799
 
793
800
 
794
 
    class SetHost(PropertySetterValue):
 
801
    class SetHost(PropertyValue):
795
802
        propname = "Host"
796
803
 
797
804
 
798
 
    class SetSecret(PropertySetterValue):
 
805
    class SetSecret(PropertyValue):
799
806
        propname = "Secret"
800
807
 
801
808
        @property
809
816
            value.close()
810
817
 
811
818
 
812
 
    class PropertySetterValueMilliseconds(PropertySetterValue):
813
 
        """Abstract class for PropertySetterValue taking a value
814
 
argument as a datetime.timedelta() but should store it as
815
 
milliseconds."""
 
819
    class MillisecondsPropertyValueArgument(PropertyValue):
 
820
        """Abstract class for PropertyValue taking a value argument as
 
821
a datetime.timedelta() but should store it as milliseconds."""
816
822
 
817
823
        @property
818
824
        def value_to_set(self):
824
830
            self._vts = int(round(value.total_seconds() * 1000))
825
831
 
826
832
 
827
 
    class SetTimeout(PropertySetterValueMilliseconds):
 
833
    class SetTimeout(MillisecondsPropertyValueArgument):
828
834
        propname = "Timeout"
829
835
 
830
836
 
831
 
    class SetExtendedTimeout(PropertySetterValueMilliseconds):
 
837
    class SetExtendedTimeout(MillisecondsPropertyValueArgument):
832
838
        propname = "ExtendedTimeout"
833
839
 
834
840
 
835
 
    class SetInterval(PropertySetterValueMilliseconds):
 
841
    class SetInterval(MillisecondsPropertyValueArgument):
836
842
        propname = "Interval"
837
843
 
838
844
 
839
 
    class SetApprovalDelay(PropertySetterValueMilliseconds):
 
845
    class SetApprovalDelay(MillisecondsPropertyValueArgument):
840
846
        propname = "ApprovalDelay"
841
847
 
842
848
 
843
 
    class SetApprovalDuration(PropertySetterValueMilliseconds):
 
849
    class SetApprovalDuration(MillisecondsPropertyValueArgument):
844
850
        propname = "ApprovalDuration"
845
851
 
846
852
 
880
886
 
881
887
 
882
888
class Test_string_to_delta(TestCaseWithAssertLogs):
883
 
    # Just test basic RFC 3339 functionality here, the doc string for
884
 
    # rfc3339_duration_to_delta() already has more comprehensive
885
 
    # tests, which is run by doctest.
886
 
 
887
 
    def test_rfc3339_zero_seconds(self):
888
 
        self.assertEqual(datetime.timedelta(),
889
 
                         string_to_delta("PT0S"))
890
 
 
891
 
    def test_rfc3339_zero_days(self):
892
 
        self.assertEqual(datetime.timedelta(), string_to_delta("P0D"))
893
 
 
894
 
    def test_rfc3339_one_second(self):
895
 
        self.assertEqual(datetime.timedelta(0, 1),
896
 
                         string_to_delta("PT1S"))
897
 
 
898
 
    def test_rfc3339_two_hours(self):
899
 
        self.assertEqual(datetime.timedelta(0, 7200),
900
 
                         string_to_delta("PT2H"))
 
889
    def test_handles_basic_rfc3339(self):
 
890
        self.assertEqual(string_to_delta("PT0S"),
 
891
                         datetime.timedelta())
 
892
        self.assertEqual(string_to_delta("P0D"),
 
893
                         datetime.timedelta())
 
894
        self.assertEqual(string_to_delta("PT1S"),
 
895
                         datetime.timedelta(0, 1))
 
896
        self.assertEqual(string_to_delta("PT2H"),
 
897
                         datetime.timedelta(0, 7200))
901
898
 
902
899
    def test_falls_back_to_pre_1_6_1_with_warning(self):
903
900
        with self.assertLogs(log, logging.WARNING):
904
901
            value = string_to_delta("2h")
905
 
        self.assertEqual(datetime.timedelta(0, 7200), value)
 
902
        self.assertEqual(value, datetime.timedelta(0, 7200))
906
903
 
907
904
 
908
905
class Test_check_option_syntax(unittest.TestCase):
951
948
        # Exit code from argparse is guaranteed to be "2".  Reference:
952
949
        # https://docs.python.org/3/library
953
950
        # /argparse.html#exiting-methods
954
 
        self.assertEqual(2, e.exception.code)
 
951
        self.assertEqual(e.exception.code, 2)
955
952
 
956
953
    @staticmethod
957
954
    @contextlib.contextmanager
958
955
    def redirect_stderr_to_devnull():
959
 
        old_stderr = sys.stderr
960
 
        with contextlib.closing(open(os.devnull, "w")) as null:
961
 
            sys.stderr = null
962
 
            try:
963
 
                yield
964
 
            finally:
965
 
                sys.stderr = old_stderr
 
956
        null = os.open(os.path.devnull, os.O_RDWR)
 
957
        stderrcopy = os.dup(sys.stderr.fileno())
 
958
        os.dup2(null, sys.stderr.fileno())
 
959
        os.close(null)
 
960
        try:
 
961
            yield
 
962
        finally:
 
963
            # restore stderr
 
964
            os.dup2(stderrcopy, sys.stderr.fileno())
 
965
            os.close(stderrcopy)
966
966
 
967
967
    def check_option_syntax(self, options):
968
968
        check_option_syntax(self.parser, options)
981
981
            options = self.parser.parse_args()
982
982
            setattr(options, action, value)
983
983
            options.verbose = True
984
 
            options.client = ["client"]
 
984
            options.client = ["foo"]
985
985
            with self.assertParseError():
986
986
                self.check_option_syntax(options)
987
987
 
1017
1017
        for action, value in self.actions.items():
1018
1018
            options = self.parser.parse_args()
1019
1019
            setattr(options, action, value)
1020
 
            options.client = ["client"]
 
1020
            options.client = ["foo"]
1021
1021
            self.check_option_syntax(options)
1022
1022
 
1023
1023
    def test_one_client_with_all_actions_except_is_enabled(self):
1026
1026
            if action == "is_enabled":
1027
1027
                continue
1028
1028
            setattr(options, action, value)
1029
 
        options.client = ["client"]
 
1029
        options.client = ["foo"]
1030
1030
        self.check_option_syntax(options)
1031
1031
 
1032
1032
    def test_two_clients_with_all_actions_except_is_enabled(self):
1035
1035
            if action == "is_enabled":
1036
1036
                continue
1037
1037
            setattr(options, action, value)
1038
 
        options.client = ["client1", "client2"]
 
1038
        options.client = ["foo", "barbar"]
1039
1039
        self.check_option_syntax(options)
1040
1040
 
1041
1041
    def test_two_clients_are_ok_with_actions_except_is_enabled(self):
1044
1044
                continue
1045
1045
            options = self.parser.parse_args()
1046
1046
            setattr(options, action, value)
1047
 
            options.client = ["client1", "client2"]
 
1047
            options.client = ["foo", "barbar"]
1048
1048
            self.check_option_syntax(options)
1049
1049
 
1050
1050
    def test_is_enabled_fails_without_client(self):
1056
1056
    def test_is_enabled_fails_with_two_clients(self):
1057
1057
        options = self.parser.parse_args()
1058
1058
        options.is_enabled = True
1059
 
        options.client = ["client1", "client2"]
 
1059
        options.client = ["foo", "barbar"]
1060
1060
        with self.assertParseError():
1061
1061
            self.check_option_syntax(options)
1062
1062
 
1079
1079
            def get_object(mockbus_self, busname, dbus_path):
1080
1080
                # Note that "self" is still the testcase instance,
1081
1081
                # this MockBus instance is in "mockbus_self".
1082
 
                self.assertEqual(dbus_busname, busname)
1083
 
                self.assertEqual(server_dbus_path, dbus_path)
 
1082
                self.assertEqual(busname, dbus_busname)
 
1083
                self.assertEqual(dbus_path, server_dbus_path)
1084
1084
                mockbus_self.called = True
1085
1085
                return mockbus_self
1086
1086
 
1089
1089
        self.assertTrue(mockbus.called)
1090
1090
 
1091
1091
    def test_logs_and_exits_on_dbus_error(self):
1092
 
        class FailingBusStub(object):
 
1092
        class MockBusFailing(object):
1093
1093
            def get_object(self, busname, dbus_path):
1094
1094
                raise dbus.exceptions.DBusException("Test")
1095
1095
 
1096
1096
        with self.assertLogs(log, logging.CRITICAL):
1097
1097
            with self.assertRaises(SystemExit) as e:
1098
 
                bus = get_mandos_dbus_object(bus=FailingBusStub())
 
1098
                bus = get_mandos_dbus_object(bus=MockBusFailing())
1099
1099
 
1100
1100
        if isinstance(e.exception.code, int):
1101
 
            self.assertNotEqual(0, e.exception.code)
 
1101
            self.assertNotEqual(e.exception.code, 0)
1102
1102
        else:
1103
1103
            self.assertIsNotNone(e.exception.code)
1104
1104
 
1105
1105
 
1106
1106
class Test_get_managed_objects(TestCaseWithAssertLogs):
1107
1107
    def test_calls_and_returns_GetManagedObjects(self):
1108
 
        managed_objects = {"/clients/client": { "Name": "client"}}
1109
 
        class ObjectManagerStub(object):
 
1108
        managed_objects = {"/clients/foo": { "Name": "foo"}}
 
1109
        class MockObjectManager(object):
1110
1110
            def GetManagedObjects(self):
1111
1111
                return managed_objects
1112
 
        retval = get_managed_objects(ObjectManagerStub())
 
1112
        retval = get_managed_objects(MockObjectManager())
1113
1113
        self.assertDictEqual(managed_objects, retval)
1114
1114
 
1115
1115
    def test_logs_and_exits_on_dbus_error(self):
1116
1116
        dbus_logger = logging.getLogger("dbus.proxies")
1117
1117
 
1118
 
        class ObjectManagerFailingStub(object):
 
1118
        class MockObjectManagerFailing(object):
1119
1119
            def GetManagedObjects(self):
1120
1120
                dbus_logger.error("Test")
1121
1121
                raise dbus.exceptions.DBusException("Test")
1132
1132
        try:
1133
1133
            with self.assertLogs(log, logging.CRITICAL) as watcher:
1134
1134
                with self.assertRaises(SystemExit) as e:
1135
 
                    get_managed_objects(ObjectManagerFailingStub())
 
1135
                    get_managed_objects(MockObjectManagerFailing())
1136
1136
        finally:
1137
1137
            dbus_logger.removeFilter(counting_handler)
1138
1138
 
1139
1139
        # Make sure the dbus logger was suppressed
1140
 
        self.assertEqual(0, counting_handler.count)
 
1140
        self.assertEqual(counting_handler.count, 0)
1141
1141
 
1142
1142
        # Test that the dbus_logger still works
1143
1143
        with self.assertLogs(dbus_logger, logging.ERROR):
1144
1144
            dbus_logger.error("Test")
1145
1145
 
1146
1146
        if isinstance(e.exception.code, int):
1147
 
            self.assertNotEqual(0, e.exception.code)
 
1147
            self.assertNotEqual(e.exception.code, 0)
1148
1148
        else:
1149
1149
            self.assertIsNotNone(e.exception.code)
1150
1150
 
1155
1155
        add_command_line_options(self.parser)
1156
1156
 
1157
1157
    def test_is_enabled(self):
1158
 
        self.assert_command_from_args(["--is-enabled", "client"],
 
1158
        self.assert_command_from_args(["--is-enabled", "foo"],
1159
1159
                                      command.IsEnabled)
1160
1160
 
1161
1161
    def assert_command_from_args(self, args, command_cls,
1165
1165
        options = self.parser.parse_args(args)
1166
1166
        check_option_syntax(self.parser, options)
1167
1167
        commands = commands_from_options(options)
1168
 
        self.assertEqual(1, len(commands))
 
1168
        self.assertEqual(len(commands), 1)
1169
1169
        command = commands[0]
1170
1170
        self.assertIsInstance(command, command_cls)
1171
1171
        for key, value in cmd_attrs.items():
1172
 
            self.assertEqual(value, getattr(command, key))
 
1172
            self.assertEqual(getattr(command, key), value)
1173
1173
 
1174
1174
    def test_is_enabled_short(self):
1175
 
        self.assert_command_from_args(["-V", "client"],
 
1175
        self.assert_command_from_args(["-V", "foo"],
1176
1176
                                      command.IsEnabled)
1177
1177
 
1178
1178
    def test_approve(self):
1179
 
        self.assert_command_from_args(["--approve", "client"],
 
1179
        self.assert_command_from_args(["--approve", "foo"],
1180
1180
                                      command.Approve)
1181
1181
 
1182
1182
    def test_approve_short(self):
1183
 
        self.assert_command_from_args(["-A", "client"],
1184
 
                                      command.Approve)
 
1183
        self.assert_command_from_args(["-A", "foo"], command.Approve)
1185
1184
 
1186
1185
    def test_deny(self):
1187
 
        self.assert_command_from_args(["--deny", "client"],
1188
 
                                      command.Deny)
 
1186
        self.assert_command_from_args(["--deny", "foo"], command.Deny)
1189
1187
 
1190
1188
    def test_deny_short(self):
1191
 
        self.assert_command_from_args(["-D", "client"], command.Deny)
 
1189
        self.assert_command_from_args(["-D", "foo"], command.Deny)
1192
1190
 
1193
1191
    def test_remove(self):
1194
 
        self.assert_command_from_args(["--remove", "client"],
 
1192
        self.assert_command_from_args(["--remove", "foo"],
1195
1193
                                      command.Remove)
1196
1194
 
1197
1195
    def test_deny_before_remove(self):
1198
1196
        options = self.parser.parse_args(["--deny", "--remove",
1199
 
                                          "client"])
 
1197
                                          "foo"])
1200
1198
        check_option_syntax(self.parser, options)
1201
1199
        commands = commands_from_options(options)
1202
 
        self.assertEqual(2, len(commands))
 
1200
        self.assertEqual(len(commands), 2)
1203
1201
        self.assertIsInstance(commands[0], command.Deny)
1204
1202
        self.assertIsInstance(commands[1], command.Remove)
1205
1203
 
1208
1206
                                          "--all"])
1209
1207
        check_option_syntax(self.parser, options)
1210
1208
        commands = commands_from_options(options)
1211
 
        self.assertEqual(2, len(commands))
 
1209
        self.assertEqual(len(commands), 2)
1212
1210
        self.assertIsInstance(commands[0], command.Deny)
1213
1211
        self.assertIsInstance(commands[1], command.Remove)
1214
1212
 
1215
1213
    def test_remove_short(self):
1216
 
        self.assert_command_from_args(["-r", "client"],
1217
 
                                      command.Remove)
 
1214
        self.assert_command_from_args(["-r", "foo"], command.Remove)
1218
1215
 
1219
1216
    def test_dump_json(self):
1220
1217
        self.assert_command_from_args(["--dump-json"],
1221
1218
                                      command.DumpJSON)
1222
1219
 
1223
1220
    def test_enable(self):
1224
 
        self.assert_command_from_args(["--enable", "client"],
 
1221
        self.assert_command_from_args(["--enable", "foo"],
1225
1222
                                      command.Enable)
1226
1223
 
1227
1224
    def test_enable_short(self):
1228
 
        self.assert_command_from_args(["-e", "client"],
1229
 
                                      command.Enable)
 
1225
        self.assert_command_from_args(["-e", "foo"], command.Enable)
1230
1226
 
1231
1227
    def test_disable(self):
1232
 
        self.assert_command_from_args(["--disable", "client"],
 
1228
        self.assert_command_from_args(["--disable", "foo"],
1233
1229
                                      command.Disable)
1234
1230
 
1235
1231
    def test_disable_short(self):
1236
 
        self.assert_command_from_args(["-d", "client"],
1237
 
                                      command.Disable)
 
1232
        self.assert_command_from_args(["-d", "foo"], command.Disable)
1238
1233
 
1239
1234
    def test_bump_timeout(self):
1240
 
        self.assert_command_from_args(["--bump-timeout", "client"],
 
1235
        self.assert_command_from_args(["--bump-timeout", "foo"],
1241
1236
                                      command.BumpTimeout)
1242
1237
 
1243
1238
    def test_bump_timeout_short(self):
1244
 
        self.assert_command_from_args(["-b", "client"],
 
1239
        self.assert_command_from_args(["-b", "foo"],
1245
1240
                                      command.BumpTimeout)
1246
1241
 
1247
1242
    def test_start_checker(self):
1248
 
        self.assert_command_from_args(["--start-checker", "client"],
 
1243
        self.assert_command_from_args(["--start-checker", "foo"],
1249
1244
                                      command.StartChecker)
1250
1245
 
1251
1246
    def test_stop_checker(self):
1252
 
        self.assert_command_from_args(["--stop-checker", "client"],
 
1247
        self.assert_command_from_args(["--stop-checker", "foo"],
1253
1248
                                      command.StopChecker)
1254
1249
 
1255
1250
    def test_approve_by_default(self):
1256
 
        self.assert_command_from_args(["--approve-by-default",
1257
 
                                       "client"],
 
1251
        self.assert_command_from_args(["--approve-by-default", "foo"],
1258
1252
                                      command.ApproveByDefault)
1259
1253
 
1260
1254
    def test_deny_by_default(self):
1261
 
        self.assert_command_from_args(["--deny-by-default", "client"],
 
1255
        self.assert_command_from_args(["--deny-by-default", "foo"],
1262
1256
                                      command.DenyByDefault)
1263
1257
 
1264
1258
    def test_checker(self):
1265
 
        self.assert_command_from_args(["--checker", ":", "client"],
 
1259
        self.assert_command_from_args(["--checker", ":", "foo"],
1266
1260
                                      command.SetChecker,
1267
1261
                                      value_to_set=":")
1268
1262
 
1269
1263
    def test_checker_empty(self):
1270
 
        self.assert_command_from_args(["--checker", "", "client"],
 
1264
        self.assert_command_from_args(["--checker", "", "foo"],
1271
1265
                                      command.SetChecker,
1272
1266
                                      value_to_set="")
1273
1267
 
1274
1268
    def test_checker_short(self):
1275
 
        self.assert_command_from_args(["-c", ":", "client"],
 
1269
        self.assert_command_from_args(["-c", ":", "foo"],
1276
1270
                                      command.SetChecker,
1277
1271
                                      value_to_set=":")
1278
1272
 
1279
1273
    def test_host(self):
1280
 
        self.assert_command_from_args(
1281
 
            ["--host", "client.example.org", "client"],
1282
 
            command.SetHost, value_to_set="client.example.org")
 
1274
        self.assert_command_from_args(["--host", "foo.example.org",
 
1275
                                       "foo"], command.SetHost,
 
1276
                                      value_to_set="foo.example.org")
1283
1277
 
1284
1278
    def test_host_short(self):
1285
 
        self.assert_command_from_args(
1286
 
            ["-H", "client.example.org", "client"], command.SetHost,
1287
 
            value_to_set="client.example.org")
 
1279
        self.assert_command_from_args(["-H", "foo.example.org",
 
1280
                                       "foo"], command.SetHost,
 
1281
                                      value_to_set="foo.example.org")
1288
1282
 
1289
1283
    def test_secret_devnull(self):
1290
1284
        self.assert_command_from_args(["--secret", os.path.devnull,
1291
 
                                       "client"], command.SetSecret,
 
1285
                                       "foo"], command.SetSecret,
1292
1286
                                      value_to_set=b"")
1293
1287
 
1294
1288
    def test_secret_tempfile(self):
1297
1291
            f.write(value)
1298
1292
            f.seek(0)
1299
1293
            self.assert_command_from_args(["--secret", f.name,
1300
 
                                           "client"],
1301
 
                                          command.SetSecret,
 
1294
                                           "foo"], command.SetSecret,
1302
1295
                                          value_to_set=value)
1303
1296
 
1304
1297
    def test_secret_devnull_short(self):
1305
 
        self.assert_command_from_args(["-s", os.path.devnull,
1306
 
                                       "client"], command.SetSecret,
 
1298
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
 
1299
                                      command.SetSecret,
1307
1300
                                      value_to_set=b"")
1308
1301
 
1309
1302
    def test_secret_tempfile_short(self):
1311
1304
            value = b"secret\0xyzzy\nbar"
1312
1305
            f.write(value)
1313
1306
            f.seek(0)
1314
 
            self.assert_command_from_args(["-s", f.name, "client"],
 
1307
            self.assert_command_from_args(["-s", f.name, "foo"],
1315
1308
                                          command.SetSecret,
1316
1309
                                          value_to_set=value)
1317
1310
 
1318
1311
    def test_timeout(self):
1319
 
        self.assert_command_from_args(["--timeout", "PT5M", "client"],
 
1312
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
1320
1313
                                      command.SetTimeout,
1321
1314
                                      value_to_set=300000)
1322
1315
 
1323
1316
    def test_timeout_short(self):
1324
 
        self.assert_command_from_args(["-t", "PT5M", "client"],
 
1317
        self.assert_command_from_args(["-t", "PT5M", "foo"],
1325
1318
                                      command.SetTimeout,
1326
1319
                                      value_to_set=300000)
1327
1320
 
1328
1321
    def test_extended_timeout(self):
1329
1322
        self.assert_command_from_args(["--extended-timeout", "PT15M",
1330
 
                                       "client"],
 
1323
                                       "foo"],
1331
1324
                                      command.SetExtendedTimeout,
1332
1325
                                      value_to_set=900000)
1333
1326
 
1334
1327
    def test_interval(self):
1335
 
        self.assert_command_from_args(["--interval", "PT2M",
1336
 
                                       "client"], command.SetInterval,
 
1328
        self.assert_command_from_args(["--interval", "PT2M", "foo"],
 
1329
                                      command.SetInterval,
1337
1330
                                      value_to_set=120000)
1338
1331
 
1339
1332
    def test_interval_short(self):
1340
 
        self.assert_command_from_args(["-i", "PT2M", "client"],
 
1333
        self.assert_command_from_args(["-i", "PT2M", "foo"],
1341
1334
                                      command.SetInterval,
1342
1335
                                      value_to_set=120000)
1343
1336
 
1344
1337
    def test_approval_delay(self):
1345
1338
        self.assert_command_from_args(["--approval-delay", "PT30S",
1346
 
                                       "client"],
 
1339
                                       "foo"],
1347
1340
                                      command.SetApprovalDelay,
1348
1341
                                      value_to_set=30000)
1349
1342
 
1350
1343
    def test_approval_duration(self):
1351
1344
        self.assert_command_from_args(["--approval-duration", "PT1S",
1352
 
                                       "client"],
 
1345
                                       "foo"],
1353
1346
                                      command.SetApprovalDuration,
1354
1347
                                      value_to_set=1000)
1355
1348
 
1379
1372
                self.attributes["Name"] = name
1380
1373
                self.calls = []
1381
1374
            def Set(self, interface, propname, value, dbus_interface):
1382
 
                testcase.assertEqual(client_dbus_interface, interface)
1383
 
                testcase.assertEqual(dbus.PROPERTIES_IFACE,
1384
 
                                     dbus_interface)
 
1375
                testcase.assertEqual(interface, client_dbus_interface)
 
1376
                testcase.assertEqual(dbus_interface,
 
1377
                                     dbus.PROPERTIES_IFACE)
1385
1378
                self.attributes[propname] = value
 
1379
            def Get(self, interface, propname, dbus_interface):
 
1380
                testcase.assertEqual(interface, client_dbus_interface)
 
1381
                testcase.assertEqual(dbus_interface,
 
1382
                                     dbus.PROPERTIES_IFACE)
 
1383
                return self.attributes[propname]
1386
1384
            def Approve(self, approve, dbus_interface):
1387
 
                testcase.assertEqual(client_dbus_interface,
1388
 
                                     dbus_interface)
 
1385
                testcase.assertEqual(dbus_interface,
 
1386
                                     client_dbus_interface)
1389
1387
                self.calls.append(("Approve", (approve,
1390
1388
                                               dbus_interface)))
1391
1389
        self.client = MockClient(
1438
1436
            LastCheckerStatus=-2)
1439
1437
        self.clients =  collections.OrderedDict(
1440
1438
            [
1441
 
                (self.client.__dbus_object_path__,
1442
 
                 self.client.attributes),
1443
 
                (self.other_client.__dbus_object_path__,
1444
 
                 self.other_client.attributes),
 
1439
                ("/clients/foo", self.client.attributes),
 
1440
                ("/clients/barbar", self.other_client.attributes),
1445
1441
            ])
1446
 
        self.one_client = {self.client.__dbus_object_path__:
1447
 
                           self.client.attributes}
 
1442
        self.one_client = {"/clients/foo": self.client.attributes}
1448
1443
 
1449
1444
    @property
1450
1445
    def bus(self):
1451
 
        class MockBus(object):
 
1446
        class Bus(object):
1452
1447
            @staticmethod
1453
1448
            def get_object(client_bus_name, path):
1454
 
                self.assertEqual(dbus_busname, client_bus_name)
1455
 
                # Note: "self" here is the TestCmd instance, not the
1456
 
                # MockBus instance, since this is a static method!
1457
 
                if path == self.client.__dbus_object_path__:
1458
 
                    return self.client
1459
 
                elif path == self.other_client.__dbus_object_path__:
1460
 
                    return self.other_client
1461
 
        return MockBus()
 
1449
                self.assertEqual(client_bus_name, dbus_busname)
 
1450
                return {
 
1451
                    # Note: "self" here is the TestCmd instance, not
 
1452
                    # the Bus instance, since this is a static method!
 
1453
                    "/clients/foo": self.client,
 
1454
                    "/clients/barbar": self.other_client,
 
1455
                }[path]
 
1456
        return Bus()
1462
1457
 
1463
1458
 
1464
1459
class TestBaseCommands(TestCommand):
1465
1460
 
1466
 
    def test_IsEnabled_exits_successfully(self):
 
1461
    def test_is_enabled(self):
 
1462
        self.assertTrue(all(command.IsEnabled().is_enabled(client,
 
1463
                                                      properties)
 
1464
                            for client, properties
 
1465
                            in self.clients.items()))
 
1466
 
 
1467
    def test_is_enabled_run_exits_successfully(self):
1467
1468
        with self.assertRaises(SystemExit) as e:
1468
1469
            command.IsEnabled().run(self.one_client)
1469
1470
        if e.exception.code is not None:
1470
 
            self.assertEqual(0, e.exception.code)
 
1471
            self.assertEqual(e.exception.code, 0)
1471
1472
        else:
1472
1473
            self.assertIsNone(e.exception.code)
1473
1474
 
1474
 
    def test_IsEnabled_exits_with_failure(self):
 
1475
    def test_is_enabled_run_exits_with_failure(self):
1475
1476
        self.client.attributes["Enabled"] = dbus.Boolean(False)
1476
1477
        with self.assertRaises(SystemExit) as e:
1477
1478
            command.IsEnabled().run(self.one_client)
1478
1479
        if isinstance(e.exception.code, int):
1479
 
            self.assertNotEqual(0, e.exception.code)
 
1480
            self.assertNotEqual(e.exception.code, 0)
1480
1481
        else:
1481
1482
            self.assertIsNotNone(e.exception.code)
1482
1483
 
1483
 
    def test_Approve(self):
 
1484
    def test_approve(self):
1484
1485
        command.Approve().run(self.clients, self.bus)
1485
1486
        for clientpath in self.clients:
1486
1487
            client = self.bus.get_object(dbus_busname, clientpath)
1487
1488
            self.assertIn(("Approve", (True, client_dbus_interface)),
1488
1489
                          client.calls)
1489
1490
 
1490
 
    def test_Deny(self):
 
1491
    def test_deny(self):
1491
1492
        command.Deny().run(self.clients, self.bus)
1492
1493
        for clientpath in self.clients:
1493
1494
            client = self.bus.get_object(dbus_busname, clientpath)
1494
1495
            self.assertIn(("Approve", (False, client_dbus_interface)),
1495
1496
                          client.calls)
1496
1497
 
1497
 
    def test_Remove(self):
1498
 
        class MandosSpy(object):
 
1498
    def test_remove(self):
 
1499
        class MockMandos(object):
1499
1500
            def __init__(self):
1500
1501
                self.calls = []
1501
1502
            def RemoveClient(self, dbus_path):
1502
1503
                self.calls.append(("RemoveClient", (dbus_path,)))
1503
 
        mandos = MandosSpy()
 
1504
        mandos = MockMandos()
1504
1505
        command.Remove().run(self.clients, self.bus, mandos)
 
1506
        self.assertEqual(len(mandos.calls), 2)
1505
1507
        for clientpath in self.clients:
1506
1508
            self.assertIn(("RemoveClient", (clientpath,)),
1507
1509
                          mandos.calls)
1558
1560
    }
1559
1561
 
1560
1562
    def test_DumpJSON_normal(self):
1561
 
        with self.capture_stdout_to_buffer() as buffer:
1562
 
            command.DumpJSON().run(self.clients)
1563
 
        json_data = json.loads(buffer.getvalue())
1564
 
        self.assertDictEqual(self.expected_json, json_data)
1565
 
 
1566
 
    @staticmethod
1567
 
    @contextlib.contextmanager
1568
 
    def capture_stdout_to_buffer():
1569
 
        capture_buffer = io.StringIO()
1570
 
        old_stdout = sys.stdout
1571
 
        sys.stdout = capture_buffer
1572
 
        try:
1573
 
            yield capture_buffer
1574
 
        finally:
1575
 
            sys.stdout = old_stdout
 
1563
        output = command.DumpJSON().output(self.clients.values())
 
1564
        json_data = json.loads(output)
 
1565
        self.assertDictEqual(json_data, self.expected_json)
1576
1566
 
1577
1567
    def test_DumpJSON_one_client(self):
1578
 
        with self.capture_stdout_to_buffer() as buffer:
1579
 
            command.DumpJSON().run(self.one_client)
1580
 
        json_data = json.loads(buffer.getvalue())
 
1568
        output = command.DumpJSON().output(self.one_client.values())
 
1569
        json_data = json.loads(output)
1581
1570
        expected_json = {"foo": self.expected_json["foo"]}
1582
 
        self.assertDictEqual(expected_json, json_data)
 
1571
        self.assertDictEqual(json_data, expected_json)
1583
1572
 
1584
1573
    def test_PrintTable_normal(self):
1585
 
        with self.capture_stdout_to_buffer() as buffer:
1586
 
            command.PrintTable().run(self.clients)
 
1574
        output = command.PrintTable().output(self.clients.values())
1587
1575
        expected_output = "\n".join((
1588
1576
            "Name   Enabled Timeout  Last Successful Check",
1589
1577
            "foo    Yes     00:05:00 2019-02-03T00:00:00  ",
1590
1578
            "barbar Yes     00:05:00 2019-02-04T00:00:00  ",
1591
 
        )) + "\n"
1592
 
        self.assertEqual(expected_output, buffer.getvalue())
 
1579
        ))
 
1580
        self.assertEqual(output, expected_output)
1593
1581
 
1594
1582
    def test_PrintTable_verbose(self):
1595
 
        with self.capture_stdout_to_buffer() as buffer:
1596
 
            command.PrintTable(verbose=True).run(self.clients)
 
1583
        output = command.PrintTable(verbose=True).output(
 
1584
            self.clients.values())
1597
1585
        columns = (
1598
1586
            (
1599
1587
                "Name   ",
1681
1669
            )
1682
1670
        )
1683
1671
        num_lines = max(len(rows) for rows in columns)
1684
 
        expected_output = ("\n".join("".join(rows[line]
1685
 
                                             for rows in columns)
1686
 
                                     for line in range(num_lines))
1687
 
                           + "\n")
1688
 
        self.assertEqual(expected_output, buffer.getvalue())
 
1672
        expected_output = "\n".join("".join(rows[line]
 
1673
                                            for rows in columns)
 
1674
                                    for line in range(num_lines))
 
1675
        self.assertEqual(output, expected_output)
1689
1676
 
1690
1677
    def test_PrintTable_one_client(self):
1691
 
        with self.capture_stdout_to_buffer() as buffer:
1692
 
            command.PrintTable().run(self.one_client)
 
1678
        output = command.PrintTable().output(self.one_client.values())
1693
1679
        expected_output = "\n".join((
1694
1680
            "Name Enabled Timeout  Last Successful Check",
1695
1681
            "foo  Yes     00:05:00 2019-02-03T00:00:00  ",
1696
 
        )) + "\n"
1697
 
        self.assertEqual(expected_output, buffer.getvalue())
1698
 
 
1699
 
 
1700
 
class TestPropertySetterCmd(TestCommand):
1701
 
    """Abstract class for tests of command.PropertySetter classes"""
 
1682
        ))
 
1683
        self.assertEqual(output, expected_output)
 
1684
 
 
1685
 
 
1686
class TestPropertyCmd(TestCommand):
 
1687
    """Abstract class for tests of command.Property classes"""
1702
1688
    def runTest(self):
1703
1689
        if not hasattr(self, "command"):
1704
1690
            return
1709
1695
            for clientpath in self.clients:
1710
1696
                client = self.bus.get_object(dbus_busname, clientpath)
1711
1697
                old_value = client.attributes[self.propname]
 
1698
                self.assertNotIsInstance(old_value, self.Unique)
1712
1699
                client.attributes[self.propname] = self.Unique()
1713
1700
            self.run_command(value_to_set, self.clients)
1714
1701
            for clientpath in self.clients:
1715
1702
                client = self.bus.get_object(dbus_busname, clientpath)
1716
1703
                value = client.attributes[self.propname]
1717
1704
                self.assertNotIsInstance(value, self.Unique)
1718
 
                self.assertEqual(value_to_get, value)
 
1705
                self.assertEqual(value, value_to_get)
1719
1706
 
1720
1707
    class Unique(object):
1721
1708
        """Class for objects which exist only to be unique objects,
1725
1712
        self.command().run(clients, self.bus)
1726
1713
 
1727
1714
 
1728
 
class TestEnableCmd(TestPropertySetterCmd):
 
1715
class TestEnableCmd(TestPropertyCmd):
1729
1716
    command = command.Enable
1730
1717
    propname = "Enabled"
1731
1718
    values_to_set = [dbus.Boolean(True)]
1732
1719
 
1733
1720
 
1734
 
class TestDisableCmd(TestPropertySetterCmd):
 
1721
class TestDisableCmd(TestPropertyCmd):
1735
1722
    command = command.Disable
1736
1723
    propname = "Enabled"
1737
1724
    values_to_set = [dbus.Boolean(False)]
1738
1725
 
1739
1726
 
1740
 
class TestBumpTimeoutCmd(TestPropertySetterCmd):
 
1727
class TestBumpTimeoutCmd(TestPropertyCmd):
1741
1728
    command = command.BumpTimeout
1742
1729
    propname = "LastCheckedOK"
1743
1730
    values_to_set = [""]
1744
1731
 
1745
1732
 
1746
 
class TestStartCheckerCmd(TestPropertySetterCmd):
 
1733
class TestStartCheckerCmd(TestPropertyCmd):
1747
1734
    command = command.StartChecker
1748
1735
    propname = "CheckerRunning"
1749
1736
    values_to_set = [dbus.Boolean(True)]
1750
1737
 
1751
1738
 
1752
 
class TestStopCheckerCmd(TestPropertySetterCmd):
 
1739
class TestStopCheckerCmd(TestPropertyCmd):
1753
1740
    command = command.StopChecker
1754
1741
    propname = "CheckerRunning"
1755
1742
    values_to_set = [dbus.Boolean(False)]
1756
1743
 
1757
1744
 
1758
 
class TestApproveByDefaultCmd(TestPropertySetterCmd):
 
1745
class TestApproveByDefaultCmd(TestPropertyCmd):
1759
1746
    command = command.ApproveByDefault
1760
1747
    propname = "ApprovedByDefault"
1761
1748
    values_to_set = [dbus.Boolean(True)]
1762
1749
 
1763
1750
 
1764
 
class TestDenyByDefaultCmd(TestPropertySetterCmd):
 
1751
class TestDenyByDefaultCmd(TestPropertyCmd):
1765
1752
    command = command.DenyByDefault
1766
1753
    propname = "ApprovedByDefault"
1767
1754
    values_to_set = [dbus.Boolean(False)]
1768
1755
 
1769
1756
 
1770
 
class TestPropertySetterValueCmd(TestPropertySetterCmd):
1771
 
    """Abstract class for tests of PropertySetterValueCmd classes"""
 
1757
class TestPropertyValueCmd(TestPropertyCmd):
 
1758
    """Abstract class for tests of PropertyValueCmd classes"""
1772
1759
 
1773
1760
    def runTest(self):
1774
 
        if type(self) is TestPropertySetterValueCmd:
 
1761
        if type(self) is TestPropertyValueCmd:
1775
1762
            return
1776
 
        return super(TestPropertySetterValueCmd, self).runTest()
 
1763
        return super(TestPropertyValueCmd, self).runTest()
1777
1764
 
1778
1765
    def run_command(self, value, clients):
1779
1766
        self.command(value).run(clients, self.bus)
1780
1767
 
1781
1768
 
1782
 
class TestSetCheckerCmd(TestPropertySetterValueCmd):
 
1769
class TestSetCheckerCmd(TestPropertyValueCmd):
1783
1770
    command = command.SetChecker
1784
1771
    propname = "Checker"
1785
1772
    values_to_set = ["", ":", "fping -q -- %s"]
1786
1773
 
1787
1774
 
1788
 
class TestSetHostCmd(TestPropertySetterValueCmd):
 
1775
class TestSetHostCmd(TestPropertyValueCmd):
1789
1776
    command = command.SetHost
1790
1777
    propname = "Host"
1791
 
    values_to_set = ["192.0.2.3", "client.example.org"]
1792
 
 
1793
 
 
1794
 
class TestSetSecretCmd(TestPropertySetterValueCmd):
 
1778
    values_to_set = ["192.0.2.3", "foo.example.org"]
 
1779
 
 
1780
 
 
1781
class TestSetSecretCmd(TestPropertyValueCmd):
1795
1782
    command = command.SetSecret
1796
1783
    propname = "Secret"
1797
1784
    values_to_set = [io.BytesIO(b""),
1798
1785
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1799
 
    values_to_get = [f.getvalue() for f in values_to_set]
1800
 
 
1801
 
 
1802
 
class TestSetTimeoutCmd(TestPropertySetterValueCmd):
 
1786
    values_to_get = [b"", b"secret\0xyzzy\nbar"]
 
1787
 
 
1788
 
 
1789
class TestSetTimeoutCmd(TestPropertyValueCmd):
1803
1790
    command = command.SetTimeout
1804
1791
    propname = "Timeout"
1805
1792
    values_to_set = [datetime.timedelta(),
1807
1794
                     datetime.timedelta(seconds=1),
1808
1795
                     datetime.timedelta(weeks=1),
1809
1796
                     datetime.timedelta(weeks=52)]
1810
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1811
 
 
1812
 
 
1813
 
class TestSetExtendedTimeoutCmd(TestPropertySetterValueCmd):
 
1797
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1798
 
 
1799
 
 
1800
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1814
1801
    command = command.SetExtendedTimeout
1815
1802
    propname = "ExtendedTimeout"
1816
1803
    values_to_set = [datetime.timedelta(),
1818
1805
                     datetime.timedelta(seconds=1),
1819
1806
                     datetime.timedelta(weeks=1),
1820
1807
                     datetime.timedelta(weeks=52)]
1821
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1822
 
 
1823
 
 
1824
 
class TestSetIntervalCmd(TestPropertySetterValueCmd):
 
1808
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1809
 
 
1810
 
 
1811
class TestSetIntervalCmd(TestPropertyValueCmd):
1825
1812
    command = command.SetInterval
1826
1813
    propname = "Interval"
1827
1814
    values_to_set = [datetime.timedelta(),
1829
1816
                     datetime.timedelta(seconds=1),
1830
1817
                     datetime.timedelta(weeks=1),
1831
1818
                     datetime.timedelta(weeks=52)]
1832
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1833
 
 
1834
 
 
1835
 
class TestSetApprovalDelayCmd(TestPropertySetterValueCmd):
 
1819
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1820
 
 
1821
 
 
1822
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1836
1823
    command = command.SetApprovalDelay
1837
1824
    propname = "ApprovalDelay"
1838
1825
    values_to_set = [datetime.timedelta(),
1840
1827
                     datetime.timedelta(seconds=1),
1841
1828
                     datetime.timedelta(weeks=1),
1842
1829
                     datetime.timedelta(weeks=52)]
1843
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1844
 
 
1845
 
 
1846
 
class TestSetApprovalDurationCmd(TestPropertySetterValueCmd):
 
1830
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1831
 
 
1832
 
 
1833
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1847
1834
    command = command.SetApprovalDuration
1848
1835
    propname = "ApprovalDuration"
1849
1836
    values_to_set = [datetime.timedelta(),
1851
1838
                     datetime.timedelta(seconds=1),
1852
1839
                     datetime.timedelta(weeks=1),
1853
1840
                     datetime.timedelta(weeks=52)]
1854
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
 
1841
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1855
1842
 
1856
1843
 
1857
1844