This repository has been archived by the owner on Feb 13, 2020. It is now read-only.
/
test_caldav.py
1271 lines (1023 loc) · 39.9 KB
/
test_caldav.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##
# Copyright (c) 2007-2012 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
import sys
import os
import stat
import grp
from os.path import dirname, abspath
from collections import namedtuple
from zope.interface import implements
from twisted.python.threadable import isInIOThread
from twisted.internet.reactor import callFromThread
from twisted.python.usage import Options, UsageError
from twisted.python.reflect import namedAny
from twisted.python import log
from twisted.python.procutils import which
from twisted.internet.interfaces import IProcessTransport, IReactorProcess
from twisted.internet.protocol import ServerFactory
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.internet.task import Clock
from twisted.internet import reactor
from twisted.application.service import IService, IServiceCollection
from twisted.application import internet
from twext.web2.dav import auth
from twext.web2.log import LogWrapperResource
from twext.python.filepath import CachingFilePath as FilePath
from twext.python.plistlib import writePlist #@UnresolvedImport
from twext.internet.tcp import MaxAcceptTCPServer, MaxAcceptSSLServer
from twistedcaldav.config import config, ConfigDict, ConfigurationError
from twistedcaldav.stdconfig import DEFAULT_CONFIG
from twistedcaldav.directory.aggregate import AggregateDirectoryService
from twistedcaldav.directory.calendar import DirectoryCalendarHomeProvisioningResource
from twistedcaldav.directory.principal import DirectoryPrincipalProvisioningResource
from twistedcaldav.test.util import TestCase, CapturingProcessProtocol
from calendarserver.tap.caldav import (
CalDAVOptions, CalDAVServiceMaker, CalDAVService, GroupOwnedUNIXServer,
DelayedStartupProcessMonitor, DelayedStartupLineLogger, TwistdSlaveProcess,
_CONTROL_SERVICE_NAME, getSystemIDs
)
from calendarserver.provision.root import RootResource
from StringIO import StringIO
# Points to top of source tree.
sourceRoot = dirname(dirname(dirname(dirname(abspath(__file__)))))
class NotAProcessTransport(object):
"""
Simple L{IProcessTransport} stub.
"""
implements(IProcessTransport)
def __init__(self, processProtocol, executable, args, env, path,
uid, gid, usePTY, childFDs):
"""
Hold on to all the attributes passed to spawnProcess.
"""
self.processProtocol = processProtocol
self.executable = executable
self.args = args
self.env = env
self.path = path
self.uid = uid
self.gid = gid
self.usePTY = usePTY
self.childFDs = childFDs
class InMemoryProcessSpawner(Clock):
"""
Stub out L{IReactorProcess} and L{IReactorClock} so that we can examine the
interaction of L{DelayedStartupProcessMonitor} and the reactor.
"""
implements(IReactorProcess)
def __init__(self):
"""
Create some storage to hold on to all the fake processes spawned.
"""
super(InMemoryProcessSpawner, self).__init__()
self.processTransports = []
self.waiting = []
def waitForOneProcess(self, amount=10.0):
"""
Wait for an L{IProcessTransport} to be created by advancing the clock.
If none are created in the specified amount of time, raise an
AssertionError.
"""
self.advance(amount)
if self.processTransports:
return self.processTransports.pop(0)
else:
raise AssertionError(
"There were no process transports available. Calls: " +
repr(self.calls)
)
def spawnProcess(self, processProtocol, executable, args=(), env={},
path=None, uid=None, gid=None, usePTY=0,
childFDs=None):
transport = NotAProcessTransport(
processProtocol, executable, args, env, path, uid, gid, usePTY,
childFDs
)
transport.startedAt = self.seconds()
self.processTransports.append(transport)
if self.waiting:
self.waiting.pop(0).callback(transport)
return transport
class TestCalDAVOptions (CalDAVOptions):
"""
A fake implementation of CalDAVOptions that provides
empty implementations of checkDirectory and checkFile.
"""
def checkDirectory(self, *args, **kwargs):
pass
def checkFile(self, *args, **kwargs):
pass
def loadConfiguration(self):
"""
Simple wrapper to avoid printing during test runs.
"""
oldout = sys.stdout
newout = sys.stdout = StringIO()
try:
return CalDAVOptions.loadConfiguration(self)
finally:
sys.stdout = oldout
log.msg(
"load configuration console output: %s" % newout.getvalue()
)
class CalDAVOptionsTest (TestCase):
"""
Test various parameters of our usage.Options subclass
"""
def setUp(self):
"""
Set up our options object, giving it a parent, and forcing the
global config to be loaded from defaults.
"""
TestCase.setUp(self)
self.config = TestCalDAVOptions()
self.config.parent = Options()
self.config.parent["uid"] = 0
self.config.parent["gid"] = 0
self.config.parent["nodaemon"] = False
def tearDown(self):
config.setDefaults(DEFAULT_CONFIG)
config.reload()
def test_overridesConfig(self):
"""
Test that values on the command line's -o and --option options
overide the config file
"""
myConfig = ConfigDict(DEFAULT_CONFIG)
myConfigFile = self.mktemp()
writePlist(myConfig, myConfigFile)
argv = [
"-f", myConfigFile,
"-o", "EnableSACLs",
"-o", "HTTPPort=80",
"-o", "BindAddresses=127.0.0.1,127.0.0.2,127.0.0.3",
"-o", "DocumentRoot=/dev/null",
"-o", "UserName=None",
"-o", "EnableProxyPrincipals=False",
]
self.config.parseOptions(argv)
self.assertEquals(config.EnableSACLs, True)
self.assertEquals(config.HTTPPort, 80)
self.assertEquals(config.BindAddresses,
["127.0.0.1", "127.0.0.2", "127.0.0.3"])
self.assertEquals(config.DocumentRoot, "/dev/null")
self.assertEquals(config.UserName, None)
self.assertEquals(config.EnableProxyPrincipals, False)
argv = ["-o", "Authentication=This Doesn't Matter"]
self.assertRaises(UsageError, self.config.parseOptions, argv)
def test_setsParent(self):
"""
Test that certain values are set on the parent (i.e. twistd's
Option's object)
"""
myConfig = ConfigDict(DEFAULT_CONFIG)
myConfigFile = self.mktemp()
writePlist(myConfig, myConfigFile)
argv = [
"-f", myConfigFile,
"-o", "PIDFile=/dev/null",
"-o", "umask=63",
# integers in plists & calendarserver command line are always
# decimal; umask is traditionally in octal.
]
self.config.parseOptions(argv)
self.assertEquals(self.config.parent["pidfile"], "/dev/null")
self.assertEquals(self.config.parent["umask"], 0077)
def test_specifyConfigFile(self):
"""
Test that specifying a config file from the command line
loads the global config with those values properly.
"""
myConfig = ConfigDict(DEFAULT_CONFIG)
myConfig.Authentication.Basic.Enabled = False
myConfig.HTTPPort = 80
myConfig.ServerHostName = "calendar.calenderserver.org"
myConfigFile = self.mktemp()
writePlist(myConfig, myConfigFile)
args = ["-f", myConfigFile]
self.config.parseOptions(args)
self.assertEquals(config.ServerHostName, myConfig["ServerHostName"])
self.assertEquals(config.HTTPPort, myConfig.HTTPPort)
self.assertEquals(
config.Authentication.Basic.Enabled,
myConfig.Authentication.Basic.Enabled
)
def test_specifyDictPath(self):
"""
Test that we can specify command line overrides to leafs using
a "/" seperated path. Such as "-o MultiProcess/ProcessCount=1"
"""
myConfig = ConfigDict(DEFAULT_CONFIG)
myConfigFile = self.mktemp()
writePlist(myConfig, myConfigFile)
argv = [
"-o", "MultiProcess/ProcessCount=102",
"-f", myConfigFile,
]
self.config.parseOptions(argv)
self.assertEquals(config.MultiProcess["ProcessCount"], 102)
class BaseServiceMakerTests(TestCase):
"""
Utility class for ServiceMaker tests.
"""
configOptions = None
def setUp(self):
TestCase.setUp(self)
self.options = TestCalDAVOptions()
self.options.parent = Options()
self.options.parent["gid"] = None
self.options.parent["uid"] = None
self.options.parent["nodaemon"] = None
self.config = ConfigDict(DEFAULT_CONFIG)
accountsFile = os.path.join(sourceRoot, "twistedcaldav/directory/test/accounts.xml")
resourcesFile = os.path.join(sourceRoot, "twistedcaldav/directory/test/resources.xml")
augmentsFile = os.path.join(sourceRoot, "twistedcaldav/directory/test/augments.xml")
pemFile = os.path.join(sourceRoot, "twistedcaldav/test/data/server.pem")
self.config["DirectoryService"] = {
"params": {"xmlFile": accountsFile},
"type": "twistedcaldav.directory.xmlfile.XMLDirectoryService"
}
self.config["ResourceService"] = {
"params": {"xmlFile": resourcesFile},
}
self.config["AugmentService"] = {
"params": {"xmlFiles": [augmentsFile]},
"type": "twistedcaldav.directory.augment.AugmentXMLDB"
}
self.config.UseDatabase = False
self.config.ServerRoot = self.mktemp()
self.config.ConfigRoot = "config"
self.config.ProcessType = "Single"
self.config.SSLPrivateKey = pemFile
self.config.SSLCertificate = pemFile
self.config.EnableSSL = True
self.config.Memcached.Pools.Default.ClientEnabled = False
self.config.Memcached.Pools.Default.ServerEnabled = False
self.config.DirectoryAddressBook.Enabled = False
self.config.SudoersFile = ""
if self.configOptions:
self.config.update(self.configOptions)
os.mkdir(self.config.ServerRoot)
os.mkdir(os.path.join(self.config.ServerRoot, self.config.DocumentRoot))
os.mkdir(os.path.join(self.config.ServerRoot, self.config.DataRoot))
os.mkdir(os.path.join(self.config.ServerRoot, self.config.ConfigRoot))
self.configFile = self.mktemp()
self.writeConfig()
def tearDown(self):
config.setDefaults(DEFAULT_CONFIG)
config.reset()
def writeConfig(self):
"""
Flush self.config out to self.configFile
"""
writePlist(self.config, self.configFile)
def makeService(self):
"""
Create a service by calling into CalDAVServiceMaker with
self.configFile
"""
self.options.parseOptions(["-f", self.configFile])
return CalDAVServiceMaker().makeService(self.options)
def getSite(self):
"""
Get the server.Site from the service by finding the HTTPFactory.
"""
service = self.makeService()
for listeningService in inServiceHierarchy(
service,
# FIXME: need a better predicate for 'is this really an HTTP
# factory' but this works for now.
# NOTE: in a database 'single' configuration, PostgresService
# will prevent the HTTP services from actually getting added to
# the hierarchy until the hierarchy has started.
# 'underlyingSite' assigned in caldav.py
lambda x: hasattr(x, 'underlyingSite')
):
return listeningService.underlyingSite
raise RuntimeError("No site found.")
def inServiceHierarchy(svc, predicate):
"""
Find services in the service collection which satisfy the given predicate.
"""
for subsvc in svc.services:
if IServiceCollection.providedBy(subsvc):
for value in inServiceHierarchy(subsvc, predicate):
yield value
if predicate(subsvc):
yield subsvc
def determineAppropriateGroupID():
"""
Determine a secondary group ID which can be used for testing.
"""
return os.getgroups()[1]
class SocketGroupOwnership(TestCase):
"""
Tests for L{GroupOwnedUNIXServer}.
"""
def test_groupOwnedUNIXSocket(self):
"""
When a L{GroupOwnedUNIXServer} is started, it will change the group of
its socket.
"""
alternateGroup = determineAppropriateGroupID()
socketName = self.mktemp()
gous = GroupOwnedUNIXServer(alternateGroup, socketName, ServerFactory(), mode=0660)
gous.privilegedStartService()
self.addCleanup(gous.stopService)
filestat = os.stat(socketName)
self.assertTrue(stat.S_ISSOCK(filestat.st_mode))
self.assertEquals(filestat.st_gid, alternateGroup)
self.assertEquals(filestat.st_uid, os.getuid())
class CalDAVServiceMakerTests(BaseServiceMakerTests):
"""
Test the service maker's behavior
"""
def test_makeServiceDispatcher(self):
"""
Test the default options of the dispatching makeService
"""
validServices = ["Slave", "Combined"]
self.config["HTTPPort"] = 0
for service in validServices:
self.config["ProcessType"] = service
self.writeConfig()
self.makeService()
self.config["ProcessType"] = "Unknown Service"
self.writeConfig()
self.assertRaises(UsageError, self.makeService)
def test_modesOnUNIXSockets(self):
"""
The logging and stats UNIX sockets that are bound as part of the
'Combined' service hierarchy should have a secure mode specified: only
the executing user should be able to open and send to them.
"""
self.config["HTTPPort"] = 0 # Don't conflict with the test above.
alternateGroup = determineAppropriateGroupID()
self.config.GroupName = grp.getgrgid(alternateGroup).gr_name
self.config["ProcessType"] = "Combined"
self.config.Stats.EnableUnixStatsSocket = True
self.writeConfig()
svc = self.makeService()
for serviceName in [_CONTROL_SERVICE_NAME]:
socketService = svc.getServiceNamed(serviceName)
self.assertIsInstance(socketService, GroupOwnedUNIXServer)
m = socketService.kwargs.get("mode", 0666)
self.assertEquals(
m, int("660", 8),
"Wrong mode on %s: %s" % (serviceName, oct(m))
)
self.assertEquals(socketService.gid, alternateGroup)
for serviceName in ["unix-stats"]:
socketService = svc.getServiceNamed(serviceName)
self.assertIsInstance(socketService, GroupOwnedUNIXServer)
m = socketService.kwargs.get("mode", 0666)
self.assertEquals(
m, int("660", 8),
"Wrong mode on %s: %s" % (serviceName, oct(m))
)
self.assertEquals(socketService.gid, alternateGroup)
def test_processMonitor(self):
"""
In the master, there should be exactly one
L{DelayedStartupProcessMonitor} in the service hierarchy so that it
will be started by startup.
"""
self.config["ProcessType"] = "Combined"
self.writeConfig()
self.assertEquals(
1,
len(
list(inServiceHierarchy(
self.makeService(),
lambda x: isinstance(x, DelayedStartupProcessMonitor)))
)
)
class SlaveServiceTest(BaseServiceMakerTests):
"""
Test various configurations of the Slave service
"""
configOptions = {
"HTTPPort": 8008,
"SSLPort": 8443,
}
def test_defaultService(self):
"""
Test the value of a Slave service in it's simplest
configuration.
"""
service = self.makeService()
self.failUnless(
IService(service),
"%s does not provide IService" % (service,)
)
self.failUnless(
service.services,
"No services configured"
)
self.failUnless(
isinstance(service, CalDAVService),
"%s is not a CalDAVService" % (service,)
)
def test_defaultListeners(self):
"""
Test that the Slave service has sub services with the
default TCP and SSL configuration
"""
# Note: the listeners are bundled within a MultiService named "ConnectionService"
service = self.makeService().getServiceNamed(CalDAVService.connectionServiceName)
expectedSubServices = dict((
(MaxAcceptTCPServer, self.config["HTTPPort"]),
(MaxAcceptSSLServer, self.config["SSLPort"]),
))
configuredSubServices = [(s.__class__, getattr(s, 'args', None))
for s in service.services]
checked = 0
for serviceClass, serviceArgs in configuredSubServices:
if serviceClass in expectedSubServices:
checked += 1
self.assertEquals(
serviceArgs[0],
dict(expectedSubServices)[serviceClass]
)
# TCP+SSL services for IPv4, TCP+SSL services for IPv6.
self.assertEquals(checked, 4)
def test_SSLKeyConfiguration(self):
"""
Test that the configuration of the SSLServer reflect the config file's
SSL Private Key and SSL Certificate
"""
service = self.makeService().getServiceNamed(CalDAVService.connectionServiceName)
sslService = None
for s in service.services:
if isinstance(s, internet.SSLServer):
sslService = s
break
self.failIf(sslService is None, "No SSL Service found")
context = sslService.args[2]
self.assertEquals(
self.config["SSLPrivateKey"],
context.privateKeyFileName
)
self.assertEquals(
self.config["SSLCertificate"],
context.certificateFileName,
)
def test_noSSL(self):
"""
Test the single service to make sure there is no SSL Service when SSL
is disabled
"""
del self.config["SSLPort"]
self.writeConfig()
service = self.makeService().getServiceNamed(CalDAVService.connectionServiceName)
self.assertNotIn(
internet.SSLServer,
[s.__class__ for s in service.services]
)
def test_noHTTP(self):
"""
Test the single service to make sure there is no TCPServer when
HTTPPort is not configured
"""
del self.config["HTTPPort"]
self.writeConfig()
service = self.makeService().getServiceNamed(CalDAVService.connectionServiceName)
self.assertNotIn(
internet.TCPServer,
[s.__class__ for s in service.services]
)
def test_singleBindAddresses(self):
"""
Test that the TCPServer and SSLServers are bound to the proper address
"""
self.config.BindAddresses = ["127.0.0.1"]
self.writeConfig()
service = self.makeService().getServiceNamed(CalDAVService.connectionServiceName)
for s in service.services:
if isinstance(s, (internet.TCPServer, internet.SSLServer)):
self.assertEquals(s.kwargs["interface"], "127.0.0.1")
def test_multipleBindAddresses(self):
"""
Test that the TCPServer and SSLServers are bound to the proper
addresses.
"""
self.config.BindAddresses = [
"127.0.0.1",
"10.0.0.2",
"172.53.13.123",
]
self.writeConfig()
service = self.makeService().getServiceNamed(CalDAVService.connectionServiceName)
tcpServers = []
sslServers = []
for s in service.services:
if isinstance(s, internet.TCPServer):
tcpServers.append(s)
elif isinstance(s, internet.SSLServer):
sslServers.append(s)
self.assertEquals(len(tcpServers), len(self.config.BindAddresses))
self.assertEquals(len(sslServers), len(self.config.BindAddresses))
for addr in self.config.BindAddresses:
for s in tcpServers:
if s.kwargs["interface"] == addr:
tcpServers.remove(s)
for s in sslServers:
if s.kwargs["interface"] == addr:
sslServers.remove(s)
self.assertEquals(len(tcpServers), 0)
self.assertEquals(len(sslServers), 0)
def test_listenBacklog(self):
"""
Test that the backlog arguments is set in TCPServer and SSLServers
"""
self.config.ListenBacklog = 1024
self.writeConfig()
service = self.makeService().getServiceNamed(CalDAVService.connectionServiceName)
for s in service.services:
if isinstance(s, (internet.TCPServer, internet.SSLServer)):
self.assertEquals(s.kwargs["backlog"], 1024)
class ServiceHTTPFactoryTests(BaseServiceMakerTests):
"""
Test the configuration of the initial resource hierarchy of the
single service
"""
configOptions = {"HTTPPort": 8008}
def test_AuthWrapperAllEnabled(self):
"""
Test the configuration of the authentication wrapper
when all schemes are enabled.
"""
self.config.Authentication.Digest.Enabled = True
self.config.Authentication.Kerberos.Enabled = True
self.config.Authentication.Kerberos.ServicePrincipal = "http/hello@bob"
self.config.Authentication.Basic.Enabled = True
self.writeConfig()
site = self.getSite()
self.failUnless(isinstance(
site.resource.resource,
auth.AuthenticationWrapper))
authWrapper = site.resource.resource
expectedSchemes = ["negotiate", "digest", "basic"]
for scheme in authWrapper.credentialFactories:
self.failUnless(scheme in expectedSchemes)
self.assertEquals(len(expectedSchemes),
len(authWrapper.credentialFactories))
def test_servicePrincipalNone(self):
"""
Test that the Kerberos principal look is attempted if the principal is empty.
"""
self.config.Authentication.Kerberos.ServicePrincipal = ""
self.config.Authentication.Kerberos.Enabled = True
self.writeConfig()
site = self.getSite()
authWrapper = site.resource.resource
self.assertFalse(authWrapper.credentialFactories.has_key("negotiate"))
def test_servicePrincipal(self):
"""
Test that the kerberos realm is the realm portion of a principal
in the form proto/host@realm
"""
self.config.Authentication.Kerberos.ServicePrincipal = "http/hello@bob"
self.config.Authentication.Kerberos.Enabled = True
self.writeConfig()
site = self.getSite()
authWrapper = site.resource.resource
ncf = authWrapper.credentialFactories["negotiate"]
self.assertEquals(ncf.service, "http@HELLO")
self.assertEquals(ncf.realm, "bob")
def test_AuthWrapperPartialEnabled(self):
"""
Test that the expected credential factories exist when
only a partial set of authentication schemes is
enabled.
"""
self.config.Authentication.Basic.Enabled = False
self.config.Authentication.Kerberos.Enabled = False
self.writeConfig()
site = self.getSite()
authWrapper = site.resource.resource
expectedSchemes = ["digest"]
for scheme in authWrapper.credentialFactories:
self.failUnless(scheme in expectedSchemes)
self.assertEquals(
len(expectedSchemes),
len(authWrapper.credentialFactories)
)
def test_LogWrapper(self):
"""
Test the configuration of the log wrapper
"""
site = self.getSite()
self.failUnless(isinstance(
site.resource,
LogWrapperResource))
def test_rootResource(self):
"""
Test the root resource
"""
site = self.getSite()
root = site.resource.resource.resource
self.failUnless(isinstance(root, RootResource))
def test_principalResource(self):
"""
Test the principal resource
"""
site = self.getSite()
root = site.resource.resource.resource
self.failUnless(isinstance(
root.getChild("principals"),
DirectoryPrincipalProvisioningResource
))
def test_calendarResource(self):
"""
Test the calendar resource
"""
site = self.getSite()
root = site.resource.resource.resource
self.failUnless(isinstance(
root.getChild("calendars"),
DirectoryCalendarHomeProvisioningResource
))
sudoersFile = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>users</key>
<array>
<dict>
<key>password</key>
<string>superuser</string>
<key>username</key>
<string>superuser</string>
</dict>
</array>
</dict>
</plist>
"""
class DirectoryServiceTest(BaseServiceMakerTests):
"""
Tests of the directory service
"""
configOptions = {"HTTPPort": 8008}
def test_sameDirectory(self):
"""
Test that the principal hierarchy has a reference
to the same DirectoryService as the calendar hierarchy
"""
site = self.getSite()
principals = site.resource.resource.resource.getChild("principals")
calendars = site.resource.resource.resource.getChild("calendars")
self.assertEquals(principals.directory, calendars.directory)
def test_aggregateDirectory(self):
"""
Assert that the base directory service is actually
an AggregateDirectoryService
"""
site = self.getSite()
principals = site.resource.resource.resource.getChild("principals")
directory = principals.directory
self.failUnless(isinstance(directory, AggregateDirectoryService))
def test_configuredDirectoryService(self):
"""
Test that the real directory service is the directory service
set in the configuration file.
"""
site = self.getSite()
principals = site.resource.resource.resource.getChild("principals")
directory = principals.directory
realDirectory = directory.serviceForRecordType("users")
configuredDirectory = namedAny(self.config.DirectoryService.type)
self.failUnless(isinstance(realDirectory, configuredDirectory))
class DummyProcessObject(object):
"""
Simple stub for Process Object API which just has an executable and some
arguments.
This is a stand in for L{TwistdSlaveProcess}.
"""
def __init__(self, scriptname, *args):
self.scriptname = scriptname
self.args = args
def getCommandLine(self):
"""
Simple command line.
"""
return [self.scriptname] + list(self.args)
def getFileDescriptors(self):
"""
Return a dummy, empty mapping of file descriptors.
"""
return {}
def getName(self):
"""
Get a dummy name.
"""
return 'Dummy'
class ScriptProcessObject(DummyProcessObject):
"""
Simple stub for the Process Object API that will run a test script.
"""
def getCommandLine(self):
"""
Get the command line to invoke this script.
"""
return [
sys.executable,
FilePath(__file__).sibling(self.scriptname).path
] + list(self.args)
class DelayedStartupProcessMonitorTests(TestCase):
"""
Test cases for L{DelayedStartupProcessMonitor}.
"""
def test_lineAfterLongLine(self):
"""
A "long" line of output from a monitored process (longer than
L{LineReceiver.MAX_LENGTH}) should be logged in chunks rather than all
at once, to avoid resource exhaustion.
"""
dspm = DelayedStartupProcessMonitor()
dspm.addProcessObject(ScriptProcessObject(
'longlines.py', str(DelayedStartupLineLogger.MAX_LENGTH)),
os.environ)
dspm.startService()
self.addCleanup(dspm.stopService)
logged = []
def tempObserver(event):
# Probably won't be a problem, but let's not have any intermittent
# test issues that stem from multi-threaded log messages randomly
# going off...
if not isInIOThread():
callFromThread(tempObserver, event)
return
if event.get('isError'):
d.errback()
m = event.get('message')[0]
if m.startswith('[Dummy] '):
logged.append(event)
if m == '[Dummy] z':
d.callback("done")
log.addObserver(tempObserver)
self.addCleanup(log.removeObserver, tempObserver)
d = Deferred()
def assertions(result):
self.assertEquals(["[Dummy] x",
"[Dummy] y",
"[Dummy] y", # final segment
"[Dummy] z"],
[''.join(evt['message'])[:len('[Dummy]') + 2]
for evt in logged])
self.assertEquals([" (truncated, continued)",
" (truncated, continued)",
"[Dummy] y",
"[Dummy] z"],
[''.join(evt['message'])[-len(" (truncated, continued)"):]
for evt in logged])
d.addCallback(assertions)
return d
def test_breakLineIntoSegments(self):
"""
Exercise the line-breaking logic with various key lengths
"""
testLogger = DelayedStartupLineLogger()
testLogger.MAX_LENGTH = 10
for input, output in [
("", []),
("a", ["a"]),