java_map_test.py
2.27 KB
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
"""
Created on Feb 5, 2010
@author: barthelemy
"""
from __future__ import unicode_literals, absolute_import
import unittest
from py4j.java_gateway import JavaGateway, GatewayParameters
from py4j.tests.java_gateway_test import (
start_example_app_process, safe_shutdown, sleep)
def get_map():
return {"a": 1, "b": 2.0, "c": "z"}
class AutoConvertTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
self.gateway = JavaGateway(
gateway_parameters=GatewayParameters(auto_convert=True))
def tearDown(self):
safe_shutdown(self)
self.p.join()
sleep()
def testAutoConvert(self):
dj = self.gateway.jvm.java.util.HashMap()
dj["b"] = 2
dj["a"] = 1
dp = {"a": 1, "b": 2}
self.assertTrue(dj.equals(dp))
class MapTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
self.gateway = JavaGateway()
def tearDown(self):
safe_shutdown(self)
self.p.join()
sleep()
def equal_maps(self, m1, m2):
if len(m1) == len(m2):
equal = True
for k in m1:
equal = m1[k] == m2[k]
if not equal:
break
return equal
else:
return False
def testMap(self):
dp0 = {}
dp = get_map()
dj = self.gateway.jvm.java.util.HashMap()
self.equal_maps(dj, dp0)
dj["a"] = 1
dj["b"] = 2.0
dj["c"] = "z"
self.equal_maps(dj, dp)
del(dj["a"])
del(dp["a"])
dj2 = self.gateway.jvm.java.util.HashMap()
dj2["b"] = 2.0
dj2["c"] = "z"
dj3 = self.gateway.jvm.java.util.HashMap()
dj3["a"] = 1
dj3["b"] = 2.0
dj3["c"] = "z"
self.equal_maps(dj, dp)
self.assertEqual(dj, dj)
self.assertEqual(dj, dj2)
# Does not always work for some reason...
# Probably not worth supporting for now...
# self.assertLess(dj, dj3)
self.assertNotEqual(dj, dp)
dps = {1: 1, 2: 2}
djs = self.gateway.jvm.java.util.HashMap()
djs[1] = 1
djs[2] = 2
self.assertEqual(str(djs), str(dps))
if __name__ == "__main__":
unittest.main()