-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest.py
More file actions
executable file
·1754 lines (1566 loc) · 71.5 KB
/
test.py
File metadata and controls
executable file
·1754 lines (1566 loc) · 71.5 KB
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
# Unit tests for OOMAnalyser
#
# Copyright (c) 2021-2025 Carsten Grohmann
# License: MIT (see LICENSE.txt)
# THIS PROGRAM COMES WITH NO WARRANTY
import http.server
import inspect
import os
import re
import socketserver
import threading
import warnings
from typing import Any, Dict, Generator, List, Optional, Tuple
import pytest
from selenium import webdriver
from selenium.common.exceptions import *
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import OOMAnalyser
class MyRequestHandler(http.server.SimpleHTTPRequestHandler):
def __init__(
self,
request: Any,
client_address: Tuple[str, int],
server: socketserver.BaseServer,
directory: Optional[str] = None,
) -> None:
self.directory = os.getcwd()
super().__init__(request, client_address, server)
# suppress all HTTP request messages
def log_message(self, format: str, *args: Any) -> None:
# super().log_message(format, *args)
pass
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
class BaseTests:
text_alloc_failed_below_low_watermark = (
"The request failed because the free memory would be below the memory low "
"watermark after its completion."
)
text_alloc_failed_no_free_chunks = (
"The request failed because there is no free chunk in the current or "
"higher order."
)
text_alloc_failed_unknown_reason = "The request failed, but the reason is unknown."
text_mem_not_heavily_fragmented = "The system memory is not heavily fragmented"
text_mem_heavily_fragmented = "The system memory is heavily fragmented"
text_oom_triggered_manually = "OOM killer was manually triggered"
text_oom_triggered_automatically = "OOM killer was automatically triggered"
text_cgroup_swap_activated = "Swap space is enabled for this cgroup."
text_cgroup_swap_deactivated = "Swap space usage is disabled for this cgroup."
text_kernel_swap_space_not_in_use = "physical memory and no system swap space"
text_kernel_swap_space_are_in_use = "system swap space are in use"
test_kernel_swap_no_space = "System swap space disabled."
test_kernel_swap_swap_total = "Swap Total"
text_with_an_oom_score_of = "with an OOM score of"
def get_lines(self, text: str, count: int) -> str:
"""
Return the number of lines specified by count from the given text
@type text: str
@type count: int
"""
lines = text.splitlines()
if count < 0:
lines.reverse()
count = count * -1
lines = lines[:count]
res = "\n".join(lines)
return res
def get_first_line(self, text: str) -> str:
"""
Return the first line of the given text
@type text: str
"""
return self.get_lines(text, 1)
def get_last_line(self, text: str) -> str:
"""
Return the last line of the given text
@type text: str
"""
return self.get_lines(text, -1)
def check_meminfo_format_rhel7(self, prefix: str, oom_text: str) -> None:
"""
Check if the example contains a properly formatted "Mem-Info:" block
@param str prefix: Prefix for error message
@param str oom_text: Whole OOM block as text
@see: OOMAnalyser.OOMDisplay.example_rhel7
"""
found = False
for line in oom_text.split("\n"):
if "active_file:1263 " in line:
found = True
assert line.startswith(
" active_file:1263 "
), f'{prefix}: Unexpected prefix for third "Mem-Info:" block line: >>>{line}<<<'
assert (
found
), f'{prefix}: Missing content "active_file:1263 " in "Mem-Info:" block of\n{oom_text}'
def to_continuous_text(self, text: str) -> str:
"""
Convert the given text into a single continuous line.
This function removes all line breaks and any whitespace before or after them,
replacing them with a single space. Additionally, it corrects formatting issues
where a space may be introduced before a closing parenthesis due to the replacement.
@param text: The input string to be converted.
@type text: str
@return: The text as a single continuous line.
@rtype: str
"""
continuous = re.sub(r"\s*\n\s*", " ", text)
# If a line ends with a closing parenthesis, the replacement of
# LF by space character will add a space before the closing
# parenthesis.
# Remove this space character to match the original text.
continuous = continuous.replace(" )", ")")
return continuous
# Common test data for parametrized tests
LOG_PREFIXES = [
"[11686.888109] ",
"Apr 01 14:13:32 mysrv: ",
"Apr 01 14:13:32 mysrv kernel: ",
"Apr 01 14:13:32 mysrv <kern.warning> kernel: ",
"Apr 01 14:13:32 mysrv kernel: [11686.888109] ",
"kernel:",
"Apr 01 14:13:32 mysrv <kern.warning> kernel:",
]
LOG_PREFIX_IDS = [
"timestamp-only",
"syslog-prefix",
"syslog-kernel",
"syslog-warning",
"syslog-kernel-timestamp",
"kernel-only",
"syslog-warning-2",
]
class BaseInBrowserTests(BaseTests):
"""Base class for all tests that run in a browser"""
# Instance attributes (initialized by setup_browser fixture)
driver: Optional[webdriver.Chrome]
# --- Begin: generic result check configuration ---
# For each test variant, set these in the child class. An empty value
# disables the corresponding check.
check_results: Dict[str, str] = {
"gfp_mask": "", # Expected text in the GFP mask field
"proc_name": "", # Expected text in the process name field
"proc_pid": "", # Expected text in the process pid field
"killed_proc_score": "", # Expected OOM score of killed process
"swap_cache_kb": "", # Expected swap cache size
"swap_used_kb": "", # Expected swap used size
"swap_free_kb": "", # Expected swap free size
"swap_total_kb": "", # Expected swap total size
"swap_active": "no check", # Set to "check" to verify swap is active
"swap_inactive": "no check", # Set to "check" to verify swap is inactive
"mem_node_info_start": "", # Expected start text in memory node info
"mem_node_info_end": "", # Expected end text in memory node info
"mem_watermarks_start": "", # Expected start text in watermarks
"mem_watermarks_end": "", # Expected end text in watermarks
"column_header": "", # Expected column header in process table
}
"""Dictionary of expected values for result validation. Empty string disables check."""
check_explanation_expected_statements: List[str] = []
"""List of text patterns that must be found in the summary/explanation section"""
check_explanation_unexpected_statements: List[str] = []
"""List of text patterns that must not be found in the summary/explanation section"""
check_results_result_table_expected: List[str] = []
"""List of text patterns that must be found in the result table"""
check_results_result_table_unexpected: List[str] = []
"""List of text patterns that must not be found in the result table"""
check_explanation_section: Dict[str, str] = {}
"""Dictionary with category and text pattern to check the summary/explanation section"""
# --- End: generic result check configuration ---
def _check_initial_validation(self) -> None:
"""Validate no warnings/errors and summary section is displayed."""
self.assert_on_warn_error()
h3_summary = self.driver.find_element(By.XPATH, '//h3[text()="Summary"]')
assert (
h3_summary.is_displayed()
), "Analysis details incl. <h3>Summary</h3> should be displayed"
def _check_simple_fields(self) -> None:
"""Validate simple equality checks for configured fields."""
simple_checks = {
"proc_name": ("trigger_proc_name", "Unexpected trigger process name"),
"proc_pid": (
"trigger_proc_pid",
"Unexpected trigger process pid: --{actual}--",
),
"gfp_mask": (
"trigger_proc_gfp_mask",
'Unexpected GFP Mask: got: "{actual}", expect: "{expected}"',
),
"killed_proc_score": (
"killed_proc_score",
"Unexpected OOM score of killed process",
),
"swap_cache_kb": ("system_swap_cache_kb", "Unexpected swap cache size"),
"swap_used_kb": ("system_swap_used_kb", "Unexpected swap used size"),
"swap_free_kb": ("system_swap_free_kb", "Unexpected swap free size"),
"swap_total_kb": ("system_swap_total_kb", "Unexpected swap total size"),
}
for key, (css_class, error_msg) in simple_checks.items():
expected_value = self.check_results.get(key, "")
if expected_value:
element = self.driver.find_element(By.CLASS_NAME, css_class)
actual_value = element.text
assert actual_value == expected_value, error_msg.format(
actual=actual_value, expected=expected_value
)
def _check_explanation_content(self) -> None:
"""Validate explanation section content (expected, unexpected, patterns)."""
continuous_explanation_text = self.to_continuous_text(
self.driver.find_element(By.ID, "explanation").text
)
for expected in self.check_explanation_expected_statements:
assert (
expected in continuous_explanation_text
), f'Missing statement "{expected}" in summary section: >{continuous_explanation_text}<'
for unexpected in self.check_explanation_unexpected_statements:
assert (
unexpected not in continuous_explanation_text
), f'Unexpected statement "{unexpected}" in summary section: >{continuous_explanation_text}<'
for category in self.check_explanation_section:
pattern = self.check_explanation_section[category]
assert (
pattern in continuous_explanation_text
), f'{category}: Pattern "{pattern}" not found in summary section: >{continuous_explanation_text}<'
def _check_result_table_content(self) -> None:
"""Validate result table content (expected and unexpected text)."""
result_table = self.driver.find_element(By.CLASS_NAME, "result__table")
if self.check_results_result_table_expected:
for expected in self.check_results_result_table_expected:
assert (
expected in result_table.text
), f'Missing statement in result table: "{expected}"'
if self.check_results_result_table_unexpected:
for unexpected in self.check_results_result_table_unexpected:
assert (
unexpected not in result_table.text
), f'Unexpected statement in result table: "{unexpected}"'
def _check_memory_node_info(self) -> None:
"""Validate memory node information section."""
mem_node_info = self.driver.find_element(By.CLASS_NAME, "mem_node_info")
if self.check_results.get("mem_node_info_start"):
expected_start = self.check_results["mem_node_info_start"]
actual_start = mem_node_info.text[: len(expected_start)]
assert actual_start == expected_start, (
f"Unexpected memory chunks at start: "
f'expected "{expected_start}", got "{actual_start}"'
)
if self.check_results.get("mem_node_info_end"):
expected_end = self.check_results["mem_node_info_end"]
actual_end = mem_node_info.text[-len(expected_end) :]
assert actual_end == expected_end, (
f"Unexpected memory information about hugepages at end: "
f'expected "{expected_end}", got "{actual_end}"'
)
def _check_memory_watermarks(self) -> None:
"""Validate memory watermarks section."""
mem_watermarks = self.driver.find_element(By.CLASS_NAME, "mem_watermarks")
if self.check_results.get("mem_watermarks_start"):
expected_start = self.check_results["mem_watermarks_start"]
actual_start = mem_watermarks.text[: len(expected_start)]
assert actual_start == expected_start, (
f"Unexpected memory watermarks at start: "
f'expected "{expected_start}", got "{actual_start}"'
)
if self.check_results.get("mem_watermarks_end"):
expected_end = self.check_results["mem_watermarks_end"]
actual_end = mem_watermarks.text[-len(expected_end) :]
assert actual_end == expected_end, (
f"Unexpected lowmem_reserve values at end: "
f'expected "{expected_end}", got "{actual_end}"'
)
def _check_column_header(self) -> None:
"""Validate process table column header."""
if self.check_results.get("column_header"):
header = self.driver.find_element(By.ID, "pstable_header")
expected_header = self.check_results["column_header"]
assert expected_header in header.text, (
f'Missing column header "{expected_header}" in header text: '
f'"{header.text}"'
)
def _check_swap_state(self) -> None:
"""Validate swap state (active or inactive)."""
if self.check_results.get("swap_active", "not set") == "check":
self.check_swap_active()
if self.check_results.get("swap_inactive", "not set") == "check":
self.check_swap_inactive()
def check_all_results(self) -> None:
"""
Generic result checker for OOM analysis results.
"""
self._check_initial_validation()
self._check_simple_fields()
self._check_explanation_content()
self._check_result_table_content()
self._check_memory_node_info()
self._check_memory_watermarks()
self._check_column_header()
self._check_swap_state()
@pytest.fixture(autouse=True)
def setup_browser(self) -> Generator[None, None, None]:
"""Setup browser and HTTP server for tests"""
warnings.simplefilter("ignore", ResourceWarning)
http_srv = self._create_http_server()
actual_port = self._start_http_server(http_srv)
self._configure_webdriver_manager()
# Setup browser
chrome_options = self._create_chrome_options()
self.driver = self._create_webdriver(chrome_options)
self.driver.get(f"http://127.0.0.1:{actual_port}/OOMAnalyser.html")
yield # Test runs here
self._cleanup_browser(http_srv)
@staticmethod
def _create_chrome_options() -> Options:
"""
Create optimized Chrome options for headless testing.
@return: Configured Chrome options
"""
chrome_options = Options()
# Performance and stability options
performance_args = [
"--headless=new",
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-gpu",
"--disable-extensions",
"--disable-logging",
"--log-level=3",
"--window-size=1920,1080",
"--disable-background-timer-throttling",
"--disable-backgrounding-occluded-windows",
"--disable-renderer-backgrounding",
]
for arg in performance_args:
chrome_options.add_argument(arg)
chrome_options.page_load_strategy = "eager"
return chrome_options
@staticmethod
def _create_http_server() -> ThreadedTCPServer:
"""Create HTTP server with automatic port assignment."""
ThreadedTCPServer.allow_reuse_address = True
return ThreadedTCPServer(("127.0.0.1", 0), MyRequestHandler)
@staticmethod
def _start_http_server(http_srv: ThreadedTCPServer) -> int:
"""Start HTTP server in background thread and return assigned port."""
server_thread = threading.Thread(target=http_srv.serve_forever, args=(0.1,))
server_thread.daemon = True
server_thread.start()
return http_srv.server_address[1]
@staticmethod
def _configure_webdriver_manager() -> None:
"""Configure WebDriver Manager environment variables."""
os.environ["WDM_LOG_LEVEL"] = "0"
os.environ["WDM_LOCAL"] = "1"
def _create_webdriver(self, chrome_options: Options) -> webdriver.Chrome:
"""Create and configure Chrome WebDriver."""
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.set_page_load_timeout(10)
return driver
def _cleanup_browser(self, http_srv: ThreadedTCPServer) -> None:
"""Cleanup browser and HTTP server."""
self.driver.close()
http_srv.shutdown()
http_srv.server_close()
def assert_on_warn(self) -> None:
notify_box = self.driver.find_element(By.ID, "notify_box")
try:
warning = notify_box.find_element(
By.CLASS_NAME, "js-notify_box__msg--warning"
)
except NoSuchElementException:
pass
else:
pytest.fail(f'Unexpected warning message: "{warning.text}"')
def assert_on_error(self) -> None:
error = self.get_first_error_msg()
if error:
pytest.fail(f'Unexpected error message: "{error}"')
for event in self.driver.get_log("browser"):
# ignore favicon.ico errors
if "favicon.ico" in event["message"]:
continue
pytest.fail(f'Error on browser console reported: "{event}"')
def assert_on_warn_error(self) -> None:
self.assert_on_warn()
self.assert_on_error()
def click_analyse_button(self) -> None:
analyse = self.driver.find_element(
By.XPATH, '//button[text()="Analyse OOM block"]'
)
analyse.click()
def click_reset_button(self) -> None:
reset = self.driver.find_element(By.XPATH, '//button[text()="Reset form"]')
if reset.is_displayed():
reset.click()
else:
new_analysis = self.driver.find_element(
By.XPATH, '//a[contains(text(), "Step 1 - Enter your OOM message")]'
)
new_analysis.click()
self.assert_on_warn_error()
def clear_notification_box(self) -> None:
"""Clear notification box"""
# Selenium doesn't provide an interface to delete objects.
# Remove all notification entries with JS.
self.driver.execute_script(
"""
var element = document.getElementById ('notify_box');
while (element.firstChild) {
element.removeChild (element.firstChild);
}
"""
)
def get_first_error_msg(self) -> str:
"""
Return the first (oldest) error message from error notification box or an empty
string if no error message exists.
@rtype: str
"""
notify_box = self.driver.find_element(By.ID, "notify_box")
try:
first_error_msg = notify_box.find_element(
By.CLASS_NAME, "js-notify_box__msg--error"
)
return first_error_msg.text
except NoSuchElementException:
return ""
def insert_example(self, select_value: str) -> None:
"""
Select and insert an example from the combobox
@param str select_value: Option value to specify the example
"""
textarea = self.driver.find_element(By.ID, "textarea_oom")
assert textarea.get_attribute("value") == "", "Empty textarea expected"
select_element = self.driver.find_element(By.ID, "examples")
select = Select(select_element)
option_values = [o.get_attribute("value") for o in select.options]
assert (
select_value in option_values
), f"Missing proper option for example {select_value}"
select.select_by_value(select_value)
assert textarea.get_attribute("value") != "", "Missing OOM text in textarea"
h3_summary = self.driver.find_element(By.XPATH, '//h3[text()="Summary"]')
assert (
not h3_summary.is_displayed()
), "Analysis details incl. <h3>Summary</h3> should be not displayed"
def analyse_oom(self, text: str) -> None:
"""
Insert text and run analysis
:param str text: OOM text to analyse
"""
textarea = self.driver.find_element(By.ID, "textarea_oom")
assert textarea.get_attribute("value") == "", "Empty textarea expected"
textarea.send_keys(text)
assert textarea.get_attribute("value") != "", "Missing OOM text in textarea"
h3_summary = self.driver.find_element(By.XPATH, '//h3[text()="Summary"]')
assert (
not h3_summary.is_displayed()
), "Analysis details incl. <h3>Summary</h3> should be not displayed"
self.clear_notification_box()
self.click_analyse_button()
def check_swap_inactive(self) -> None:
explanation = self.driver.find_element(By.ID, "explanation")
continuous_text = self.to_continuous_text(explanation.text)
assert (
self.text_kernel_swap_space_not_in_use in continuous_text
), f'Missing statement "{self.text_kernel_swap_space_not_in_use}"'
assert (
self.text_kernel_swap_space_are_in_use not in continuous_text
), f'Unexpected statement "{self.text_kernel_swap_space_are_in_use}"'
def check_swap_active(self) -> None:
explanation = self.driver.find_element(By.ID, "explanation")
continuous_text = self.to_continuous_text(explanation.text)
assert (
self.text_kernel_swap_space_are_in_use in continuous_text
), f'Missing statement "{self.text_kernel_swap_space_are_in_use}"'
def _test_prefix_removal(
self, example: str, prefix: str, handle_meminfo_special: bool = False
) -> None:
"""
Generic test for removal of leading but useless columns.
@param example: OOM example text
@param prefix: Prefix to add to each line
@param handle_meminfo_special: If True, handle Mem-Info block specially
"""
# First pass: original example
self.analyse_oom(example)
self.check_all_results()
self.click_reset_button()
# Second pass: with prefix
lines = example.split("\n")
new_lines = []
for line in lines:
if (
handle_meminfo_special
and OOMAnalyser.OOMEntity.REC_MEMINFO_BLOCK_SECOND_PART.search(line)
):
new_line = f'{" " * len(prefix)}{line}'
else:
new_line = f"{prefix}{line}"
new_lines.append(new_line)
oom_text = "\n".join(new_lines)
self.analyse_oom(oom_text)
self.check_all_results()
self.click_reset_button()
def _test_insert_and_analyse(self, example_name: str) -> None:
"""
Generic test for inserting and analysing an example.
@param example_name: Name of example to select from dropdown
"""
self.clear_notification_box()
self.insert_example(example_name)
self.click_analyse_button()
self.check_all_results()
@pytest.mark.browser
class TestInBrowser(BaseInBrowserTests):
"""Test OOM web page in a browser"""
def test_010_load_page(self) -> None:
"""Test if the page is loading"""
assert "OOMAnalyser" in self.driver.title
def test_020_load_js(self) -> None:
"""Test if JS is loaded"""
elem = self.driver.find_element(By.ID, "version")
assert elem.text is not None, "Version statement not set - JS not loaded"
def test_033_empty_textarea(self) -> None:
"""Test "Analyse OOM block" with an empty textarea"""
textarea = self.driver.find_element(By.ID, "textarea_oom")
assert textarea.get_attribute("value") == "", "Empty textarea expected"
# textarea.send_keys(text)
assert (
textarea.get_attribute("value") == ""
), "Expected empty text area, but text found"
h3_summary = self.driver.find_element(By.XPATH, '//h3[text()="Summary"]')
assert (
not h3_summary.is_displayed()
), "Analysis details incl. <h3>Summary</h3> should be not displayed"
self.clear_notification_box()
self.click_analyse_button()
assert (
self.get_first_error_msg()
== "ERROR: Empty OOM text. Please insert an OOM message block."
)
self.click_reset_button()
def test_034_begin_but_no_end(self) -> None:
"""Test incomplete OOM text - just the beginning"""
example = """\
sed invoked oom-killer: gfp_mask=0x201da, order=0, oom_score_adj=0
sed cpuset=/ mems_allowed=0-1
CPU: 4 PID: 29481 Comm: sed Not tainted 3.10.0-514.6.1.el7.x86_64 #1
"""
self.analyse_oom(example)
assert (
self.get_first_error_msg()
== "ERROR: The inserted OOM is incomplete! The initial pattern was "
"found but not the final."
)
self.click_reset_button()
def test_035_no_begin_but_end(self) -> None:
"""Test incomplete OOM text - just the end"""
example = """\
Out of memory: Kill process 6576 (java) score 651 or sacrifice child
Killed process 6576 (java) total-vm:33914892kB, anon-rss:20629004kB, file-rss:0kB, shmem-rss:0kB
"""
self.analyse_oom(example)
assert (
self.get_first_error_msg()
== "ERROR: Failed to extract kernel version from OOM text"
)
self.click_reset_button()
def test_090_scroll_to_top(self) -> None:
"""Test scrolling to the top of the page"""
# scroll to the bottom of the page
self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
initial_position = self.driver.execute_script("return window.scrollY;")
self.analyse_oom(OOMAnalyser.OOMDisplay.example_rhel7)
# Wait briefly for smooth scroll to be initiated, then verify scroll started
# Under parallel execution, smooth scroll animations are unreliable due to resource
# contention, so we verify scroll was initiated then force completion
wait = WebDriverWait(self.driver, 5)
wait.until(
lambda driver: driver.execute_script("return window.scrollY;")
< initial_position,
message="Scroll to top should have been initiated within 5 seconds",
)
# Force instant scroll to top to complete the test reliably
# (smooth scroll animation may be too slow/interrupted in parallel execution)
self.driver.execute_script("window.scrollTo(0, 0);")
# Verify final position
final_position = self.driver.execute_script("return window.scrollY;")
assert (
final_position == 0
), f"Page should be at top (0), but is at {final_position}"
@pytest.mark.python_only
class TestPython(BaseTests):
def test_000_configured(self) -> None:
"""Check if all kernel classes are instantiated in OOMAnalyser.AllKernelConfigs"""
all_kernel_classes = {
cls.__name__
for name, cls in inspect.getmembers(OOMAnalyser, inspect.isclass)
if issubclass(cls, OOMAnalyser.BaseKernelConfig)
}
all_configured_kernels = {
inst.__class__.__name__ for inst in OOMAnalyser.AllKernelConfigs
}
missing = all_kernel_classes - all_configured_kernels
assert not missing, f"Missing kernel instances in AllKernelConfigs: {missing}"
def test_010_trigger_proc_space(self) -> None:
"""Test RE to find the name of the trigger process"""
first = self.get_first_line(OOMAnalyser.OOMDisplay.example_rhel7)
pattern = OOMAnalyser.OOMAnalyser.oom_result.kconfig.EXTRACT_PATTERN[
"invoked oom-killer"
][0]
rec = re.compile(pattern, re.MULTILINE)
match = rec.search(first)
assert (
match
), "Error: re.search('invoked oom-killer') failed for simple process name"
first = first.replace("sed", "VM Monitoring Task")
match = rec.search(first)
assert (
match
), "Error: re.search('invoked oom-killer') failed for process name with space"
@pytest.mark.parametrize(
"process_name,description",
[
pytest.param("sed", "simple process name", id="simple"),
pytest.param(
"VM Monitoring Task", "process name with spaces", id="with-spaces"
),
pytest.param(
"kworker/0:1",
"process name with special characters (slash and colon)",
id="special-chars",
),
pytest.param("php-fpm", "process name with hyphen", id="hyphen"),
],
)
def test_020_killed_proc_space(self, process_name, description) -> None:
"""Test RE to find name of the killed process"""
pattern_key = "global oom: kill process - pid, name and score"
original_process_name = "sed"
original_text = self.get_lines(OOMAnalyser.OOMDisplay.example_rhel7, -2)
pattern = OOMAnalyser.OOMAnalyser.oom_result.kconfig.EXTRACT_PATTERN[
pattern_key
][0]
rec = re.compile(pattern, re.MULTILINE)
text = original_text.replace(original_process_name, process_name)
match = rec.search(text)
assert (
match
), f'Error: Search for process names failed for {description}: "{process_name}"'
@pytest.mark.parametrize(
"expected_pos,line",
[
pytest.param(
1,
"[11686.888109] CPU: 4 PID: 29481 Comm: sed Not tainted 3.10.0-514.6.1.el7.x86_64 #1",
id="timestamp-only",
),
pytest.param(
5,
"Apr 01 14:13:32 mysrv kernel: CPU: 4 PID: 29481 Comm: sed Not tainted 3.10.0-514.6.1.el7.x86_64 #1",
id="syslog-prefix",
),
pytest.param(
6,
"Apr 01 14:13:32 mysrv kernel: [11686.888109] CPU: 4 PID: 29481 Comm: sed Not tainted 3.10.0-514.6.1.el7.x86_64 #1",
id="syslog-timestamp",
),
],
)
def test_030_OOMEntity_number_of_columns_to_strip(self, expected_pos, line) -> None:
"""Test stripping useless / leading columns"""
oom_entity = OOMAnalyser.OOMEntity(OOMAnalyser.OOMDisplay.example_rhel7)
to_strip = oom_entity._number_of_columns_to_strip(line)
assert (
to_strip == expected_pos
), f'Calc wrong number of columns to strip for "{line}": got: {to_strip}, expect: {expected_pos}'
@pytest.mark.parametrize(
"input_lines,expected,description",
[
pytest.param(
["Apr 01 14:13:32 mysrv kernel:CPU: 4 PID: 29481 Comm: sed"],
["Apr 01 14:13:32 mysrv CPU: 4 PID: 29481 Comm: sed"],
"kernel: without space (edge case)",
id="no-space",
),
pytest.param(
["Apr 01 14:13:32 mysrv kernel: CPU: 4 PID: 29481 Comm: sed"],
["Apr 01 14:13:32 mysrv CPU: 4 PID: 29481 Comm: sed"],
"kernel: with space (standard case)",
id="with-space",
),
pytest.param(
["Apr 01 14:13:32 mysrv kernel:[11686.888109] Out of memory"],
["Apr 01 14:13:32 mysrv [11686.888109] Out of memory"],
"kernel: before timestamp pattern",
id="before-timestamp",
),
pytest.param(
["[11686.888109] CPU: 4 PID: 29481 Comm: sed"],
["[11686.888109] CPU: 4 PID: 29481 Comm: sed"],
"no kernel: pattern (unchanged)",
id="no-kernel-pattern",
),
pytest.param(
[
"Apr 01 14:13:32 mysrv kernel:Out of memory: Killed process 29481",
"Apr 01 14:13:32 mysrv kernel: CPU: 4 PID: 29481",
"[11686.888109] Hardware name: HP ProLiant",
],
[
"Apr 01 14:13:32 mysrv Out of memory: Killed process 29481",
"Apr 01 14:13:32 mysrv CPU: 4 PID: 29481",
"[11686.888109] Hardware name: HP ProLiant",
],
"multiple lines with mixed patterns",
id="multiple-lines",
),
pytest.param(
[],
[],
"empty list",
id="empty",
),
pytest.param(
["kernel:kernel: This is unusual but possible"],
[" This is unusual but possible"],
"multiple kernel: occurrences (edge case)",
id="multiple-occurrences",
),
],
)
def test_031_OOMEntity_remove_kernel_colon(
self, input_lines, expected, description
) -> None:
"""Test removal of kernel: pattern from OOM log lines"""
oom_entity = OOMAnalyser.OOMEntity(OOMAnalyser.OOMDisplay.example_rhel7)
result = oom_entity._remove_kernel_colon(input_lines)
assert (
result == expected
), f"Failed test: {description}. Got: {result}, expected: {expected}"
def test_040_extract_block_from_next_pos(self) -> None:
"""Test extracting a single block (all lines till the next line with a colon)"""
oom = OOMAnalyser.OOMEntity(OOMAnalyser.OOMDisplay.example_rhel7)
analyser = OOMAnalyser.OOMAnalyser(oom)
text = analyser._extract_block_from_next_pos("Hardware name:")
expected = """\
Hardware name: HP ProLiant DL385 G7, BIOS A18 12/08/2012
ffff880182272f10 00000000021dcb0a ffff880418207938 ffffffff816861ac
ffff8804182079c8 ffffffff81681157 ffffffff810eab9c ffff8804182fe910
ffff8804182fe928 0000000000000202 ffff880182272f10 ffff8804182079b8
"""
assert text == expected
@pytest.mark.parametrize(
"text,kversion",
[
pytest.param(
"CPU: 0 PID: 19163 Comm: kworker/0:0 Tainted: G OE 5.4.0-80-lowlatency #90~18.04.1-Ubuntu",
"5.4.0-80-lowlatency",
id="ubuntu-5.4",
),
pytest.param(
"CPU: 4 PID: 1 Comm: systemd Not tainted 3.10.0-1062.9.1.el7.x86_64 #1",
"3.10.0-1062.9.1.el7.x86_64",
id="rhel7-3.10",
),
],
)
def test_050_extract_kernel_version(self, text, kversion) -> None:
"""Test extracting the kernel version"""
oom = OOMAnalyser.OOMEntity(OOMAnalyser.OOMDisplay.example_rhel7)
analyser = OOMAnalyser.OOMAnalyser(oom)
analyser.oom_entity.text = text
assert analyser._identify_kernel_version(), analyser.oom_result.error_msg
assert analyser.oom_result.kversion == kversion
@pytest.mark.parametrize(
"kcfg,kversion",
[
pytest.param(
OOMAnalyser.KernelConfig_6_11(),
"CPU: 4 UID: 123456 PID: 29481 Comm: sed Not tainted 6.12.0 #1",
id="6.11",
),
pytest.param(
OOMAnalyser.KernelConfig_5_18(),
"CPU: 4 PID: 29481 Comm: sed Not tainted 5.23.0 #1",
id="5.18",
),
pytest.param(
OOMAnalyser.KernelConfig_5_12(),
"CPU: 4 PID: 29481 Comm: sed Not tainted 5.13.0-514 #1",
id="5.12",
),
pytest.param(
OOMAnalyser.KernelConfig_5_8(),
"CPU: 4 PID: 29481 Comm: sed Not tainted 5.8.0-514 #1",
id="5.8",
),
pytest.param(
OOMAnalyser.KernelConfig_5_4(),
"CPU: 4 PID: 29481 Comm: sed Not tainted 5.5.1 #1",
id="5.4",
),
pytest.param(
OOMAnalyser.KernelConfig_4_6(),
"CPU: 4 PID: 29481 Comm: sed Not tainted 4.6.0-514 #1",
id="4.6",
),
pytest.param(
OOMAnalyser.KernelConfig_3_10_EL7(),
"CPU: 4 PID: 29481 Comm: sed Not tainted 3.10.0-1062.9.1.el7.x86_64 #1",
id="3.10-el7",
),
pytest.param(
OOMAnalyser.BaseKernelConfig(),
"CPU: 4 PID: 29481 Comm: sed Not tainted 2.33.0 #1",
id="2.33-base",
),
],
)
def test_060_choosing_kernel_config(self, kcfg, kversion) -> None:
"""Test choosing the right kernel configuration"""
oom = OOMAnalyser.OOMEntity(kversion)
analyser = OOMAnalyser.OOMAnalyser(oom)
kernel_found = analyser._identify_kernel_version()
assert kernel_found, f'Failed to identify kernel from string "{kversion}"'
analyser._choose_kernel_config()
result = analyser.oom_result.kconfig
assert type(result) == type(kcfg), (
f'Mismatch between expected kernel config "{type(kcfg)}" and chosen '
f'config "{type(result)}" for kernel version "{kversion}"'
)
@pytest.mark.parametrize(
"kversion,min_version,expected_result",
[
pytest.param("5.19-rc6", (5, 16, ""), True, id="5.19-rc6-ge-5.16"),
pytest.param("5.19-rc6", (5, 19, ""), True, id="5.19-rc6-ge-5.19"),
pytest.param("5.19-rc6", (5, 20, ""), False, id="5.19-rc6-lt-5.20"),
pytest.param("5.18.6-arch1-1", (5, 18, ""), True, id="5.18-arch-ge-5.18"),
pytest.param("5.18.6-arch1-1", (5, 1, ""), True, id="5.18-arch-ge-5.1"),
pytest.param("5.18.6-arch1-1", (5, 19, ""), False, id="5.18-arch-lt-5.19"),
pytest.param(
"5.13.0-1028-aws #31~20.04.1-Ubuntu",
(5, 14, ""),
False,
id="5.13-aws-lt-5.14",
),
pytest.param(
"5.13.0-1028-aws #31~20.04.1-Ubuntu",
(5, 13, ""),
True,
id="5.13-aws-ge-5.13",
),
pytest.param(
"5.13.0-1028-aws #31~20.04.1-Ubuntu",
(5, 13, "-aws"),
True,
id="5.13-aws-with-string",
),
pytest.param(
"5.13.0-1028-aws #31~20.04.1-Ubuntu",
(5, 13, "not_in_version"),
False,
id="5.13-aws-wrong-string",
),
pytest.param(
"5.13.0-1028-aws #31~20.04.1-Ubuntu",
(5, 12, ""),
True,
id="5.13-aws-ge-5.12",
),
pytest.param("4.14.288", (5, 0, ""), False, id="4.14-lt-5.0"),
pytest.param("4.14.288", (4, 14, ""), True, id="4.14-ge-4.14"),
pytest.param(
"3.10.0-514.6.1.el7.x86_64 #1",
(3, 11, ""),
False,
id="3.10-el7-lt-3.11",
),
pytest.param(
"3.10.0-514.6.1.el7.x86_64 #1",
(3, 10, ".el7."),
True,