Thomas Wouters | 3ccec68 | 2007-08-28 15:28:19 +0000 | [diff] [blame] | 1 | """Unit tests for buffer objects. |
| 2 | |
| 3 | For now, tests just new or changed functionality. |
| 4 | |
| 5 | """ |
| 6 | |
Serhiy Storchaka | b8e54dd | 2015-12-30 20:43:29 +0200 | [diff] [blame] | 7 | import copy |
| 8 | import pickle |
Benjamin Peterson | 550b945 | 2014-06-23 20:12:27 -0700 | [diff] [blame] | 9 | import sys |
Thomas Wouters | 3ccec68 | 2007-08-28 15:28:19 +0000 | [diff] [blame] | 10 | import unittest |
| 11 | from test import test_support |
| 12 | |
| 13 | class BufferTests(unittest.TestCase): |
| 14 | |
| 15 | def test_extended_getslice(self): |
| 16 | # Test extended slicing by comparing with list slicing. |
| 17 | s = "".join(chr(c) for c in list(range(255, -1, -1))) |
| 18 | b = buffer(s) |
| 19 | indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300) |
| 20 | for start in indices: |
| 21 | for stop in indices: |
| 22 | # Skip step 0 (invalid) |
| 23 | for step in indices[1:]: |
| 24 | self.assertEqual(b[start:stop:step], |
| 25 | s[start:stop:step]) |
| 26 | |
Kristján Valur Jónsson | 1d108bc | 2013-03-19 16:50:51 -0700 | [diff] [blame] | 27 | def test_newbuffer_interface(self): |
| 28 | # Test that the buffer object has the new buffer interface |
| 29 | # as used by the memoryview object |
| 30 | s = "".join(chr(c) for c in list(range(255, -1, -1))) |
| 31 | b = buffer(s) |
| 32 | m = memoryview(b) # Should not raise an exception |
| 33 | self.assertEqual(m.tobytes(), s) |
| 34 | |
Benjamin Peterson | 550b945 | 2014-06-23 20:12:27 -0700 | [diff] [blame] | 35 | def test_large_buffer_size_and_offset(self): |
| 36 | data = bytearray('hola mundo') |
| 37 | buf = buffer(data, sys.maxsize, sys.maxsize) |
| 38 | self.assertEqual(buf[:4096], "") |
| 39 | |
Serhiy Storchaka | b8e54dd | 2015-12-30 20:43:29 +0200 | [diff] [blame] | 40 | def test_copy(self): |
| 41 | buf = buffer(b'abc') |
| 42 | with self.assertRaises(TypeError): |
| 43 | copy.copy(buf) |
| 44 | |
| 45 | def test_pickle(self): |
| 46 | buf = buffer(b'abc') |
| 47 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 48 | with self.assertRaises(TypeError): |
| 49 | pickle.dumps(buf, proto) |
| 50 | |
Thomas Wouters | 3ccec68 | 2007-08-28 15:28:19 +0000 | [diff] [blame] | 51 | |
| 52 | def test_main(): |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 53 | with test_support.check_py3k_warnings(("buffer.. not supported", |
| 54 | DeprecationWarning)): |
| 55 | test_support.run_unittest(BufferTests) |
Thomas Wouters | 3ccec68 | 2007-08-28 15:28:19 +0000 | [diff] [blame] | 56 | |
| 57 | if __name__ == "__main__": |
| 58 | test_main() |