File: zcml.rst

package info (click to toggle)
zope.component 4.3.0-3
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 780 kB
  • sloc: python: 5,600; makefile: 130
file content (1182 lines) | stat: -rw-r--r-- 33,599 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
ZCML directives
===============

Components may be registered using the registration API exposed by
``zope.component`` (provideAdapter, provideUtility, etc.).  They may
also be registered using configuration files.  The common way to do
that is by using ZCML (Zope Configuration Markup Language), an XML
spelling of component registration.

In ZCML, each XML element is a *directive*.  There are different
top-level directives that let us register components.  We will
introduce them one by one here.

This helper will let us easily execute ZCML snippets:

.. doctest::

   >>> from cStringIO import StringIO
   >>> from zope.configuration.xmlconfig import xmlconfig
   >>> def runSnippet(snippet):
   ...     template = """\
   ...     <configure xmlns='http://namespaces.zope.org/zope'
   ...                i18n_domain="zope">
   ...     %s
   ...     </configure>"""
   ...     xmlconfig(StringIO(template % snippet))

adapter
-------

Adapters play a key role in the Component Architecture.  In ZCML, they
are registered with the <adapter /> directive.

.. doctest::

   >>> from zope.component.testfiles.adapter import A1, A2, A3, Handler
   >>> from zope.component.testfiles.adapter import I1, I2, I3, IS
   >>> from zope.component.testfiles.components import IContent, Content, Comp, comp

Before we register the first test adapter, we can verify that adapter
lookup doesn't work yet:

.. doctest::

   >>> from zope.component.tests.examples import clearZCML
   >>> clearZCML()
   >>> from zope.component.testfiles.components import IApp
   >>> IApp(Content(), None) is None
   True

Then we register the adapter and see that the lookup works:

.. doctest::

   >>> runSnippet('''
   ...   <adapter
   ...       factory="zope.component.testfiles.components.Comp"
   ...       provides="zope.component.testfiles.components.IApp"
   ...       for="zope.component.testfiles.components.IContent"
   ...       />''')

   >>> IApp(Content()).__class__
   <class 'zope.component.testfiles.components.Comp'>

It is also possible to give adapters names.  Then the combination of
required interface, provided interface and name makes the adapter
lookup unique.  The name is supplied using the ``name`` argument to
the <adapter /> directive:

.. doctest::

   >>> import zope.component
   >>> from zope.component.tests.examples import clearZCML
   >>> clearZCML()
   >>> zope.component.queryAdapter(Content(), IApp, 'test') is None
   True

   >>> runSnippet('''
   ...   <adapter
   ...       factory="zope.component.testfiles.components.Comp"
   ...       provides="zope.component.testfiles.components.IApp"
   ...       for="zope.component.testfiles.components.IContent"
   ...       name="test"
   ...       />''')

   >>> zope.component.getAdapter(Content(), IApp, 'test').__class__
   <class 'zope.component.testfiles.components.Comp'>

Adapter factories
~~~~~~~~~~~~~~~~~

It is possible to supply more than one adapter factory.  In this case,
during adapter lookup each factory will be called and the return value
will be given to the next factory.  The return value of the last
factory is returned as the result of the adapter lookup.  For examle:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       factory="zope.component.testfiles.adapter.A1
   ...                zope.component.testfiles.adapter.A2
   ...                zope.component.testfiles.adapter.A3"
   ...       provides="zope.component.testfiles.components.IApp"
   ...       for="zope.component.testfiles.components.IContent"
   ...       />''')

The resulting adapter is an A3, around an A2, around an A1, around the
adapted object:

.. doctest::

   >>> content = Content()
   >>> a3 = IApp(content)
   >>> a3.__class__ is A3
   True

   >>> a2 = a3.context[0]
   >>> a2.__class__ is A2
   True

   >>> a1 = a2.context[0]
   >>> a1.__class__ is A1
   True

   >>> a1.context[0] is content
   True

Of course, if no factory is provided at all, we will get an error:

.. doctest::

   >>> runSnippet('''
   ...   <adapter
   ...       factory=""
   ...       provides="zope.component.testfiles.components.IApp"
   ...       for="zope.component.testfiles.components.IContent"
   ...       />''')
   Traceback (most recent call last):
      ...
   ZopeXMLConfigurationError: File "<string>", line 4.2-8.8
         ValueError: No factory specified


Declaring ``for``, ``provides`` and ``name`` in Python
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The <adapter /> directive can figure out from the in-line Python declaration
(using ``zope.component.adapts()`` or ``zope.component.adapter()``,
``zope.interface.implements`` as well as ``zope.component.named``) what the
adapter should be registered for and what it provides:

.. doctest::

   >>> clearZCML()
   >>> IApp(Content(), None) is None
   True

   >>> runSnippet('''
   ...   <adapter factory="zope.component.testfiles.components.Comp" />''')

   >>> IApp(Content()).__class__
   <class 'zope.component.testfiles.components.Comp'>

Of course, if the adapter has no ``implements()`` declaration, ZCML
can't figure out what it provides:

.. doctest::

   >>> runSnippet('''
   ...   <adapter
   ...       factory="zope.component.testfiles.adapter.A4"
   ...       for="zope.component.testfiles.components.IContent"
   ...       />''')
   Traceback (most recent call last):
      ...
   ZopeXMLConfigurationError: File "<string>", line 4.2-7.8
         TypeError: Missing 'provides' attribute

On the other hand, if the factory implements more than one interface,
ZCML can't figure out what it should provide either:

.. doctest::

   >>> runSnippet('''
   ...   <adapter
   ...       factory="zope.component.testfiles.adapter.A5"
   ...       for="zope.component.testfiles.components.IContent"
   ...       />''')
   Traceback (most recent call last):
      ...
   ZopeXMLConfigurationError: File "<string>", line 4.2-7.8
         TypeError: Missing 'provides' attribute

Let's now register an adapter that has a name specified in Python:

   >>> runSnippet('''
   ...   <adapter factory="zope.component.testfiles.components.Comp4" />''')

   >>> zope.component.getAdapter(Content(), IApp, 'app').__class__
   <class 'zope.component.testfiles.components.Comp4'>

A not so common edge case is registering adapters directly for
classes, not for interfaces.  For example:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       for="zope.component.testfiles.components.Content"
   ...       provides="zope.component.testfiles.adapter.I1"
   ...       factory="zope.component.testfiles.adapter.A1"
   ...       />''')

   >>> content = Content()
   >>> a1 = zope.component.getAdapter(content, I1, '')
   >>> isinstance(a1, A1)
   True

This time, any object providing ``IContent`` won't work if it's not an
instance of the ``Content`` class:

.. doctest::

   >>> import zope.interface
   >>> class MyContent:
   ...     zope.interface.implements(IContent)
   >>> zope.component.getAdapter(MyContent(), I1, '')  # doctest: +ELLIPSIS
   Traceback (most recent call last):
      ...
   ComponentLookupError: ...

Multi-adapters
~~~~~~~~~~~~~~

Conventional adapters adapt one object to provide another interface.
Multi-adapters adapt several objects at once:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       for="zope.component.testfiles.components.IContent
   ...            zope.component.testfiles.adapter.I1
   ...            zope.component.testfiles.adapter.I2"
   ...       provides="zope.component.testfiles.adapter.I3"
   ...       factory="zope.component.testfiles.adapter.A3"
   ...       />''')

   >>> content = Content()
   >>> a1 = A1()
   >>> a2 = A2()
   >>> a3 = zope.component.queryMultiAdapter((content, a1, a2), I3)
   >>> a3.__class__ is A3
   True
   >>> a3.context == (content, a1, a2)
   True

You can even adapt an empty list of objects (we call this a
null-adapter):

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       for=""
   ...       provides="zope.component.testfiles.adapter.I3"
   ...       factory="zope.component.testfiles.adapter.A3"
   ...       />''')

   >>> a3 = zope.component.queryMultiAdapter((), I3)
   >>> a3.__class__ is A3
   True
   >>> a3.context == ()
   True

Even with multi-adapters, ZCML can figure out the ``for`` and
``provides`` parameters from the Python declarations:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter factory="zope.component.testfiles.adapter.A3" />''')

   >>> a3 = zope.component.queryMultiAdapter((content, a1, a2), I3)
   >>> a3.__class__ is A3
   True
   >>> a3.context == (content, a1, a2)
   True

Chained factories are not supported for multi-adapters, though:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       for="zope.component.testfiles.components.IContent
   ...            zope.component.testfiles.adapter.I1
   ...            zope.component.testfiles.adapter.I2"
   ...       provides="zope.component.testfiles.components.IApp"
   ...       factory="zope.component.testfiles.adapter.A1
   ...                zope.component.testfiles.adapter.A2"
   ...       />''')
   Traceback (most recent call last):
      ...
   ZopeXMLConfigurationError: File "<string>", line 4.2-11.8
         ValueError: Can't use multiple factories and multiple for

And neither for null-adapters:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       for=""
   ...       provides="zope.component.testfiles.components.IApp"
   ...       factory="zope.component.testfiles.adapter.A1
   ...                zope.component.testfiles.adapter.A2"
   ...       />''')
   Traceback (most recent call last):
      ...
   ZopeXMLConfigurationError: File "<string>", line 4.2-9.8
         ValueError: Can't use multiple factories and multiple for

Protected adapters
~~~~~~~~~~~~~~~~~~

Adapters can be protected with a permission.  First we have to define
a permission for which we'll have to register the <permission />
directive:

.. doctest::

   >>> clearZCML()
   >>> IApp(Content(), None) is None
   True

   >>> import zope.security
   >>> from zope.configuration.xmlconfig import XMLConfig
   >>> XMLConfig('meta.zcml', zope.security)()
   >>> runSnippet('''
   ...   <permission
   ...       id="y.x"
   ...       title="XY"
   ...       description="Allow XY."
   ...       />
   ...   <adapter
   ...       factory="zope.component.testfiles.components.Comp"
   ...       provides="zope.component.testfiles.components.IApp"
   ...       for="zope.component.testfiles.components.IContent"
   ...       permission="y.x"
   ...       />''')

We see that the adapter is a location proxy now so that the
appropriate permissions can be found from the context:

.. doctest::

   >>> IApp(Content()).__class__
   <class 'zope.component.testfiles.components.Comp'>
   >>> type(IApp(Content()))
   <class 'zope.location.location.LocationProxy'>

We can also go about it a different way.  Let's make a public adapter
and wrap the adapter in a security proxy.  That often happens when
an adapter is turned over to untrusted code:

.. doctest::

   >>> clearZCML()
   >>> IApp(Content(), None) is None
   True

   >>> runSnippet('''
   ...   <adapter
   ...       factory="zope.component.testfiles.components.Comp"
   ...       provides="zope.component.testfiles.components.IApp"
   ...       for="zope.component.testfiles.components.IContent"
   ...       permission="zope.Public"
   ...       />''')

   >>> from zope.security.checker import ProxyFactory
   >>> adapter = ProxyFactory(IApp(Content()))
   >>> from zope.security.proxy import getTestProxyItems
   >>> items = [item[0] for item in getTestProxyItems(adapter)]
   >>> items
   ['a', 'f']

   >>> from zope.security.proxy import removeSecurityProxy
   >>> removeSecurityProxy(adapter).__class__ is Comp
   True

Of course, this still works when we let the ZCML directive handler
figure out ``for`` and ``provides`` from the Python declarations:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       factory="zope.component.testfiles.components.Comp"
   ...       permission="zope.Public"
   ...       />''')

   >>> adapter = ProxyFactory(IApp(Content()))
   >>> [item[0] for item in getTestProxyItems(adapter)]
   ['a', 'f']
   >>> removeSecurityProxy(adapter).__class__ is Comp
   True

It also works with multi adapters:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       factory="zope.component.testfiles.adapter.A3"
   ...       provides="zope.component.testfiles.adapter.I3"
   ...       for="zope.component.testfiles.components.IContent
   ...            zope.component.testfiles.adapter.I1
   ...            zope.component.testfiles.adapter.I2"
   ...       permission="zope.Public"
   ...       />''')

   >>> content = Content()
   >>> a1 = A1()
   >>> a2 = A2()
   >>> a3 = ProxyFactory(zope.component.queryMultiAdapter((content, a1, a2), I3))
   >>> a3.__class__ == A3
   True
   >>> [item[0] for item in getTestProxyItems(a3)]
   ['f1', 'f2', 'f3']

It's probably not worth mentioning, but when we try to protect an
adapter with a permission that doesn't exist, we'll obviously get an
error:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       factory="zope.component.testfiles.components.Comp"
   ...       provides="zope.component.testfiles.components.IApp"
   ...       for="zope.component.testfiles.components.IContent"
   ...       permission="zope.UndefinedPermission"
   ...       />''')
   Traceback (most recent call last):
      ...
   ConfigurationExecutionError: exceptions.ValueError: ('Undefined permission id', 'zope.UndefinedPermission')
      in:
      File "<string>", line 4.2-9.8
      Could not read source.

Trusted adapters
~~~~~~~~~~~~~~~~

Trusted adapters are adapters that are trusted to do anything with the
objects they are given so that these objects are not security-proxied.
They are registered using the ``trusted`` argument to the <adapter />
directive:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       for="zope.component.testfiles.components.IContent"
   ...       provides="zope.component.testfiles.adapter.I1"
   ...       factory="zope.component.testfiles.adapter.A1"
   ...       trusted="yes"
   ...       />''')

With an unproxied object, it's business as usual:

.. doctest::

   >>> ob = Content()
   >>> type(I1(ob)) is A1
   True

With a security-proxied object, however, we get a security-proxied
adapter:

.. doctest::

   >>> p = ProxyFactory(ob)
   >>> a = I1(p)
   >>> type(a)
   <type 'zope.security._proxy._Proxy'>

While the adapter is security-proxied, the object it adapts is now
proxy-free.  The adapter has umlimited access to it:

.. doctest::

   >>> a = removeSecurityProxy(a)
   >>> type(a) is A1
   True
   >>> a.context[0] is ob
   True

We can also protect the trusted adapter with a permission:

.. doctest::

   >>> clearZCML()
   >>> XMLConfig('meta.zcml', zope.security)()
   >>> runSnippet('''
   ...   <permission
   ...       id="y.x"
   ...       title="XY"
   ...       description="Allow XY."
   ...       />
   ...   <adapter
   ...       for="zope.component.testfiles.components.IContent"
   ...       provides="zope.component.testfiles.adapter.I1"
   ...       factory="zope.component.testfiles.adapter.A1"
   ...       permission="y.x"
   ...       trusted="yes"
   ...       />''')

Again, with an unproxied object, it's business as usual:

.. doctest::

   >>> ob = Content()
   >>> type(I1(ob)) is A1
   True

With a security-proxied object, we again get a security-proxied
adapter:

.. doctest::

   >>> p = ProxyFactory(ob)
   >>> a = I1(p)
   >>> type(a)
   <type 'zope.security._proxy._Proxy'>

Since we protected the adapter with a permission, we now encounter a
location proxy behind the security proxy:

.. doctest::

   >>> a = removeSecurityProxy(a)
   >>> type(a)
   <class 'zope.location.location.LocationProxy'>
   >>> a.context[0] is ob
   True

There's one exception to all of this: When you use the public
permission (``zope.Public``), there will be no location proxy:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       for="zope.component.testfiles.components.IContent"
   ...       provides="zope.component.testfiles.adapter.I1"
   ...       factory="zope.component.testfiles.adapter.A1"
   ...       permission="zope.Public"
   ...       trusted="yes"
   ...       />''')

   >>> ob = Content()
   >>> p = ProxyFactory(ob)
   >>> a = I1(p)
   >>> type(a)
   <type 'zope.security._proxy._Proxy'>

   >>> a = removeSecurityProxy(a)
   >>> type(a) is A1
   True

We can also explicitply pass the ``locate`` argument to make sure we
get location proxies:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <adapter
   ...       for="zope.component.testfiles.components.IContent"
   ...       provides="zope.component.testfiles.adapter.I1"
   ...       factory="zope.component.testfiles.adapter.A1"
   ...       trusted="yes"
   ...       locate="yes"
   ...       />''')

   >>> ob = Content()
   >>> p = ProxyFactory(ob)
   >>> a = I1(p)
   >>> type(a)
   <type 'zope.security._proxy._Proxy'>

   >>> a = removeSecurityProxy(a)
   >>> type(a)
   <class 'zope.location.location.LocationProxy'>


subscriber
----------

With the <subscriber /> directive you can register subscription
adapters or event subscribers with the adapter registry.  Consider
this very typical example of a <subscriber /> directive:
 
.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <subscriber
   ...       provides="zope.component.testfiles.adapter.IS"
   ...       factory="zope.component.testfiles.adapter.A3"
   ...       for="zope.component.testfiles.components.IContent
   ...            zope.component.testfiles.adapter.I1"
   ...       />''')

   >>> content = Content()
   >>> a1 = A1()

   >>> subscribers = zope.component.subscribers((content, a1), IS)
   >>> a3 = subscribers[0]
   >>> a3.__class__ is A3
   True
   >>> a3.context == (content, a1)
   True

Note how ZCML provides some additional information when registering
components, such as the ZCML filename and line numbers:

.. doctest::

   >>> sm = zope.component.getSiteManager()
   >>> doc = [reg.info for reg in sm.registeredSubscriptionAdapters()
   ...        if reg.provided is IS][0]
   >>> print doc
   File "<string>", line 4.2-9.8
     Could not read source.

The "fun" behind subscription adapters/subscribers is that when
several ones are declared for the same for/provides, they are all
found.  With regular adapters, the most specific one (and in doubt the
one registered last) wins.  Consider these two subscribers:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <subscriber
   ...       provides="zope.component.testfiles.adapter.IS"
   ...       factory="zope.component.testfiles.adapter.A3"
   ...       for="zope.component.testfiles.components.IContent
   ...            zope.component.testfiles.adapter.I1"
   ...       />
   ...   <subscriber
   ...       provides="zope.component.testfiles.adapter.IS"
   ...       factory="zope.component.testfiles.adapter.A2"
   ...       for="zope.component.testfiles.components.IContent
   ...            zope.component.testfiles.adapter.I1"
   ...       />''')

   >>> subscribers = zope.component.subscribers((content, a1), IS)
   >>> len(subscribers)
   2
   >>> sorted([a.__class__.__name__ for a in subscribers])
   ['A2', 'A3']

Declaring ``for`` and ``provides`` in Python
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Like the <adapter /> directive, the <subscriber /> directive can
figure out from the in-line Python declaration (using
``zope.component.adapts()`` or ``zope.component.adapter()``) what the
subscriber should be registered for:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <subscriber
   ...       provides="zope.component.testfiles.adapter.IS"
   ...       factory="zope.component.testfiles.adapter.A3"
   ...       />''')

   >>> content = Content()
   >>> a2 = A2()
   >>> subscribers = zope.component.subscribers((content, a1, a2), IS)

   >>> a3 = subscribers[0]
   >>> a3.__class__ is A3
   True
   >>> a3.context == (content, a1, a2)
   True

In the same way the directive can figure out what a subscriber
provides:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <subscriber handler="zope.component.testfiles.adapter.A3" />''')

   >>> sm = zope.component.getSiteManager()
   >>> a3 = sm.adapters.subscriptions((IContent, I1, I2), None)[0]
   >>> a3 is A3
   True

A not so common edge case is declaring subscribers directly for
classes, not for interfaces.  For example:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <subscriber
   ...       for="zope.component.testfiles.components.Content"
   ...       provides="zope.component.testfiles.adapter.I1"
   ...       factory="zope.component.testfiles.adapter.A1"
   ...       />''')

   >>> subs = list(zope.component.subscribers((Content(),), I1))
   >>> isinstance(subs[0], A1)
   True

This time, any object providing ``IContent`` won't work if it's not an
instance of the ``Content`` class:

.. doctest::

   >>> list(zope.component.subscribers((MyContent(),), I1))
   []

Protected subscribers
~~~~~~~~~~~~~~~~~~~~~

Subscribers can also be protected with a permission.  First we have to
define a permission for which we'll have to register the <permission />
directive:

.. doctest::

   >>> clearZCML()
   >>> XMLConfig('meta.zcml', zope.security)()
   >>> runSnippet('''
   ...   <permission
   ...       id="y.x"
   ...       title="XY"
   ...       description="Allow XY."
   ...       />
   ...   <subscriber
   ...       provides="zope.component.testfiles.adapter.IS"
   ...       factory="zope.component.testfiles.adapter.A3"
   ...       for="zope.component.testfiles.components.IContent
   ...            zope.component.testfiles.adapter.I1"
   ...       permission="y.x"
   ...       />''')

   >>> subscribers = zope.component.subscribers((content, a1), IS)
   >>> a3 = subscribers[0]
   >>> a3.__class__ is A3
   True
   >>> type(a3)
   <class 'zope.location.location.LocationProxy'>
   >>> a3.context == (content, a1)
   True

Trusted subscribers
~~~~~~~~~~~~~~~~~~~

Like trusted adapters, trusted subscribers are subscribers that are
trusted to do anything with the objects they are given so that these
objects are not security-proxied.  In analogy to the <adapter />
directive, they are registered using the ``trusted`` argument to the
<subscriber /> directive:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <subscriber
   ...       provides="zope.component.testfiles.adapter.IS"
   ...       factory="zope.component.testfiles.adapter.A3"
   ...       for="zope.component.testfiles.components.IContent
   ...            zope.component.testfiles.adapter.I1"
   ...       trusted="yes"
   ...       />''')

With an unproxied object, it's business as usual:

.. doctest::

   >>> subscribers = zope.component.subscribers((content, a1), IS)
   >>> a3 = subscribers[0]
   >>> a3.__class__ is A3
   True
   >>> a3.context == (content, a1)
   True
   >>> type(a3) is A3
   True

Now with a proxied object.  We will see that the subscriber has
unproxied access to it, but the subscriber itself is proxied:

.. doctest::

   >>> p = ProxyFactory(content)
   >>> a3 = zope.component.subscribers((p, a1), IS)[0]
   >>> type(a3)
   <type 'zope.security._proxy._Proxy'>

There's no location proxy behind the security proxy:

.. doctest::

   >>> removeSecurityProxy(a3).context[0] is content
   True
   >>> type(removeSecurityProxy(a3)) is A3
   True

If you want the trusted subscriber to be located, you'll also have to
use the ``locate`` argument:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <subscriber
   ...       provides="zope.component.testfiles.adapter.IS"
   ...       factory="zope.component.testfiles.adapter.A3"
   ...       for="zope.component.testfiles.components.IContent
   ...            zope.component.testfiles.adapter.I1"
   ...       trusted="yes"
   ...       locate="yes"
   ...       />''')

Again, it's business as usual with an unproxied object:

.. doctest::

   >>> subscribers = zope.component.subscribers((content, a1), IS)
   >>> a3 = subscribers[0]
   >>> a3.__class__ is A3
   True
   >>> a3.context == (content, a1)
   True
   >>> type(a3) is A3
   True

With a proxied object, we again get a security-proxied subscriber:

.. doctest::

   >>> p = ProxyFactory(content)
   >>> a3 = zope.component.subscribers((p, a1), IS)[0]

   >>> type(a3)
   <type 'zope.security._proxy._Proxy'>

   >>> removeSecurityProxy(a3).context[0] is content
   True

However, thanks to the ``locate`` argument, we now have a location
proxy behind the security proxy:

.. doctest::

   >>> type(removeSecurityProxy(a3))
   <class 'zope.location.location.LocationProxy'>

Event subscriber (handlers)
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sometimes, subscribers don't need to be adapters that actually provide
anything.  It's enough that a callable is called for a certain event.

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <subscriber
   ...       for="zope.component.testfiles.components.IContent
   ...            zope.component.testfiles.adapter.I1"
   ...       handler="zope.component.testfiles.adapter.Handler"
   ...       />''')

In this case, simply getting the subscribers is enough to invoke them:

.. doctest::

   >>> list(zope.component.subscribers((content, a1), None))
   []
   >>> content.args == ((a1,),)
   True


utility
-------

Apart from adapters (and subscription adapters), the Component
Architecture knows a second kind of component: utilities.  They are
registered using the <utility /> directive.

Before we register the first test utility, we can verify that utility
lookup doesn't work yet:

.. doctest::

   >>> clearZCML()
   >>> zope.component.queryUtility(IApp) is None
   True

Then we register the utility:

.. doctest::

   >>> runSnippet('''
   ...   <utility
   ...       component="zope.component.testfiles.components.comp"
   ...       provides="zope.component.testfiles.components.IApp"
   ...       />''')
   >>> zope.component.getUtility(IApp) is comp
   True

Like adapters, utilities can also have names.  There can be more than
one utility registered for a certain interface, as long as they each
have a different name.

First, we make sure that there's no utility yet:

.. doctest::

   >>> clearZCML()
   >>> zope.component.queryUtility(IApp, 'test') is None
   True

Then we register it:

.. doctest::

   >>> runSnippet('''
   ...   <utility
   ...       component="zope.component.testfiles.components.comp"
   ...       provides="zope.component.testfiles.components.IApp"
   ...       name="test"
   ...       />''')
   >>> zope.component.getUtility(IApp, 'test') is comp
   True

Utilities can also be registered from a factory.  In this case, the
ZCML handler calls the factory (without any arguments) and registers
the returned value as a utility.  Typically, you'd pass a class for
the factory:

.. doctest::

   >>> clearZCML()
   >>> zope.component.queryUtility(IApp) is None
   True

   >>> runSnippet('''
   ...   <utility
   ...       factory="zope.component.testfiles.components.Comp"
   ...       provides="zope.component.testfiles.components.IApp"
   ...       />''')
   >>> zope.component.getUtility(IApp).__class__ is Comp
   True

Declaring ``provides`` in Python
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Like other directives, <utility /> can also figure out which interface
a utility provides from the Python declaration:

.. doctest::

   >>> clearZCML()
   >>> zope.component.queryUtility(IApp) is None
   True

   >>> runSnippet('''
   ...   <utility component="zope.component.testfiles.components.comp" />''')
   >>> zope.component.getUtility(IApp) is comp
   True

It won't work if the component that is to be registered doesn't
provide anything:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <utility component="zope.component.testfiles.adapter.a4" />''')
   Traceback (most recent call last):
      ...
   ZopeXMLConfigurationError: File "<string>", line 4.2-4.61
         TypeError: Missing 'provides' attribute

Or if more than one interface is provided (then the ZCML directive
handler doesn't know under which the utility should be registered):

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <utility component="zope.component.testfiles.adapter.a5" />''')
   Traceback (most recent call last):
      ...
   ZopeXMLConfigurationError: File "<string>", line 4.2-4.61
         TypeError: Missing 'provides' attribute

We can repeat the same drill for utility factories:

.. doctest::

   >>> clearZCML()
   >>> runSnippet('''
   ...   <utility factory="zope.component.testfiles.components.Comp" />''')
   >>> zope.component.getUtility(IApp).__class__ is Comp
   True

   >>> runSnippet('''
   ...   <utility factory="zope.component.testfiles.adapter.A4" />''')
   Traceback (most recent call last):
      ...
   ZopeXMLConfigurationError: File "<string>", line 4.2-4.59
         TypeError: Missing 'provides' attribute

   >>> clearZCML()
   >>> runSnippet('''
   ...   <utility factory="zope.component.testfiles.adapter.A5" />''')
   Traceback (most recent call last):
      ...
   ZopeXMLConfigurationError: File "<string>", line 4.2-4.59
         TypeError: Missing 'provides' attribute

Declaring ``name`` in Python
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Let's now register a utility that has a name specified in Python:

   >>> runSnippet('''
   ...   <utility component="zope.component.testfiles.components.comp4" />''')

   >>> from zope.component.testfiles.components import comp4
   >>> zope.component.getUtility(IApp, name='app') is comp4
   True

   >>> runSnippet('''
   ...   <utility factory="zope.component.testfiles.components.Comp4" />''')

   >>> zope.component.getUtility(IApp, name='app') is comp4
   False
   >>> zope.component.getUtility(IApp, name='app').__class__
   <class 'zope.component.testfiles.components.Comp4'>


Protected utilities
~~~~~~~~~~~~~~~~~~~

TODO::

    def testProtectedUtility(self):
        """Test that we can protect a utility.

        Also:
        Check that multiple configurations for the same utility and
        don't interfere.
        """
        self.assertEqual(zope.component.queryUtility(IV), None)
        xmlconfig(StringIO(template % (
            '''
            <permission id="tell.everyone" title="Yay" />
            <utility
              component="zope.component.testfiles.components.comp"
              provides="zope.component.testfiles.components.IApp"
              permission="tell.everyone"
              />
            <permission id="top.secret" title="shhhh" />
            <utility
              component="zope.component.testfiles.components.comp"
              provides="zope.component.testfiles.components.IAppb"
              permission="top.secret"
              />
            '''
            )))

        utility = ProxyFactory(zope.component.getUtility(IApp))
        items = getTestProxyItems(utility)
        self.assertEqual(items, [('a', 'tell.everyone'),
                                 ('f', 'tell.everyone')
                                 ])
        self.assertEqual(removeSecurityProxy(utility), comp)

    def testUtilityUndefinedPermission(self):
        config = StringIO(template % (
             '''
             <utility
              component="zope.component.testfiles.components.comp"
              provides="zope.component.testfiles.components.IApp"
              permission="zope.UndefinedPermission"
              />
            '''
            ))
        self.assertRaises(ValueError, xmlconfig, config,
                          testing=1)

interface
---------

The <interface /> directive lets us register an interface.  Interfaces
are registered as named utilities.  We therefore needn't go though all
the lookup details again, it is sufficient to see whether the
directive handler emits the right actions.

First we provide a stub configuration context:

.. doctest::

   >>> import re, pprint
   >>> atre = re.compile(' at [0-9a-fA-Fx]+')
   >>> class Context(object):
   ...    actions = ()
   ...    def action(self, discriminator, callable, args):
   ...        self.actions += ((discriminator, callable, args), )
   ...    def __repr__(self):
   ...        stream = StringIO()
   ...        pprinter = pprint.PrettyPrinter(stream=stream, width=60)
   ...        pprinter.pprint(self.actions)
   ...        r = stream.getvalue()
   ...        return (''.join(atre.split(r))).strip()
   >>> context = Context()

Then we provide a test interface that we'd like to register:

.. doctest::

   >>> from zope.interface import Interface
   >>> class I(Interface):
   ...     pass

It doesn't yet provide ``ITestType``:

.. doctest::

   >>> from zope.component.tests.examples import ITestType
   >>> ITestType.providedBy(I)
   False

However, after calling the directive handler...

.. doctest::

   >>> from zope.component.zcml import interface
   >>> interface(context, I, ITestType)
   >>> context
   ((None,
     <function provideInterface>,
     ('',
      <InterfaceClass __builtin__.I>,
      <InterfaceClass zope.component.tests.examples.ITestType>)),)

...it does provide ``ITestType``:

.. doctest::

   >>> from zope.interface.interfaces import IInterface
   >>> ITestType.extends(IInterface)
   True
   >>> IInterface.providedBy(I)
   True