-
Notifications
You must be signed in to change notification settings - Fork 564
/
test.py
executable file
·2430 lines (2166 loc) · 90.6 KB
/
test.py
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
#! /usr/bin/env python3
#
# Copyright (c) 2009 University of Washington
#
# SPDX-License-Identifier: GPL-2.0-only
#
import argparse
import fnmatch
import os
import queue
import shutil
import signal
import subprocess
import sys
import threading
import time
import xml.etree.ElementTree as ET
from utils import get_list_from_file
# Global variable
args = None
# imported from waflib Logs
colors_lst = {
"USE": True,
"BOLD": "\x1b[01;1m",
"RED": "\x1b[01;31m",
"GREEN": "\x1b[32m",
"YELLOW": "\x1b[33m",
"PINK": "\x1b[35m",
"BLUE": "\x1b[01;34m",
"CYAN": "\x1b[36m",
"GREY": "\x1b[37m",
"NORMAL": "\x1b[0m",
"cursor_on": "\x1b[?25h",
"cursor_off": "\x1b[?25l",
}
def get_color(cl):
if colors_lst["USE"]:
return colors_lst.get(cl, "")
return ""
class color_dict(object):
def __getattr__(self, a):
return get_color(a)
def __call__(self, a):
return get_color(a)
colors = color_dict()
#
# XXX This should really be part of a ns3 command to list the configuration
# items relative to optional ns-3 pieces.
#
# A list of interesting configuration items in the ns3 configuration
# cache which we may be interested in when deciding on which examples
# to run and how to run them. These are set by ns3 during the
# configuration phase and the corresponding assignments are usually
# found in the associated subdirectory CMakeLists.txt files.
#
interesting_config_items = [
"NS3_ENABLED_MODULES",
"NS3_ENABLED_CONTRIBUTED_MODULES",
"NS3_MODULE_PATH",
"ENABLE_EXAMPLES",
"ENABLE_TESTS",
"EXAMPLE_DIRECTORIES",
"ENABLE_PYTHON_BINDINGS",
"NSCLICK",
"ENABLE_BRITE",
"ENABLE_OPENFLOW",
"APPNAME",
"BUILD_PROFILE",
"VERSION",
"PYTHON",
"VALGRIND_FOUND",
]
ENABLE_EXAMPLES = True
ENABLE_TESTS = True
NSCLICK = False
ENABLE_BRITE = False
ENABLE_OPENFLOW = False
ENABLE_PYTHON_BINDINGS = False
EXAMPLE_DIRECTORIES = []
APPNAME = ""
BUILD_PROFILE = ""
BUILD_PROFILE_SUFFIX = ""
VERSION = ""
PYTHON = ""
VALGRIND_FOUND = True
#
# This will be given a prefix and a suffix when the ns3 config file is
# read.
#
test_runner_name = "test-runner"
#
# If the user has constrained us to run certain kinds of tests, we can tell ns3
# to only build
#
core_kinds = ["core", "performance", "system", "unit"]
#
# Exclude tests that are problematic for valgrind.
#
core_valgrind_skip_tests = [
"routing-click",
"lte-rr-ff-mac-scheduler",
"lte-tdmt-ff-mac-scheduler",
"lte-fdmt-ff-mac-scheduler",
"lte-pf-ff-mac-scheduler",
"lte-tta-ff-mac-scheduler",
"lte-fdbet-ff-mac-scheduler",
"lte-ttbet-ff-mac-scheduler",
"lte-fdtbfq-ff-mac-scheduler",
"lte-tdtbfq-ff-mac-scheduler",
"lte-pss-ff-mac-scheduler",
]
#
# Parse the examples-to-run file if it exists.
#
# This function adds any C++ examples or Python examples that are to be run
# to the lists in example_tests and python_tests, respectively.
#
def parse_examples_to_run_file(
examples_to_run_path,
cpp_executable_dir,
python_script_dir,
example_tests,
example_names_original,
python_tests,
):
# Look for the examples-to-run file exists.
if not os.path.exists(examples_to_run_path):
return
# Each tuple in the C++ list of examples to run contains
#
# (example_name, do_run, do_valgrind_run)
#
# where example_name is the executable to be run, do_run is a
# condition under which to run the example, and do_valgrind_run is
# a condition under which to run the example under valgrind. This
# is needed because NSC causes illegal instruction crashes with
# some tests when they are run under valgrind.
#
# Note that the two conditions are Python statements that
# can depend on ns3 configuration variables. For example,
# when NSC was in the codebase, we could write:
#
# ("tcp-nsc-lfn", "NSC_ENABLED == True", "NSC_ENABLED == False", "QUICK"),
#
cpp_examples = get_list_from_file(examples_to_run_path, "cpp_examples")
for cpp_example in cpp_examples:
# Old example specification did not include
# 'fullness', so for compatibility,
# allow 3 components, & set the 'fullness' to QUICK
if len(cpp_example) == 3:
example_name, do_run, do_valgrind_run = cpp_example
fullness = "QUICK"
elif len(cpp_example) == 4:
example_name, do_run, do_valgrind_run, fullness = cpp_example
fullness: str = fullness.upper()
if fullness != "QUICK" and fullness != "EXTENSIVE" and fullness != "TAKES_FOREVER":
raise ValueError(
f"Invalid value provided for example '{example_name}' "
+ f"expected 'QUICK', 'EXTENSIVE', or 'TAKES_FOREVER', got: '{fullness}'"
)
else:
# If we have the name of the example we're error-ing for, provide it
# Otherwise, just give a generic message
if len(cpp_example) >= 1:
raise RuntimeError(
f"Incorrect number of fields declaration of example '{cpp_example[0]}', "
+ f"expected 3, or 4 got: {len(cpp_example)}"
)
else:
raise RuntimeError(
f"Incorrect number of fields declaration of example, "
+ f"expected 3, or 4 got: {len(cpp_example)}"
)
# Separate the example name from its arguments.
example_name_original = example_name
example_name_parts = example_name.split(" ", 1)
if len(example_name_parts) == 1:
example_name = example_name_parts[0]
example_arguments = ""
else:
example_name = example_name_parts[0]
example_arguments = example_name_parts[1]
# Add the proper prefix and suffix to the example name to
# match what is done in the CMakeLists.txt file.
example_path = "%s%s-%s%s" % (APPNAME, VERSION, example_name, BUILD_PROFILE_SUFFIX)
# Set the full path for the example.
example_path = os.path.join(cpp_executable_dir, example_path)
example_path += ".exe" if sys.platform == "win32" else ""
example_name = os.path.join(os.path.relpath(cpp_executable_dir, NS3_BUILDDIR), example_name)
# Add all of the C++ examples that were built, i.e. found
# in the directory, to the list of C++ examples to run.
if os.path.exists(example_path):
# Add any arguments to the path.
if len(example_name_parts) != 1:
example_path = "%s %s" % (example_path, example_arguments)
example_name = "%s %s" % (example_name, example_arguments)
# Add this example.
example_tests.append((example_name, example_path, do_run, do_valgrind_run, fullness))
example_names_original.append(example_name_original)
# Each tuple in the Python list of examples to run contains
#
# (example_name, do_run, fullness)
#
# where example_name is the Python script to be run and
# do_run is a condition under which to run the example.
#
# Note that the condition is a Python statement that can
# depend on ns3 configuration variables. For example,
#
# ("brite-generic-example.py", "ENABLE_BRITE == True", "QUICK"),
#
python_examples = get_list_from_file(examples_to_run_path, "python_examples")
# Old example specification did not include
# 'fullness', so for compatibility,
# allow 2 components, & set the 'fullness' to QUICK
for python_example in python_examples:
if len(python_example) == 2:
example_name, do_run = python_example
fullness = "QUICK"
elif len(python_example) == 3:
example_name, do_run, fullness = python_example
else:
# If we have the name of the example we're error-ing for, provide it
# Otherwise, just give a generic message
if len(python_example) >= 1:
raise RuntimeError(
f"Incorrect number of fields declaration of example '{python_example[0]}', "
+ f"expected 2, or 3 got: {len(python_example)}"
)
else:
raise RuntimeError(
f"Incorrect number of fields declaration of example, "
+ f"expected 2, or 3 got: {len(python_example)}"
)
# Separate the example name from its arguments.
example_name_parts = example_name.split(" ", 1)
if len(example_name_parts) == 1:
example_name = example_name_parts[0]
example_arguments = ""
else:
example_name = example_name_parts[0]
example_arguments = example_name_parts[1]
# Set the full path for the example.
example_path = os.path.join(python_script_dir, example_name)
# Add all of the Python examples that were found to the
# list of Python examples to run.
if os.path.exists(example_path):
# Add any arguments to the path.
if len(example_name_parts) != 1:
example_path = "%s %s" % (example_path, example_arguments)
# Add this example.
python_tests.append((example_path, do_run, fullness))
#
# The test suites are going to want to output status. They are running
# concurrently. This means that unless we are careful, the output of
# the test suites will be interleaved. Rather than introducing a lock
# file that could unintentionally start serializing execution, we ask
# the tests to write their output to a temporary directory and then
# put together the final output file when we "join" the test tasks back
# to the main thread. In addition to this issue, the example programs
# often write lots and lots of trace files which we will just ignore.
# We put all of them into the temp directory as well, so they can be
# easily deleted.
#
TMP_OUTPUT_DIR = "testpy-output"
def read_test(test):
result = test.find("Result").text
name = test.find("Name").text
if not test.find("Reason") is None:
reason = test.find("Reason").text
else:
reason = ""
if not test.find("Time") is None:
time_real = test.find("Time").get("real")
else:
time_real = ""
return (result, name, reason, time_real)
#
# A simple example of writing a text file with a test result summary. It is
# expected that this output will be fine for developers looking for problems.
#
def node_to_text(test, f, test_type="Suite"):
(result, name, reason, time_real) = read_test(test)
if reason:
reason = " (%s)" % reason
output = '%s: Test %s "%s" (%s)%s\n' % (result, test_type, name, time_real, reason)
f.write(output)
for details in test.findall("FailureDetails"):
f.write(" Details:\n")
f.write(" Message: %s\n" % details.find("Message").text)
f.write(" Condition: %s\n" % details.find("Condition").text)
f.write(" Actual: %s\n" % details.find("Actual").text)
f.write(" Limit: %s\n" % details.find("Limit").text)
f.write(" File: %s\n" % details.find("File").text)
f.write(" Line: %s\n" % details.find("Line").text)
for child in test.findall("Test"):
node_to_text(child, f, "Case")
def translate_to_text(results_file, text_file):
text_file += ".txt" if ".txt" not in text_file else ""
print('Writing results to text file "%s"...' % text_file, end="")
et = ET.parse(results_file)
with open(text_file, "w", encoding="utf-8") as f:
for test in et.findall("Test"):
node_to_text(test, f)
for example in et.findall("Example"):
result = example.find("Result").text
name = example.find("Name").text
if not example.find("Time") is None:
time_real = example.find("Time").get("real")
else:
time_real = ""
output = '%s: Example "%s" (%s)\n' % (result, name, time_real)
f.write(output)
print("done.")
#
# A simple example of writing an HTML file with a test result summary. It is
# expected that this will eventually be made prettier as time progresses and
# we have time to tweak it. This may end up being moved to a separate module
# since it will probably grow over time.
#
def translate_to_html(results_file, html_file):
html_file += ".html" if ".html" not in html_file else ""
print("Writing results to html file %s..." % html_file, end="")
with open(html_file, "w", encoding="utf-8") as f:
f.write("<html>\n")
f.write("<body>\n")
f.write("<center><h1>ns-3 Test Results</h1></center>\n")
#
# Read and parse the whole results file.
#
et = ET.parse(results_file)
#
# Iterate through the test suites
#
f.write("<h2>Test Suites</h2>\n")
for suite in et.findall("Test"):
#
# For each test suite, get its name, result and execution time info
#
(result, name, reason, time) = read_test(suite)
#
# Print a level three header with the result, name and time. If the
# test suite passed, the header is printed in green. If the suite was
# skipped, print it in orange, otherwise assume something bad happened
# and print in red.
#
if result == "PASS":
f.write('<h3 style="color:green">%s: %s (%s)</h3>\n' % (result, name, time))
elif result == "SKIP":
f.write(
'<h3 style="color:#ff6600">%s: %s (%s) (%s)</h3>\n'
% (result, name, time, reason)
)
else:
f.write('<h3 style="color:red">%s: %s (%s)</h3>\n' % (result, name, time))
#
# The test case information goes in a table.
#
f.write('<table border="1">\n')
#
# The first column of the table has the heading Result
#
f.write("<th> Result </th>\n")
#
# If the suite crashed or is skipped, there is no further information, so just
# declare a new table row with the result (CRASH or SKIP) in it. Looks like:
#
# +--------+
# | Result |
# +--------+
# | CRASH |
# +--------+
#
# Then go on to the next test suite. Valgrind and skipped errors look the same.
#
if result in ["CRASH", "SKIP", "VALGR"]:
f.write("<tr>\n")
if result == "SKIP":
f.write('<td style="color:#ff6600">%s</td>\n' % result)
else:
f.write('<td style="color:red">%s</td>\n' % result)
f.write("</tr>\n")
f.write("</table>\n")
continue
#
# If the suite didn't crash, we expect more information, so fill out
# the table heading row. Like,
#
# +--------+----------------+------+
# | Result | Test Case Name | Time |
# +--------+----------------+------+
#
f.write("<th>Test Case Name</th>\n")
f.write("<th> Time </th>\n")
#
# If the test case failed, we need to print out some failure details
# so extend the heading row again. Like,
#
# +--------+----------------+------+-----------------+
# | Result | Test Case Name | Time | Failure Details |
# +--------+----------------+------+-----------------+
#
if result == "FAIL":
f.write("<th>Failure Details</th>\n")
#
# Now iterate through all the test cases.
#
for case in suite.findall("Test"):
#
# Get the name, result and timing information from xml to use in
# printing table below.
#
(result, name, reason, time) = read_test(case)
#
# If the test case failed, we iterate through possibly multiple
# failure details
#
if result == "FAIL":
#
# There can be multiple failures for each test case. The first
# row always gets the result, name and timing information along
# with the failure details. Remaining failures don't duplicate
# this information but just get blanks for readability. Like,
#
# +--------+----------------+------+-----------------+
# | Result | Test Case Name | Time | Failure Details |
# +--------+----------------+------+-----------------+
# | FAIL | The name | time | It's busted |
# +--------+----------------+------+-----------------+
# | | | | Really broken |
# +--------+----------------+------+-----------------+
# | | | | Busted bad |
# +--------+----------------+------+-----------------+
#
first_row = True
for details in case.findall("FailureDetails"):
#
# Start a new row in the table for each possible Failure Detail
#
f.write("<tr>\n")
if first_row:
first_row = False
f.write('<td style="color:red">%s</td>\n' % result)
f.write("<td>%s</td>\n" % name)
f.write("<td>%s</td>\n" % time)
else:
f.write("<td></td>\n")
f.write("<td></td>\n")
f.write("<td></td>\n")
f.write("<td>")
f.write("<b>Message: </b>%s, " % details.find("Message").text)
f.write("<b>Condition: </b>%s, " % details.find("Condition").text)
f.write("<b>Actual: </b>%s, " % details.find("Actual").text)
f.write("<b>Limit: </b>%s, " % details.find("Limit").text)
f.write("<b>File: </b>%s, " % details.find("File").text)
f.write("<b>Line: </b>%s" % details.find("Line").text)
f.write("</td>\n")
#
# End the table row
#
f.write("</td>\n")
else:
#
# If this particular test case passed, then we just print the PASS
# result in green, followed by the test case name and its execution
# time information. These go off in <td> ... </td> table data.
# The details table entry is left blank.
#
# +--------+----------------+------+---------+
# | Result | Test Case Name | Time | Details |
# +--------+----------------+------+---------+
# | PASS | The name | time | |
# +--------+----------------+------+---------+
#
f.write("<tr>\n")
f.write('<td style="color:green">%s</td>\n' % result)
f.write("<td>%s</td>\n" % name)
f.write("<td>%s</td>\n" % time)
f.write("<td>%s</td>\n" % reason)
f.write("</tr>\n")
#
# All of the rows are written, so we need to end the table.
#
f.write("</table>\n")
#
# That's it for all of the test suites. Now we have to do something about
# our examples.
#
f.write("<h2>Examples</h2>\n")
#
# Example status is rendered in a table just like the suites.
#
f.write('<table border="1">\n')
#
# The table headings look like,
#
# +--------+--------------+--------------+---------+
# | Result | Example Name | Elapsed Time | Details |
# +--------+--------------+--------------+---------+
#
f.write("<th> Result </th>\n")
f.write("<th>Example Name</th>\n")
f.write("<th>Elapsed Time</th>\n")
f.write("<th>Details</th>\n")
#
# Now iterate through all the examples
#
for example in et.findall("Example"):
#
# Start a new row for each example
#
f.write("<tr>\n")
#
# Get the result and name of the example in question
#
(result, name, reason, time) = read_test(example)
#
# If the example either failed or crashed, print its result status
# in red; otherwise green. This goes in a <td> ... </td> table data
#
if result == "PASS":
f.write('<td style="color:green">%s</td>\n' % result)
elif result == "SKIP":
f.write('<td style="color:#ff6600">%s</fd>\n' % result)
else:
f.write('<td style="color:red">%s</td>\n' % result)
#
# Write the example name as a new tag data.
#
f.write("<td>%s</td>\n" % name)
#
# Write the elapsed time as a new tag data.
#
f.write("<td>%s</td>\n" % time)
#
# Write the reason, if it exist
#
f.write("<td>%s</td>\n" % reason)
#
# That's it for the current example, so terminate the row.
#
f.write("</tr>\n")
#
# That's it for the table of examples, so terminate the table.
#
f.write("</table>\n")
#
# And that's it for the report, so finish up.
#
f.write("</body>\n")
f.write("</html>\n")
print("done.")
#
# Python Control-C handling is broken in the presence of multiple threads.
# Signals get delivered to the runnable/running thread by default and if
# it is blocked, the signal is simply ignored. So we hook sigint and set
# a global variable telling the system to shut down gracefully.
#
thread_exit = False
def sigint_hook(signal, frame):
global thread_exit
thread_exit = True
return 0
#
# In general, the build process itself naturally takes care of figuring out
# which tests are built into the test runner. For example, if ns3 configure
# determines that ENABLE_EMU is false due to some missing dependency,
# the tests for the emu net device simply will not be built and will
# therefore not be included in the built test runner.
#
# Examples, however, are a different story. In that case, we are just given
# a list of examples that could be run. Instead of just failing, for example,
# an example if its library support is not present, we look into the ns3
# saved configuration for relevant configuration items.
#
# XXX This function pokes around in the ns3 internal state file. To be a
# little less hacky, we should add a command to ns3 to return this info
# and use that result.
#
platform = sys.platform
platform = "bsd" if "bsd" in platform else platform
lock_filename = ".lock-ns3_%s_build" % platform
def read_ns3_config():
try:
# sys.platform reports linux2 for python2 and linux for python3
with open(lock_filename, "rt", encoding="utf-8") as f:
for line in f:
if line.startswith("top_dir ="):
key, val = line.split("=")
top_dir = eval(val.strip())
if line.startswith("out_dir ="):
key, val = line.split("=")
out_dir = eval(val.strip())
except FileNotFoundError:
print(
"The .lock-ns3 file was not found. You must configure before running test.py.",
file=sys.stderr,
)
sys.exit(2)
global NS3_BASEDIR
NS3_BASEDIR = top_dir
global NS3_BUILDDIR
NS3_BUILDDIR = out_dir
with open(lock_filename, encoding="utf-8") as f:
for line in f.readlines():
for item in interesting_config_items:
if line.startswith(item):
exec(line, globals())
if args.verbose:
for item in interesting_config_items:
print("%s ==" % item, eval(item))
#
# It seems pointless to fork a process to run ns3 to fork a process to run
# the test runner, so we just run the test runner directly. The main thing
# that ns3 would do for us would be to sort out the shared library path but
# we can deal with that easily and do here.
#
# There can be many different ns-3 repositories on a system, and each has
# its own shared libraries, so ns-3 doesn't hardcode a shared library search
# path -- it is cooked up dynamically, so we do that too.
#
def make_paths():
have_DYLD_LIBRARY_PATH = False
have_LD_LIBRARY_PATH = False
have_PATH = False
have_PYTHONPATH = False
keys = list(os.environ.keys())
for key in keys:
if key == "DYLD_LIBRARY_PATH":
have_DYLD_LIBRARY_PATH = True
if key == "LD_LIBRARY_PATH":
have_LD_LIBRARY_PATH = True
if key == "PATH":
have_PATH = True
if key == "PYTHONPATH":
have_PYTHONPATH = True
pypath = os.environ["PYTHONPATH"] = os.path.join(NS3_BUILDDIR, "bindings", "python")
if not have_PYTHONPATH:
os.environ["PYTHONPATH"] = pypath
else:
os.environ["PYTHONPATH"] += ":" + pypath
if args.verbose:
print('os.environ["PYTHONPATH"] == %s' % os.environ["PYTHONPATH"])
if sys.platform == "darwin":
if not have_DYLD_LIBRARY_PATH:
os.environ["DYLD_LIBRARY_PATH"] = ""
for path in NS3_MODULE_PATH:
os.environ["DYLD_LIBRARY_PATH"] += ":" + path
if args.verbose:
print('os.environ["DYLD_LIBRARY_PATH"] == %s' % os.environ["DYLD_LIBRARY_PATH"])
elif sys.platform == "win32":
if not have_PATH:
os.environ["PATH"] = ""
for path in NS3_MODULE_PATH:
os.environ["PATH"] += ";" + path
if args.verbose:
print('os.environ["PATH"] == %s' % os.environ["PATH"])
elif sys.platform == "cygwin":
if not have_PATH:
os.environ["PATH"] = ""
for path in NS3_MODULE_PATH:
os.environ["PATH"] += ":" + path
if args.verbose:
print('os.environ["PATH"] == %s' % os.environ["PATH"])
else:
if not have_LD_LIBRARY_PATH:
os.environ["LD_LIBRARY_PATH"] = ""
for path in NS3_MODULE_PATH:
os.environ["LD_LIBRARY_PATH"] += ":" + str(path)
if args.verbose:
print('os.environ["LD_LIBRARY_PATH"] == %s' % os.environ["LD_LIBRARY_PATH"])
#
# Short note on generating suppressions:
#
# See the valgrind documentation for a description of suppressions. The easiest
# way to generate a suppression expression is by using the valgrind
# --gen-suppressions option. To do that you have to figure out how to run the
# test in question.
#
# If you do "test.py -v -g -s <suitename> then test.py will output most of what
# you need. For example, if you are getting a valgrind error in the
# devices-mesh-dot11s-regression test suite, you can run:
#
# ./test.py -v -g -s devices-mesh-dot11s-regression
#
# You should see in the verbose output something that looks like:
#
# Synchronously execute valgrind --suppressions=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/testpy.supp
# --leak-check=full --error-exitcode=2 /home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/build/debug/utils/ns3-dev-test-runner-debug
# --suite=devices-mesh-dot11s-regression --basedir=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev
# --tempdir=testpy-output/2010-01-12-22-47-50-CUT
# --out=testpy-output/2010-01-12-22-47-50-CUT/devices-mesh-dot11s-regression.xml
#
# You need to pull out the useful pieces, and so could run the following to
# reproduce your error:
#
# valgrind --suppressions=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/testpy.supp
# --leak-check=full --error-exitcode=2 /home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/build/debug/utils/ns3-dev-test-runner-debug
# --suite=devices-mesh-dot11s-regression --basedir=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev
# --tempdir=testpy-output
#
# Hint: Use the first part of the command as is, and point the "tempdir" to
# somewhere real. You don't need to specify an "out" file.
#
# When you run the above command you should see your valgrind error. The
# suppression expression(s) can be generated by adding the --gen-suppressions=yes
# option to valgrind. Use something like:
#
# valgrind --gen-suppressions=yes --suppressions=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/testpy.supp
# --leak-check=full --error-exitcode=2 /home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/build/debug/utils/ns3-dev-test-runner-debug
# --suite=devices-mesh-dot11s-regression --basedir=/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev
# --tempdir=testpy-output
#
# Now when valgrind detects an error it will ask:
#
# ==27235== ---- Print suppression ? --- [Return/N/n/Y/y/C/c] ----
#
# to which you just enter 'y'<ret>.
#
# You will be provided with a suppression expression that looks something like
# the following:
# {
# <insert_a_suppression_name_here>
# Memcheck:Addr8
# fun:_ZN3ns36dot11s15HwmpProtocolMac8SendPreqESt6vectorINS0_6IePreqESaIS3_EE
# fun:_ZN3ns36dot11s15HwmpProtocolMac10SendMyPreqEv
# fun:_ZN3ns36dot11s15HwmpProtocolMac18RequestDestinationENS_12Mac48AddressEjj
# ...
# the rest of the stack frame
# ...
# }
#
# You need to add a suppression name which will only be printed out by valgrind in
# verbose mode (but it needs to be there in any case). The entire stack frame is
# shown to completely characterize the error, but in most cases you won't need
# all of that info. For example, if you want to turn off all errors that happen
# when the function (fun:) is called, you can just delete the rest of the stack
# frame. You can also use wildcards to make the mangled signatures more readable.
#
# I added the following to the testpy.supp file for this particular error:
#
# {
# Suppress invalid read size errors in SendPreq() when using HwmpProtocolMac
# Memcheck:Addr8
# fun:*HwmpProtocolMac*SendPreq*
# }
#
# Now, when you run valgrind the error will be suppressed.
#
# Until ns-3.36, we used a suppression in testpy.supp in the top-level
# ns-3 directory. It was defined below, but commented out once it was
# no longer needed. If it is needed again in the future, define the
# below variable again, and remove the alternative definition to None
#
VALGRIND_SUPPRESSIONS_FILE = ".ns3.supp"
# VALGRIND_SUPPRESSIONS_FILE = None
# When the TEST_LOGS environment variable is set to 1 or true,
# NS_LOG is set to NS_LOG=*, and stdout/stderr
# from tests are discarded to prevent running out of memory.
TEST_LOGS = bool(os.getenv("TEST_LOGS", False))
def run_job_synchronously(shell_command, directory, valgrind, is_python, build_path=""):
if VALGRIND_SUPPRESSIONS_FILE is not None:
suppressions_path = os.path.join(NS3_BASEDIR, VALGRIND_SUPPRESSIONS_FILE)
if is_python:
path_cmd = PYTHON[0] + " " + os.path.join(NS3_BASEDIR, shell_command)
else:
if len(build_path):
path_cmd = os.path.join(build_path, shell_command)
else:
path_cmd = os.path.join(NS3_BUILDDIR, shell_command)
if valgrind:
if VALGRIND_SUPPRESSIONS_FILE:
cmd = (
"valgrind --suppressions=%s --leak-check=full --show-reachable=yes --error-exitcode=2 --errors-for-leak-kinds=all %s"
% (suppressions_path, path_cmd)
)
else:
cmd = (
"valgrind --leak-check=full --show-reachable=yes --error-exitcode=2 --errors-for-leak-kinds=all %s"
% (path_cmd)
)
else:
cmd = path_cmd
if args.verbose:
print("Synchronously execute %s" % cmd)
start_time = time.time()
proc = subprocess.Popen(
cmd,
shell=True,
cwd=directory,
stdout=subprocess.PIPE if not TEST_LOGS else subprocess.DEVNULL,
stderr=subprocess.PIPE if not TEST_LOGS else subprocess.STDOUT,
)
stdout_results, stderr_results = proc.communicate()
stdout_results = b"" if stdout_results is None else stdout_results
stderr_results = b"" if stderr_results is None else stderr_results
elapsed_time = time.time() - start_time
retval = proc.returncode
def decode_stream_results(stream_results: bytes, stream_name: str) -> str:
try:
stream_results = stream_results.decode()
except UnicodeDecodeError:
def decode(byte_array: bytes):
try:
byte_array.decode()
except UnicodeDecodeError:
return byte_array
# Find lines where the decoding error happened
non_utf8_lines = list(map(lambda line: decode(line), stream_results.splitlines()))
non_utf8_lines = list(filter(lambda line: line is not None, non_utf8_lines))
print(
f"Non-decodable characters found in {stream_name} output of {cmd}: {non_utf8_lines}"
)
# Continue decoding on errors
stream_results = stream_results.decode(errors="backslashreplace")
return stream_results
stdout_results = decode_stream_results(stdout_results, "stdout")
stderr_results = decode_stream_results(stderr_results, "stderr")
if args.verbose:
print("Return code = ", retval)
print("stderr = ", stderr_results)
return (retval, stdout_results, stderr_results, elapsed_time)
#
# This class defines a unit of testing work. It will typically refer to
# a test suite to run using the test-runner, or an example to run directly.
#
class Job:
def __init__(self):
self.is_break = False
self.is_skip = False
self.skip_reason = ""
self.is_example = False
self.is_pyexample = False
self.shell_command = ""
self.display_name = ""
self.basedir = ""
self.tempdir = ""
self.cwd = ""
self.tmp_file_name = ""
self.returncode = False
self.elapsed_time = 0
self.build_path = ""
#
# A job is either a standard job or a special job indicating that a worker
# thread should exist. This special job is indicated by setting is_break
# to true.
#
def set_is_break(self, is_break):
self.is_break = is_break
#
# If a job is to be skipped, we actually run it through the worker threads
# to keep the PASS, FAIL, CRASH and SKIP processing all in one place.
#
def set_is_skip(self, is_skip):
self.is_skip = is_skip
#
# If a job is to be skipped, log the reason.
#
def set_skip_reason(self, skip_reason):
self.skip_reason = skip_reason
#
# Examples are treated differently than standard test suites. This is
# mostly because they are completely unaware that they are being run as
# tests. So we have to do some special case processing to make them look
# like tests.
#
def set_is_example(self, is_example):
self.is_example = is_example
#
# Examples are treated differently than standard test suites. This is
# mostly because they are completely unaware that they are being run as
# tests. So we have to do some special case processing to make them look
# like tests.
#
def set_is_pyexample(self, is_pyexample):
self.is_pyexample = is_pyexample
#
# This is the shell command that will be executed in the job. For example,
#
# "utils/ns3-dev-test-runner-debug --test-name=some-test-suite"
#
def set_shell_command(self, shell_command):
self.shell_command = shell_command
#