Zack Williams | 41513bf | 2018-07-07 20:08:35 -0700 | [diff] [blame] | 1 | # Copyright 2017-present Open Networking Foundation |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
Zsolt Haraszti | dafefe1 | 2016-11-14 21:29:58 -0800 | [diff] [blame] | 14 | from unittest import TestCase, main |
| 15 | |
| 16 | from common.utils.ordered_weakvalue_dict import OrderedWeakValueDict |
| 17 | |
| 18 | |
| 19 | class O(object): |
| 20 | def __init__(self, a): |
| 21 | self.a = a |
| 22 | |
| 23 | |
| 24 | class TestOrderedWeakValueDict(TestCase): |
| 25 | |
| 26 | def test_standard_behavior(self): |
| 27 | holder = dict() # a real dict so we can control which object real ref |
| 28 | def mk(k): |
| 29 | o = O(k) |
| 30 | holder[k] = o |
| 31 | return o |
| 32 | o = OrderedWeakValueDict((k, mk(k)) for k in xrange(10)) |
| 33 | self.assertEqual(len(o), 10) |
| 34 | self.assertEqual(o[3].a, 3) |
| 35 | o[3] = mk(-3) |
| 36 | self.assertEqual(o[3].a, -3) |
| 37 | del o[3] |
| 38 | self.assertEqual(len(o), 9) |
| 39 | o[100] = mk(100) |
| 40 | self.assertEqual(len(o), 10) |
| 41 | self.assertEqual(o.keys(), [0, 1, 2, 4, 5, 6, 7, 8, 9, 100]) |
| 42 | |
| 43 | # remove a few items from the holder, they should be gone from o too |
| 44 | del holder[1] |
| 45 | del holder[5] |
| 46 | del holder[6] |
| 47 | |
| 48 | self.assertEqual(o.keys(), [0, 2, 4, 7, 8, 9, 100]) |
| 49 | self.assertEqual([v.a for v in o.values()], [0, 2, 4, 7, 8, 9, 100]) |
| 50 | |
| 51 | |