From: <zy...@us...> - 2009-03-22 03:00:56
|
Revision: 6106 http://jython.svn.sourceforge.net/jython/?rev=6106&view=rev Author: zyasoft Date: 2009-03-22 03:00:51 +0000 (Sun, 22 Mar 2009) Log Message: ----------- dict() now can be constructed from a Map in user-level code. This fixes bug #1146. Modified Paths: -------------- trunk/jython/Lib/test/test_dict_jy.py trunk/jython/src/org/python/core/PyDictionary.java Modified: trunk/jython/Lib/test/test_dict_jy.py =================================================================== --- trunk/jython/Lib/test/test_dict_jy.py 2009-03-21 22:29:19 UTC (rev 6105) +++ trunk/jython/Lib/test/test_dict_jy.py 2009-03-22 03:00:51 UTC (rev 6106) @@ -1,4 +1,5 @@ from test import test_support +import java import unittest class DictInitTest(unittest.TestCase): @@ -93,9 +94,29 @@ raise CustomKeyError("custom message") self.assertRaises(CustomKeyError, lambda: DerivedDict()['foo']) +class JavaIntegrationTest(unittest.TestCase): + "Tests for instantiating dicts from Java maps and hashtables" + def test_hashmap(self): + x = java.util.HashMap() + x.put('a', 1) + x.put('b', 2) + x.put('c', 3) + x.put((1,2), "xyz") + y = dict(x) + self.assertEqual(set(y.items()), set([('a', 1), ('b', 2), ('c', 3), ((1,2), "xyz")])) + def test_hashtable(self): + x = java.util.Hashtable() + x.put('a', 1) + x.put('b', 2) + x.put('c', 3) + x.put((1,2), "xyz") + y = dict(x) + self.assertEqual(set(y.items()), set([('a', 1), ('b', 2), ('c', 3), ((1,2), "xyz")])) + + def test_main(): - test_support.run_unittest(DictInitTest, DictCmpTest, DerivedDictTest) + test_support.run_unittest(DictInitTest, DictCmpTest, DerivedDictTest, JavaIntegrationTest) if __name__ == '__main__': test_main() Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2009-03-21 22:29:19 UTC (rev 6105) +++ trunk/jython/src/org/python/core/PyDictionary.java 2009-03-22 03:00:51 UTC (rev 6106) @@ -4,6 +4,7 @@ import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; +import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -421,7 +422,12 @@ } if (nargs == 1) { PyObject arg = args[0]; - if (arg.__findattr__("keys") != null) { + + Object proxy = arg.getJavaProxy(); + if (proxy instanceof Map) { + merge((Map)proxy); + } + else if (arg.__findattr__("keys") != null) { merge(arg); } else { mergeFromSeq(arg); @@ -432,6 +438,13 @@ } } + private void merge(Map<Object,Object> other) { + for (Entry<Object,Object> entry : other.entrySet()) { + dict___setitem__(Py.java2py(entry.getKey()), Py.java2py(entry.getValue())); + } + } + + /** * Merge another PyObject that supports keys() with this * dict. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |