Source

pyobjc / pyobjc-core / PyObjCTest / test_keyvaluecoding.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
# Tests for PyObjCTools.KeyValueCoding
from PyObjCTools.TestSupport import *

from PyObjCTools import KeyValueCoding
import operator
import os


class TestHelpers (TestCase):
    def test_msum(self):
        self.assertEqual(KeyValueCoding.msum([1, 1e100, 1, -1e100] * 10000), 20000)
        self.assertEqual(KeyValueCoding.msum([1.0, 2.0, 3.0, 4.0]), 10.0)

    def test_keyCaps(self):
        self.assertEqual(KeyValueCoding.keyCaps("attr"), "Attr")
        self.assertEqual(KeyValueCoding.keyCaps("Attr"), "Attr")
        self.assertEqual(KeyValueCoding.keyCaps("AttR"), "AttR")
        self.assertEqual(KeyValueCoding.keyCaps("attr_with_value"), "Attr_with_value")

        self.assertEqual(KeyValueCoding.keyCaps(b"attr"), b"Attr")
        self.assertEqual(KeyValueCoding.keyCaps(b"Attr"), b"Attr")
        self.assertEqual(KeyValueCoding.keyCaps(b"AttR"), b"AttR")
        self.assertEqual(KeyValueCoding.keyCaps(b"attr_with_value"), b"Attr_with_value")


class TestArrayOperators (TestCase):
    def test_unknown_function(self):
        values = [ { 'a': 1 } ]

        self.assertRaises(KeyError, KeyValueCoding.getKeyPath, values, '@nofunction.a')


    def test_sum(self):
        arrayOperators = KeyValueCoding._ArrayOperators

        values = [
                { 'a' : 1 },
                { 'a' : 2, 'b': 4 },
                { 'a' : 3, 'b': 2 },
                { 'a' : 4 },
        ]
        self.assertEqual(arrayOperators.sum(values, 'a'), 10)
        self.assertEqual(arrayOperators.sum(values, 'b'), 6)
        self.assertEqual(arrayOperators.sum(values, 'c'), 0)
        self.assertEqual(arrayOperators.sum([], 'b'), 0)
        self.assertRaises(KeyError, arrayOperators.sum, [], ())

        self.assertEqual(KeyValueCoding.getKeyPath(values, '@sum.a'), 10)
        self.assertEqual(KeyValueCoding.getKeyPath(values, '@sum.b'), 6)
        self.assertEqual(KeyValueCoding.getKeyPath(values, '@sum.c'), 0)


    def test_avg(self):
        arrayOperators = KeyValueCoding._ArrayOperators

        values = [
                { 'a' : 1 },
                { 'a' : 2, 'b': 4 },
                { 'a' : 3, 'b': 2 },
                { 'a' : 4 },
        ]
        self.assertEqual(arrayOperators.avg(values, 'a'), 2.5)
        self.assertEqual(arrayOperators.avg(values, 'b'), 1.5)
        self.assertEqual(arrayOperators.avg(values, 'c'), 0)
        self.assertEqual(arrayOperators.avg([], 'b'), 0)
        self.assertRaises(KeyError, arrayOperators.avg, [], ())

        self.assertEqual(KeyValueCoding.getKeyPath(values, '@avg.a'), 2.5)
        self.assertEqual(KeyValueCoding.getKeyPath(values, '@avg.b'), 1.5)
        self.assertEqual(KeyValueCoding.getKeyPath(values, '@avg.c'), 0)

    def test_count(self):
        arrayOperators = KeyValueCoding._ArrayOperators

        values = [
                { 'a' : 1 },
                { 'a' : 2, 'b': 4 },
                { 'a' : 3, 'b': 2 },
                { 'a' : 4 },
        ]
        self.assertEqual(arrayOperators.count(values, 'a'), len(values))
        self.assertEqual(arrayOperators.count(values, 'b'), len(values))
        self.assertEqual(arrayOperators.count(values, ()), len(values))
        self.assertEqual(KeyValueCoding.getKeyPath(values, '@count'), len(values))
        self.assertEqual(KeyValueCoding.getKeyPath(values, '@count.a'), len(values))

    def test_max(self):
        arrayOperators = KeyValueCoding._ArrayOperators

        values = [
                { 'a' : 1 },
                { 'a' : 2, 'b': 5 },
                { 'a' : 3, 'b': 2 },
                { 'a' : 4 },
        ]
        self.assertEqual(arrayOperators.max(values, 'a'), 4)
        self.assertEqual(arrayOperators.max(values, 'b'), 5)
        self.assertRaises(KeyError, arrayOperators.max, values, ())
        self.assertEqual(KeyValueCoding.getKeyPath(values, '@max.a'), 4)

    def test_min(self):
        arrayOperators = KeyValueCoding._ArrayOperators

        values = [
                { 'a' : 1 },
                { 'a' : 2, 'b': 5 },
                { 'a' : 3, 'b': 2 },
                { 'a' : 4 },
        ]
        self.assertEqual(arrayOperators.min(values, 'a'), 1)
        self.assertEqual(arrayOperators.min(values, 'b'), 2)
        self.assertRaises(KeyError, arrayOperators.min, values, ())
        self.assertEqual(KeyValueCoding.getKeyPath(values, '@min.a'), 1)

    def test_unionOfObjects(self):
        arrayOperators = KeyValueCoding._ArrayOperators

        values = [
                { 'a' : { 'b': 1 } },
                { 'a' : { 'b': 1 } },
                { 'a' : { 'b': 2 } },
                { 'a' : { 'b': 3 } },
        ]
        
        self.assertEqual(arrayOperators.unionOfObjects(values, ('a', 'b')), [1, 1, 2, 3 ])
        self.assertEqual(KeyValueCoding.getKeyPath(values, '@unionOfObjects.a.b'), [1, 1, 2, 3])

        values.append({'a': {}})
        self.assertRaises(KeyError, arrayOperators.unionOfObjects, values, ('a', 'b'))

    def test_distinctUnionOfObjects(self):
        arrayOperators = KeyValueCoding._ArrayOperators

        class Int (object):
            def __init__(self, value):
                self._value = value

            def __repr__(self):
                return 'Int(%r)'%(self._value)

            def __eq__(self, other):
                if isinstance(other, int):
                    return self._value == other

                elif isinstance(other, Int):
                    return self._value == other._value

                else:
                    return False

            def __hash__(self): raise TypeError

        values = [
                { 'a' : { 'b': 1 } },
                { 'a' : { 'b': Int(1) } },
                { 'a' : { 'b': 2 } },
                { 'a' : { 'b': Int(3) } },
                { 'a' : { 'b': Int(3) } },
        ]
        
        self.assertEqual(arrayOperators.distinctUnionOfObjects(values, ('a', 'b')), [1, 2, 3 ])
        self.assertEqual(KeyValueCoding.getKeyPath(values, '@distinctUnionOfObjects.a.b'), [1, 2, 3 ])

        values.append({'a': {}})
        self.assertRaises(KeyError, arrayOperators.distinctUnionOfObjects, values, ('a', 'b'))
        self.assertRaises(KeyError, KeyValueCoding.getKeyPath, values, '@distinctUnionOfObjects.a.b')

        class Rec (object):
            def __init__(self, b):
                self.b = b

            def __eq__(self, other):
                return type(self) == type(other) and self.b == other.b

            def __hash__(self): raise TypeError

        values = [
                { 'a' : Rec(1) },
                { 'a' : Rec(1) },
                { 'a' : Rec(2) },
                { 'a' : Rec(3) },
        ]
        self.assertEqual(arrayOperators.distinctUnionOfObjects(values, ('a', 'b')), [1, 2, 3 ])

    def test_unionOfArrays(self):
        arrayOperators = KeyValueCoding._ArrayOperators

        class Rec (object):
            def __init__(self, **kwds):
                for k, v in kwds.items():
                    setattr(self, k, v)

            def __eq__(self, other):
                return type(self) is type(other) and self.__dict__ == other.__dict__

            def __hash__(self): raise TypeError

        class Str (object):
            def __init__(self, value):
                self._value = value

            def __repr__(self):
                return 'Str(%r)'%(self._value)

            def __eq__(self, other):
                if isinstance(other, str):
                    return self._value == other

                elif isinstance(other, Str):
                    return self._value == other._value

                else:
                    return False

            def __cmp__(self, other):
                if isinstance(other, str):
                    return cmp(self._value, other)

                elif isinstance(other, Str):
                    return cmp(self._value, other._value)

                else:
                    return NotImplementedError

            def __hash__(self): raise TypeError

        transactions = [
            [
                dict(payee='Green Power', amount=120.0),
                dict(payee='Green Power', amount=150.0),
                dict(payee=Str('Green Power'), amount=170.0),
                Rec(payee='Car Loan', amount=250.0),
                dict(payee='Car Loan', amount=250.0),
                dict(payee='Car Loan', amount=250.0),
                dict(payee=Str('General Cable'), amount=120.0),
                dict(payee='General Cable', amount=155.0),
                Rec(payee='General Cable', amount=120.0),
                dict(payee='Mortgage', amount=1250.0),
                dict(payee='Mortgage', amount=1250.0),
                dict(payee='Mortgage', amount=1250.0),
                dict(payee='Animal Hospital', amount=600.0),
            ],
            [
                dict(payee='General Cable - Cottage',   amount=120.0),
                dict(payee='General Cable - Cottage',   amount=155.0),
                Rec(payee='General Cable - Cottage',   amount=120.0),
                dict(payee='Second Mortgage',   amount=1250.0),
                dict(payee='Second Mortgage',   amount=1250.0),
                dict(payee=Str('Second Mortgage'),   amount=1250.0),
                dict(payee='Hobby Shop',   amount=600.0),
            ]
        ]

        self.assertEqual(arrayOperators.distinctUnionOfArrays(transactions, ('payee',)), ['Green Power', 'Car Loan', 'General Cable', 'Mortgage', 'Animal Hospital', 'General Cable - Cottage', 'Second Mortgage', 'Hobby Shop'])
        self.assertEqual(KeyValueCoding.getKeyPath(transactions, '@distinctUnionOfArrays.payee'), ['Green Power', 'Car Loan', 'General Cable', 'Mortgage', 'Animal Hospital', 'General Cable - Cottage', 'Second Mortgage', 'Hobby Shop'])
        self.assertEqual(arrayOperators.unionOfArrays(transactions, ('payee',)), [
            'Green Power', 
            'Green Power', 
            'Green Power', 
            'Car Loan', 
            'Car Loan', 
            'Car Loan', 
            'General Cable', 
            'General Cable', 
            'General Cable', 
            'Mortgage', 
            'Mortgage', 
            'Mortgage', 
            'Animal Hospital', 
            'General Cable - Cottage', 
            'General Cable - Cottage', 
            'General Cable - Cottage', 
            'Second Mortgage', 
            'Second Mortgage', 
            'Second Mortgage', 
            'Hobby Shop'
        ])
        self.assertEqual(KeyValueCoding.getKeyPath(transactions, '@unionOfArrays.payee'), [
            'Green Power', 
            'Green Power', 
            'Green Power', 
            'Car Loan', 
            'Car Loan', 
            'Car Loan', 
            'General Cable', 
            'General Cable', 
            'General Cable', 
            'Mortgage', 
            'Mortgage', 
            'Mortgage', 
            'Animal Hospital', 
            'General Cable - Cottage', 
            'General Cable - Cottage', 
            'General Cable - Cottage', 
            'Second Mortgage', 
            'Second Mortgage', 
            'Second Mortgage', 
            'Hobby Shop'
        ])

        self.assertRaises(KeyError, arrayOperators.unionOfArrays, transactions, 'date')
        self.assertRaises(KeyError, arrayOperators.distinctUnionOfArrays, transactions, 'date')

    def testUnionOfSets(self):
        arrayOperators = KeyValueCoding._ArrayOperators

        class Rec (object):
            def __init__(self, n):
                self.n = n

            def __eq__(self, other):
                return self.n == other.n

            def __hash__(self):
                return hash(self.n)

        
        values = {
            frozenset({
                Rec(1),
                Rec(1),
                Rec(2),
            }),
            frozenset({
                Rec(1),
                Rec(3),
            }),
        }

        self.assertEqual(arrayOperators.distinctUnionOfSets(values, 'n'), {1,2,3})

class TestDeprecatedJunk (TestCase):
    def test_deprecated_class (self):
        with filterWarnings('error', DeprecationWarning):
            self.assertRaises(DeprecationWarning, KeyValueCoding.ArrayOperators)


        o = KeyValueCoding.ArrayOperators()
        self.assertIsInstance(o, KeyValueCoding._ArrayOperators)

    def test_deprecated_object (self):
        with filterWarnings('error', DeprecationWarning):
            self.assertRaises(DeprecationWarning, getattr, KeyValueCoding.arrayOperators, 'avg')

        self.assertEqual(KeyValueCoding.arrayOperators.avg, KeyValueCoding._ArrayOperators.avg)



null = objc.lookUpClass('NSNull').null()

class TestPythonObject (TestCase):
    def test_dict_get(self):
        d = {'a':1 }
        self.assertEqual(KeyValueCoding.getKey(d, 'a'), 1)
        self.assertRaises(KeyError, KeyValueCoding.getKey, d, 'b')

    def test_array_get(self):
        l = [{'a': 1, 'b':2 }, {'a':2} ]
        self.assertEqual(KeyValueCoding.getKey(l, 'a'), [1, 2])
        self.assertEqual(KeyValueCoding.getKey(l, 'b'), [2, null])

    def test_attr_get(self):
        class Record (object):
            __slots__ = ('slot1', '__dict__')
            def __init__(self, **kwds):
                for k, v in kwds.items():
                    setattr(self, k, v)

            @property
            def prop1(self):
                return 'a property'

        r = Record(slot1=42, attr1='a')

        self.assertEqual(KeyValueCoding.getKey(r, 'slot1'), 42)
        self.assertEqual(KeyValueCoding.getKey(r, 'attr1'), 'a')
        self.assertEqual(KeyValueCoding.getKey(r, 'prop1'), 'a property')
        self.assertEqual(KeyValueCoding.getKeyPath(r, 'slot1'), 42)
        self.assertEqual(KeyValueCoding.getKeyPath(r, 'attr1'), 'a')
        self.assertEqual(KeyValueCoding.getKeyPath(r, 'prop1'), 'a property')

        r = Record(attr1=Record(attr2='b', attr3=[Record(a=1), Record(a=2, b='b')]))
        self.assertRaises(KeyError, KeyValueCoding.getKey, r, 'slot1')
        self.assertRaises(KeyError, KeyValueCoding.getKey, r, 'attr99')
        self.assertRaises(KeyError, KeyValueCoding.getKeyPath, r, 'slot1')
        self.assertRaises(KeyError, KeyValueCoding.getKeyPath, r, 'attr99')

        self.assertEqual(KeyValueCoding.getKeyPath(r, 'attr1.attr2'), 'b')
        self.assertEqual(KeyValueCoding.getKeyPath(r, 'attr1.attr3.a'), [1, 2])
        self.assertEqual(KeyValueCoding.getKeyPath(r, 'attr1.attr3.b'), [null, 'b'])
        self.assertRaises(KeyError, KeyValueCoding.getKeyPath, r, 'attr3')
        self.assertRaises(KeyError, KeyValueCoding.getKeyPath, r, 'attr1.attr9')


    def test_cocoa_get(self):
        r = objc.lookUpClass('NSObject').alloc().init()
        self.assertEqual(KeyValueCoding.getKey(r, 'description'), r.description())
        self.assertEqual(KeyValueCoding.getKeyPath(r, 'description'), r.description())
        self.assertEqual(KeyValueCoding.getKeyPath(r, 'description.length'), len(r.description()))
        self.assertRaises(KeyError, KeyValueCoding.getKey, r, 'nosuchattr')
        self.assertRaises(KeyError, KeyValueCoding.getKeyPath, r, 'description.nosuchattr')

    def test_accessor_get(self):
        class Object (object):
            def get_attr1(self):
                return "attr1"

            def getAttr1(self):
                return "Attr1"

            def attr1(self):
                return ".attr1"

            def get_attr2(self):
                return "attr2"

            def attr2(self):
                return '.attr2'

            def attr3(self):
                return '.attr3'

            def isAttr4(self):
                return "attr4?"

            @objc.selector
            def attrsel(self):
                return 'selattr'

        r = Object()
        self.assertEqual(KeyValueCoding.getKey(r, 'attr1'), 'Attr1')
        self.assertEqual(KeyValueCoding.getKey(r, 'attr2'), 'attr2')
        self.assertEqual(KeyValueCoding.getKey(r, 'attr3'), '.attr3')
        self.assertEqual(KeyValueCoding.getKey(r, 'attr4'), 'attr4?')
        self.assertEqual(KeyValueCoding.getKey(r, 'attrsel'), 'selattr')

        t = Object()
        o = objc.lookUpClass('NSObject').alloc().init()
        l = []

        r.attr5 = t.isAttr4
        r.attr6 = o.description
        r.attr7 = l.__len__
        r.attr8 = os.getpid
        r.attr9 = 'attribute 9'

        self.assertEqual(KeyValueCoding.getKey(r, 'attr5'), t.isAttr4)
        self.assertEqual( KeyValueCoding.getKey(r, 'attr6'), r.attr6)
        self.assertEqual(KeyValueCoding.getKey(r, 'attr7'), l.__len__)
        self.assertEqual(KeyValueCoding.getKey(r, 'attr8'), os.getpid())
        self.assertEqual(KeyValueCoding.getKey(r, 'attr9'), 'attribute 9')
        self.assertEqual(KeyValueCoding.getKey(1.5, 'hex'), (1.5).hex())

    def test_none_get(self):
        self.assertEqual(KeyValueCoding.getKey(None, 'a'), None)
        self.assertEqual(KeyValueCoding.getKeyPath(None, 'a'), None)

    def test_none_set(self):
        # setKey(None, 'any', 'value') is documented as a no-op
        # check that this doesn't raise an exception.
        v = None
        KeyValueCoding.setKey(v, 'a', 42)
        KeyValueCoding.setKeyPath(v, 'a', 42)

    def test_dict_set(self):
        v = {'a': 42, 'c':{} }

        KeyValueCoding.setKey(v, 'a', 43)
        KeyValueCoding.setKey(v, 'b', 'B')
        self.assertEqual(v, {'a': 43, 'b': 'B', 'c':{} })

        KeyValueCoding.setKeyPath(v, 'a', 44)
        KeyValueCoding.setKeyPath(v, 'b', 'C')
        KeyValueCoding.setKeyPath(v, 'c.a', 'A')
        self.assertEqual(v, {'a': 44, 'b': 'C', 'c':{'a': 'A'} })

    def test_attr_set(self):
        class R (object):
            @property
            def attr3(self):
                return self._attr3

            @attr3.setter
            def attr3(self, v):
                self._attr3 = v * 2

            @property
            def attr4(self):
                return self._attr4

            def attr6(self):
                return self._attr6

        r = R()
        r._attr1 = 42
        r._attr4 = 43
        r.attr5 = {}
        r._attr6 = 9

        KeyValueCoding.setKey(r, 'attr1', 1)
        KeyValueCoding.setKey(r, 'attr2', 2)
        KeyValueCoding.setKey(r, 'attr3', 3)
        self.assertRaises(KeyError, KeyValueCoding.setKey, r, 'attr4', 4)
        KeyValueCoding.setKey(r, 'attr6', 7)

        self.assertEqual(r._attr1, 1)
        self.assertEqual(r.attr2, 2)
        self.assertEqual(r.attr3, 6)
        self.assertEqual(r._attr3, 6)
        self.assertEqual(r._attr6, 7)

        KeyValueCoding.setKeyPath(r, 'attr1', 'one')
        KeyValueCoding.setKeyPath(r, 'attr2', 'two')
        KeyValueCoding.setKeyPath(r, 'attr3', 'three')
        KeyValueCoding.setKeyPath(r, 'attr5.sub1', 3)
        KeyValueCoding.setKeyPath(r, 'attr6', 'seven')

        self.assertEqual(r._attr1, 'one')
        self.assertEqual(r.attr2, 'two')
        self.assertEqual(r.attr3, 'threethree')
        self.assertEqual(r._attr3, 'threethree')
        self.assertEqual(r.attr5, {'sub1': 3})
        self.assertEqual(r._attr6, 'seven')

    def test_cocoa_set(self):
        o = objc.lookUpClass('NSMutableDictionary').alloc().init()
        KeyValueCoding.setKey(o, 'attr', 'value')
        self.assertEqual(o, {'attr': 'value'})

        KeyValueCoding.setKeyPath(o, 'attr', 'value2')
        self.assertEqual(o, {'attr': 'value2'})

        o = objc.lookUpClass('NSObject').alloc().init()
        self.assertRaises(KeyError, KeyValueCoding.setKey, o, 'description', 'hello')
        self.assertRaises(KeyError, KeyValueCoding.setKeyPath, o, 'description', 'hello')

    def test_accessor(self):
        class Record (object):
            def __init__(self):
                self._attr1 = 1
                self._attr2 = 2
                self._attr3 = 3

            def attr1(self):
                return self._attr1

            def setAttr1_(self, value):
                self._attr1 = (1, value)

            def setAttr1(self, value):
                self._attr1 = (2, value)

            def set_attr1(self, value):
                self._attr1 = (3, value)

            def setAttr2(self, value):
                self._attr2 = (2, value)

            def set_attr2(self, value):
                self._attr2 = (3, value)

            def set_attr3(self, value):
                self._attr3 = (3, value)
            
            set_no_attr = 4

        o = Record()
        self.assertEqual(o._attr1, 1)
        self.assertEqual(o._attr2, 2)
        self.assertEqual(o._attr3, 3)
        self.assertEqual(o.set_no_attr, 4)

        KeyValueCoding.setKey(o, 'attr1', 9)
        KeyValueCoding.setKey(o, 'attr2', 10)
        KeyValueCoding.setKey(o, 'attr3', 11)
        KeyValueCoding.setKey(o, 'no_attr', 12)

        
        self.assertEqual(o._attr1, (1, 9))
        self.assertEqual(o._attr2, (2, 10))
        self.assertEqual(o._attr3, (3, 11))
        self.assertEqual(o.no_attr, 12)

        KeyValueCoding.setKeyPath(o, 'attr1', 29)
        KeyValueCoding.setKeyPath(o, 'attr2', 210)
        KeyValueCoding.setKeyPath(o, 'attr3', 211)
        
        self.assertEqual(o._attr1, (1, 29))
        self.assertEqual(o._attr2, (2, 210))
        self.assertEqual(o._attr3, (3, 211))

        o._attr1 = {'a': 'b'}
        KeyValueCoding.setKeyPath(o, 'attr1.a', 30)
        self.assertEqual(o._attr1, {'a': 30})


    def testMixedGraph(self):
        arr = objc.lookUpClass('NSMutableArray').alloc().init()
        d1 = objc.lookUpClass('NSMutableDictionary').alloc().init()
        d2 = objc.lookUpClass('NSMutableDictionary').alloc().init()
        d3 = {}
        
        root = { 'a': arr, 'd': d2 }

        arr.addObject_(d1)
        arr.addObject_(d3)
        d1['k'] = 1
        d3['k'] = 2

        KeyValueCoding.setKeyPath(root, 'd.a', 'the letter A')
        self.assertEqual(d2, {'a': 'the letter A', })

        self.assertEqual(KeyValueCoding.getKeyPath(root, 'd.a'), 'the letter A')
        self.assertEqual(KeyValueCoding.getKeyPath(arr, 'k'), [1, 2])
        self.assertEqual(KeyValueCoding.getKeyPath(root, 'a.k'), [1, 2])

    def testMixedGraph2(self):
        arr = objc.lookUpClass('NSMutableArray').alloc().init()
        d1 = objc.lookUpClass('NSMutableDictionary').alloc().init()
        d2 = objc.lookUpClass('NSMutableDictionary').alloc().init()
        d3 = {}
        
        root = objc.lookUpClass('NSMutableDictionary').dictionaryWithDictionary_({ 'a': arr, 'd': d2 })

        arr.addObject_(d1)
        arr.addObject_(d3)
        d1['k'] = 1
        d3['k'] = 2

        KeyValueCoding.setKeyPath(root, 'd.a', 'the letter A')
        self.assertEqual(d2, {'a': 'the letter A', })

        self.assertEqual(KeyValueCoding.getKeyPath(root, 'd.a'), 'the letter A')
        self.assertEqual(KeyValueCoding.getKeyPath(arr, 'k'), [1, 2])
        self.assertEqual(KeyValueCoding.getKeyPath(root, 'a.k'), [1, 2])



class TestKVCHelper (TestCase):
    def setUp(self):
        self._orig = {
            'getKey': KeyValueCoding.getKey,
            'setKey': KeyValueCoding.setKey,
            'getKeyPath': KeyValueCoding.getKeyPath,
            'setKeyPath': KeyValueCoding.setKeyPath,
        }
        self._trace = []
        def getKey(obj, k):
            self._trace.append(('get', obj, k))
        def setKey(obj, k, v):
            self._trace.append(('set', obj, k, v))
        def getKeyPath(obj, k):
            self._trace.append(('get-path', obj, k))
        def setKeyPath(obj, k, v):
            self._trace.append(('set-path', obj, k, v))
        KeyValueCoding.getKey = getKey
        KeyValueCoding.setKey = setKey
        KeyValueCoding.getKeyPath = getKeyPath
        KeyValueCoding.setKeyPath = setKeyPath


    def tearDown(self):
        for k in self._orig:
            setattr(KeyValueCoding, k, self._orig[k])

    def test_repr(self):
        for o in [
                object(), 42, "42", b"42", b"42".decode('latin1')
                ]:
            self.assertEqual(repr(KeyValueCoding.kvc(o)), repr(o))

    def test_attribute_access(self):
        v = object()
        o = KeyValueCoding.kvc(v)
        o.key
        o.key2
        getattr(o, "key3.key4")
        self.assertEqual(self._trace,  [
            ('get', v, 'key'),
            ('get', v, 'key2'),
            ('get', v, 'key3.key4'),
        ])
        self._trace[:] = []

        o.key = 42
        setattr(o, "key3.key4", 99)
        self.assertEqual(self._trace,  [
            ('set', v, 'key', 42),
            ('set', v, 'key3.key4', 99),
        ])
        self._trace[:] = []

        class Object (object):
            pass

        v = Object()
        o = KeyValueCoding.kvc(v)
        o.key = 42
        o._key = 99
        self.assertEqual(self._trace,  [
            ('set', v, 'key', 42),
        ])
        self.assertEqual(o._key, 99)
        self.assertIn('_key', o.__dict__)
        self.assertNotIn('key', o.__dict__)


    def test_item_access(self):
        v = object()
        o = KeyValueCoding.kvc(v)
        o['key']
        o['key2']
        o['key3.key4']
        self.assertEqual(self._trace,  [
            ('get-path', v, 'key'),
            ('get-path', v, 'key2'),
            ('get-path', v, 'key3.key4'),
        ])
        self._trace[:] = []

        o["key"] = 42
        o["key3.key4"] = 99
        self.assertEqual(self._trace,  [
            ('set-path', v, 'key', 42),
            ('set-path', v, 'key3.key4', 99),
        ])
        self._trace[:] = []


        self.assertRaises(TypeError, operator.getitem, o, 42)
        self.assertRaises(TypeError, operator.setitem, o, 42, 99)

if __name__ == "__main__":
    main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.