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.
This commit is contained in:
Kevin McCarthy
2014-06-08 22:09:25 -10:00
parent dcb6f7ded6
commit 0c44ec9233
2 changed files with 29 additions and 6 deletions
+8 -6
View File
@@ -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'}
+21
View File
@@ -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()