| 1 | #!/usr/bin/python |
| 2 | |
| 3 | from itertools import imap |
| 4 | import unittest, sys, findbits |
| 5 | |
| 6 | class TestFindBits(unittest.TestCase): |
| 7 | def setUp(self): |
| 8 | self.old_stdout = sys.stdout |
| 9 | sys.stdout = OutputBuffer() |
| 10 | |
| 11 | def tearDown(self): |
| 12 | sys.stdout = self.old_stdout |
| 13 | |
| 14 | INVERT_CASES = [ |
| 15 | ('10', '01'), |
| 16 | ('', ''), |
| 17 | ] |
| 18 | def test_invert(self): |
| 19 | self.commutative_test(findbits.invert, self.INVERT_CASES) |
| 20 | |
| 21 | SEARCH_CASES = [ |
| 22 | ('1111', '10111101', ['Match at bit 2', '0<1111>0']), |
| 23 | ('00', '10111101', ['Not found']), |
| 24 | ] |
| 25 | def test_search(self): |
| 26 | for target, data, expected_fragments in self.SEARCH_CASES: |
| 27 | sys.stdout.clear_buffer() |
| 28 | findbits.search(target, data) |
| 29 | for fragment in expected_fragments: |
| 30 | self.assertIn(fragment, sys.stdout.content) |
| 31 | |
| 32 | BINSTRING_CASES = [ |
| 33 | (42, '101010'), |
| 34 | (1, '1'), |
| 35 | (0, ''), |
| 36 | ] |
| 37 | def test_binstring(self): |
| 38 | self.unary_operation_test(findbits.binstring, self.BINSTRING_CASES) |
| 39 | |
| 40 | REVERSE_CASES = [ |
| 41 | ('abc', 'cba'), |
| 42 | ('', ''), |
| 43 | ] |
| 44 | def test_stringreverse(self): |
| 45 | self.commutative_test(findbits.stringreverse, self.REVERSE_CASES) |
| 46 | |
| 47 | def commutative_test(self, operation, cases): |
| 48 | self.unary_operation_test(operation, cases) |
| 49 | self.unary_operation_test(operation, imap(reversed, cases)) |
| 50 | |
| 51 | def unary_operation_test(self, operation, cases): |
| 52 | for case_in, case_out in cases: |
| 53 | self.assertEqual(operation(case_in), case_out) |
| 54 | |
| 55 | |
| 56 | class OutputBuffer(object): |
| 57 | def __init__(self): |
| 58 | self.clear_buffer() |
| 59 | |
| 60 | def clear_buffer(self): |
| 61 | self.content = '' |
| 62 | |
| 63 | def write(self, data): |
| 64 | self.content += data |
| 65 | |
| 66 | |
| 67 | if __name__ == '__main__': |
| 68 | unittest.main() |