134
142
for obj in self.hashes_to_check:
135
143
self.assertEqual(hash(obj), _default_hash(obj))
145
class HashRandomizationTests(unittest.TestCase):
147
# Each subclass should define a field "repr_", containing the repr() of
148
# an object to be tested
150
def get_hash_command(self, repr_):
151
return 'print(hash(%s))' % repr_
153
def get_hash(self, repr_, seed=None):
154
env = os.environ.copy()
156
env['PYTHONHASHSEED'] = str(seed)
158
env.pop('PYTHONHASHSEED', None)
159
cmd_line = [sys.executable, '-c', self.get_hash_command(repr_)]
160
p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
161
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
163
out, err = p.communicate()
164
out = test_support.strip_python_stderr(out)
165
return int(out.strip())
167
def test_randomized_hash(self):
168
# two runs should return different hashes
169
run1 = self.get_hash(self.repr_, seed='random')
170
run2 = self.get_hash(self.repr_, seed='random')
171
self.assertNotEqual(run1, run2)
173
class StringlikeHashRandomizationTests(HashRandomizationTests):
174
def test_null_hash(self):
175
# PYTHONHASHSEED=0 disables the randomized hash
177
known_hash_of_obj = 1453079729188098211
179
known_hash_of_obj = -1600925533
181
# Randomization is disabled by default:
182
self.assertEqual(self.get_hash(self.repr_), known_hash_of_obj)
184
# It can also be disabled by setting the seed to 0:
185
self.assertEqual(self.get_hash(self.repr_, seed=0), known_hash_of_obj)
187
def test_fixed_hash(self):
188
# test a fixed seed for the randomized hash
189
# Note that all types share the same values:
191
if sys.byteorder == 'little':
192
h = -4410911502303878509
194
h = -3570150969479994130
196
if sys.byteorder == 'little':
200
self.assertEqual(self.get_hash(self.repr_, seed=42), h)
202
class StrHashRandomizationTests(StringlikeHashRandomizationTests):
205
def test_empty_string(self):
206
self.assertEqual(hash(""), 0)
208
class UnicodeHashRandomizationTests(StringlikeHashRandomizationTests):
211
def test_empty_string(self):
212
self.assertEqual(hash(u""), 0)
214
class BufferHashRandomizationTests(StringlikeHashRandomizationTests):
215
repr_ = 'buffer("abc")'
217
def test_empty_string(self):
218
self.assertEqual(hash(buffer("")), 0)
220
class DatetimeTests(HashRandomizationTests):
221
def get_hash_command(self, repr_):
222
return 'import datetime; print(hash(%s))' % repr_
224
class DatetimeDateTests(DatetimeTests):
225
repr_ = repr(datetime.date(1066, 10, 14))
227
class DatetimeDatetimeTests(DatetimeTests):
228
repr_ = repr(datetime.datetime(1, 2, 3, 4, 5, 6, 7))
230
class DatetimeTimeTests(DatetimeTests):
231
repr_ = repr(datetime.time(0))
138
235
test_support.run_unittest(HashEqualityTestCase,
139
236
HashInheritanceTestCase,
140
HashBuiltinsTestCase)
237
HashBuiltinsTestCase,
238
StrHashRandomizationTests,
239
UnicodeHashRandomizationTests,
240
BufferHashRandomizationTests,
242
DatetimeDatetimeTests,
143
247
if __name__ == "__main__":