2012-06-21 04:21:13 +08:00
|
|
|
#!/usr/bin/python
|
|
|
|
|
|
|
|
from itertools import imap
|
|
|
|
import unittest, sys, findbits
|
|
|
|
|
|
|
|
class TestFindBits(unittest.TestCase):
|
2019-03-09 17:52:45 +08:00
|
|
|
def setUp(self):
|
|
|
|
self.old_stdout = sys.stdout
|
|
|
|
sys.stdout = OutputBuffer()
|
2012-06-21 04:21:13 +08:00
|
|
|
|
2019-03-09 17:52:45 +08:00
|
|
|
def tearDown(self):
|
|
|
|
sys.stdout = self.old_stdout
|
2012-06-21 04:21:13 +08:00
|
|
|
|
2019-03-09 17:52:45 +08:00
|
|
|
INVERT_CASES = [
|
|
|
|
('10', '01'),
|
|
|
|
('', ''),
|
|
|
|
]
|
|
|
|
def test_invert(self):
|
|
|
|
self.commutative_test(findbits.invert, self.INVERT_CASES)
|
2012-06-21 04:21:13 +08:00
|
|
|
|
2019-03-09 17:52:45 +08:00
|
|
|
SEARCH_CASES = [
|
|
|
|
('1111', '10111101', ['Match at bit 2', '0<1111>0']),
|
|
|
|
('00', '10111101', ['Not found']),
|
|
|
|
]
|
|
|
|
def test_search(self):
|
|
|
|
for target, data, expected_fragments in self.SEARCH_CASES:
|
|
|
|
sys.stdout.clear_buffer()
|
|
|
|
findbits.search(target, data)
|
|
|
|
for fragment in expected_fragments:
|
|
|
|
self.assertIn(fragment, sys.stdout.content)
|
2012-06-21 04:21:13 +08:00
|
|
|
|
2019-03-09 17:52:45 +08:00
|
|
|
BINSTRING_CASES = [
|
|
|
|
(42, '101010'),
|
|
|
|
(1, '1'),
|
|
|
|
(0, ''),
|
|
|
|
]
|
|
|
|
def test_binstring(self):
|
|
|
|
self.unary_operation_test(findbits.binstring, self.BINSTRING_CASES)
|
2012-06-21 04:21:13 +08:00
|
|
|
|
2019-03-09 17:52:45 +08:00
|
|
|
REVERSE_CASES = [
|
|
|
|
('abc', 'cba'),
|
|
|
|
('', ''),
|
|
|
|
]
|
|
|
|
def test_stringreverse(self):
|
|
|
|
self.commutative_test(findbits.stringreverse, self.REVERSE_CASES)
|
2012-06-21 04:21:13 +08:00
|
|
|
|
2019-03-09 17:52:45 +08:00
|
|
|
def commutative_test(self, operation, cases):
|
|
|
|
self.unary_operation_test(operation, cases)
|
|
|
|
self.unary_operation_test(operation, imap(reversed, cases))
|
2012-06-21 04:21:13 +08:00
|
|
|
|
2019-03-09 17:52:45 +08:00
|
|
|
def unary_operation_test(self, operation, cases):
|
|
|
|
for case_in, case_out in cases:
|
|
|
|
self.assertEqual(operation(case_in), case_out)
|
2012-06-21 04:21:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
class OutputBuffer(object):
|
2019-03-09 17:52:45 +08:00
|
|
|
def __init__(self):
|
|
|
|
self.clear_buffer()
|
2018-01-10 02:17:21 +08:00
|
|
|
|
2019-03-09 17:52:45 +08:00
|
|
|
def clear_buffer(self):
|
|
|
|
self.content = ''
|
2018-01-10 02:17:21 +08:00
|
|
|
|
2019-03-09 17:52:45 +08:00
|
|
|
def write(self, data):
|
|
|
|
self.content += data
|
2012-06-21 04:21:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2019-03-09 17:52:45 +08:00
|
|
|
unittest.main()
|