Source

pyobjc / pyobjc-core / PyObjCTest / test2_dict_interface.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
"""
test.test_dict from python 2.7 adapted for testing NSMutableDictionary
"""
from PyObjCTools.TestSupport import *

import objc
import operator
NSDictionary = objc.lookUpClass('NSDictionary')
NSMutableDictionary = objc.lookUpClass('NSMutableDictionary')

import test.test_dict


class TestDict (test.test_dict.DictTest, TestCase):
    def setUp(self):
        test.test_dict.dict = NSMutableDictionary

    def tearDown(self):
        del test.test_dict.dict

    def test_literal_constructor(self): pass

    def test_bool(self):
        self.assertIs(not NSMutableDictionary(), True)
        self.assertTrue(NSMutableDictionary({1: 2}))
        self.assertIs(bool(NSMutableDictionary()), False)
        self.assertIs(bool(NSMutableDictionary({1: 2})), True)

    def test_keys(self):
        d = NSMutableDictionary()
        self.assertEqual(d.keys(), [])
        d = NSMutableDictionary({'a': 1, 'b': 2})
        k = d.keys()
        self.assertTrue(d.has_key('a'))
        self.assertTrue(d.has_key('b'))

        self.assertRaises(TypeError, d.keys, None)

    def test_values(self):
        d = NSMutableDictionary({})
        self.assertEqual(d.values(), [])
        d = NSMutableDictionary({1:2})
        self.assertEqual(d.values(), [2])

        self.assertRaises(TypeError, d.values, None)

    def test_items(self):
        d = NSMutableDictionary({})
        self.assertEqual(d.items(), [])

        d = NSMutableDictionary({1:2})
        self.assertEqual(d.items(), [(1, 2)])

        self.assertRaises(TypeError, d.items, None)

    def test_has_key(self):
        d = NSMutableDictionary({})
        self.assertFalse(d.has_key('a'))
        d = NSMutableDictionary({'a': 1, 'b': 2})
        k = list(d.keys())
        k.sort()
        self.assertEqual(k, ['a', 'b'])

        self.assertRaises(TypeError, d.has_key)

    def test_contains(self):
        d = NSMutableDictionary({})
        self.assertNotIn('a', d)
        self.assertFalse('a' in d)
        self.assertTrue('a' not in d)
        d = NSMutableDictionary({'a': 1, 'b': 2})
        self.assertIn('a', d)
        self.assertIn('b', d)
        self.assertNotIn('c', d)

        self.assertRaises(TypeError, d.__contains__)

    def test_len(self):
        d = NSMutableDictionary({})
        self.assertEqual(len(d), 0)
        d = NSMutableDictionary({'a': 1, 'b': 2})
        self.assertEqual(len(d), 2)

    def test_getitem(self):
        d = NSMutableDictionary({'a': 1, 'b': 2})
        self.assertEqual(d['a'], 1)
        self.assertEqual(d['b'], 2)
        d['c'] = 3
        d['a'] = 4
        self.assertEqual(d['c'], 3)
        self.assertEqual(d['a'], 4)
        del d['b']
        self.assertEqual(d, {'a': 4, 'c': 3})

        self.assertRaises(TypeError, d.__getitem__)

        class BadEq(object):
            def __eq__(self, other):
                raise Exc()
            def __hash__(self):
                return 24

        d = NSMutableDictionary({})
        d[BadEq()] = 42
        self.assertRaises(KeyError, d.__getitem__, 23)

        class Exc(Exception): pass

        class BadHash(object):
            fail = False
            def __hash__(self):
                if self.fail:
                    raise Exc()
                else:
                    return 42

        #x = BadHash()
        #d[x] = 42
        #x.fail = True
        #self.assertRaises(Exc, d.__getitem__, x)

    def test_clear(self):
        d = NSMutableDictionary({1:1, 2:2, 3:3})
        d.clear()
        self.assertEqual(d, {})

        self.assertRaises(TypeError, d.clear, None)

    def test_update(self):
        d = NSMutableDictionary({})
        d.update({1:100})
        d.update({2:20})
        d.update({1:1, 2:2, 3:3})
        self.assertEqual(d, {1:1, 2:2, 3:3})

        d.update()
        self.assertEqual(d, {1:1, 2:2, 3:3})

        self.assertRaises((TypeError, AttributeError), d.update, None)

        class SimpleUserDict:
            def __init__(self):
                self.d = {1:1, 2:2, 3:3}
            def keys(self):
                return self.d.keys()
            def __getitem__(self, i):
                return self.d[i]
        d.clear()
        d.update(SimpleUserDict())
        self.assertEqual(d, {1:1, 2:2, 3:3})

        class Exc(Exception): pass

        d.clear()
        class FailingUserDict:
            def keys(self):
                raise Exc()
        self.assertRaises(Exc, d.update, FailingUserDict())

        class FailingUserDict:
            def keys(self):
                class BogonIter:
                    def __init__(self):
                        self.i = 1
                    def __iter__(self):
                        return self
                    def next(self):
                        if self.i:
                            self.i = 0
                            return 'a'
                        raise Exc()
                return BogonIter()
            def __getitem__(self, key):
                return key
        self.assertRaises(Exc, d.update, FailingUserDict())

        class FailingUserDict:
            def keys(self):
                class BogonIter:
                    def __init__(self):
                        self.i = ord('a')
                    def __iter__(self):
                        return self
                    def next(self):
                        if self.i <= ord('z'):
                            rtn = chr(self.i)
                            self.i += 1
                            return rtn
                        raise StopIteration()
                return BogonIter()
            def __getitem__(self, key):
                raise Exc()
        self.assertRaises(Exc, d.update, FailingUserDict())

        class badseq(object):
            def __iter__(self):
                return self
            def next(self):
                raise Exc()

        self.assertRaises(Exc, NSMutableDictionary({}).update, badseq())

        self.assertRaises(ValueError, NSMutableDictionary({}).update, [(1, 2, 3)])

    def test_fromkeys(self):
        self.assertEqual(NSMutableDictionary.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
        d = NSMutableDictionary({})
        self.assertIsNot(d.fromkeys('abc'), d)
        self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
        self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0})
        self.assertEqual(d.fromkeys([]), {})
        def g():
            yield 1
        self.assertEqual(d.fromkeys(g()), {1:None})
        self.assertRaises(TypeError, NSMutableDictionary({}).fromkeys, 3)
        #class dictlike(dict): pass
        #self.assertEqual(dictlike.fromkeys('a'), {'a':None})
        #self.assertEqual(dictlike().fromkeys('a'), {'a':None})
        #self.assertIsInstance(dictlike.fromkeys('a'), dictlike)
        #self.assertIsInstance(dictlike().fromkeys('a'), dictlike)
        #class mydict(dict):
        #    def __new__(cls):
        #        return UserDict.UserDict()
        #ud = mydict.fromkeys('ab')
        #self.assertEqual(ud, {'a':None, 'b':None})
        #self.assertIsInstance(ud, UserDict.UserDict)
        #self.assertRaises(TypeError, dict.fromkeys)

        class Exc(Exception): pass

        #class baddict1(dict):
        #    def __init__(self):
        #        raise Exc()

        #self.assertRaises(Exc, baddict1.fromkeys, [1])

        class BadSeq(object):
            def __iter__(self):
                return self
            def next(self):
                raise Exc()

        self.assertRaises(Exc, NSMutableDictionary.fromkeys, BadSeq())

        #class baddict2(dict):
        #    def __setitem__(self, key, value):
        #        raise Exc()

        #self.assertRaises(Exc, baddict2.fromkeys, [1])

        # test fast path for dictionary inputs
        d = NSMutableDictionary(zip(range(6), range(6)))
        self.assertEqual(NSMutableDictionary.fromkeys(d, 0), NSMutableDictionary(zip(range(6), [0]*6)))

    def test_copy(self):
        d = NSMutableDictionary({1:1, 2:2, 3:3})
        self.assertEqual(d.copy(), {1:1, 2:2, 3:3})
        self.assertEqual(NSMutableDictionary({}).copy(), {})
        self.assertRaises(TypeError, d.copy, None)

    def test_get(self):
        d = NSMutableDictionary({})
        self.assertIs(d.get('c'), None)
        self.assertEqual(d.get('c', 3), 3)
        d = NSMutableDictionary({'a': 1, 'b': 2})
        self.assertIs(d.get('c'), None)
        self.assertEqual(d.get('c', 3), 3)
        self.assertEqual(d.get('a'), 1)
        self.assertEqual(d.get('a', 3), 1)
        self.assertRaises(TypeError, d.get)
        self.assertRaises(TypeError, d.get, None, None, None)

    def test_setdefault(self):
        # dict.setdefault()
        d = NSMutableDictionary({})
        self.assertIs(d.setdefault('key0'), None)
        d.setdefault('key0', [])
        self.assertIs(d.setdefault('key0'), None)
        d.setdefault('key', []).append(3)
        self.assertEqual(d['key'][0], 3)
        d.setdefault('key', []).append(4)
        self.assertEqual(len(d['key']), 2)
        self.assertRaises(TypeError, d.setdefault)

        class Exc(Exception): pass

        class BadHash(object):
            fail = False
            def __hash__(self):
                if self.fail:
                    raise Exc()
                else:
                    return 42

        #x = BadHash()
        #d[x] = 42
        #x.fail = True
        #self.assertRaises(Exc, d.setdefault, x, [])

    def test_popitem(self):
        # dict.popitem()
        for copymode in -1, +1:
            # -1: b has same structure as a
            # +1: b is a.copy()
            for log2size in range(12):
                size = 2**log2size
                a = NSMutableDictionary({})
                b = NSMutableDictionary({})
                for i in range(size):
                    a[repr(i)] = i
                    if copymode < 0:
                        b[repr(i)] = i
                if copymode > 0:
                    b = a.mutableCopy()
                for i in range(size):
                    ka, va = ta = a.popitem()
                    self.assertEqual(va, int(ka))
                    kb, vb = tb = b.popitem()
                    self.assertEqual(vb, int(kb))
                    self.assertFalse(copymode < 0 and ta != tb)
                self.assertFalse(a)
                self.assertFalse(b)

        d = NSMutableDictionary({})
        self.assertRaises(KeyError, d.popitem)

    def test_pop(self):
        # Tests for pop with specified key
        d = NSMutableDictionary({})
        k, v = 'abc', 'def'
        d[k] = v
        self.assertRaises(KeyError, d.pop, 'ghi')

        self.assertEqual(d.pop(k), v)
        self.assertEqual(len(d), 0)

        self.assertRaises(KeyError, d.pop, k)

        # verify longs/ints get same value when key > 32 bits
        # (for 64-bit archs).  See SF bug #689659.
        x = 4503599627370496L
        y = 4503599627370496
        h = NSMutableDictionary({x: 'anything', y: 'something else'})
        self.assertEqual(h[x], h[y])

        self.assertEqual(d.pop(k, v), v)
        d[k] = v
        self.assertEqual(d.pop(k, 1), v)

        self.assertRaises(TypeError, d.pop)

        class Exc(Exception): pass

        class BadHash(object):
            fail = False
            def __hash__(self):
                if self.fail:
                    raise Exc()
                else:
                    return 42

        #x = BadHash()
        #d[x] = 42
        #x.fail = True
        #self.assertRaises(Exc, d.pop, x)

    def test_mutatingiteration(self):
        # XXX: Reimplement iteration using NSFastIteration,
        return

        # changing dict size during iteration
        d = NSMutableDictionary({})
        d[1] = 1
        try:
            for i in d:
                d[i+1] = 1
        except RuntimeError:
            pass
        else:
            self.fail("RuntimeError not raised")

    def test_repr(self): pass
    def test_le(self): pass
    def test_missing(self): pass
    def test_tuple_keyerror(self):
        # SF #1576657
        d = NSMutableDictionary()
        try:
            d[(1,)]
        except KeyError as exc:
            pass
        else:
            fail("KeyError not raised")
        self.assertEqual(exc.args, ((1,),))

    def test_bad_key(self): pass
    def test_resize1(self): pass
    def test_resize2(self): pass
    def test_empty_presized_dict_in_freelist(self): pass
    def test_container_iterator(self): pass
    def test_track_literals(self): pass
    def test_track_dynamic(self): pass
    def test_track_subtypes(self): pass

class GeneralMappingTests (test.test_dict.GeneralMappingTests):
    type2test = NSMutableDictionary


if __name__ == "__main__":
    main()