unit_test 7.81 KB
Newer Older
Matthew P. Russell's avatar
Matthew P. Russell committed
1
#!/g/15/2020uc/support/bin/python3.7
Matthew P. Russell's avatar
Matthew P. Russell committed
2
3
4
5
6
7
8
9
"""
unit_test
matt russell
comp15 2020 summer
updated 12/11/2020

unit_test - a frictionless C++ unit testing framework.

Matthew P. Russell's avatar
Matthew P. Russell committed
10
details relating to this script can be found in the README
Matthew P. Russell's avatar
Matthew P. Russell committed
11
"""
Matthew P. Russell's avatar
Matthew P. Russell committed
12
13
14
15
16
17
18
19
20
21
import subprocess
import sys
import re
import os
import shutil
from math import ceil

#-----------------------------------------------------------------------------#
#                              initial setup                                  #
#-----------------------------------------------------------------------------#
Matthew P. Russell's avatar
Matthew P. Russell committed
22
ORIG_DRIVERFILE = '/comp/15/lib/unit_test_driver.cpp' 
23
DRIVERFILE      = './unit_test_driver.cpp'            # Must match Makefile
Matthew P. Russell's avatar
Matthew P. Russell committed
24
25
26
27
28

# color codes for pretty printing to the terminal
FAILURE = "31"
SUCCESS = "32"
INFO    = "34"
Matthew P. Russell's avatar
Matthew P. Russell committed
29
30
OSTREAM = "35"
OUTPUT  = "37"
Matthew P. Russell's avatar
Matthew P. Russell committed
31
32
33
34

# inform prints the provided string to cout in the provided color
# if linebreak == True, add a dotted line
# if extraline == True, add an extra newline
Matthew P. Russell's avatar
Matthew P. Russell committed
35
36
37
38
def inform(s, color=INFO, linebreak=False):    
    if color == INFO:
        sys.stderr.write("\n\n")

Matthew P. Russell's avatar
Matthew P. Russell committed
39
40
41
42
43
    sys.stderr.write("\033[1;" + color + "m" + s + "\033[0m\n")

    if linebreak:
        sys.stderr.write("-----------------------------------\n")

Matthew P. Russell's avatar
Matthew P. Russell committed
44
45
46
47
48
49
50
def std_out(s, color=OSTREAM, linebreak=False):

    sys.stderr.write("\n\033[1;" + color + "m" + s + "\033[0m\n")

    if linebreak:
        sys.stderr.write("------\n")

Matthew P. Russell's avatar
Matthew P. Russell committed
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
# cleanup removes the copied driver
def cleanup():
    os.remove(DRIVERFILE)
        
inform("\nsetting up tests", color=INFO, linebreak=True)

# copy the (incomplete) driver to the cwd
try:    
    shutil.copyfile(ORIG_DRIVERFILE, DRIVERFILE)
except shutil.SameFileError:  # if the driver is already here
    pass


#-----------------------------------------------------------------------------#
#     extract test names and function definitions from the testing file(s)    #
#-----------------------------------------------------------------------------#
test_files = [f for f in os.listdir('./') if "_tests.cpp" in f]
test_names = []
decl_lines = []

for test_file_name in test_files:
    curr_test_file = open(test_file_name, 'r').read()

    # extract the void function declarations that take no args
    curr_test_list = re.findall(r'\n\s*void .*\(\)', curr_test_file)

    # extract the names of the tests for this test file
    test_names.extend([x.split()[1].split('(')[0] for x in curr_test_list])

    # extract the function definitions of the tests for this test file
    # these will be used to forward declare the functions in the driver
    decl_lines.extend([x.lstrip() + ';\n' for x in curr_test_list])

    
#-----------------------------------------------------------------------------#
#              augment the driver file with the test information              #
#-----------------------------------------------------------------------------#

# extract the contents of the driver file as a list of strings (one per line)
with open(DRIVERFILE, 'r') as driver_file:
    driver_contents = driver_file.readlines()
 
# find the right locations to insert the forward declarations and the pairs
for i, line in enumerate(driver_contents):
    if "typedef void (*FnPtr)();"           in line:  decl_line_num = i + 1           
    if "std::map<std::string, FnPtr> tests" in line:  pair_line_num = i + 1

# insert the pairs (note these are later in the file, so do them first)
for test_name in test_names:
    pair_line = "\t{ \"" + test_name + "\" , " + test_name + " },\n"
    driver_contents.insert(pair_line_num, pair_line)
    pair_line_num += 1

# insert the forward declarations
for decl_line in decl_lines:
    driver_contents.insert(decl_line_num, decl_line)
    decl_line_num += 1
  
# save the new driver file 
driver_contents = "".join(driver_contents)
with open(DRIVERFILE, 'w') as driver_file:
    driver_file.write(driver_contents)

Matthew P. Russell's avatar
Matthew P. Russell committed
114
inform("tests were set up successfully", color=SUCCESS)
Matthew P. Russell's avatar
Matthew P. Russell committed
115
116
117
118
119
120
121
122


#-----------------------------------------------------------------------------#
#            initialize variables for keeping track of the grade              #
#-----------------------------------------------------------------------------#

num_tests = len(test_names)

123
num_tests_passed = 0
Matthew P. Russell's avatar
Matthew P. Russell committed
124

125
num_valgrind_passed = 0
Matthew P. Russell's avatar
Matthew P. Russell committed
126
127
128
129
130
131
132
133
134
135
136

#-----------------------------------------------------------------------------#
#                            compile the tests                                #
#-----------------------------------------------------------------------------#
inform("compiling tests", color=INFO, linebreak=True)
compilation_result = subprocess.run(['make'],
                                    capture_output = True,
                                    universal_newlines = True)

# if compilation fails, show the result and quit
if compilation_result.returncode == 0:
Matthew P. Russell's avatar
Matthew P. Russell committed
137
    inform("compilation passed", color=SUCCESS)
Matthew P. Russell's avatar
Matthew P. Russell committed
138
139
else:
    inform("compilation failed", color=FAILURE, linebreak=True)
Matthew P. Russell's avatar
Matthew P. Russell committed
140
    inform(compilation_result.stderr, color=FAILURE)
Matthew P. Russell's avatar
Matthew P. Russell committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    subprocess.run(['make', 'clean'])
    cleanup()
    sys.exit(1)

#-----------------------------------------------------------------------------#
#                              run the tests                                  #
#-----------------------------------------------------------------------------#
for test in test_names:
    human_readable_name = " ".join(test.split('_'))
    
    inform(human_readable_name, color=INFO, linebreak=True)

    # run the test and capture the output of cerr
    test_result = subprocess.run(["./a.out", test],
                                 capture_output = True,
                                 universal_newlines = True)
    #test was successful
    if test_result.returncode == 0:
159
        num_tests_passed += 1
Matthew P. Russell's avatar
Matthew P. Russell committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

        inform("test passed", color=SUCCESS)

        # Run valgrind
        valgrind_command = ['valgrind',
                            '--leak-check=full',
                            '--show-leak-kinds=all',
                            './a.out',
                            test]

        VALGRIND_RESULT = subprocess.run(valgrind_command,
                                         capture_output=True,
                                         universal_newlines=True)

        # memory errors force nonzero return code by default
        if VALGRIND_RESULT.returncode != 0:
            valgrind_passed = False
        else:
Matthew P. Russell's avatar
Matthew P. Russell committed
178
            valgrind_passed = True # only set to False if leaks are present
Matthew P. Russell's avatar
Matthew P. Russell committed
179

Matthew P. Russell's avatar
Matthew P. Russell committed
180
181
            passphrase = "All heap blocks were freed -- no leaks are possible" 
            if passphrase not in VALGRIND_RESULT.stderr:
Matthew P. Russell's avatar
Matthew P. Russell committed
182
183

                # only capture the part after "LEAK SUMMARY"
Matthew P. Russell's avatar
Matthew P. Russell committed
184
                VALGRIND_INFO = VALGRIND_RESULT.stderr.split("LEAK SUMMARY")[1]
Matthew P. Russell's avatar
Matthew P. Russell committed
185
186

                # check for leaks
Matthew P. Russell's avatar
Matthew P. Russell committed
187
                for line in VALGRIND_INFO.split('\n'):
Matthew P. Russell's avatar
Matthew P. Russell committed
188
189
190
191
192
                    if "lost" in line and "0 bytes in 0 blocks" not in line:
                        valgrind_passed = False
                        break

        if valgrind_passed:
Matthew P. Russell's avatar
Matthew P. Russell committed
193
            inform("valgrind passed", color=SUCCESS)
194
            num_valgrind_passed += 1
Matthew P. Russell's avatar
Matthew P. Russell committed
195
        else:
Matthew P. Russell's avatar
Matthew P. Russell committed
196
            inform("valgrind failed", color=FAILURE)
Matthew P. Russell's avatar
Matthew P. Russell committed
197
            inform(VALGRIND_RESULT.stderr, color=FAILURE)
Matthew P. Russell's avatar
Matthew P. Russell committed
198
199
200
201
202
203
               
    # if here, then the regular test failed
    else:
        inform("test failed", color=FAILURE)
        if abs(test_result.returncode) == 11:
            inform("segmentation fault!", color=FAILURE)
Matthew P. Russell's avatar
Matthew P. Russell committed
204
205
206
207
208
209
210
211
212
213
        inform("valgrind failed by default", color=FAILURE)

    # print output streams if they exist in test
    if test_result.stdout:
        std_out("stdout", linebreak=True)
        inform(test_result.stdout, color=OUTPUT)
    if test_result.stderr:
        std_out("stderr", linebreak=True)
        inform(test_result.stderr, color=OUTPUT)

214
215
inform(str(num_tests_passsed) + " / " + str(num_tests) +
       " tests passed", color=INFO)
Matthew P. Russell's avatar
Matthew P. Russell committed
216

217
218
inform(str(num_valgrind_passsed) + " / " + str(num_tests) +
       " valgrind tests passed", color=INFO)
Matthew P. Russell's avatar
Matthew P. Russell committed
219
220
221
222

# clean up
subprocess.run(['make','clean'])
cleanup()