479
479
if options.is_enabled:
480
commands.append(command.IsEnabled())
480
commands.append(IsEnabledCmd())
482
482
if options.approve:
483
commands.append(command.Approve())
483
commands.append(ApproveCmd())
486
commands.append(command.Deny())
486
commands.append(DenyCmd())
488
488
if options.remove:
489
commands.append(command.Remove())
489
commands.append(RemoveCmd())
491
491
if options.dump_json:
492
commands.append(command.DumpJSON())
492
commands.append(DumpJSONCmd())
494
494
if options.enable:
495
commands.append(command.Enable())
495
commands.append(EnableCmd())
497
497
if options.disable:
498
commands.append(command.Disable())
498
commands.append(DisableCmd())
500
500
if options.bump_timeout:
501
commands.append(command.BumpTimeout())
501
commands.append(BumpTimeoutCmd())
503
503
if options.start_checker:
504
commands.append(command.StartChecker())
504
commands.append(StartCheckerCmd())
506
506
if options.stop_checker:
507
commands.append(command.StopChecker())
507
commands.append(StopCheckerCmd())
509
509
if options.approved_by_default is not None:
510
510
if options.approved_by_default:
511
commands.append(command.ApproveByDefault())
511
commands.append(ApproveByDefaultCmd())
513
commands.append(command.DenyByDefault())
513
commands.append(DenyByDefaultCmd())
515
515
if options.checker is not None:
516
commands.append(command.SetChecker(options.checker))
516
commands.append(SetCheckerCmd(options.checker))
518
518
if options.host is not None:
519
commands.append(command.SetHost(options.host))
519
commands.append(SetHostCmd(options.host))
521
521
if options.secret is not None:
522
commands.append(command.SetSecret(options.secret))
522
commands.append(SetSecretCmd(options.secret))
524
524
if options.timeout is not None:
525
commands.append(command.SetTimeout(options.timeout))
525
commands.append(SetTimeoutCmd(options.timeout))
527
527
if options.extended_timeout:
529
command.SetExtendedTimeout(options.extended_timeout))
529
SetExtendedTimeoutCmd(options.extended_timeout))
531
531
if options.interval is not None:
532
commands.append(command.SetInterval(options.interval))
532
commands.append(SetIntervalCmd(options.interval))
534
534
if options.approval_delay is not None:
536
command.SetApprovalDelay(options.approval_delay))
535
commands.append(SetApprovalDelayCmd(options.approval_delay))
538
537
if options.approval_duration is not None:
540
command.SetApprovalDuration(options.approval_duration))
539
SetApprovalDurationCmd(options.approval_duration))
542
541
# If no command option has been given, show table of clients,
543
542
# optionally verbosely
545
commands.append(command.PrintTable(verbose=options.verbose))
544
commands.append(PrintTableCmd(verbose=options.verbose))
550
class command(object):
551
"""A namespace for command classes"""
554
"""Abstract base class for commands"""
555
def run(self, clients, bus=None, mandos=None):
556
"""Normal commands should implement run_on_one_client(),
557
but commands which want to operate on all clients at the same time can
558
override this run() method instead.
561
for clientpath, properties in clients.items():
562
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
563
dbus_busname, str(clientpath))
564
client = bus.get_object(dbus_busname, clientpath)
565
self.run_on_one_client(client, properties)
568
class IsEnabled(Base):
569
def run(self, clients, bus=None, mandos=None):
570
client, properties = next(iter(clients.items()))
571
if self.is_enabled(client, properties):
574
def is_enabled(self, client, properties):
575
return properties["Enabled"]
579
def run_on_one_client(self, client, properties):
580
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
581
client.__dbus_object_path__,
582
client_dbus_interface)
583
client.Approve(dbus.Boolean(True),
584
dbus_interface=client_dbus_interface)
588
def run_on_one_client(self, client, properties):
589
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
590
client.__dbus_object_path__,
591
client_dbus_interface)
592
client.Approve(dbus.Boolean(False),
593
dbus_interface=client_dbus_interface)
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__)
606
"""Abstract class for commands outputting client details"""
607
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
608
"Created", "Interval", "Host", "KeyID",
609
"Fingerprint", "CheckerRunning",
610
"LastEnabled", "ApprovalPending",
611
"ApprovedByDefault", "LastApprovalRequest",
612
"ApprovalDelay", "ApprovalDuration",
613
"Checker", "ExtendedTimeout", "Expires",
616
def run(self, clients, bus=None, mandos=None):
617
print(self.output(clients.values()))
619
def output(self, clients):
620
raise NotImplementedError()
623
class DumpJSON(Output):
624
def output(self, clients):
625
data = {client["Name"]:
626
{key: self.dbus_boolean_to_bool(client[key])
627
for key in self.all_keywords}
628
for client in clients}
629
return json.dumps(data, indent=4, separators=(',', ': '))
549
class Command(object):
550
"""Abstract class for commands"""
551
def run(self, clients, bus=None, mandos=None):
552
"""Normal commands should implement run_on_one_client(), but
553
commands which want to operate on all clients at the same time
554
can override this run() method instead."""
556
for clientpath, properties in clients.items():
557
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
558
dbus_busname, str(clientpath))
559
client = bus.get_object(dbus_busname, clientpath)
560
self.run_on_one_client(client, properties)
563
class IsEnabledCmd(Command):
564
def run(self, clients, bus=None, mandos=None):
565
client, properties = next(iter(clients.items()))
566
if self.is_enabled(client, properties):
569
def is_enabled(self, client, properties):
570
return properties["Enabled"]
573
class ApproveCmd(Command):
574
def run_on_one_client(self, client, properties):
575
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
576
client.__dbus_object_path__, client_dbus_interface)
577
client.Approve(dbus.Boolean(True),
578
dbus_interface=client_dbus_interface)
581
class DenyCmd(Command):
582
def run_on_one_client(self, client, properties):
583
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
584
client.__dbus_object_path__, client_dbus_interface)
585
client.Approve(dbus.Boolean(False),
586
dbus_interface=client_dbus_interface)
589
class RemoveCmd(Command):
590
def run_on_one_client(self, client, properties):
591
log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", dbus_busname,
592
server_dbus_path, server_dbus_interface,
593
str(client.__dbus_object_path__))
594
self.mandos.RemoveClient(client.__dbus_object_path__)
597
class OutputCmd(Command):
598
"""Abstract class for commands outputting client details"""
599
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
600
"Created", "Interval", "Host", "KeyID",
601
"Fingerprint", "CheckerRunning", "LastEnabled",
602
"ApprovalPending", "ApprovedByDefault",
603
"LastApprovalRequest", "ApprovalDelay",
604
"ApprovalDuration", "Checker", "ExtendedTimeout",
605
"Expires", "LastCheckerStatus")
607
def run(self, clients, bus=None, mandos=None):
608
print(self.output(clients.values()))
610
def output(self, clients):
611
raise NotImplementedError()
614
class DumpJSONCmd(OutputCmd):
615
def output(self, clients):
616
data = {client["Name"]:
617
{key: self.dbus_boolean_to_bool(client[key])
618
for key in self.all_keywords}
619
for client in clients}
620
return json.dumps(data, indent=4, separators=(',', ': '))
623
def dbus_boolean_to_bool(value):
624
if isinstance(value, dbus.Boolean):
629
class PrintTableCmd(OutputCmd):
630
def __init__(self, verbose=False):
631
self.verbose = verbose
633
def output(self, clients):
634
default_keywords = ("Name", "Enabled", "Timeout",
636
keywords = default_keywords
638
keywords = self.all_keywords
639
return str(self.TableOfClients(clients, keywords))
641
class TableOfClients(object):
644
"Enabled": "Enabled",
645
"Timeout": "Timeout",
646
"LastCheckedOK": "Last Successful Check",
647
"LastApprovalRequest": "Last Approval Request",
648
"Created": "Created",
649
"Interval": "Interval",
651
"Fingerprint": "Fingerprint",
653
"CheckerRunning": "Check Is Running",
654
"LastEnabled": "Last Enabled",
655
"ApprovalPending": "Approval Is Pending",
656
"ApprovedByDefault": "Approved By Default",
657
"ApprovalDelay": "Approval Delay",
658
"ApprovalDuration": "Approval Duration",
659
"Checker": "Checker",
660
"ExtendedTimeout": "Extended Timeout",
661
"Expires": "Expires",
662
"LastCheckerStatus": "Last Checker Status",
665
def __init__(self, clients, keywords):
666
self.clients = clients
667
self.keywords = keywords
670
return "\n".join(self.rows())
672
if sys.version_info.major == 2:
673
__unicode__ = __str__
675
return str(self).encode(locale.getpreferredencoding())
678
format_string = self.row_formatting_string()
679
rows = [self.header_line(format_string)]
680
rows.extend(self.client_line(client, format_string)
681
for client in self.clients)
684
def row_formatting_string(self):
685
"Format string used to format table rows"
686
return " ".join("{{{key}:{width}}}".format(
687
width=max(len(self.tableheaders[key]),
688
*(len(self.string_from_client(client, key))
689
for client in self.clients)),
691
for key in self.keywords)
693
def string_from_client(self, client, key):
694
return self.valuetostring(client[key], key)
697
def valuetostring(cls, value, keyword):
698
if isinstance(value, dbus.Boolean):
699
return "Yes" if value else "No"
700
if keyword in ("Timeout", "Interval", "ApprovalDelay",
701
"ApprovalDuration", "ExtendedTimeout"):
702
return cls.milliseconds_to_string(value)
705
def header_line(self, format_string):
706
return format_string.format(**self.tableheaders)
708
def client_line(self, client, format_string):
709
return format_string.format(
710
**{key: self.string_from_client(client, key)
711
for key in self.keywords})
632
def dbus_boolean_to_bool(value):
633
if isinstance(value, dbus.Boolean):
638
class PrintTable(Output):
639
def __init__(self, verbose=False):
640
self.verbose = verbose
642
def output(self, clients):
643
default_keywords = ("Name", "Enabled", "Timeout",
645
keywords = default_keywords
647
keywords = self.all_keywords
648
return str(self.TableOfClients(clients, keywords))
650
class TableOfClients(object):
653
"Enabled": "Enabled",
654
"Timeout": "Timeout",
655
"LastCheckedOK": "Last Successful Check",
656
"LastApprovalRequest": "Last Approval Request",
657
"Created": "Created",
658
"Interval": "Interval",
660
"Fingerprint": "Fingerprint",
662
"CheckerRunning": "Check Is Running",
663
"LastEnabled": "Last Enabled",
664
"ApprovalPending": "Approval Is Pending",
665
"ApprovedByDefault": "Approved By Default",
666
"ApprovalDelay": "Approval Delay",
667
"ApprovalDuration": "Approval Duration",
668
"Checker": "Checker",
669
"ExtendedTimeout": "Extended Timeout",
670
"Expires": "Expires",
671
"LastCheckerStatus": "Last Checker Status",
674
def __init__(self, clients, keywords):
675
self.clients = clients
676
self.keywords = keywords
679
return "\n".join(self.rows())
681
if sys.version_info.major == 2:
682
__unicode__ = __str__
684
return str(self).encode(
685
locale.getpreferredencoding())
688
format_string = self.row_formatting_string()
689
rows = [self.header_line(format_string)]
690
rows.extend(self.client_line(client, format_string)
691
for client in self.clients)
694
def row_formatting_string(self):
695
"Format string used to format table rows"
696
return " ".join("{{{key}:{width}}}".format(
697
width=max(len(self.tableheaders[key]),
698
*(len(self.string_from_client(client,
700
for client in self.clients)),
702
for key in self.keywords)
704
def string_from_client(self, client, key):
705
return self.valuetostring(client[key], key)
708
def valuetostring(cls, value, keyword):
709
if isinstance(value, dbus.Boolean):
710
return "Yes" if value else "No"
711
if keyword in ("Timeout", "Interval", "ApprovalDelay",
712
"ApprovalDuration", "ExtendedTimeout"):
713
return cls.milliseconds_to_string(value)
716
def header_line(self, format_string):
717
return format_string.format(**self.tableheaders)
719
def client_line(self, client, format_string):
720
return format_string.format(
721
**{key: self.string_from_client(client, key)
722
for key in self.keywords})
725
def milliseconds_to_string(ms):
726
td = datetime.timedelta(0, 0, 0, ms)
727
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
728
.format(days="{}T".format(td.days)
730
hours=td.seconds // 3600,
731
minutes=(td.seconds % 3600) // 60,
732
seconds=td.seconds % 60))
735
class Property(Base):
736
"Abstract class for Actions for setting one client property"
738
def run_on_one_client(self, client, properties):
739
"""Set the Client's D-Bus property"""
740
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
741
client.__dbus_object_path__,
742
dbus.PROPERTIES_IFACE, client_dbus_interface,
743
self.propname, self.value_to_set
744
if not isinstance(self.value_to_set,
746
else bool(self.value_to_set))
747
client.Set(client_dbus_interface, self.propname,
749
dbus_interface=dbus.PROPERTIES_IFACE)
753
raise NotImplementedError()
756
class Enable(Property):
758
value_to_set = dbus.Boolean(True)
761
class Disable(Property):
763
value_to_set = dbus.Boolean(False)
766
class BumpTimeout(Property):
767
propname = "LastCheckedOK"
771
class StartChecker(Property):
772
propname = "CheckerRunning"
773
value_to_set = dbus.Boolean(True)
776
class StopChecker(Property):
777
propname = "CheckerRunning"
778
value_to_set = dbus.Boolean(False)
781
class ApproveByDefault(Property):
782
propname = "ApprovedByDefault"
783
value_to_set = dbus.Boolean(True)
786
class DenyByDefault(Property):
787
propname = "ApprovedByDefault"
788
value_to_set = dbus.Boolean(False)
791
class PropertyValue(Property):
792
"Abstract class for Property recieving a value as argument"
793
def __init__(self, value):
794
self.value_to_set = value
797
class SetChecker(PropertyValue):
801
class SetHost(PropertyValue):
805
class SetSecret(PropertyValue):
809
def value_to_set(self):
813
def value_to_set(self, value):
814
"""When setting, read data from supplied file object"""
815
self._vts = value.read()
819
class MillisecondsPropertyValueArgument(PropertyValue):
820
"""Abstract class for PropertyValue taking a value argument as
714
def milliseconds_to_string(ms):
715
td = datetime.timedelta(0, 0, 0, ms)
716
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
717
.format(days="{}T".format(td.days)
719
hours=td.seconds // 3600,
720
minutes=(td.seconds % 3600) // 60,
721
seconds=td.seconds % 60))
724
class PropertyCmd(Command):
725
"""Abstract class for Actions for setting one client property"""
727
def run_on_one_client(self, client, properties):
728
"""Set the Client's D-Bus property"""
729
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
730
client.__dbus_object_path__,
731
dbus.PROPERTIES_IFACE, client_dbus_interface,
732
self.propname, self.value_to_set
733
if not isinstance(self.value_to_set, dbus.Boolean)
734
else bool(self.value_to_set))
735
client.Set(client_dbus_interface, self.propname,
737
dbus_interface=dbus.PROPERTIES_IFACE)
741
raise NotImplementedError()
744
class EnableCmd(PropertyCmd):
746
value_to_set = dbus.Boolean(True)
749
class DisableCmd(PropertyCmd):
751
value_to_set = dbus.Boolean(False)
754
class BumpTimeoutCmd(PropertyCmd):
755
propname = "LastCheckedOK"
759
class StartCheckerCmd(PropertyCmd):
760
propname = "CheckerRunning"
761
value_to_set = dbus.Boolean(True)
764
class StopCheckerCmd(PropertyCmd):
765
propname = "CheckerRunning"
766
value_to_set = dbus.Boolean(False)
769
class ApproveByDefaultCmd(PropertyCmd):
770
propname = "ApprovedByDefault"
771
value_to_set = dbus.Boolean(True)
774
class DenyByDefaultCmd(PropertyCmd):
775
propname = "ApprovedByDefault"
776
value_to_set = dbus.Boolean(False)
779
class PropertyValueCmd(PropertyCmd):
780
"""Abstract class for PropertyCmd recieving a value as argument"""
781
def __init__(self, value):
782
self.value_to_set = value
785
class SetCheckerCmd(PropertyValueCmd):
789
class SetHostCmd(PropertyValueCmd):
793
class SetSecretCmd(PropertyValueCmd):
797
def value_to_set(self):
801
def value_to_set(self, value):
802
"""When setting, read data from supplied file object"""
803
self._vts = value.read()
807
class MillisecondsPropertyValueArgumentCmd(PropertyValueCmd):
808
"""Abstract class for PropertyValueCmd taking a value argument as
821
809
a datetime.timedelta() but should store it as milliseconds."""
824
def value_to_set(self):
828
def value_to_set(self, value):
829
"When setting, convert value from a datetime.timedelta"
830
self._vts = int(round(value.total_seconds() * 1000))
833
class SetTimeout(MillisecondsPropertyValueArgument):
837
class SetExtendedTimeout(MillisecondsPropertyValueArgument):
838
propname = "ExtendedTimeout"
841
class SetInterval(MillisecondsPropertyValueArgument):
842
propname = "Interval"
845
class SetApprovalDelay(MillisecondsPropertyValueArgument):
846
propname = "ApprovalDelay"
849
class SetApprovalDuration(MillisecondsPropertyValueArgument):
850
propname = "ApprovalDuration"
812
def value_to_set(self):
816
def value_to_set(self, value):
817
"""When setting, convert value from a datetime.timedelta"""
818
self._vts = int(round(value.total_seconds() * 1000))
821
class SetTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
825
class SetExtendedTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
826
propname = "ExtendedTimeout"
829
class SetIntervalCmd(MillisecondsPropertyValueArgumentCmd):
830
propname = "Interval"
833
class SetApprovalDelayCmd(MillisecondsPropertyValueArgumentCmd):
834
propname = "ApprovalDelay"
837
class SetApprovalDurationCmd(MillisecondsPropertyValueArgumentCmd):
838
propname = "ApprovalDuration"
854
class TestCaseWithAssertLogs(unittest.TestCase):
855
"""unittest.TestCase.assertLogs only exists in Python 3.4"""
857
if not hasattr(unittest.TestCase, "assertLogs"):
858
@contextlib.contextmanager
859
def assertLogs(self, logger, level=logging.INFO):
860
capturing_handler = self.CapturingLevelHandler(level)
861
old_level = logger.level
862
old_propagate = logger.propagate
863
logger.addHandler(capturing_handler)
864
logger.setLevel(level)
865
logger.propagate = False
867
yield capturing_handler.watcher
869
logger.propagate = old_propagate
870
logger.removeHandler(capturing_handler)
871
logger.setLevel(old_level)
872
self.assertGreater(len(capturing_handler.watcher.records),
875
class CapturingLevelHandler(logging.Handler):
876
def __init__(self, level, *args, **kwargs):
877
logging.Handler.__init__(self, *args, **kwargs)
878
self.watcher = self.LoggingWatcher([], [])
879
def emit(self, record):
880
self.watcher.records.append(record)
881
self.watcher.output.append(self.format(record))
883
LoggingWatcher = collections.namedtuple("LoggingWatcher",
888
class Test_string_to_delta(TestCaseWithAssertLogs):
889
# Just test basic RFC 3339 functionality here, the doc string for
890
# rfc3339_duration_to_delta() already has more comprehensive
891
# tests, which is run by doctest.
893
def test_rfc3339_zero_seconds(self):
842
class Test_string_to_delta(unittest.TestCase):
843
def test_handles_basic_rfc3339(self):
894
844
self.assertEqual(string_to_delta("PT0S"),
895
845
datetime.timedelta())
897
def test_rfc3339_zero_days(self):
898
846
self.assertEqual(string_to_delta("P0D"),
899
847
datetime.timedelta())
901
def test_rfc3339_one_second(self):
902
848
self.assertEqual(string_to_delta("PT1S"),
903
849
datetime.timedelta(0, 1))
905
def test_rfc3339_two_hours(self):
906
850
self.assertEqual(string_to_delta("PT2H"),
907
851
datetime.timedelta(0, 7200))
909
853
def test_falls_back_to_pre_1_6_1_with_warning(self):
910
with self.assertLogs(log, logging.WARNING):
911
value = string_to_delta("2h")
854
# assertLogs only exists in Python 3.4
855
if hasattr(self, "assertLogs"):
856
with self.assertLogs(log, logging.WARNING):
857
value = string_to_delta("2h")
859
class WarningFilter(logging.Filter):
860
"""Don't show, but record the presence of, warnings"""
861
def filter(self, record):
862
is_warning = record.levelno >= logging.WARNING
863
self.found = is_warning or getattr(self, "found",
865
return not is_warning
866
warning_filter = WarningFilter()
867
log.addFilter(warning_filter)
869
value = string_to_delta("2h")
871
log.removeFilter(warning_filter)
872
self.assertTrue(getattr(warning_filter, "found", False))
912
873
self.assertEqual(value, datetime.timedelta(0, 7200))
1464
class TestBaseCommands(TestCommand):
1424
class TestIsEnabledCmd(TestCmd):
1425
def test_is_enabled(self):
1426
self.assertTrue(all(IsEnabledCmd().is_enabled(client,
1428
for client, properties
1429
in self.clients.items()))
1466
def test_IsEnabled_exits_successfully(self):
1431
def test_is_enabled_run_exits_successfully(self):
1467
1432
with self.assertRaises(SystemExit) as e:
1468
command.IsEnabled().run(self.one_client)
1433
IsEnabledCmd().run(self.one_client)
1469
1434
if e.exception.code is not None:
1470
1435
self.assertEqual(e.exception.code, 0)
1472
1437
self.assertIsNone(e.exception.code)
1474
def test_IsEnabled_exits_with_failure(self):
1439
def test_is_enabled_run_exits_with_failure(self):
1475
1440
self.client.attributes["Enabled"] = dbus.Boolean(False)
1476
1441
with self.assertRaises(SystemExit) as e:
1477
command.IsEnabled().run(self.one_client)
1442
IsEnabledCmd().run(self.one_client)
1478
1443
if isinstance(e.exception.code, int):
1479
1444
self.assertNotEqual(e.exception.code, 0)
1481
1446
self.assertIsNotNone(e.exception.code)
1483
def test_Approve(self):
1484
command.Approve().run(self.clients, self.bus)
1449
class TestApproveCmd(TestCmd):
1450
def test_approve(self):
1451
ApproveCmd().run(self.clients, self.bus)
1485
1452
for clientpath in self.clients:
1486
1453
client = self.bus.get_object(dbus_busname, clientpath)
1487
1454
self.assertIn(("Approve", (True, client_dbus_interface)),
1490
def test_Deny(self):
1491
command.Deny().run(self.clients, self.bus)
1458
class TestDenyCmd(TestCmd):
1459
def test_deny(self):
1460
DenyCmd().run(self.clients, self.bus)
1492
1461
for clientpath in self.clients:
1493
1462
client = self.bus.get_object(dbus_busname, clientpath)
1494
1463
self.assertIn(("Approve", (False, client_dbus_interface)),
1497
def test_Remove(self):
1467
class TestRemoveCmd(TestCmd):
1468
def test_remove(self):
1498
1469
class MockMandos(object):
1499
1470
def __init__(self):
1500
1471
self.calls = []
1501
1472
def RemoveClient(self, dbus_path):
1502
1473
self.calls.append(("RemoveClient", (dbus_path,)))
1503
1474
mandos = MockMandos()
1504
command.Remove().run(self.clients, self.bus, mandos)
1475
super(TestRemoveCmd, self).setUp()
1476
RemoveCmd().run(self.clients, self.bus, mandos)
1477
self.assertEqual(len(mandos.calls), 2)
1505
1478
for clientpath in self.clients:
1506
1479
self.assertIn(("RemoveClient", (clientpath,)),
1512
"KeyID": ("92ed150794387c03ce684574b1139a65"
1513
"94a34f895daaaf09fd8ea90a27cddb12"),
1514
"Host": "foo.example.org",
1517
"LastCheckedOK": "2019-02-03T00:00:00",
1518
"Created": "2019-01-02T00:00:00",
1520
"Fingerprint": ("778827225BA7DE539C5A"
1521
"7CFA59CFF7CDBD9A5920"),
1522
"CheckerRunning": False,
1523
"LastEnabled": "2019-01-03T00:00:00",
1524
"ApprovalPending": False,
1525
"ApprovedByDefault": True,
1526
"LastApprovalRequest": "",
1528
"ApprovalDuration": 1000,
1529
"Checker": "fping -q -- %(host)s",
1530
"ExtendedTimeout": 900000,
1531
"Expires": "2019-02-04T00:00:00",
1532
"LastCheckerStatus": 0,
1536
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1537
"6ab612cff5ad227247e46c2b020f441c"),
1538
"Host": "192.0.2.3",
1541
"LastCheckedOK": "2019-02-04T00:00:00",
1542
"Created": "2019-01-03T00:00:00",
1544
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1545
"F547B3A107558FCA3A27"),
1546
"CheckerRunning": True,
1547
"LastEnabled": "2019-01-04T00:00:00",
1548
"ApprovalPending": False,
1549
"ApprovedByDefault": False,
1550
"LastApprovalRequest": "2019-01-03T00:00:00",
1551
"ApprovalDelay": 30000,
1552
"ApprovalDuration": 93785000,
1554
"ExtendedTimeout": 900000,
1555
"Expires": "2019-02-05T00:00:00",
1556
"LastCheckerStatus": -2,
1560
def test_DumpJSON_normal(self):
1561
output = command.DumpJSON().output(self.clients.values())
1483
class TestDumpJSONCmd(TestCmd):
1485
self.expected_json = {
1488
"KeyID": ("92ed150794387c03ce684574b1139a65"
1489
"94a34f895daaaf09fd8ea90a27cddb12"),
1490
"Host": "foo.example.org",
1493
"LastCheckedOK": "2019-02-03T00:00:00",
1494
"Created": "2019-01-02T00:00:00",
1496
"Fingerprint": ("778827225BA7DE539C5A"
1497
"7CFA59CFF7CDBD9A5920"),
1498
"CheckerRunning": False,
1499
"LastEnabled": "2019-01-03T00:00:00",
1500
"ApprovalPending": False,
1501
"ApprovedByDefault": True,
1502
"LastApprovalRequest": "",
1504
"ApprovalDuration": 1000,
1505
"Checker": "fping -q -- %(host)s",
1506
"ExtendedTimeout": 900000,
1507
"Expires": "2019-02-04T00:00:00",
1508
"LastCheckerStatus": 0,
1512
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1513
"6ab612cff5ad227247e46c2b020f441c"),
1514
"Host": "192.0.2.3",
1517
"LastCheckedOK": "2019-02-04T00:00:00",
1518
"Created": "2019-01-03T00:00:00",
1520
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1521
"F547B3A107558FCA3A27"),
1522
"CheckerRunning": True,
1523
"LastEnabled": "2019-01-04T00:00:00",
1524
"ApprovalPending": False,
1525
"ApprovedByDefault": False,
1526
"LastApprovalRequest": "2019-01-03T00:00:00",
1527
"ApprovalDelay": 30000,
1528
"ApprovalDuration": 93785000,
1530
"ExtendedTimeout": 900000,
1531
"Expires": "2019-02-05T00:00:00",
1532
"LastCheckerStatus": -2,
1535
return super(TestDumpJSONCmd, self).setUp()
1537
def test_normal(self):
1538
output = DumpJSONCmd().output(self.clients.values())
1562
1539
json_data = json.loads(output)
1563
1540
self.assertDictEqual(json_data, self.expected_json)
1565
def test_DumpJSON_one_client(self):
1566
output = command.DumpJSON().output(self.one_client.values())
1542
def test_one_client(self):
1543
output = DumpJSONCmd().output(self.one_client.values())
1567
1544
json_data = json.loads(output)
1568
1545
expected_json = {"foo": self.expected_json["foo"]}
1569
1546
self.assertDictEqual(json_data, expected_json)
1571
def test_PrintTable_normal(self):
1572
output = command.PrintTable().output(self.clients.values())
1549
class TestPrintTableCmd(TestCmd):
1550
def test_normal(self):
1551
output = PrintTableCmd().output(self.clients.values())
1573
1552
expected_output = "\n".join((
1574
1553
"Name Enabled Timeout Last Successful Check",
1575
1554
"foo Yes 00:05:00 2019-02-03T00:00:00 ",