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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
|
# Copyright (c) Meta Platforms, Inc. and affiliates.
# SPDX-License-Identifier: LGPL-2.1-or-later
import ast
import contextlib
import io
from pathlib import Path
import sys
import tempfile
import unittest.mock
from drgn.commands import (
CommandArgumentError,
CommandExitStatusError,
CommandNamespace,
CommandNotFoundError,
DrgnCodeBuilder,
ParsedCommand,
_repr_black,
_repr_raw_bytes,
_sanitize_rst,
argument,
command,
parse_shell_command,
raw_command,
)
from tests import TestCase
class TestParseShellCommand(TestCase):
def assert_parses_to(self, source, *, args, redirections=[], pipeline=None):
self.assertEqual(
parse_shell_command(source),
ParsedCommand(args=args, redirections=redirections, pipeline=pipeline),
)
def test_one_arg(self):
self.assert_parses_to("foo", args=["foo"])
def test_multiple_args(self):
self.assert_parses_to("foo bar baz\t qux", args=["foo", "bar", "baz", "qux"])
def test_escape_space(self):
self.assert_parses_to(r"foo\ bar baz", args=["foo bar", "baz"])
def test_escape_backslash(self):
self.assert_parses_to(r"foo\\ bar", args=["foo\\", "bar"])
def test_escape_double_quote(self):
self.assert_parses_to(r"foo\"bar", args=['foo"bar'])
def test_escape_single_quote(self):
self.assert_parses_to(r"foo\'bar", args=["foo'bar"])
def test_escape_other(self):
self.assert_parses_to(r"foo\a", args=["fooa"])
def test_double_quotes(self):
self.assert_parses_to('"foo bar baz\'qux"', args=["foo bar baz'qux"])
def test_double_quotes_empty(self):
self.assert_parses_to('""', args=[""])
def test_double_quotes_escape(self):
# In double quotes, backslash only has special meaning before these
# characters and newline.
self.assert_parses_to(r' "\$\`\"\\" ', args=['$`"\\'])
def test_double_quotes_escape_newline(self):
self.assert_parses_to('"\\\n"', args=["\n"])
def test_double_quotes_backslash_single_quote(self):
self.assert_parses_to(r""" "\'" """, args=[r"\'"])
def test_double_quotes_backslash_other(self):
self.assert_parses_to(r'"\a"', args=[r"\a"])
def test_single_quotes(self):
self.assert_parses_to("' foo bar \"baz'", args=[' foo bar "baz'])
def test_single_quotes_empty(self):
self.assert_parses_to("''", args=[""])
def test_single_quotes_backslash(self):
# In single quotes, backslash does not have a special meaning.
self.assert_parses_to(r"'\$'", args=[r"\$"])
def test_single_quotes_backslash_single_quote(self):
self.assert_parses_to(r"'\'", args=["\\"])
def test_concatenate_escapes_and_quotes(self):
self.assert_parses_to(r""" foo' bar'\ baz"q u x" """, args=["foo bar bazq u x"])
def test_redirect_input(self):
for source in (
"foo < infile",
"foo <infile",
"foo< infile",
"foo<infile",
"<infile foo",
"< infile foo",
):
with self.subTest(source=source):
self.assert_parses_to(
source, args=["foo"], redirections=[(0, "<", "infile")]
)
def test_redirect_input_fd(self):
for source in (
"foo 0< infile",
"foo 0<infile",
"0<infile foo",
"0< infile foo",
):
with self.subTest(source=source):
self.assert_parses_to(
source, args=["foo"], redirections=[(0, "<", "infile")]
)
def test_redirect_output(self):
for source in (
"foo > outfile",
"foo >outfile",
"foo> outfile",
"foo>outfile",
">outfile foo",
"> outfile foo",
):
with self.subTest(source=source):
self.assert_parses_to(
source, args=["foo"], redirections=[(1, ">", "outfile")]
)
def test_redirect_output_fd(self):
for source in (
"foo 1> outfile",
"foo 1>outfile",
"1>outfile foo",
"1> outfile foo",
):
with self.subTest(source=source):
self.assert_parses_to(
source, args=["foo"], redirections=[(1, ">", "outfile")]
)
for source in (
"foo 2> outfile",
"foo 2>outfile",
"2>outfile foo",
"2> outfile foo",
):
with self.subTest(source=source):
self.assert_parses_to(
source, args=["foo"], redirections=[(2, ">", "outfile")]
)
def test_append_output(self):
for source in (
"foo >> outfile",
"foo >>outfile",
"foo>> outfile",
"foo>>outfile",
">>outfile foo",
">> outfile foo",
):
with self.subTest(source=source):
self.assert_parses_to(
source, args=["foo"], redirections=[(1, ">>", "outfile")]
)
def test_append_output_fd(self):
for source in (
"foo 1>> outfile",
"foo 1>>outfile",
"1>>outfile foo",
"1>> outfile foo",
):
with self.subTest(source=source):
self.assert_parses_to(
source, args=["foo"], redirections=[(1, ">>", "outfile")]
)
for source in (
"foo 2>> outfile",
"foo 2>>outfile",
"2>>outfile foo",
"2>> outfile foo",
):
with self.subTest(source=source):
self.assert_parses_to(
source, args=["foo"], redirections=[(2, ">>", "outfile")]
)
def test_redirect_input_and_output(self):
self.assert_parses_to(
"foo < infile > outfile",
args=["foo"],
redirections=[(0, "<", "infile"), (1, ">", "outfile")],
)
def test_redirect_input_multiple(self):
self.assert_parses_to(
"< infile1 foo< infile2 <infile3",
args=["foo"],
redirections=[
(0, "<", "infile1"),
(0, "<", "infile2"),
(0, "<", "infile3"),
],
)
def test_redirect_output_multiple(self):
self.assert_parses_to(
"> outfile1 foo>> outfile2 >outfile3",
args=["foo"],
redirections=[
(1, ">", "outfile1"),
(1, ">>", "outfile2"),
(1, ">", "outfile3"),
],
)
def test_pipeline(self):
self.assert_parses_to(
"foo | grep 'bar baz' | sort",
args=["foo"],
pipeline="grep 'bar baz' | sort",
)
def test_pipeline_and_redirect(self):
self.assert_parses_to(
"foo < infile | grep 'bar baz' >outfile2",
args=["foo"],
redirections=[(0, "<", "infile")],
pipeline="grep 'bar baz' >outfile2",
)
def test_only_redirect(self):
self.assert_parses_to(
"< infile >outfile",
args=[],
redirections=[(0, "<", "infile"), (1, ">", "outfile")],
)
def test_pipeline_empty(self):
self.assertRaisesRegex(
SyntaxError, "unexpected end of input", parse_shell_command, "foo | "
)
def test_pipe_after_redirect(self):
for source in (
"foo < |",
"foo > |",
"foo >> |",
):
self.assertRaisesRegex(
SyntaxError, r"unexpected '\|'", parse_shell_command, source
)
def test_nothing_before_pipe(self):
self.assert_parses_to("| cat", args=[], pipeline="cat")
def test_redirect_after_redirect(self):
self.assertRaisesRegex(
SyntaxError, "unexpected '<'", parse_shell_command, "foo < <"
)
self.assertRaisesRegex(
SyntaxError, "unexpected '>'", parse_shell_command, "foo < >"
)
self.assertRaisesRegex(
SyntaxError, "unexpected '>>'", parse_shell_command, "foo < >>"
)
def test_nothing_after_redirect(self):
self.assertRaisesRegex(
SyntaxError, "unexpected end of input", parse_shell_command, ">"
)
self.assertRaisesRegex(
SyntaxError, "unexpected end of input", parse_shell_command, "foo >"
)
def test_comment(self):
self.assert_parses_to("foo # bar < infile | baz", args=["foo"])
def test_hash_in_word(self):
self.assert_parses_to("foo#bar #baz", args=["foo#bar"])
_COMMANDS = CommandNamespace()
@command(
description="write arguments to standard output",
arguments=(argument("string", nargs="*"),),
namespace=_COMMANDS,
)
def _cmd_echo(prog, name, args, **kwargs):
print(*args.string)
@command(
description="write arguments to standard error",
arguments=(argument("string", nargs="*"),),
namespace=_COMMANDS,
)
def _cmd_echoerr(prog, name, args, **kwargs):
print(*args.string, file=sys.stderr)
@command(
description="reverse standard input",
namespace=_COMMANDS,
)
def _cmd_tac(prog, name, args, **kwargs):
lines = sys.stdin.readlines()
lines.reverse()
sys.stdout.writelines(lines)
@raw_command(
description="call ast.literal_eval()",
usage="literal expr",
long_description="",
namespace=_COMMANDS,
)
def _cmd_literal(prog, name, args, **kwargs):
return ast.literal_eval(args)
class TestRunCommand(TestCase):
@staticmethod
def run_command(source, **kwargs):
return _COMMANDS.run(None, source, globals={}, **kwargs)
def test_command_not_found(self):
self.assertRaises(CommandNotFoundError, self.run_command, "asdf")
def test_redirect_output(self):
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "file"
self.run_command(f"echo foo bar > {path}")
self.assertEqual(path.read_text(), "foo bar\n")
def test_clobber_output(self):
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "file"
path.write_text("x\n")
self.run_command(f"echo foo bar > {path}")
self.assertEqual(path.read_text(), "foo bar\n")
def test_append_output(self):
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "file"
path.write_text("foo\n")
self.run_command(f"echo bar >> {path}")
self.assertEqual(path.read_text(), "foo\nbar\n")
def test_redirect_output_multiple(self):
with tempfile.TemporaryDirectory() as temp_dir:
path1 = Path(temp_dir) / "file1"
path2 = Path(temp_dir) / "file2"
self.run_command(f"echo foo bar > {path1} > {path2}")
# Both files are created, but the output is written to the last
# one.
self.assertEqual(path1.read_text(), "")
self.assertEqual(path2.read_text(), "foo bar\n")
def test_redirect_error(self):
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "file"
self.run_command(f"echoerr foo bar 2> {path}")
self.assertEqual(path.read_text(), "foo bar\n")
def test_clobber_error(self):
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "file"
path.write_text("x\n")
self.run_command(f"echoerr foo bar 2> {path}")
self.assertEqual(path.read_text(), "foo bar\n")
def test_append_error(self):
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "file"
path.write_text("foo\n")
self.run_command(f"echoerr bar 2>> {path}")
self.assertEqual(path.read_text(), "foo\nbar\n")
def test_redirect_input(self):
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "file"
path.write_text("foo\nbar\n")
f = io.StringIO()
with contextlib.redirect_stdout(f):
self.run_command(f"tac < {path}")
self.assertEqual(f.getvalue(), "bar\nfoo\n")
def test_redirect_input_multiple(self):
with tempfile.TemporaryDirectory() as temp_dir:
path1 = Path(temp_dir) / "file1"
path2 = Path(temp_dir) / "file2"
path1.write_text("foo\n")
path2.write_text("bar\n")
f = io.StringIO()
with contextlib.redirect_stdout(f):
self.run_command(f"tac < {path1} < {path2}")
# The last redirection wins.
self.assertEqual(f.getvalue(), "bar\n")
def test_pipe(self):
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "file"
self.run_command(f"echo hello | grep -o hell > {path}")
self.assertEqual(path.read_text(), "hell\n")
def test_redirect_input_and_pipe(self):
with tempfile.TemporaryDirectory() as temp_dir:
in_path = Path(temp_dir) / "infile"
out_path = Path(temp_dir) / "outfile"
in_path.write_text("foo\nbar\n")
self.run_command(f"tac < {in_path} | grep foo > {out_path}")
self.assertEqual(out_path.read_text(), "foo\n")
def test_redirect_output_and_pipe(self):
with tempfile.TemporaryDirectory() as temp_dir:
path1 = Path(temp_dir) / "file1"
path2 = Path(temp_dir) / "file2"
self.run_command(f"echo foo bar > {path1} | cat > {path2}")
# Redirection wins over pipe.
self.assertEqual(path1.read_text(), "foo bar\n")
self.assertEqual(path2.read_text(), "")
def test_redirect_input_failure(self):
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "file"
self.assertRaises(OSError, self.run_command, f"tac < {path}")
def test_redirect_output_failure(self):
with tempfile.TemporaryDirectory() as temp_dir:
path1 = Path(temp_dir) / "file"
path2 = Path(temp_dir) / "dir/file"
path1.write_text("foo\n")
self.assertRaises(OSError, self.run_command, f"echo < {path1} > {path2}")
def test_empty(self):
self.assertRaisesRegex(
SyntaxError, "expected command name", self.run_command, ""
)
self.assertRaisesRegex(
SyntaxError, "expected command name", self.run_command, " \t"
)
self.assertRaisesRegex(
SyntaxError, "expected command name", self.run_command, "# comment"
)
def test_not_command_name(self):
self.assertRaisesRegex(
SyntaxError, "expected command name", self.run_command, "< /dev/null"
)
self.assertRaisesRegex(
SyntaxError, "expected command name", self.run_command, "| cat"
)
def test_redirect_invalid_input_fd(self):
self.assertRaises(NotImplementedError, self.run_command, "echo 1< /dev/null")
def test_redirect_invalid_output_fd(self):
self.assertRaises(NotImplementedError, self.run_command, "echo 0> /dev/null")
self.assertRaises(NotImplementedError, self.run_command, "echo 0>> /dev/null")
def test_pipe_failure(self):
self.assertRaises(CommandExitStatusError, self.run_command, "echo foo | false")
def test_onerror(self):
onerror = unittest.mock.Mock()
self.run_command("asdf", onerror=onerror)
onerror.assert_called_once()
def test_onerror_raises(self):
def onerror(e):
1 / 0
self.assertRaises(ZeroDivisionError, self.run_command, "asdf", onerror=onerror)
def test_raw(self):
self.assertEqual(self.run_command("literal (1, 2)"), (1, 2))
def test_argument_error(self):
self.assertRaises(
CommandArgumentError, self.run_command, "tac --garbage 2> /dev/null"
)
class TestSanitizeRst(TestCase):
def test_empty(self):
self.assertEqual(_sanitize_rst(""), "")
def test_none(self):
self.assertEqual(_sanitize_rst(None), None)
def test_bold(self):
self.assertEqual(_sanitize_rst("**true**"), "true")
def test_italic(self):
self.assertEqual(_sanitize_rst("*CPU*"), "CPU")
def test_escaped_asterisk(self):
self.assertEqual(_sanitize_rst(r"\*"), "*")
def test_bold_escaped_asterisk(self):
self.assertEqual(_sanitize_rst(r"**\***"), "*")
def test_escaped_backslash(self):
self.assertEqual(_sanitize_rst("\\\\"), "\\")
def test_bold_and_escaped_dash(self):
self.assertEqual(_sanitize_rst(r"**\-\-drgn**"), "--drgn")
class TestReprBlack(TestCase):
def test_simple(self):
self.assertEqual(_repr_black("foo"), '"foo"')
def test_single_quote(self):
self.assertEqual(_repr_black("ne'er"), '"ne\'er"')
def test_double_quote(self):
self.assertEqual(_repr_black('l"oL'), "'l\"oL'")
class TestReprRawBytes(TestCase):
def test_simple(self):
self.assertEqual(_repr_raw_bytes(b"foo"), 'rb"foo"')
def test_single_quote(self):
self.assertEqual(_repr_raw_bytes(b"ne'er"), 'rb"ne\'er"')
def test_double_quote(self):
self.assertEqual(_repr_raw_bytes(b'l"oL'), "rb'l\"oL'")
def test_single_and_double_quote(self):
self.assertEqual(_repr_raw_bytes(b"ne'er l\"oL"), 'b"ne\'er l\\"oL"')
def test_ends_with_backslash(self):
self.assertEqual(_repr_raw_bytes(b"foo\\"), r'b"foo\\"')
def test_single_quote_and_ends_with_backslash(self):
self.assertEqual(_repr_raw_bytes(b"ne'er\\"), 'b"ne\'er\\\\"')
def test_double_quote_and_ends_with_backslash(self):
self.assertEqual(_repr_raw_bytes(b'l"oL\\'), "b'l\"oL\\\\'")
def test_single_and_double_quote_and_ends_with_backslash(self):
self.assertEqual(_repr_raw_bytes(b"ne'er l\"oL\\"), 'b"ne\'er l\\"oL\\\\"')
class TestDrgnCodeBuilder(TestCase):
def test_empty(self):
self.assertEqual(DrgnCodeBuilder(None).get(), "")
def test_no_imports(self):
code = DrgnCodeBuilder(None)
code.append("pass\n")
self.assertEqual(code.get(), "pass\n")
def test_sort_imports(self):
code = DrgnCodeBuilder(None)
code.add_import("sys")
code.add_import("os")
self.assertEqual(
code.get(),
"""\
import os
import sys
""",
)
def test_deduplicate_imports(self):
code = DrgnCodeBuilder(None)
code.add_import("os")
code.add_import("sys")
code.add_import("os")
self.assertEqual(
code.get(),
"""\
import os
import sys
""",
)
def test_sort_from_imports(self):
code = DrgnCodeBuilder(None)
code.add_import("sys")
code.add_import("os")
code.add_from_import("sys", "stdout")
self.assertEqual(
code.get(),
"""\
import os
import sys
from sys import stdout
""",
)
def test_first_party_imports(self):
code = DrgnCodeBuilder(None)
code.add_import("os")
code.add_import("sys")
code.add_import("drgn")
self.assertEqual(
code.get(),
"""\
import os
import sys
import drgn
""",
)
def test_merge_from_imports(self):
code = DrgnCodeBuilder(None)
code.add_from_import("drgn", "Object", "Program")
code.add_from_import("drgn", "Object")
code.add_from_import("drgn", "Type")
self.assertEqual(
code.get(),
"""\
from drgn import Object, Program, Type
""",
)
def test_long_from_imports(self):
code = DrgnCodeBuilder(None)
code.add_from_import(
"os",
"abort",
"access",
"chdir",
"chmod",
"chown",
"close",
"closerange",
"confstr",
"copy_file_range",
)
self.assertEqual(
code.get(),
"""\
from os import (
abort,
access,
chdir,
chmod,
chown,
close,
closerange,
confstr,
copy_file_range,
)
""",
)
def test_imports_and_code(self):
code = DrgnCodeBuilder(None)
code.append("pass\n")
code.add_import("os")
self.assertEqual(
code.get(),
"""\
import os
pass
""",
)
|