1 #!/usr/bin/env python2
2 """
3 builtin_lib_test.py: Tests for builtin_lib.py
4 """
5 from __future__ import print_function
6
7 import cStringIO
8 import unittest
9 # We use native/line_input.c, a fork of readline.c, but this is good enough for
10 # unit testing
11 import readline
12
13 from core import test_lib
14 from core import state
15 from core import alloc
16 from core import ui
17 from frontend import flag_def # side effect: flags are defined!
18
19 _ = flag_def
20 from osh import builtin_lib # module under test
21
22
23 class BuiltinTest(unittest.TestCase):
24 def testHistoryBuiltin(self):
25 test_path = '_tmp/builtin_test_history.txt'
26 with open(test_path, 'w') as f:
27 f.write("""\
28 echo hello
29 ls one/
30 ls two/
31 echo bye
32 """)
33 readline.read_history_file(test_path)
34
35 # Show all
36 f = cStringIO.StringIO()
37 out = _TestHistory(['history'])
38
39 self.assertEqual(
40 out, """\
41 1 echo hello
42 2 ls one/
43 3 ls two/
44 4 echo bye
45 """)
46
47 # Show two history items
48 out = _TestHistory(['history', '2'])
49 # Note: whitespace here is exact
50 self.assertEqual(out, """\
51 3 ls two/
52 4 echo bye
53 """)
54
55 # Delete single history item.
56 # This functionality is *silent*
57 # so call history again after
58 # this to feed the test assertion
59
60 _TestHistory(['history', '-d', '4'])
61
62 # Call history
63 out = _TestHistory(['history'])
64
65 # Note: whitespace here is exact
66 self.assertEqual(
67 out, """\
68 1 echo hello
69 2 ls one/
70 3 ls two/
71 """)
72
73 # Clear history
74 # This functionality is *silent*
75 # so call history again after
76 # this to feed the test assertion
77
78 _TestHistory(['history', '-c'])
79
80 # Call history
81 out = _TestHistory(['history'])
82
83 self.assertEqual(out, """\
84 """)
85
86
87 def _TestHistory(argv):
88 f = cStringIO.StringIO()
89 arena = alloc.Arena()
90 mem = state.Mem('', [], arena, [])
91 errfmt = ui.ErrorFormatter()
92 b = builtin_lib.History(readline, mem, errfmt, f)
93 cmd_val = test_lib.MakeBuiltinArgv(argv)
94 b.Run(cmd_val)
95 return f.getvalue()
96
97
98 if __name__ == '__main__':
99 unittest.main()