summaryrefslogtreecommitdiff
path: root/cleopatre/devkit/tests/fw_wd/run-test
blob: ce1d77218e956cda222a68981c479ef57ac6682c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#!/usr/bin/python
"""Test FW watch daemon."""
from shutil import copy, rmtree
from os import symlink, mkdir, chmod
import sys
import subprocess
import gzip
import time

busybox_path = '../common/busybox/busybox'
fw_wd_path = '../../../application/fw_wd'

trace_content = """\
Test trace line 1
Test trace line 2
Test trace line 3
Test trace line 4
Test trace line 5
"""

trace_files_content = {
'/etc/hpav.info': """\
hpav.info file line 1
hpav.info file line 2
""",
'/proc/uptime': """\
uptime line 1
""",
}

fw_wd_stub = """\
#!/bin/sh
test -f /tmp/fw_wd_run && echo "fw_wd stop test" && exit 1
touch /tmp/fw_wd_run
echo "fw_wd run"
exit %(retcode)s
"""

fw_wd_wait_stub = """\
#!/bin/sh
echo "fw_wd run"
trap : TERM
sleep 100 &
pid=$!
wait $pid
kill $pid
"""

reboot_stub = """\
#!/bin/sh
echo "reboot run"
exit %(retcode)s
"""

default_content = """\
REBOOT=%(reboot)s
TRACE_ENABLED=%(trace_enabled)s
TRACE_FOLDER="/usr/local/trace/"
TRACE_FILES="%(trace_files)s"
TRACE_CMDS="%(trace_cmds)s"
"""

chroot_env = {
        'PATH': '/bin:/sbin:/usr/bin:/usr/sbin',
        'USER': 'testuser',
        'SHELL': '/bin/sh',
        }

trace_cmds = [ [ ], [ 'echo choucroute' ] ]
trace_cmds_result = [ [ ], [ 'choucroute\n' ] ]

class TestParams:
    def __init__(self, test_name, **kw):
        self.test_name = test_name
        self.fw_wd_retcode = 0
        self.reboot = True
        self.reboot_retcode = 0
        self.trace_enabled = True
        self.trace_present = True
        self.trace_files = [ '/proc/uptime', '/etc/hpav.info' ]
        self.trace_cmds_test = False
        self.trace_dir = True
        self.old_traces = [ ]
        self.kill = False
        self.__dict__.update(kw)

def chroot_call(root_path, command):
    """Call a command in the chrooted environment, raise error on any
    problem."""
    subprocess.check_call([ 'fakechroot', '/usr/sbin/chroot', root_path ] +
            command)

def create_file(root_path, filename, content, executable=False):
    """Create a text file in rootfs with given content.  Give execution
    permissions if requested."""
    f = open(root_path + filename, 'w')
    f.write(content)
    f.close()
    if executable:
        chmod(root_path + filename, 0755)

def create_rootfs(root_path, test_params):
    """Create a full rootfs from given test parameters.  Clean up if rootfs is
    existent."""
    # Create basic rootfs.
    rmtree(root_path, ignore_errors=True)
    mkdir(root_path)
    for p in [ '/bin', '/sbin', '/usr', '/usr/bin', '/usr/sbin', '/usr/local',
            '/proc', '/proc/self', '/dev', '/etc', '/etc/default', '/tmp' ]:
        mkdir(root_path + p)
    copy(busybox_path, root_path + '/bin')
    symlink('/bin/busybox', root_path + '/proc/self/exe')
    chroot_call(root_path, [ '/bin/busybox', '--install', '-s' ])
    copy(fw_wd_path + '/fwwatchd', root_path + '/usr/bin')
    create_file(root_path, '/dev/null', '')
    # Create test stubs.
    if not test_params.kill:
        create_file(root_path, '/usr/bin/fw_wd',
                fw_wd_stub % { 'retcode': test_params.fw_wd_retcode },
                executable=True)
    else:
        create_file(root_path, '/usr/bin/fw_wd', fw_wd_wait_stub,
                executable=True)
    create_file(root_path, '/sbin/reboot',
            reboot_stub % { 'retcode': test_params.reboot_retcode },
            executable=True)
    if test_params.trace_present:
        create_file(root_path, '/dev/trace', trace_content)
    for f in test_params.trace_files:
        create_file(root_path, f, trace_files_content[f])
    if test_params.trace_dir:
        mkdir(root_path + '/usr/local/trace')
    for i in test_params.old_traces:
        create_file(root_path, '/usr/local/trace/trace_%d.gz' % i,
                'Old trace %d' % i)
    # Create default file.
    def bool_value(b):
        return 'true' if b else 'false'
    def list_value(l):
        return ':'.join(l)
    create_file(root_path, '/etc/default/fwwatchd', default_content % {
        'reboot': bool_value(test_params.reboot),
        'trace_enabled': bool_value(test_params.trace_enabled),
        'trace_files': list_value(test_params.trace_files),
        'trace_cmds': list_value(trace_cmds[test_params.trace_cmds_test]),
        })

def check(root_path, test_params, stdout):
    """Check test result."""
    # Check stdout.
    if not test_params.trace_enabled:
        expected_stdout = ''
    else:
        expected_stdout = 'fw_wd run\n'
        if test_params.fw_wd_retcode == 0 and not test_params.kill:
            if test_params.reboot:
                expected_stdout += 'reboot run\n'
                if test_params.reboot_retcode == 0:
                    expected_stdout += 'fw_wd stop test\n'
    if expected_stdout != stdout:
        print test_params.test_name, "failed (%s != %s)" % (repr(stdout),
                repr(expected_stdout))
        return False
    # Check trace file.
    expected_trace = ''
    expected_last_head_trace = ''
    if test_params.trace_enabled and test_params.fw_wd_retcode == 0 \
            and not test_params.kill:
        if test_params.trace_present:
            expected_last_head_trace = \
                    '\n'.join(trace_content.split('\n')[0:3]) + '\n'
            expected_trace += expected_last_head_trace + trace_content
        for f in test_params.trace_files:
            expected_trace += "==== %s ====\n" % f
            expected_trace += trace_files_content[f]
            expected_trace += "\n"
        for cmd, result in zip(trace_cmds[test_params.trace_cmds_test],
                trace_cmds_result[test_params.trace_cmds_test]):
            expected_trace += "==== %s ====\n" % cmd
            expected_trace += result
            expected_trace += "\n"
    expected_trace_nb = max(test_params.old_traces + [ 0 ] ) + 1
    expected_file_name = '/usr/local/trace/trace_%d.gz' % expected_trace_nb
    try:
        f = gzip.open(root_path + expected_file_name)
        if not expected_trace:
            print test_params.test_name, \
                    "failed (%s exists)" % expected_file_name
            return False
        else:
            trace = f.read()
            if expected_trace != trace:
                print test_params.test_name, "failed"
                print "expected trace:\n", expected_trace
                print "trace:\n", trace
                return False
        f.close()
    except IOError:
        if expected_trace:
            print test_params.test_name, \
                    "failed (can not open %s)" % expected_file_name
            return False
    return True

def run_test(root_path, test_params):
    """Run FW watch daemon in a chrooted environment and check result.  Return
    a number of failed test."""
    create_rootfs('root', test_params)
    proc = subprocess.Popen([ 'fakechroot', '/usr/sbin/chroot', root_path,
        '/usr/bin/fwwatchd' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        env=chroot_env)
    if test_params.kill:
        time.sleep(0.1)
        proc.terminate()
    stdout = proc.communicate()[0]
    result = check('root', test_params, stdout)
    return 0 if result else 1

if __name__ == '__main__':
    failed = 0
    tp = TestParams("default params")
    failed += run_test('root', tp)
    # Watchdog test.
    tp = TestParams("fw_wd fail", fw_wd_retcode=1)
    failed += run_test('root', tp)
    tp = TestParams("kill script", kill=True)
    failed += run_test('root', tp)
    # Trace tests.
    tp = TestParams("trace disabled", trace_enabled=False)
    failed += run_test('root', tp)
    tp = TestParams("trace not available", trace_present=False)
    failed += run_test('root', tp)
    tp = TestParams("no trace files", trace_files=[ ])
    failed += run_test('root', tp)
    tp = TestParams("trace commands", trace_cmds_test=True)
    failed += run_test('root', tp)
    tp = TestParams("no trace dir", trace_dir=False)
    failed += run_test('root', tp)
    tp = TestParams("old traces", old_traces=[ 1, 2, 8 ])
    failed += run_test('root', tp)
    # Reboot tests.
    tp = TestParams("no reboot", reboot=False)
    failed += run_test('root', tp)
    tp = TestParams("reboot fail", reboot_retcode=1)
    failed += run_test('root', tp)
    # Bye.
    print "failed %d tests" % failed
    sys.exit (1 if failed else 0)