Source

pyobjc / pyobjc-core / PyObjCTest / test_keyvaluecoding.py

Full commit
  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
# Tests for PyObjCTools.KeyValueCoding
from PyObjCTools.TestSupport import *

from PyObjCTools import KeyValueCoding
import operator


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_missing(self):
        self.fail("Missing tests for KVC on Python objects")

    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.assertEquals(KeyValueCoding.getKey(l, 'a'), [1, 2])
        self.assertEquals(KeyValueCoding.getKey(l, 'b'), [2, null])



class TestObjectiveCObject (TestCase):
    def test_missing(self):
        self.fail("Missing tests for KVC on Cocoa objects")


class TestMixed (TestCase):
    def test_missing(self):
        self.fail("Test keypath operations on mixed graphs")


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()