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 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
|
import asyncio
import datetime
from io import StringIO
from typing import Awaitable
from typing import Callable
from typing import Dict
from typing import Iterable
from typing import List
from typing import Optional
from typing import Tuple
from typing import cast
import pytest
from rich import print as rprint
from textual.app import App
from textual.coordinate import Coordinate
from textual.pilot import Pilot
from textual.widget import Widget
from textual.widgets import DataTable
from textual.widgets import Label
import memray.reporters.tui
from memray import AllocationRecord
from memray import AllocatorType
from memray.reporters.tui import Location
from memray.reporters.tui import MemoryGraph
from memray.reporters.tui import Snapshot
from memray.reporters.tui import SnapshotFetched
from memray.reporters.tui import TUIApp
from memray.reporters.tui import aggregate_allocations
from tests.utils import MockAllocationRecord
from tests.utils import async_run
class MockApp(TUIApp):
CSS_PATH = None # type: ignore
def __init__(self, *args, disable_update_thread=True, **kwargs):
super().__init__(*args, **kwargs)
if disable_update_thread:
# Make the update thread return immediately when started
self._update_thread.cancel()
def add_mock_snapshot(
self,
snapshot: List[MockAllocationRecord],
disconnected: bool = False,
native: bool = True,
) -> None:
records = cast(List[AllocationRecord], snapshot)
self.post_message(
SnapshotFetched(
Snapshot(
heap_size=sum(record.size for record in records),
records=records,
records_by_location=aggregate_allocations(
cast(List[AllocationRecord], records), native_traces=native
),
),
disconnected,
)
)
def add_mock_snapshots(
self,
snapshots: List[List[MockAllocationRecord]],
disconnect_after_last: bool = True,
native: bool = True,
) -> None:
for i, snapshot in enumerate(snapshots):
disconnected = i == len(snapshots) - 1 and disconnect_after_last
self.add_mock_snapshot(snapshot, disconnected=disconnected, native=native)
class MockReader:
def __init__(
self,
snapshots: List[List[MockAllocationRecord]],
has_native_traces: bool = True,
pid: Optional[int] = None,
command_line: Optional[str] = None,
):
self._snapshots = cast(List[List[AllocationRecord]], snapshots)
self._next_snapshot = 0
self.is_active = True
self.command_line = command_line
self.pid = pid
self.has_native_traces = has_native_traces
def get_current_snapshot(
self, *, merge_threads: bool
) -> Iterable[AllocationRecord]:
assert isinstance(merge_threads, bool) # ignore unused argument
assert self.is_active
snapshot = self._snapshots[self._next_snapshot]
self._next_snapshot += 1
self.is_active = self._next_snapshot < len(self._snapshots)
return snapshot
@pytest.fixture
def compare(monkeypatch, tmp_path, snap_compare):
monkeypatch.setattr(memray.reporters.tui, "datetime", FakeDatetime)
def compare_impl(
cmdline_override: Optional[str] = None,
press: Iterable[str] = (),
terminal_size: Tuple[int, int] = (80, 24),
run_before: Optional[Callable[[Pilot], Optional[Awaitable[None]]]] = None,
native: bool = True,
):
async def run_before_wrapper(pilot) -> None:
if run_before is not None:
result = run_before(pilot)
if result is not None:
await result
await pilot.pause()
header = pilot.app.screen.query_one("Header")
header.last_update = header.start + datetime.timedelta(seconds=42)
app = MockApp(
MockReader([], has_native_traces=native),
cmdline_override=cmdline_override,
)
app_global = "_CURRENT_APP_"
tmp_main = tmp_path / "main.py"
with monkeypatch.context() as app_patch:
app_patch.setitem(globals(), app_global, app)
tmp_main.write_text(f"from {__name__} import {app_global} as app")
return snap_compare(
str(tmp_main),
press=press,
terminal_size=terminal_size,
run_before=run_before_wrapper,
)
yield compare_impl
def render_widget(widget: Widget) -> str:
output = StringIO()
rprint(widget.renderable, file=output) # type: ignore
return output.getvalue()
def extract_label_text(app: App) -> Dict[str, str]:
return {
label.id: render_widget(label)
for label in app.screen.query(Label)
if label.id is not None
}
def mock_allocation(
stack: Optional[List[Tuple[str, str, int]]] = None,
tid: int = 1,
address: int = 0,
size: int = 1024,
allocator: AllocatorType = AllocatorType.MALLOC,
stack_id: int = 0,
n_allocations: int = 1,
thread_name: str = "",
):
hybrid_stack = stack
if hybrid_stack is not None:
stack = [
(func, filename, lineno)
for func, filename, lineno in hybrid_stack
if filename.endswith(".py")
]
return MockAllocationRecord(
tid=tid,
address=address,
size=size,
allocator=allocator,
stack_id=stack_id,
n_allocations=n_allocations,
thread_name=thread_name,
_stack=stack,
_hybrid_stack=hybrid_stack,
)
SHORT_SNAPSHOTS = [
[
mock_allocation(
stack=[
("malloc", "malloc.c", 1234),
("f1", "f.py", 16),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
],
[
mock_allocation(
stack=[
("malloc", "malloc.c", 1234),
("f1", "f.py", 16),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
mock_allocation(
stack=[
("malloc", "malloc.c", 1234),
("f2", "f.py", 32),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
mock_allocation(
stack=[
("malloc", "malloc.c", 1234),
("f2", "f.py", 32),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
],
]
LONG_SNAPSHOTS = [
[
mock_allocation(
stack=[
("malloc", "malloc.c", 1234),
("f1", "f.py", 16),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
],
[
mock_allocation(
stack=[
("malloc", "malloc.c", 1234),
("f1", "f.py", 16),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
mock_allocation(
stack=[
("malloc", "malloc.c", 1234),
("f2", "f.py", 32),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
mock_allocation(
size=333,
stack=[
("malloc", "malloc.c", 1234),
*[(f"something{i}", "something.py", i) for i in range(20)],
("f2", "f.py", 32),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
],
]
class FakeDatetime(datetime.datetime):
@classmethod
def now(cls):
return cls(2023, 10, 13, 12)
class TestGraph:
def test_empty(self):
# GIVEN
plot = MemoryGraph(max_data_points=50)
# WHEN
graph = tuple(plot.render_line(i).text for i in range(plot._height))
# THEN
assert plot._maxval == 1.0
assert plot._minval == 0.0
assert graph == (" " * 50, " " * 50, " " * 50, " " * 50)
def test_size_of_graph(self):
# GIVEN
size = 36
rows = 10
plot = MemoryGraph(max_data_points=size, height=rows)
# WHEN
for point in range(50):
plot.add_value(point)
graph = tuple(plot.render_line(i).text for i in range(plot._height))
# THEN
assert len(graph) == rows
assert all(len(line) == size for line in graph)
def test_one_point_lower_than_max(self):
# GIVEN
plot = MemoryGraph(max_data_points=50)
# WHEN
plot.add_value(0.5)
graph = tuple(plot.render_line(i).text for i in range(plot._height))
# THEN
assert plot._maxval == 1.0
assert plot._minval == 0.0
assert graph == (
" ",
" ",
" ▐",
" ▐",
)
def test_one_point_bigger_than_max(self):
# GIVEN
plot = MemoryGraph(max_data_points=50)
# WHEN
plot.add_value(500.0)
graph = tuple(plot.render_line(i).text for i in range(plot._height))
# THEN
assert plot._maxval == 500.0
assert plot._minval == 0
assert graph == (
" ▐",
" ▐",
" ▐",
" ▐",
)
def test_one_point_bigger_than_max_after_resize(self):
# GIVEN
plot = MemoryGraph(max_data_points=50)
# WHEN
plot.add_value(1000)
for _ in range(50 * 2):
plot.add_value(0)
plot.add_value(500.0)
graph = tuple(plot.render_line(i).text for i in range(plot._height))
# THEN
assert plot._maxval == 1000.0
assert plot._minval == 0
assert graph == (
" ",
" ",
" ▐",
" ▐",
)
def test_multiple_points(self):
# GIVEN
plot = MemoryGraph(max_data_points=50)
plot.add_value(100.0)
for _ in range(50 * 2):
plot.add_value(0)
# WHEN
for point in range(50):
plot.add_value(point)
graph = tuple(plot.render_line(i).text for i in range(plot._height))
# THEN
assert plot._maxval == 100.0
assert plot._minval == 0
assert graph == (
" ",
" ",
" ▄▄▄▄▄▄██████",
" ▗▄▄▄▄▄▟██████████████████",
)
def test_multiple_points_scattered(self):
# GIVEN
plot = MemoryGraph(max_data_points=50)
plot.add_value(100.0)
for _ in range(50 * 2):
plot.add_value(0)
# WHEN
plot.add_value(100)
plot.add_value(15)
plot.add_value(30)
plot.add_value(75)
graph = tuple(plot.render_line(i).text for i in range(plot._height))
# THEN
assert plot._maxval == 100.0
assert plot._minval == 0
assert graph == (
" ▌ ",
" ▌▐",
" ▌▟",
" ██",
)
@pytest.mark.parametrize("native_traces", [False, True])
def test_update_thread(native_traces):
"""Test that our update thread posts the expected messages to our app."""
# GIVEN
snapshots = SHORT_SNAPSHOTS
reader = MockReader(snapshots, native_traces)
messages = []
all_messages_received = asyncio.Event()
class MessageInterceptingApp(MockApp):
def __init__(self, reader):
super().__init__(reader, poll_interval=0.01, disable_update_thread=False)
def on_snapshot_fetched(self, message):
messages.append(message)
if message.disconnected:
all_messages_received.set()
app = MessageInterceptingApp(reader)
# WHEN
async def run_test():
async with app.run_test() as pilot:
await all_messages_received.wait()
await pilot.pause()
async_run(run_test())
# THEN
assert len(messages) == len(snapshots)
for i, message in enumerate(messages):
last_message = i == len(messages) - 1
assert message.disconnected is last_message
assert message.snapshot.heap_size == sum(a.size for a in snapshots[i])
assert message.snapshot.records == snapshots[i]
assert message.snapshot.records_by_location == aggregate_allocations(
message.snapshot.records,
native_traces=native_traces,
)
@pytest.mark.parametrize(
"pid, display_val",
[
pytest.param(999, "PID: 999", id="Known PID"),
pytest.param(None, "PID: ???", id="Unknown PID"),
],
)
def test_pid_display(pid, display_val):
# GIVEN
reader = MockReader([], pid=pid)
app = MockApp(reader)
labels = {}
# WHEN
async def run_test():
async with app.run_test() as pilot:
await pilot.pause()
labels.update(extract_label_text(pilot.app))
async_run(run_test())
# THEN
assert labels["pid"].rstrip() == display_val
@pytest.mark.parametrize(
"command_line, display_val",
[
pytest.param("foo bar baz", "CMD: foo bar baz", id="Known command"),
pytest.param(
"/path/to/foo bar baz",
"CMD: /path/to/foo bar baz",
id="Known command with path",
),
pytest.param(
"/path/to/memray bar baz",
"CMD: memray bar baz",
id="Memray script with path",
),
pytest.param(
"/path/to/memray/__main__.py bar baz",
"CMD: memray bar baz",
id="Memray module with path",
),
pytest.param(None, "CMD: ???", id="Unknown command"),
],
)
def test_command_line_display(command_line, display_val):
# GIVEN
reader = MockReader([], command_line=command_line)
app = MockApp(reader)
labels = {}
# WHEN
async def run_test():
async with app.run_test() as pilot:
await pilot.pause()
labels.update(extract_label_text(pilot.app))
async_run(run_test())
# THEN
assert labels["cmd"].rstrip() == display_val
def test_header_with_no_snapshots():
# GIVEN
reader = MockReader([])
app = MockApp(reader)
labels = {}
# WHEN
async def run_test():
async with app.run_test() as pilot:
await pilot.pause()
labels.update(extract_label_text(pilot.app))
async_run(run_test())
# THEN
assert labels["tid"].split() == "TID: *".split()
assert labels["thread"].split() == "All threads".split()
assert labels["samples"].split() == "Samples: 0".split()
def test_header_with_empty_snapshot():
# GIVEN
reader = MockReader([])
app = MockApp(reader)
labels = {}
# WHEN
async def run_test():
async with app.run_test() as pilot:
app.add_mock_snapshot([])
await pilot.pause()
labels.update(extract_label_text(pilot.app))
async_run(run_test())
# THEN
assert labels["tid"].split() == "TID: *".split()
assert labels["thread"].split() == "All threads".split()
assert labels["samples"].split() == "Samples: 1".split()
def test_sorting():
"""Test that our sort keys correctly sort the data table"""
# GIVEN
snapshot = [
mock_allocation(
size=10,
n_allocations=5,
stack=[("a", "a.py", 1)],
),
mock_allocation(
size=50,
n_allocations=1,
stack=[("b", "b.py", 1)],
),
mock_allocation(
size=100,
n_allocations=2,
stack=[("c", "c.py", 1), ("b", "b.py", 1)],
),
mock_allocation(
size=25,
n_allocations=4,
stack=[("d", "d.py", 1)],
),
]
own_order = "cbda"
total_order = "bcda"
allocations_order = "adbc"
reader = MockReader([])
app = MockApp(reader)
order_by_key = {}
# WHEN
async def run_test():
async with app.run_test() as pilot:
app.add_mock_snapshot(snapshot)
await pilot.pause()
datatable = pilot.app.screen.query_one(DataTable)
function_col_key = datatable.ordered_columns[0].key
for key in ("", "o", "a", "t"):
await pilot.press(key)
order_by_key[key] = "".join(
datatable.get_cell(row.key, function_col_key).plain
for row in datatable.ordered_rows
)
async_run(run_test())
# THEN
assert order_by_key[""] == total_order
assert order_by_key["o"] == own_order
assert order_by_key["a"] == allocations_order
assert order_by_key["t"] == total_order
def test_switching_threads():
"""Test that we can switch which thread is displayed"""
# GIVEN
thread_names = ["Thread A", "", "Thread C"]
thread_labels = [
"Thread 1 of 3 (Thread A)",
"Thread 2 of 3",
"Thread 3 of 3 (Thread C)",
]
snapshot = [
mock_allocation(
tid=1,
stack=[("a", "a.py", 1)],
thread_name=thread_names[0],
),
mock_allocation(
tid=2,
stack=[("b", "b.py", 1)],
thread_name=thread_names[1],
),
mock_allocation(
tid=3,
stack=[("c", "c.py", 1)],
thread_name=thread_names[2],
),
]
reader = MockReader([])
app = MockApp(reader)
functions = []
tids = []
threads = []
# WHEN
async def run_test():
async with app.run_test() as pilot:
app.add_mock_snapshot(snapshot)
await pilot.pause()
datatable = pilot.app.screen.query_one(DataTable)
for key in ("m", ">", ">", ">", "<", "<", "<"):
await pilot.press(key)
functions.append(datatable.get_cell_at(Coordinate(0, 0)).plain)
labels = extract_label_text(app)
tids.append(" ".join(labels["tid"].split()))
threads.append(" ".join(labels["thread"].split()))
async_run(run_test())
# THEN
order = [0, 1, 2, 0, 2, 1, 0]
assert functions == ["abc"[i] for i in order]
assert tids == [f"TID: {hex(i+1)}" for i in order]
assert threads == [thread_labels[i] for i in order]
def test_merge_mode_new_threads():
"""Test that the 'All threads' is still displayed when a new thread is created."""
# GIVEN
snapshot = [
mock_allocation(
tid=1,
stack=[("a", "a.py", 1)],
),
mock_allocation(
tid=2,
stack=[("b", "b.py", 1)],
),
mock_allocation(
tid=3,
stack=[("c", "c.py", 1)],
),
]
new_thread = mock_allocation(tid=4, stack=[("d", "d.py", 1)])
reader = MockReader([])
app = MockApp(reader)
label = []
# WHEN
async def run_test():
async with app.run_test() as pilot:
await pilot.press("m")
app.add_mock_snapshot(snapshot)
await pilot.pause()
await pilot.press("m")
app.add_mock_snapshot(snapshot + [new_thread])
await pilot.pause()
label.append(extract_label_text(app)["thread"])
async_run(run_test())
# THEN
assert label == ["All threads\n"]
def test_merging_allocations_from_all_threads():
"""Test that we can display allocations from all threads"""
# GIVEN
snapshot = [
mock_allocation(
tid=1,
size=1024,
stack=[("a", "a.py", 1)],
),
mock_allocation(
tid=2,
size=2 * 1024,
stack=[("b", "b.py", 1)],
),
mock_allocation(
tid=3,
size=3 * 1024,
stack=[("c", "c.py", 1)],
),
]
reader = MockReader([])
app = MockApp(reader)
functions = []
tids = []
threads = []
# WHEN
async def run_test():
async with app.run_test() as pilot:
app.add_mock_snapshot(snapshot)
await pilot.pause()
datatable = pilot.app.screen.query_one(DataTable)
for key in ("m", ">", "m", "<", "m", "<"):
await pilot.press(key)
functions.append(datatable.get_cell_at(Coordinate(0, 0)).plain)
labels = extract_label_text(app)
tids.append(" ".join(labels["tid"].split()))
threads.append(" ".join(labels["thread"].split()))
async_run(run_test())
# THEN
order = [0, 1, 2, 2, 1, 0]
merged = [False, False, True, True, False, False]
assert functions == ["abc"[i] for i in order]
assert tids == [
"TID: *" if all else f"TID: {hex(i+1)}" for i, all in zip(order, merged)
]
assert threads == [
"All threads" if all else f"Thread {i+1} of 3" for i, all in zip(order, merged)
]
@pytest.mark.parametrize(
"terminal_size, press, snapshots",
[
pytest.param(
(80, 24), [], SHORT_SNAPSHOTS, id="narrow-terminal-short-snapshots"
),
pytest.param(
(80, 24),
["tab"],
LONG_SNAPSHOTS,
id="narrow-terminal-focus-header-long-snapshots",
),
pytest.param((120, 24), [], LONG_SNAPSHOTS, id="wide-terminal-long-snapshots"),
pytest.param(
(200, 24), [], SHORT_SNAPSHOTS, id="very-wide-terminal-short-snapshots"
),
],
)
def test_tui_basic(terminal_size, press, snapshots, compare):
async def run_before(pilot) -> None:
pilot.app.add_mock_snapshots(snapshots)
assert compare(
press=press,
run_before=run_before,
terminal_size=terminal_size,
)
@pytest.mark.parametrize(
"terminal_size, disconnected",
[
pytest.param((50, 24), False, id="narrow-terminal-connected"),
pytest.param((50, 24), True, id="narrow-terminal-disconnected"),
pytest.param((81, 24), True, id="wider-terminal"),
],
)
def test_tui_pause(terminal_size, disconnected, compare):
async def run_before(pilot: Pilot) -> None:
app = cast(MockApp, pilot.app)
app.add_mock_snapshot(SHORT_SNAPSHOTS[0])
await pilot.pause()
await pilot.press("space")
await pilot.press("tab")
await pilot.pause()
app.add_mock_snapshot(SHORT_SNAPSHOTS[1], disconnected=disconnected)
assert compare(
run_before=run_before,
terminal_size=terminal_size,
)
def test_tui_gradient(compare):
snapshot = [
mock_allocation(
stack=[(f"function{j}", f"/abc/lel_{j}.py", i) for j in range(i, -1, -1)],
size=1024 + 10 * i,
n_allocations=1,
)
for i in range(0, 30)
]
async def run_before(pilot) -> None:
pilot.app.add_mock_snapshots([snapshot], native=False)
assert compare(run_before=run_before, terminal_size=(125, 40), native=False)
class TestAggregateResults:
def test_simple_allocations(self):
# GIVEN
mock_allocation_records = [
MockAllocationRecord(
tid=1,
address=0x1000000,
size=10,
allocator=AllocatorType.MALLOC,
stack_id=1,
n_allocations=2,
_stack=[
("me", "fun.py", 12),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
MockAllocationRecord(
tid=1,
address=0x1000000,
size=20,
allocator=AllocatorType.MALLOC,
stack_id=1,
n_allocations=1,
_stack=[
("sibling", "fun.py", 16),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
]
allocation_records = cast(List[AllocationRecord], mock_allocation_records)
# WHEN
result = aggregate_allocations(allocation_records)
# THEN
grandparent = result[Location(function="grandparent", file="fun.py")]
assert grandparent.own_memory == 0
assert grandparent.total_memory == 30
assert grandparent.n_allocations == 3
me = result[Location(function="me", file="fun.py")]
assert me.own_memory == 10
assert me.total_memory == 10
assert me.n_allocations == 2
parent = result[Location(function="parent", file="fun.py")]
assert parent.own_memory == 0
assert parent.total_memory == 30
assert parent.n_allocations == 3
def test_missing_frames(self):
# GIVEN
mock_allocation_records = [
MockAllocationRecord(
tid=1,
address=0x1000000,
size=10,
allocator=AllocatorType.MALLOC,
stack_id=1,
n_allocations=2,
_stack=[],
),
MockAllocationRecord(
tid=1,
address=0x1000000,
size=20,
allocator=AllocatorType.MALLOC,
stack_id=1,
n_allocations=1,
_stack=[
("sibling", "fun.py", 16),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
MockAllocationRecord(
tid=1,
address=0x1000000,
size=30,
allocator=AllocatorType.MALLOC,
stack_id=2,
n_allocations=1,
_stack=[],
),
]
allocation_records = cast(List[AllocationRecord], mock_allocation_records)
# WHEN
result = aggregate_allocations(allocation_records)
# THEN
grandparent = result[Location(function="grandparent", file="fun.py")]
assert grandparent.own_memory == 0
assert grandparent.total_memory == 20
assert grandparent.n_allocations == 1
me = result[Location(function="???", file="???")]
assert me.own_memory == 40
assert me.total_memory == 40
assert me.n_allocations == 3
def test_native_frames(self):
# GIVEN
mock_allocation_records = [
MockAllocationRecord(
tid=1,
address=0x1000000,
size=10,
allocator=AllocatorType.MALLOC,
stack_id=1,
n_allocations=2,
_stack=[],
_hybrid_stack=[],
),
MockAllocationRecord(
tid=1,
address=0x1000000,
size=20,
allocator=AllocatorType.MALLOC,
stack_id=1,
n_allocations=1,
_hybrid_stack=[
("sibling", "fun.c", 16),
("parent", "fun.py", 8),
("grandparent", "fun.py", 4),
],
),
MockAllocationRecord(
tid=1,
address=0x1000000,
size=30,
allocator=AllocatorType.MALLOC,
stack_id=2,
n_allocations=1,
_hybrid_stack=[],
),
]
allocation_records = cast(List[AllocationRecord], mock_allocation_records)
# WHEN
result = aggregate_allocations(allocation_records, native_traces=True)
# THEN
grandparent = result[Location(function="grandparent", file="fun.py")]
assert grandparent.own_memory == 0
assert grandparent.total_memory == 20
assert grandparent.n_allocations == 1
me = result[Location(function="???", file="???")]
assert me.own_memory == 40
assert me.total_memory == 40
assert me.n_allocations == 3
def test_merge_threads(compare):
async def run_before(pilot: Pilot) -> None:
snapshot = [
mock_allocation(
tid=1,
stack=[("a", "a.py", 1)],
),
mock_allocation(
tid=2,
stack=[("b", "b.py", 1)],
),
mock_allocation(
tid=3,
stack=[("c", "c.py", 1)],
),
]
app = cast(MockApp, pilot.app)
await pilot.press("m")
app.add_mock_snapshot(snapshot)
await pilot.pause()
await pilot.press("m")
await pilot.pause()
app.add_mock_snapshot(snapshot)
assert compare(
run_before=run_before,
terminal_size=(150, 24),
)
def test_unmerge_threads(compare):
async def run_before(pilot: Pilot) -> None:
snapshot = [
mock_allocation(
tid=1,
stack=[("a", "a.py", 1)],
),
mock_allocation(
tid=2,
stack=[("b", "b.py", 1)],
),
mock_allocation(
tid=3,
stack=[("c", "c.py", 1)],
),
]
app = cast(MockApp, pilot.app)
app.add_mock_snapshot(snapshot)
await pilot.press("m")
await pilot.pause()
await pilot.press(">")
await pilot.press("m")
await pilot.press(">")
await pilot.press("m")
await pilot.pause()
app.add_mock_snapshot(snapshot)
assert compare(
run_before=run_before,
terminal_size=(150, 24),
)
|