drgn/tests/test_corereader.py
Omar Sandoval 6a6d37c5e1 Make Program and CoreReader context managers
This is preparation for the next change, so that a Program can clean up
after itself. The Program will close the CoreReader, and the CoreReader
will close the underlying file.
2018-07-11 19:16:34 -07:00

73 lines
2.5 KiB
Python

import contextlib
import tempfile
import unittest
from drgn.corereader import CoreReader
@contextlib.contextmanager
def tmpfile(data):
file = tempfile.TemporaryFile()
try:
file.write(data)
file.flush()
yield file
finally:
file.close()
class TestCoreReader(unittest.TestCase):
def test_bad_segments(self):
with tmpfile(b'') as file:
self.assertRaises(TypeError, CoreReader, file, 0)
self.assertRaises(TypeError, CoreReader, file, [0])
self.assertRaises(ValueError, CoreReader, file, [()])
self.assertRaises(OverflowError, CoreReader, file,
[(2**64, 0, 0, 0, 0)])
def test_simple_read(self):
data = b'hello, world!'
segments = [(0, 0xffff0000, 0x0, len(data), len(data))]
with tmpfile(data) as file:
core_reader = CoreReader(file, segments)
self.assertEqual(core_reader.read(0xffff0000, len(data)), data)
def test_bad_address(self):
data = b'hello, world!'
segments = [(0, 0xffff0000, 0x0, len(data), len(data))]
with tmpfile(data) as file:
core_reader = CoreReader(file, segments)
self.assertRaisesRegex(ValueError, 'could not find memory segment',
core_reader.read, 0xdeadbeef, 4)
def test_segment_overflow(self):
data = b'hello, world!'
segments = [(0, 0xffff0000, 0x0, len(data), len(data))]
with tmpfile(data) as file:
core_reader = CoreReader(file, segments)
self.assertRaisesRegex(ValueError, 'could not find memory segment',
core_reader.read, 0xffff0000, len(data) + 1)
def test_contiguous_segments(self):
data = b'hello, world!\0foobar'
segments = [
(0, 0xffff0000, 0x0, 4, 4),
(14, 0xfffff000, 0x0, 6, 6),
(4, 0xffff0004, 0x0, 10, 10),
]
with tmpfile(data) as file:
core_reader = CoreReader(file, segments)
self.assertEqual(core_reader.read(0xffff0000, 14), data[:14])
def test_zero_filled_segment(self):
data = b'hello, world!'
segments = [
(0, 0xffff0000, 0x0, 13, 17),
]
with tmpfile(data) as file:
core_reader = CoreReader(file, segments)
self.assertEqual(core_reader.read(0xffff0000, len(data) + 4),
data + bytes(4))
self.assertEqual(core_reader.read(0xffff0000 + len(data), 4),
bytes(4))