From 0c44ec9233960a3ca21f32d2952c2add7314e3f7 Mon Sep 17 00:00:00 2001 From: Kevin McCarthy Date: Sun, 8 Jun 2014 22:09:25 -1000 Subject: [PATCH] Restore random seed function for byte endpoints os.urandom() ignores random.seed(), so I'm restoring the use of random.randint in a python3 compatible way. --- httpbin/core.py | 14 ++++++++------ test_httpbin.py | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/httpbin/core.py b/httpbin/core.py index 9b81d68..26156a6 100644 --- a/httpbin/core.py +++ b/httpbin/core.py @@ -458,7 +458,9 @@ def random_bytes(n): random.seed(int(params['seed'])) response = make_response() - response.data = os.urandom(n) + + # Note: can't just use os.urandom here because it ignores the seed + response.data = bytearray(random.randint(0, 255) for i in range(n)) response.content_type = 'application/octet-stream' return response @@ -478,16 +480,16 @@ def stream_random_bytes(n): chunk_size = 10 * 1024 def generate_bytes(): - chunks = [] + chunks = bytearray() for i in xrange(n): - chunks.append(os.urandom(1)) + chunks.append(random.randint(0, 255)) if len(chunks) == chunk_size: - yield(bytes().join(chunks)) - chunks = [] + yield(bytes(chunks)) + chunks = bytearray() if chunks: - yield(bytes().join(chunks)) + yield(bytes(chunks)) headers = {'Transfer-Encoding': 'chunked', 'Content-Type': 'application/octet-stream'} diff --git a/test_httpbin.py b/test_httpbin.py index 624b64b..d7aff75 100755 --- a/test_httpbin.py +++ b/test_httpbin.py @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- import base64 import unittest +import six from werkzeug.http import parse_dict_header from hashlib import md5 from six import BytesIO @@ -134,11 +135,31 @@ class HttpbinTestCase(unittest.TestCase): self.assertEqual(len(response.get_data()), 1024) self.assertEqual(response.status_code, 200) + def test_bytes_with_seed(self): + response = self.app.get('/bytes/10?seed=0') + # The RNG changed in python3, so even though we are + # setting the seed, we can't expect the value to be the + # same across both interpreters. + if six.PY3: + self.assertEqual(response.data, b'\xc5\xd7\x14\x84\xf8\xcf\x9b\xf4\xb7o') + else: + self.assertEqual(response.data, b'\xd8\xc2kB\x82g\xc8Mz\x95') + def test_stream_bytes(self): response = self.app.get('/stream-bytes/1024') self.assertEqual(len(response.get_data()), 1024) self.assertEqual(response.status_code, 200) + def test_stream_bytes_with_seed(self): + response = self.app.get('/stream-bytes/10?seed=0') + # The RNG changed in python3, so even though we are + # setting the seed, we can't expect the value to be the + # same across both interpreters. + if six.PY3: + self.assertEqual(response.data, b'\xc5\xd7\x14\x84\xf8\xcf\x9b\xf4\xb7o') + else: + self.assertEqual(response.data, b'\xd8\xc2kB\x82g\xc8Mz\x95') + if __name__ == '__main__': unittest.main()