test_parse_psl_coverage.py 12.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
import os
import sys
from json2html import *
import random
import logging
from os.path import join, abspath
from pathlib import Path
import json
from yattag import Doc

test_dir = Path(Path(abspath(__file__)).parent).parent
build_dir = os.path.join(str(test_dir.absolute()), "build")
func_cov_dir = os.path.join(str(build_dir), "functional_coverage")
14 15 16 17
psl_dir = os.path.join(str(func_cov_dir), "coverage_data")
html_dir = os.path.join(str(func_cov_dir), "html")

dut_top = " "
18 19 20

log = logging.getLogger(__name__)

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

def merge_psl_coverage_files(out_file, in_file_prefix):
	"""
	Merge PSL coverage details from multiple files to single file
	"""
	if(out_file.startswith(in_file_prefix)):
		log.error("File name for merging should not have the same prefix as merged files")
		system.exit(0)

	json_out_path = os.path.join(func_cov_dir, out_file)
	json_out_file = open(json_out_path, 'w')
	json_out_list = []
	for filename in os.listdir(psl_dir):
		if (not (filename.startswith(in_file_prefix) and \
		         filename.endswith(".json"))):
			continue

		in_filename = os.path.join(psl_dir, filename)
39
		print("Merging JSON PSL coverage from: {}\n".format(in_filename))
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
		json_in_file = open(in_filename, 'r')
		json_obj = json.load(json_in_file)

		# Add test name to each PSL point
		for psl_point in json_obj["details"]:
			psl_point["test"] = filename.strip(in_file_prefix).replace(".json","")

		json_out_list.extend(json_obj["details"])

	json_str = json.dumps(json_out_list, indent=1)
	json_out_file.write(json_str)
	json_out_file.close()


def collapse_psl_coverage_files(non_collapsed):
	"""
	Collapses PSL coverage which is output from multiple testcase/testbench
	runs into single psl_coverage output.
	If DUT is instantiated in multiple testbenches, above levels of
	hierarchy from "dut_top" will be ignored and these files will be collapsed.
	E.g. if "dut_top" = "can_top_level",
	then multiple instances of CTU CAN FD will not generate multiple PSL outputs.
	Collapsing policy is following:
		- cover - If at least one of collapsed points is covered -> COVERED
		- assert - If at least one of collapsed points is failed -> FAILED
	Each cover point which is covered has also appended a testcase name where
	it was covered.
	"""
	log.info("Collapsing PSL points with common hierarchy below: {}".format(dut_top))
	collapsed = []

	# We do stupid quadratic sort because we don't really care if it is gonna last 10
	# or 40 seconds... If we ever get to the point that this takes too long we know
	# that we have reeealy lot of PSL points and we turned into Semiconductor monster!
	for psl_in in non_collapsed:

		found = False
		for psl_out in collapsed:

			# Check if name in output list is equal to searched name from "dut_top"
			# entity down. Skip if not
			in_name = psl_in["name"].split(dut_top)[-1]
			out_name = psl_out["name"].split(dut_top)[-1]
			if (out_name != in_name):
				continue

			if (not ("colapsed_points" in psl_out)):
				psl_out["colapsed_name"] = str(dut_top + in_name)
				psl_out["colapsed_points"] = []

			psl_out["colapsed_points"].append(psl_in)

			# If any of colapsed points is covered -> whole point is covered
			if (psl_in["status"] == "covered"):
				psl_out["status"] = "covered"
				psl_out["count"] += psl_in["count"]

			# If any of colapsed points is failed -> whole point is failed
			if (psl_in["status"] == "failed"):
				psl_out["status"] = "failed"

			# Assertion hits add up for both failed and passed
			if (psl_out["directive"] == "assertion"):
				psl_out["count"] += psl_in["count"]

			found = True
			break;

		# Input point was not collapsed into any of output points -> Add directly
		if (not found):
			collapsed.append(psl_in)

	return collapsed


def get_collapsed_file_name(psl_point):
	"""
	Create unique file name for collapsed PSL points
	"""
	file_name = dut_top + psl_point["name"].split(dut_top)[-1]
	file_name = file_name.replace(".","_")
	file_name = file_name.replace(" ","_")
	file_name = file_name.replace(")","_")
	file_name = file_name.replace("(","_")
	file_name = file_name.replace("@","_")
	file_name = file_name + "_" + str(psl_point["line"])
	return file_name


def load_json_psl_coverage(filename):
130 131 132
	"""
	Load PSL Coverage JSON file to JSON object.
	"""
133
	psl_cov_path = os.path.join(func_cov_dir, filename)
134 135
	
	# Read JSON string from file
136
	log.info("Loading JSON PSL output: {}".format(psl_cov_path))
137 138 139 140 141 142 143 144 145 146 147 148
	json_file = open(psl_cov_path, 'r')
	return json.load(json_file)


def split_json_coverage_by_file(json):
	"""
	Parse input PSL Coverage JSON file. Group PSL endpoints by file.
	Return dictionary in format:
		{filename : psl_points} where psl_points is a list of PSL points in
		filename.
	"""
	file_dict = {}
149
	for psl_point in json:
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

		# Create new list if first PSL of a file is parsed
		if (not(psl_point["file"] in file_dict)):
			file_dict[psl_point["file"]] = []
		
		file_dict[psl_point["file"]].append(psl_point)

	return file_dict


def add_html_table_header(doc, tag, text, headers, back_color="White"):
	"""
	Add header to HTML table.
	"""
	with tag('tr'):
		for header in headers:
			with tag('th', bgcolor=back_color):
				text(header)


def calc_coverage_results(psl_points, psl_type):
	"""
	Calculate coverage results from list of PSL points in JSON format.
	"""
	ok = 0
	nok = 0
	for psl_point in psl_points:
		if (psl_point["directive"] != psl_type):
			continue;
		if (psl_point["status"] == "passed" or
			psl_point["status"] == "covered"):
			ok += 1
		else:
			nok +=1
	return [ok, nok]


def calc_coverage_color(coverage):
	"""
	Return color based on coverage result.
	"""
	if (coverage < 0 or coverage > 100):
		log("Invalid coverage input should be between 0 - 100 %")
		return

	if (coverage > 90):
		return "Lime"
	elif (coverage > 80):
		return "Orange"
	elif (coverage > 70):
		return "OrangeRed"
	else:
		return "Red"


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
def print_cov_cell_percentage(doc, tag, text, psl_points, coverage_type, merge_abs_vals):
	"""
	"""
	[ok, nok] = calc_coverage_results(psl_points, coverage_type)
	summ = max(1, ok + nok)
	percents = ok/summ * 100
	color = calc_coverage_color(percents)

	if (merge_abs_vals):
		if (ok + nok > 0):
			with tag('td', bgcolor=color):
				text("({}/{}) {}%".format(ok, summ, percents))
		else:
			with tag('td', bgcolor="Silver"):
				text("NA")
	else:
		with tag('td'):
			text(ok)
		with tag('td'):
			text(nok)

		if (ok + nok > 0):
			with tag('td', bgcolor=color):
				text("{}%".format(percents))
		else:
			with tag('td', bgcolor="Silver"):
				text("NA")	
				

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
def add_psl_html_header(doc, tag, text, filename, psl_points):
	"""
	Create HTML page header with info about coverage data within list of
	PSL points in JSON format.
	"""
	with tag('table', width='100%', border=0, cellspacing=0, cellpadding=0):
		with tag('tr'):			
			with tag('th', ('class','title')):
				with tag('font', size=10):
					text("GHDL PSL Functional coverage report")
			with tag('table', width='100%', border="1px solid black"):
				headers = ["Filename"]
				headers.append("Covered")
				headers.append("Not-Covered")
				headers.append("Functional coverage")
				headers.append("Passed")
				headers.append("Failed")
				headers.append("Assertions passed")
				add_html_table_header(doc, tag, text, headers, back_color="Aquamarine")

				with tag('td'):
					text(filename)

				# Calculate results for each type
				coverage_types = ["cover", "assertion"]
				for coverage_type in coverage_types:
260 261
					print_cov_cell_percentage(doc, tag, text, psl_points, \
						coverage_type, merge_abs_vals=False)
262 263


264
def add_non_colapsed_psl_table_entry(doc, tag, text, psl_point, def_bg_color="White"):
265
	"""
266 267
	Add HTML table entry for non-collapsed PSL functional coverage point. 

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
	with tag('td'):
		text(psl_point["name"].split(".")[-1])		
	with tag('td'):
		text(psl_point["test"])
	with tag('td', width="50%", style="word-break:break-all;"):
		text(dut_top + psl_point["name"])
	with tag('td'):
		text(psl_point["line"])
	with tag('td'):
		text(psl_point["count"])

	if (psl_point["status"] == "covered" or \
		psl_point["status"] == "passed"):
		color = "Lime"
	else:
		color = "red"

	with tag('td', ('bgcolor',color)):
		text(psl_point["status"])


def add_colapsed_psl_table_entry(doc, tag, text, psl_point, def_bg_color="White"):
	"""
	Add HTML table entry for collapsed PSL functional coverage point. Adds
	llink reference to collapsed entries on separate site.
	"""
	with tag('td'):
		text(psl_point["name"].split(".")[-1])
	
	with tag('td'):
		file_name = get_collapsed_file_name(psl_point)
		with tag('a', href=file_name+".html"):
			text("Open collapsed tests")
	with tag('td'):
		text(dut_top + psl_point["name"].split(dut_top)[-1])
	with tag('td'):
		text(psl_point["line"])
	with tag('td'):
		text(psl_point["count"])

	if (psl_point["status"] == "covered" or \
		psl_point["status"] == "passed"):
		color = "Lime"
	else:
		color = "red"

	with tag('td', ('bgcolor',color)):
		text(psl_point["status"])
317

318 319 320 321 322 323 324 325 326 327

def add_psl_table_entry(doc, tag, text, psl_point, def_bg_color="White"):
	"""
	Add PSL point in JSON format to HTML table. For collapsed entries,
	overall result is shown and link to collapsed points is inserted.
	"""
	# Add default entry (single or collapsed)
	with tag('tr', ('bgcolor',def_bg_color)):
		if ("colapsed_points" in psl_point):
			add_colapsed_psl_table_entry(doc, tag, text, psl_point, def_bg_color="White")
328
		else:
329
			add_non_colapsed_psl_table_entry(doc, tag, text, psl_point, def_bg_color="White")
330

331 332 333 334 335
	# Create separate page with collapsed PSL points for this PSL statement
	# Add unique filename
	if ("colapsed_points" in psl_point):
		file_name = os.path.join(html_dir, get_collapsed_file_name(psl_point))
		create_psl_file_page(file_name, psl_point["colapsed_points"]);
336 337 338 339 340 341


def create_psl_file_page(filename, psl_points):
	"""
	Create HTML file with list of PSL coverage statements.
	"""
342
	parsed_file_name = os.path.basename(filename)
343
	html_cov_path = os.path.join(html_dir, 
344
						"{}.html".format(parsed_file_name))
345 346 347 348 349
	html_file = open(html_cov_path, 'w')

	doc, tag, text = Doc().tagtext()

	# Add Common header
350
	add_psl_html_header(doc, tag, text, parsed_file_name, psl_points)
351 352 353 354 355 356 357 358 359 360

	# Add "Cover" and "Assertion" points
	psl_types = [{"name" : "Cover Points" , "type" : "cover"}, \
				 {"name" : "Assertions" , "type" : "assertion"}]
	for psl_type in psl_types:
		with tag('p'):
			with tag('table', width='100%', border="1px solid black"):
				with tag('caption'):
					with tag('font', size=5):
						text(psl_type["name"])
361
				titles = ["PSL Point Name", "Test name", "Full Path Name", "Line", "Count", "Status"]
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
				add_html_table_header(doc, tag, text, titles, back_color="Peru")
				for psl_point in psl_points:
					if (psl_point["directive"] == psl_type["type"]):
						add_psl_table_entry(doc, tag, text, psl_point)

	html_file.write(doc.getvalue())
	html_file.close()


def create_psl_file_refs_table(doc, tag, text, psl_by_files):
	"""
	Create entries to HTML table for each file. Calculates
	coverage summary for each file. Adds Reference to files.
	"""
	for file_name, psl_list in psl_by_files.items():
		with tag('tr'):
			with tag('td'):
379
				name = os.path.basename(file_name)
380
				with tag('a', href= os.path.join("html", name + ".html")):
381
					text(name)
382 383
			coverage_types = ["cover", "assertion"]
			for coverage_type in coverage_types:
384 385
				print_cov_cell_percentage(doc, tag, text, psl_list, \
						coverage_type, merge_abs_vals=True)
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


def create_psl_report(psl_by_files, psl_orig):
	"""
	Generates PSL report. Each list within psl_by_files has separate
	HTML page. Summary page is created from psl_orig
	"""
	# Create HTML page for each source file
	for file_name, psl_list in psl_by_files.items():
		create_psl_file_page(file_name, psl_list)

	html_rep_path = os.path.join(func_cov_dir, "functional_coverage_report.html")
	html_file = open(html_rep_path, 'w')

	doc, tag, text = Doc().tagtext()

	# Add Common Header
	add_psl_html_header(doc, tag, text, "TOP LEVEL", psl_orig)

	with tag('p'):
		with tag('table', width="100%", border="1px solid black"):
			header = ["File name", "Coverage", "Asserts"]
			add_html_table_header(doc, tag, text, header, back_color="Peru")
			create_psl_file_refs_table(doc, tag, text, psl_by_files)
	
	html_file.write(doc.getvalue())
	html_file.close()


if __name__ == "__main__":

417 418
	#dut_top = "can_top_level"
	dut_top = "."
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

	# Merge PSL coverage files from all Testcases
	merge_psl_coverage_files("merged_psl.json", "psl_cov")
	json_orig = load_json_psl_coverage("merged_psl.json")
	json_by_file = split_json_coverage_by_file(json_orig)

	# Colapse for each source file and also Merge all colapsed into
	# single list so that overal coverage is calculated only out of colapsed
	# psl points!
	json_by_file_colapsed = {}
	json_together_colapsed = []
	for filename, psls_for_file in json_by_file.items():
		colapsed = collapse_psl_coverage_files(psls_for_file);
		json_by_file_colapsed[filename] = colapsed
		json_together_colapsed.extend(colapsed)

	# Create PSL report
	create_psl_report(json_by_file_colapsed, json_together_colapsed)