Debian Codegraph @

tests/linux_kernel/crash_commands/__init__.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 import contextlib
5 import io
6 import os
7 import sys
8 import types
9
10 from drgn.commands._crash.common import CRASH_COMMAND_NAMESPACE
11 from tests import with_default_prog
12 from tests.linux_kernel import LinuxKernelTestCase
13
14
15 class CrashCommandTestCaseBase:
16 """A mix-in to add to a general test case class for testing crash commands"""
17
18 # Run a crash command and capture its stdout and stderr.
19 @classmethod
20 def run_crash_command(cls, command):
21 with contextlib.redirect_stdout(
22 io.StringIO()
23 ) as stdout, contextlib.redirect_stderr(io.StringIO()) as stderr:
24 CRASH_COMMAND_NAMESPACE.run(cls.prog, command)
25 return types.SimpleNamespace(stdout=stdout.getvalue(), stderr=stderr.getvalue())
26
27 # Run a crash command with --drgn. Capture its stdout and check that it
28 # doesn't write anything to stderr.
29 #
30 # mode must be "capture", "compile", or "exec".
31 #
32 # If mode is "compile" or "exec", check that it outputs valid, non-empty
33 # Python code.
34 #
35 # If mode is "exec", also execute the code and capture any globals it sets.
36 def run_crash_command_drgn_option(self, command, mode="exec"):
37 assert mode in {"capture", "compile", "exec"}
38
39 ret = self.run_crash_command(command + " --drgn")
40
41 self.assertFalse(ret.stderr)
42
43 if os.getenv("DRGN_TEST_LOG_CRASH_DRGN"):
44 sys.stderr.write(
45 f"""
46 {'=' * 88}
47 %crash {command} --drgn
48 {'-' * 88}
49 {ret.stdout}\
50 {'=' * 88}
51 """
52 )
53 sys.stderr.flush()
54
55 if mode == "compile" or mode == "exec":
56 self.assertTrue(ret.stdout)
57 ret.code = compile(ret.stdout, command + " --drgn", "exec")
58
59 if mode == "exec":
60 ret.globals = {"prog": self.prog}
61 with with_default_prog(self.prog):
62 exec(ret.stdout, ret.globals)
63
64 return ret
65
66 # Run a crash command with and without --drgn. mode is passed to
67 # run_crash_command_drgn_option().
68 def check_crash_command(self, command, mode="exec"):
69 drgn_option = self.run_crash_command_drgn_option(command, mode)
70
71 ret = self.run_crash_command(command)
72
73 if os.getenv("DRGN_TEST_LOG_CRASH_OUTPUT"):
74 sys.stderr.write(
75 f"""
76 {'=' * 88}
77 %crash {command}
78 {'-' * 88}
79 {ret.stdout}\
80 {'=' * 88}
81 """
82 )
83 sys.stderr.flush()
84
85 ret.drgn_option = drgn_option
86 return ret
87
88
89 class CrashCommandTestCase(CrashCommandTestCaseBase, LinuxKernelTestCase):
90 pass