File: test_util.py

package info (click to toggle)
python-pyramid 1.10.2+dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 4,052 kB
  • sloc: python: 42,982; makefile: 41
file content (1242 lines) | stat: -rw-r--r-- 37,798 bytes parent folder | download
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
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
import unittest
from pyramid.compat import PY2, text_, bytes_


class Test_InstancePropertyHelper(unittest.TestCase):
    def _makeOne(self):
        cls = self._getTargetClass()
        return cls()

    def _getTargetClass(self):
        from pyramid.util import InstancePropertyHelper

        return InstancePropertyHelper

    def test_callable(self):
        def worker(obj):
            return obj.bar

        foo = Dummy()
        helper = self._getTargetClass()
        helper.set_property(foo, worker)
        foo.bar = 1
        self.assertEqual(1, foo.worker)
        foo.bar = 2
        self.assertEqual(2, foo.worker)

    def test_callable_with_name(self):
        def worker(obj):
            return obj.bar

        foo = Dummy()
        helper = self._getTargetClass()
        helper.set_property(foo, worker, name='x')
        foo.bar = 1
        self.assertEqual(1, foo.x)
        foo.bar = 2
        self.assertEqual(2, foo.x)

    def test_callable_with_reify(self):
        def worker(obj):
            return obj.bar

        foo = Dummy()
        helper = self._getTargetClass()
        helper.set_property(foo, worker, reify=True)
        foo.bar = 1
        self.assertEqual(1, foo.worker)
        foo.bar = 2
        self.assertEqual(1, foo.worker)

    def test_callable_with_name_reify(self):
        def worker(obj):
            return obj.bar

        foo = Dummy()
        helper = self._getTargetClass()
        helper.set_property(foo, worker, name='x')
        helper.set_property(foo, worker, name='y', reify=True)
        foo.bar = 1
        self.assertEqual(1, foo.y)
        self.assertEqual(1, foo.x)
        foo.bar = 2
        self.assertEqual(2, foo.x)
        self.assertEqual(1, foo.y)

    def test_property_without_name(self):
        def worker(obj):  # pragma: no cover
            pass

        foo = Dummy()
        helper = self._getTargetClass()
        self.assertRaises(
            ValueError, helper.set_property, foo, property(worker)
        )

    def test_property_with_name(self):
        def worker(obj):
            return obj.bar

        foo = Dummy()
        helper = self._getTargetClass()
        helper.set_property(foo, property(worker), name='x')
        foo.bar = 1
        self.assertEqual(1, foo.x)
        foo.bar = 2
        self.assertEqual(2, foo.x)

    def test_property_with_reify(self):
        def worker(obj):  # pragma: no cover
            pass

        foo = Dummy()
        helper = self._getTargetClass()
        self.assertRaises(
            ValueError,
            helper.set_property,
            foo,
            property(worker),
            name='x',
            reify=True,
        )

    def test_override_property(self):
        def worker(obj):  # pragma: no cover
            pass

        foo = Dummy()
        helper = self._getTargetClass()
        helper.set_property(foo, worker, name='x')

        def doit():
            foo.x = 1

        self.assertRaises(AttributeError, doit)

    def test_override_reify(self):
        def worker(obj):  # pragma: no cover
            pass

        foo = Dummy()
        helper = self._getTargetClass()
        helper.set_property(foo, worker, name='x', reify=True)
        foo.x = 1
        self.assertEqual(1, foo.x)
        foo.x = 2
        self.assertEqual(2, foo.x)

    def test_reset_property(self):
        foo = Dummy()
        helper = self._getTargetClass()
        helper.set_property(foo, lambda _: 1, name='x')
        self.assertEqual(1, foo.x)
        helper.set_property(foo, lambda _: 2, name='x')
        self.assertEqual(2, foo.x)

    def test_reset_reify(self):
        """ This is questionable behavior, but may as well get notified
        if it changes."""
        foo = Dummy()
        helper = self._getTargetClass()
        helper.set_property(foo, lambda _: 1, name='x', reify=True)
        self.assertEqual(1, foo.x)
        helper.set_property(foo, lambda _: 2, name='x', reify=True)
        self.assertEqual(1, foo.x)

    def test_make_property(self):
        from pyramid.decorator import reify

        helper = self._getTargetClass()
        name, fn = helper.make_property(lambda x: 1, name='x', reify=True)
        self.assertEqual(name, 'x')
        self.assertTrue(isinstance(fn, reify))

    def test_apply_properties_with_iterable(self):
        foo = Dummy()
        helper = self._getTargetClass()
        x = helper.make_property(lambda _: 1, name='x', reify=True)
        y = helper.make_property(lambda _: 2, name='y')
        helper.apply_properties(foo, [x, y])
        self.assertEqual(1, foo.x)
        self.assertEqual(2, foo.y)

    def test_apply_properties_with_dict(self):
        foo = Dummy()
        helper = self._getTargetClass()
        x_name, x_fn = helper.make_property(lambda _: 1, name='x', reify=True)
        y_name, y_fn = helper.make_property(lambda _: 2, name='y')
        helper.apply_properties(foo, {x_name: x_fn, y_name: y_fn})
        self.assertEqual(1, foo.x)
        self.assertEqual(2, foo.y)

    def test_make_property_unicode(self):
        from pyramid.compat import text_
        from pyramid.exceptions import ConfigurationError

        cls = self._getTargetClass()
        if PY2:
            name = text_(b'La Pe\xc3\xb1a', 'utf-8')
        else:
            name = b'La Pe\xc3\xb1a'

        def make_bad_name():
            cls.make_property(lambda x: 1, name=name, reify=True)

        self.assertRaises(ConfigurationError, make_bad_name)

    def test_add_property(self):
        helper = self._makeOne()
        helper.add_property(lambda obj: obj.bar, name='x', reify=True)
        helper.add_property(lambda obj: obj.bar, name='y')
        self.assertEqual(len(helper.properties), 2)
        foo = Dummy()
        helper.apply(foo)
        foo.bar = 1
        self.assertEqual(foo.x, 1)
        self.assertEqual(foo.y, 1)
        foo.bar = 2
        self.assertEqual(foo.x, 1)
        self.assertEqual(foo.y, 2)

    def test_apply_multiple_times(self):
        helper = self._makeOne()
        helper.add_property(lambda obj: 1, name='x')
        foo, bar = Dummy(), Dummy()
        helper.apply(foo)
        self.assertEqual(foo.x, 1)
        helper.add_property(lambda obj: 2, name='x')
        helper.apply(bar)
        self.assertEqual(foo.x, 1)
        self.assertEqual(bar.x, 2)


class Test_InstancePropertyMixin(unittest.TestCase):
    def _makeOne(self):
        cls = self._getTargetClass()

        class Foo(cls):
            pass

        return Foo()

    def _getTargetClass(self):
        from pyramid.util import InstancePropertyMixin

        return InstancePropertyMixin

    def test_callable(self):
        def worker(obj):
            return obj.bar

        foo = self._makeOne()
        foo.set_property(worker)
        foo.bar = 1
        self.assertEqual(1, foo.worker)
        foo.bar = 2
        self.assertEqual(2, foo.worker)

    def test_callable_with_name(self):
        def worker(obj):
            return obj.bar

        foo = self._makeOne()
        foo.set_property(worker, name='x')
        foo.bar = 1
        self.assertEqual(1, foo.x)
        foo.bar = 2
        self.assertEqual(2, foo.x)

    def test_callable_with_reify(self):
        def worker(obj):
            return obj.bar

        foo = self._makeOne()
        foo.set_property(worker, reify=True)
        foo.bar = 1
        self.assertEqual(1, foo.worker)
        foo.bar = 2
        self.assertEqual(1, foo.worker)

    def test_callable_with_name_reify(self):
        def worker(obj):
            return obj.bar

        foo = self._makeOne()
        foo.set_property(worker, name='x')
        foo.set_property(worker, name='y', reify=True)
        foo.bar = 1
        self.assertEqual(1, foo.y)
        self.assertEqual(1, foo.x)
        foo.bar = 2
        self.assertEqual(2, foo.x)
        self.assertEqual(1, foo.y)

    def test_property_without_name(self):
        def worker(obj):  # pragma: no cover
            pass

        foo = self._makeOne()
        self.assertRaises(ValueError, foo.set_property, property(worker))

    def test_property_with_name(self):
        def worker(obj):
            return obj.bar

        foo = self._makeOne()
        foo.set_property(property(worker), name='x')
        foo.bar = 1
        self.assertEqual(1, foo.x)
        foo.bar = 2
        self.assertEqual(2, foo.x)

    def test_property_with_reify(self):
        def worker(obj):  # pragma: no cover
            pass

        foo = self._makeOne()
        self.assertRaises(
            ValueError,
            foo.set_property,
            property(worker),
            name='x',
            reify=True,
        )

    def test_override_property(self):
        def worker(obj):  # pragma: no cover
            pass

        foo = self._makeOne()
        foo.set_property(worker, name='x')

        def doit():
            foo.x = 1

        self.assertRaises(AttributeError, doit)

    def test_override_reify(self):
        def worker(obj):  # pragma: no cover
            pass

        foo = self._makeOne()
        foo.set_property(worker, name='x', reify=True)
        foo.x = 1
        self.assertEqual(1, foo.x)
        foo.x = 2
        self.assertEqual(2, foo.x)

    def test_reset_property(self):
        foo = self._makeOne()
        foo.set_property(lambda _: 1, name='x')
        self.assertEqual(1, foo.x)
        foo.set_property(lambda _: 2, name='x')
        self.assertEqual(2, foo.x)

    def test_reset_reify(self):
        """ This is questionable behavior, but may as well get notified
        if it changes."""
        foo = self._makeOne()
        foo.set_property(lambda _: 1, name='x', reify=True)
        self.assertEqual(1, foo.x)
        foo.set_property(lambda _: 2, name='x', reify=True)
        self.assertEqual(1, foo.x)

    def test_new_class_keeps_parent_module_name(self):
        foo = self._makeOne()
        self.assertEqual(foo.__module__, 'tests.test_util')
        self.assertEqual(foo.__class__.__module__, 'tests.test_util')
        foo.set_property(lambda _: 1, name='x', reify=True)
        self.assertEqual(foo.__module__, 'tests.test_util')
        self.assertEqual(foo.__class__.__module__, 'tests.test_util')


class Test_WeakOrderedSet(unittest.TestCase):
    def _makeOne(self):
        from pyramid.config import WeakOrderedSet

        return WeakOrderedSet()

    def test_ctor(self):
        wos = self._makeOne()
        self.assertEqual(len(wos), 0)
        self.assertEqual(wos.last, None)

    def test_add_item(self):
        wos = self._makeOne()
        reg = Dummy()
        wos.add(reg)
        self.assertEqual(list(wos), [reg])
        self.assertTrue(reg in wos)
        self.assertEqual(wos.last, reg)

    def test_add_multiple_items(self):
        wos = self._makeOne()
        reg1 = Dummy()
        reg2 = Dummy()
        wos.add(reg1)
        wos.add(reg2)
        self.assertEqual(len(wos), 2)
        self.assertEqual(list(wos), [reg1, reg2])
        self.assertTrue(reg1 in wos)
        self.assertTrue(reg2 in wos)
        self.assertEqual(wos.last, reg2)

    def test_add_duplicate_items(self):
        wos = self._makeOne()
        reg = Dummy()
        wos.add(reg)
        wos.add(reg)
        self.assertEqual(len(wos), 1)
        self.assertEqual(list(wos), [reg])
        self.assertTrue(reg in wos)
        self.assertEqual(wos.last, reg)

    def test_weakref_removal(self):
        wos = self._makeOne()
        reg = Dummy()
        wos.add(reg)
        wos.remove(reg)
        self.assertEqual(len(wos), 0)
        self.assertEqual(list(wos), [])
        self.assertEqual(wos.last, None)

    def test_last_updated(self):
        wos = self._makeOne()
        reg = Dummy()
        reg2 = Dummy()
        wos.add(reg)
        wos.add(reg2)
        wos.remove(reg2)
        self.assertEqual(len(wos), 1)
        self.assertEqual(list(wos), [reg])
        self.assertEqual(wos.last, reg)

    def test_empty(self):
        wos = self._makeOne()
        reg = Dummy()
        reg2 = Dummy()
        wos.add(reg)
        wos.add(reg2)
        wos.empty()
        self.assertEqual(len(wos), 0)
        self.assertEqual(list(wos), [])
        self.assertEqual(wos.last, None)


class Test_strings_differ(unittest.TestCase):
    def _callFUT(self, *args, **kw):
        from pyramid.util import strings_differ

        return strings_differ(*args, **kw)

    def test_it_bytes(self):
        self.assertFalse(self._callFUT(b'foo', b'foo'))
        self.assertTrue(self._callFUT(b'123', b'345'))
        self.assertTrue(self._callFUT(b'1234', b'123'))
        self.assertTrue(self._callFUT(b'123', b'1234'))

    def test_it_native_str(self):
        self.assertFalse(self._callFUT('123', '123'))
        self.assertTrue(self._callFUT('123', '1234'))

    def test_it_with_internal_comparator(self):
        result = self._callFUT(b'foo', b'foo', compare_digest=None)
        self.assertFalse(result)

        result = self._callFUT(b'123', b'abc', compare_digest=None)
        self.assertTrue(result)

    def test_it_with_external_comparator(self):
        class DummyComparator(object):
            called = False

            def __init__(self, ret_val):
                self.ret_val = ret_val

            def __call__(self, a, b):
                self.called = True
                return self.ret_val

        dummy_compare = DummyComparator(True)
        result = self._callFUT(b'foo', b'foo', compare_digest=dummy_compare)
        self.assertTrue(dummy_compare.called)
        self.assertFalse(result)

        dummy_compare = DummyComparator(False)
        result = self._callFUT(b'123', b'345', compare_digest=dummy_compare)
        self.assertTrue(dummy_compare.called)
        self.assertTrue(result)

        dummy_compare = DummyComparator(False)
        result = self._callFUT(b'abc', b'abc', compare_digest=dummy_compare)
        self.assertTrue(dummy_compare.called)
        self.assertTrue(result)


class Test_object_description(unittest.TestCase):
    def _callFUT(self, object):
        from pyramid.util import object_description

        return object_description(object)

    def test_string(self):
        self.assertEqual(self._callFUT('abc'), 'abc')

    def test_int(self):
        self.assertEqual(self._callFUT(1), '1')

    def test_bool(self):
        self.assertEqual(self._callFUT(True), 'True')

    def test_None(self):
        self.assertEqual(self._callFUT(None), 'None')

    def test_float(self):
        self.assertEqual(self._callFUT(1.2), '1.2')

    def test_tuple(self):
        self.assertEqual(self._callFUT(('a', 'b')), "('a', 'b')")

    def test_set(self):
        if PY2:
            self.assertEqual(self._callFUT(set(['a'])), "set(['a'])")
        else:
            self.assertEqual(self._callFUT(set(['a'])), "{'a'}")

    def test_list(self):
        self.assertEqual(self._callFUT(['a']), "['a']")

    def test_dict(self):
        self.assertEqual(self._callFUT({'a': 1}), "{'a': 1}")

    def test_nomodule(self):
        o = object()
        self.assertEqual(self._callFUT(o), 'object %s' % str(o))

    def test_module(self):
        import pyramid

        self.assertEqual(self._callFUT(pyramid), 'module pyramid')

    def test_method(self):
        self.assertEqual(
            self._callFUT(self.test_method),
            'method test_method of class tests.test_util.'
            'Test_object_description',
        )

    def test_class(self):
        self.assertEqual(
            self._callFUT(self.__class__),
            'class tests.test_util.Test_object_description',
        )

    def test_function(self):
        self.assertEqual(
            self._callFUT(dummyfunc), 'function tests.test_util.dummyfunc'
        )

    def test_instance(self):
        inst = Dummy()
        self.assertEqual(self._callFUT(inst), "object %s" % str(inst))

    def test_shortened_repr(self):
        inst = ['1'] * 1000
        self.assertEqual(self._callFUT(inst), str(inst)[:100] + ' ... ]')


class TestTopologicalSorter(unittest.TestCase):
    def _makeOne(self, *arg, **kw):
        from pyramid.util import TopologicalSorter

        return TopologicalSorter(*arg, **kw)

    def test_remove(self):
        inst = self._makeOne()
        inst.names.append('name')
        inst.name2val['name'] = 1
        inst.req_after.add('name')
        inst.req_before.add('name')
        inst.name2after['name'] = ('bob',)
        inst.name2before['name'] = ('fred',)
        inst.order.append(('bob', 'name'))
        inst.order.append(('name', 'fred'))
        inst.remove('name')
        self.assertFalse(inst.names)
        self.assertFalse(inst.req_before)
        self.assertFalse(inst.req_after)
        self.assertFalse(inst.name2before)
        self.assertFalse(inst.name2after)
        self.assertFalse(inst.name2val)
        self.assertFalse(inst.order)

    def test_add(self):
        from pyramid.util import LAST

        sorter = self._makeOne()
        sorter.add('name', 'factory')
        self.assertEqual(sorter.names, ['name'])
        self.assertEqual(sorter.name2val, {'name': 'factory'})
        self.assertEqual(sorter.order, [('name', LAST)])
        sorter.add('name2', 'factory2')
        self.assertEqual(sorter.names, ['name', 'name2'])
        self.assertEqual(
            sorter.name2val, {'name': 'factory', 'name2': 'factory2'}
        )
        self.assertEqual(sorter.order, [('name', LAST), ('name2', LAST)])
        sorter.add('name3', 'factory3', before='name2')
        self.assertEqual(sorter.names, ['name', 'name2', 'name3'])
        self.assertEqual(
            sorter.name2val,
            {'name': 'factory', 'name2': 'factory2', 'name3': 'factory3'},
        )
        self.assertEqual(
            sorter.order, [('name', LAST), ('name2', LAST), ('name3', 'name2')]
        )

    def test_sorted_ordering_1(self):
        sorter = self._makeOne()
        sorter.add('name1', 'factory1')
        sorter.add('name2', 'factory2')
        self.assertEqual(
            sorter.sorted(), [('name1', 'factory1'), ('name2', 'factory2')]
        )

    def test_sorted_ordering_2(self):
        from pyramid.util import FIRST

        sorter = self._makeOne()
        sorter.add('name1', 'factory1')
        sorter.add('name2', 'factory2', after=FIRST)
        self.assertEqual(
            sorter.sorted(), [('name2', 'factory2'), ('name1', 'factory1')]
        )

    def test_sorted_ordering_3(self):
        from pyramid.util import FIRST

        sorter = self._makeOne()
        add = sorter.add
        add('auth', 'auth_factory', after='browserid')
        add('dbt', 'dbt_factory')
        add('retry', 'retry_factory', before='txnmgr', after='exceptionview')
        add('browserid', 'browserid_factory')
        add('txnmgr', 'txnmgr_factory', after='exceptionview')
        add('exceptionview', 'excview_factory', after=FIRST)
        self.assertEqual(
            sorter.sorted(),
            [
                ('exceptionview', 'excview_factory'),
                ('retry', 'retry_factory'),
                ('txnmgr', 'txnmgr_factory'),
                ('dbt', 'dbt_factory'),
                ('browserid', 'browserid_factory'),
                ('auth', 'auth_factory'),
            ],
        )

    def test_sorted_ordering_4(self):
        from pyramid.util import FIRST

        sorter = self._makeOne()
        add = sorter.add
        add('exceptionview', 'excview_factory', after=FIRST)
        add('auth', 'auth_factory', after='browserid')
        add('retry', 'retry_factory', before='txnmgr', after='exceptionview')
        add('browserid', 'browserid_factory')
        add('txnmgr', 'txnmgr_factory', after='exceptionview')
        add('dbt', 'dbt_factory')
        self.assertEqual(
            sorter.sorted(),
            [
                ('exceptionview', 'excview_factory'),
                ('retry', 'retry_factory'),
                ('txnmgr', 'txnmgr_factory'),
                ('browserid', 'browserid_factory'),
                ('auth', 'auth_factory'),
                ('dbt', 'dbt_factory'),
            ],
        )

    def test_sorted_ordering_5(self):
        from pyramid.util import LAST, FIRST

        sorter = self._makeOne()
        add = sorter.add
        add('exceptionview', 'excview_factory')
        add('auth', 'auth_factory', after=FIRST)
        add('retry', 'retry_factory', before='txnmgr', after='exceptionview')
        add('browserid', 'browserid_factory', after=FIRST)
        add('txnmgr', 'txnmgr_factory', after='exceptionview', before=LAST)
        add('dbt', 'dbt_factory')
        self.assertEqual(
            sorter.sorted(),
            [
                ('browserid', 'browserid_factory'),
                ('auth', 'auth_factory'),
                ('exceptionview', 'excview_factory'),
                ('retry', 'retry_factory'),
                ('txnmgr', 'txnmgr_factory'),
                ('dbt', 'dbt_factory'),
            ],
        )

    def test_sorted_ordering_missing_before_partial(self):
        from pyramid.exceptions import ConfigurationError

        sorter = self._makeOne()
        add = sorter.add
        add('dbt', 'dbt_factory')
        add('auth', 'auth_factory', after='browserid')
        add('retry', 'retry_factory', before='txnmgr', after='exceptionview')
        add('browserid', 'browserid_factory')
        self.assertRaises(ConfigurationError, sorter.sorted)

    def test_sorted_ordering_missing_after_partial(self):
        from pyramid.exceptions import ConfigurationError

        sorter = self._makeOne()
        add = sorter.add
        add('dbt', 'dbt_factory')
        add('auth', 'auth_factory', after='txnmgr')
        add('retry', 'retry_factory', before='dbt', after='exceptionview')
        add('browserid', 'browserid_factory')
        self.assertRaises(ConfigurationError, sorter.sorted)

    def test_sorted_ordering_missing_before_and_after_partials(self):
        from pyramid.exceptions import ConfigurationError

        sorter = self._makeOne()
        add = sorter.add
        add('dbt', 'dbt_factory')
        add('auth', 'auth_factory', after='browserid')
        add('retry', 'retry_factory', before='foo', after='txnmgr')
        add('browserid', 'browserid_factory')
        self.assertRaises(ConfigurationError, sorter.sorted)

    def test_sorted_ordering_missing_before_partial_with_fallback(self):
        from pyramid.util import LAST

        sorter = self._makeOne()
        add = sorter.add
        add('exceptionview', 'excview_factory', before=LAST)
        add('auth', 'auth_factory', after='browserid')
        add(
            'retry',
            'retry_factory',
            before=('txnmgr', LAST),
            after='exceptionview',
        )
        add('browserid', 'browserid_factory')
        add('dbt', 'dbt_factory')
        self.assertEqual(
            sorter.sorted(),
            [
                ('exceptionview', 'excview_factory'),
                ('retry', 'retry_factory'),
                ('browserid', 'browserid_factory'),
                ('auth', 'auth_factory'),
                ('dbt', 'dbt_factory'),
            ],
        )

    def test_sorted_ordering_missing_after_partial_with_fallback(self):
        from pyramid.util import FIRST

        sorter = self._makeOne()
        add = sorter.add
        add('exceptionview', 'excview_factory', after=FIRST)
        add('auth', 'auth_factory', after=('txnmgr', 'browserid'))
        add('retry', 'retry_factory', after='exceptionview')
        add('browserid', 'browserid_factory')
        add('dbt', 'dbt_factory')
        self.assertEqual(
            sorter.sorted(),
            [
                ('exceptionview', 'excview_factory'),
                ('retry', 'retry_factory'),
                ('browserid', 'browserid_factory'),
                ('auth', 'auth_factory'),
                ('dbt', 'dbt_factory'),
            ],
        )

    def test_sorted_ordering_with_partial_fallbacks(self):
        from pyramid.util import LAST

        sorter = self._makeOne()
        add = sorter.add
        add('exceptionview', 'excview_factory', before=('wontbethere', LAST))
        add('retry', 'retry_factory', after='exceptionview')
        add(
            'browserid', 'browserid_factory', before=('wont2', 'exceptionview')
        )
        self.assertEqual(
            sorter.sorted(),
            [
                ('browserid', 'browserid_factory'),
                ('exceptionview', 'excview_factory'),
                ('retry', 'retry_factory'),
            ],
        )

    def test_sorted_ordering_with_multiple_matching_fallbacks(self):
        from pyramid.util import LAST

        sorter = self._makeOne()
        add = sorter.add
        add('exceptionview', 'excview_factory', before=LAST)
        add('retry', 'retry_factory', after='exceptionview')
        add(
            'browserid', 'browserid_factory', before=('retry', 'exceptionview')
        )
        self.assertEqual(
            sorter.sorted(),
            [
                ('browserid', 'browserid_factory'),
                ('exceptionview', 'excview_factory'),
                ('retry', 'retry_factory'),
            ],
        )

    def test_sorted_ordering_with_missing_fallbacks(self):
        from pyramid.exceptions import ConfigurationError
        from pyramid.util import LAST

        sorter = self._makeOne()
        add = sorter.add
        add('exceptionview', 'excview_factory', before=LAST)
        add('retry', 'retry_factory', after='exceptionview')
        add('browserid', 'browserid_factory', before=('txnmgr', 'auth'))
        self.assertRaises(ConfigurationError, sorter.sorted)

    def test_sorted_ordering_conflict_direct(self):
        from pyramid.exceptions import CyclicDependencyError

        sorter = self._makeOne()
        add = sorter.add
        add('browserid', 'browserid_factory')
        add('auth', 'auth_factory', before='browserid', after='browserid')
        self.assertRaises(CyclicDependencyError, sorter.sorted)

    def test_sorted_ordering_conflict_indirect(self):
        from pyramid.exceptions import CyclicDependencyError

        sorter = self._makeOne()
        add = sorter.add
        add('browserid', 'browserid_factory')
        add('auth', 'auth_factory', before='browserid')
        add('dbt', 'dbt_factory', after='browserid', before='auth')
        self.assertRaises(CyclicDependencyError, sorter.sorted)


class TestSentinel(unittest.TestCase):
    def test_repr(self):
        from pyramid.util import Sentinel

        r = repr(Sentinel('ABC'))
        self.assertEqual(r, 'ABC')


class TestCallableName(unittest.TestCase):
    def test_valid_ascii(self):
        from pyramid.util import get_callable_name
        from pyramid.compat import text_

        if PY2:
            name = text_(b'hello world', 'utf-8')
        else:
            name = b'hello world'

        self.assertEqual(get_callable_name(name), 'hello world')

    def test_invalid_ascii(self):
        from pyramid.util import get_callable_name
        from pyramid.compat import text_
        from pyramid.exceptions import ConfigurationError

        def get_bad_name():
            if PY2:
                name = text_(b'La Pe\xc3\xb1a', 'utf-8')
            else:
                name = b'La Pe\xc3\xb1a'

            get_callable_name(name)

        self.assertRaises(ConfigurationError, get_bad_name)


class Test_hide_attrs(unittest.TestCase):
    def _callFUT(self, obj, *attrs):
        from pyramid.util import hide_attrs

        return hide_attrs(obj, *attrs)

    def _makeDummy(self):
        from pyramid.decorator import reify

        class Dummy(object):
            x = 1

            @reify
            def foo(self):
                return self.x

        return Dummy()

    def test_restores_attrs(self):
        obj = self._makeDummy()
        obj.bar = 'asdf'
        orig_foo = obj.foo
        with self._callFUT(obj, 'foo', 'bar'):
            obj.foo = object()
            obj.bar = 'nope'
        self.assertEqual(obj.foo, orig_foo)
        self.assertEqual(obj.bar, 'asdf')

    def test_restores_attrs_on_exception(self):
        obj = self._makeDummy()
        orig_foo = obj.foo
        try:
            with self._callFUT(obj, 'foo'):
                obj.foo = object()
                raise RuntimeError()
        except RuntimeError:
            self.assertEqual(obj.foo, orig_foo)
        else:  # pragma: no cover
            self.fail("RuntimeError not raised")

    def test_restores_attrs_to_none(self):
        obj = self._makeDummy()
        obj.foo = None
        with self._callFUT(obj, 'foo'):
            obj.foo = object()
        self.assertEqual(obj.foo, None)

    def test_deletes_attrs(self):
        obj = self._makeDummy()
        with self._callFUT(obj, 'foo'):
            obj.foo = object()
        self.assertTrue('foo' not in obj.__dict__)

    def test_does_not_delete_attr_if_no_attr_to_delete(self):
        obj = self._makeDummy()
        with self._callFUT(obj, 'foo'):
            pass
        self.assertTrue('foo' not in obj.__dict__)


def dummyfunc():  # pragma: no cover
    pass


class Dummy(object):
    pass


class Test_is_same_domain(unittest.TestCase):
    def _callFUT(self, *args, **kw):
        from pyramid.util import is_same_domain

        return is_same_domain(*args, **kw)

    def test_it(self):
        self.assertTrue(self._callFUT("example.com", "example.com"))
        self.assertFalse(self._callFUT("evil.com", "example.com"))
        self.assertFalse(self._callFUT("evil.example.com", "example.com"))
        self.assertFalse(self._callFUT("example.com", ""))

    def test_with_wildcard(self):
        self.assertTrue(self._callFUT("example.com", ".example.com"))
        self.assertTrue(self._callFUT("good.example.com", ".example.com"))

    def test_with_port(self):
        self.assertTrue(self._callFUT("example.com:8080", "example.com:8080"))
        self.assertFalse(self._callFUT("example.com:8080", "example.com"))
        self.assertFalse(self._callFUT("example.com", "example.com:8080"))


class Test_make_contextmanager(unittest.TestCase):
    def _callFUT(self, *args, **kw):
        from pyramid.util import make_contextmanager

        return make_contextmanager(*args, **kw)

    def test_with_None(self):
        mgr = self._callFUT(None)
        with mgr() as ctx:
            self.assertIsNone(ctx)

    def test_with_generator(self):
        def mygen(ctx):
            yield ctx

        mgr = self._callFUT(mygen)
        with mgr('a') as ctx:
            self.assertEqual(ctx, 'a')

    def test_with_multiple_yield_generator(self):
        def mygen():
            yield 'a'
            yield 'b'

        mgr = self._callFUT(mygen)
        try:
            with mgr() as ctx:
                self.assertEqual(ctx, 'a')
        except RuntimeError:
            pass
        else:  # pragma: no cover
            raise AssertionError('expected raise from multiple yields')

    def test_with_regular_fn(self):
        def mygen():
            return 'a'

        mgr = self._callFUT(mygen)
        with mgr() as ctx:
            self.assertEqual(ctx, 'a')


class Test_takes_one_arg(unittest.TestCase):
    def _callFUT(self, view, attr=None, argname=None):
        from pyramid.util import takes_one_arg

        return takes_one_arg(view, attr=attr, argname=argname)

    def test_requestonly_newstyle_class_no_init(self):
        class foo(object):
            """ """

        self.assertFalse(self._callFUT(foo))

    def test_requestonly_newstyle_class_init_toomanyargs(self):
        class foo(object):
            def __init__(self, context, request):
                """ """

        self.assertFalse(self._callFUT(foo))

    def test_requestonly_newstyle_class_init_onearg_named_request(self):
        class foo(object):
            def __init__(self, request):
                """ """

        self.assertTrue(self._callFUT(foo))

    def test_newstyle_class_init_onearg_named_somethingelse(self):
        class foo(object):
            def __init__(self, req):
                """ """

        self.assertTrue(self._callFUT(foo))

    def test_newstyle_class_init_defaultargs_firstname_not_request(self):
        class foo(object):
            def __init__(self, context, request=None):
                """ """

        self.assertFalse(self._callFUT(foo))

    def test_newstyle_class_init_defaultargs_firstname_request(self):
        class foo(object):
            def __init__(self, request, foo=1, bar=2):
                """ """

        self.assertTrue(self._callFUT(foo, argname='request'))

    def test_newstyle_class_init_firstname_request_with_secondname(self):
        class foo(object):
            def __init__(self, request, two):
                """ """

        self.assertFalse(self._callFUT(foo))

    def test_newstyle_class_init_noargs(self):
        class foo(object):
            def __init__():
                """ """

        self.assertFalse(self._callFUT(foo))

    def test_oldstyle_class_no_init(self):
        class foo:
            """ """

        self.assertFalse(self._callFUT(foo))

    def test_oldstyle_class_init_toomanyargs(self):
        class foo:
            def __init__(self, context, request):
                """ """

        self.assertFalse(self._callFUT(foo))

    def test_oldstyle_class_init_onearg_named_request(self):
        class foo:
            def __init__(self, request):
                """ """

        self.assertTrue(self._callFUT(foo))

    def test_oldstyle_class_init_onearg_named_somethingelse(self):
        class foo:
            def __init__(self, req):
                """ """

        self.assertTrue(self._callFUT(foo))

    def test_oldstyle_class_init_defaultargs_firstname_not_request(self):
        class foo:
            def __init__(self, context, request=None):
                """ """

        self.assertFalse(self._callFUT(foo))

    def test_oldstyle_class_init_defaultargs_firstname_request(self):
        class foo:
            def __init__(self, request, foo=1, bar=2):
                """ """

        self.assertTrue(self._callFUT(foo, argname='request'), True)

    def test_oldstyle_class_init_noargs(self):
        class foo:
            def __init__():
                """ """

        self.assertFalse(self._callFUT(foo))

    def test_function_toomanyargs(self):
        def foo(context, request):
            """ """

        self.assertFalse(self._callFUT(foo))

    def test_function_with_attr_false(self):
        def bar(context, request):
            """ """

        def foo(context, request):
            """ """

        foo.bar = bar
        self.assertFalse(self._callFUT(foo, 'bar'))

    def test_function_with_attr_true(self):
        def bar(context, request):
            """ """

        def foo(request):
            """ """

        foo.bar = bar
        self.assertTrue(self._callFUT(foo, 'bar'))

    def test_function_onearg_named_request(self):
        def foo(request):
            """ """

        self.assertTrue(self._callFUT(foo))

    def test_function_onearg_named_somethingelse(self):
        def foo(req):
            """ """

        self.assertTrue(self._callFUT(foo))

    def test_function_defaultargs_firstname_not_request(self):
        def foo(context, request=None):
            """ """

        self.assertFalse(self._callFUT(foo))

    def test_function_defaultargs_firstname_request(self):
        def foo(request, foo=1, bar=2):
            """ """

        self.assertTrue(self._callFUT(foo, argname='request'))

    def test_function_noargs(self):
        def foo():
            """ """

        self.assertFalse(self._callFUT(foo))

    def test_instance_toomanyargs(self):
        class Foo:
            def __call__(self, context, request):
                """ """

        foo = Foo()
        self.assertFalse(self._callFUT(foo))

    def test_instance_defaultargs_onearg_named_request(self):
        class Foo:
            def __call__(self, request):
                """ """

        foo = Foo()
        self.assertTrue(self._callFUT(foo))

    def test_instance_defaultargs_onearg_named_somethingelse(self):
        class Foo:
            def __call__(self, req):
                """ """

        foo = Foo()
        self.assertTrue(self._callFUT(foo))

    def test_instance_defaultargs_firstname_not_request(self):
        class Foo:
            def __call__(self, context, request=None):
                """ """

        foo = Foo()
        self.assertFalse(self._callFUT(foo))

    def test_instance_defaultargs_firstname_request(self):
        class Foo:
            def __call__(self, request, foo=1, bar=2):
                """ """

        foo = Foo()
        self.assertTrue(self._callFUT(foo, argname='request'), True)

    def test_instance_nocall(self):
        class Foo:
            pass

        foo = Foo()
        self.assertFalse(self._callFUT(foo))

    def test_method_onearg_named_request(self):
        class Foo:
            def method(self, request):
                """ """

        foo = Foo()
        self.assertTrue(self._callFUT(foo.method))

    def test_function_annotations(self):
        def foo(bar):
            """ """

        # avoid SyntaxErrors in python2, this if effectively nop
        getattr(foo, '__annotations__', {}).update({'bar': 'baz'})
        self.assertTrue(self._callFUT(foo))


class TestSimpleSerializer(unittest.TestCase):
    def _makeOne(self):
        from pyramid.util import SimpleSerializer

        return SimpleSerializer()

    def test_loads(self):
        inst = self._makeOne()
        self.assertEqual(inst.loads(b'abc'), text_('abc'))

    def test_dumps(self):
        inst = self._makeOne()
        self.assertEqual(inst.dumps('abc'), bytes_('abc'))