blob: c7114cde8b9baf59e9456616b722b2e75d7dfdf4 [file] [log] [blame]
Thomas Wouters3ccec682007-08-28 15:28:19 +00001"""Unit tests for buffer objects.
2
3For now, tests just new or changed functionality.
4
5"""
6
Serhiy Storchakab8e54dd2015-12-30 20:43:29 +02007import copy
8import pickle
Benjamin Peterson550b9452014-06-23 20:12:27 -07009import sys
Thomas Wouters3ccec682007-08-28 15:28:19 +000010import unittest
Serhiy Storchaka3dd1ccb2017-08-02 11:33:33 +030011import warnings
Thomas Wouters3ccec682007-08-28 15:28:19 +000012from test import test_support
13
14class BufferTests(unittest.TestCase):
15
16 def test_extended_getslice(self):
17 # Test extended slicing by comparing with list slicing.
18 s = "".join(chr(c) for c in list(range(255, -1, -1)))
19 b = buffer(s)
20 indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
21 for start in indices:
22 for stop in indices:
23 # Skip step 0 (invalid)
24 for step in indices[1:]:
25 self.assertEqual(b[start:stop:step],
26 s[start:stop:step])
27
Kristján Valur Jónsson1d108bc2013-03-19 16:50:51 -070028 def test_newbuffer_interface(self):
29 # Test that the buffer object has the new buffer interface
30 # as used by the memoryview object
31 s = "".join(chr(c) for c in list(range(255, -1, -1)))
32 b = buffer(s)
33 m = memoryview(b) # Should not raise an exception
34 self.assertEqual(m.tobytes(), s)
35
Benjamin Peterson550b9452014-06-23 20:12:27 -070036 def test_large_buffer_size_and_offset(self):
37 data = bytearray('hola mundo')
38 buf = buffer(data, sys.maxsize, sys.maxsize)
39 self.assertEqual(buf[:4096], "")
40
Serhiy Storchakab8e54dd2015-12-30 20:43:29 +020041 def test_copy(self):
42 buf = buffer(b'abc')
Serhiy Storchaka3dd1ccb2017-08-02 11:33:33 +030043 with self.assertRaises(TypeError), warnings.catch_warnings():
44 warnings.filterwarnings('ignore', ".*buffer", DeprecationWarning)
Serhiy Storchakab8e54dd2015-12-30 20:43:29 +020045 copy.copy(buf)
46
Serhiy Storchaka3dd1ccb2017-08-02 11:33:33 +030047 @test_support.cpython_only
48 def test_pickle(self):
49 buf = buffer(b'abc')
50 for proto in range(2):
51 with self.assertRaises(TypeError):
52 pickle.dumps(buf, proto)
53 with test_support.check_py3k_warnings(
54 (".*buffer", DeprecationWarning)):
55 pickle.dumps(buf, 2)
Serhiy Storchakab8e54dd2015-12-30 20:43:29 +020056
Thomas Wouters3ccec682007-08-28 15:28:19 +000057
58def test_main():
Florent Xicluna07627882010-03-21 01:14:24 +000059 with test_support.check_py3k_warnings(("buffer.. not supported",
60 DeprecationWarning)):
61 test_support.run_unittest(BufferTests)
Thomas Wouters3ccec682007-08-28 15:28:19 +000062
63if __name__ == "__main__":
64 test_main()