summaryrefslogtreecommitdiff
path: root/graph-coverage.py
blob: f54005c2f2e7f9c613f79fae4909c9c714af2730 (plain)
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
#!/usr/bin/python

# Copyright (c) 2013 Samsung Electronics
# Copyright (c) 2013-2014 Daniel Willmann <daniel@totalueberwachung.de>

import os
import argparse
from datetime import datetime
import sqlite3

class MakeList(argparse.Action):
	def __call__(self, parser, namespace, values, option_string=None):
		setattr(namespace, self.dest, values.split(','))

parser = argparse.ArgumentParser(description="Record/graph coverage information")

display = parser.add_argument_group('Record')
# Cluster functions together
display.add_argument("-r", "--record", dest="coverage_file",
                type=argparse.FileType('r'),
		help="update database with coverage information")
display.add_argument("-i", "--id", dest="date",
                help="id to use for build (default is current date)")

graph = parser.add_argument_group('Graph options')
graph.add_argument("-g", "--graph", dest="graph",
		help="generate a graph.")
graph.add_argument("-l", "--label", dest="label",
		help="Label of the graph", default="")
graph.add_argument("-f", "--files", dest="files", action=MakeList,
                help="Only use these files for calculation")
graph.add_argument("-m", "--max-points", dest="max_points", type=int, default=30,
		help="Only display the last N coverage points (default 30)")

parser.add_argument("-q", "--quiet",
		action="store_false", dest="verbose", default=True,
		help="don't print status messages to stdout")
parser.add_argument("-p", "--prefix", dest="prefix",
		help="prefix needed for the addr2line tool")
parser.add_argument("db", help="database file")

options = parser.parse_args()

conn = sqlite3.connect(options.db)

c = conn.cursor()

try:
        c.execute('''CREATE TABLE coverage (date text, testname text,
                        filename text, all_fn int, covered_fn int,
                        all_ln int, covered_ln int)''')
except:
        pass

if options.date:
        date = options.date
else:
        date = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
print "Collecting coverage for build", date

testname = ""
filename = ""
all_fn = 0
cov_fn = 0
all_ln = 0
cov_ln = 0

state = "NONE"
if options.coverage_file:
  for line in options.coverage_file:
        line = line.rstrip()
        if line == "end_of_record":
                if state == "NONE":
                        continue
                c.execute("INSERT INTO coverage VALUES (?, ?, ?, ?, ?, ?, ?)",
                                (date, testname, filename, all_fn, cov_fn,
                                all_ln, cov_ln))
                testname = ""
                filename = ""
                all_fn = 0
                cov_fn = 0
                all_ln = 0
                cov_ln = 0
                state = "NONE"
                continue

        try:
                header, data = line.split(':')
        except Exception as e:
                print "Error while parsing %s: %s" % (line, e)
                sys.exit(1)

        if state == "NONE" and header == "TN":
                testname = data
                state = "TEST"
                continue
        if state == "TEST" and header == "SF":
                if options.prefix:
                        if data.startswith(options.prefix):
                                filename = data.replace(options.prefix, "")
                        else:
                                testname = ""
                                filename = ""
                                all_fn = 0
                                cov_fn = 0
                                all_ln = 0
                                cov_ln = 0
                                state = "NONE"
                else:
                        filename = data
                continue
        if state == "TEST" and header == "FNF":
                all_fn = int(data)
                continue
        if state == "TEST" and header == "FNH":
                cov_fn = int(data)
                continue
        if state == "TEST" and header == "LF":
                all_ln = int(data)
                continue
        if state == "TEST" and header == "LH":
                cov_ln = int(data)
                continue

conn.commit()

if options.graph:
        import matplotlib

        matplotlib.use("GtkAgg")
#        matplotlib.rc('text', usetex=True)
        matplotlib.rc('font', family='serif')
        matplotlib.rc('axes', titlesize='small')
        matplotlib.rc('legend', fontsize='small')
        matplotlib.rc('figure.subplot', bottom=0.20, top=0.90, left=0.10, right=0.95)

        import numpy
        from numpy import array
        from pylab import *

        dates = c.execute("SELECT DISTINCT date from coverage ORDER BY date").fetchall()

	# Only graph the last x coverage points
	if (len(dates) > options.max_points):
		dates = dates[-options.max_points:]

        fn_per = []
        ln_per = []

        files = []
        querystr = "SELECT date, SUM(all_fn), SUM(covered_fn), SUM(all_ln), SUM(covered_ln) from coverage WHERE date = ?"
        if options.files:
                querystr = querystr + " and ( " + " or ".join(["filename like ?" for x in options.files]) + " )"
                files = [x + "%" for x in options.files]

        for date in dates:
                params = [date[0]]
                if files:
                        params.extend(files)
                query = c.execute(querystr, params)

                for result in query.fetchall():
			if not result[0]:
				print "Missing coverage information"
				fn_per.append(0.0)
				ln_per.append(0.0)
				continue
                        print result[0]
                        print "Function coverage: % 3.2f%%" % (float(result[2])/result[1] * 100, )
                        print "Line coverage:     % 3.2f%%" % (float(result[4])/result[3] * 100, )
                        fn_per.append(float(result[2])/result[1]*100)
                        ln_per.append(float(result[4])/result[3]*100)

        fncov = plot(numpy.arange(len(dates)), fn_per, 'o-', linewidth=1.0)
        lncov = plot(numpy.arange(len(dates)), ln_per, 'o-',linewidth=1.0)

        legend((fncov[0], lncov[0]), ('Functions %0.2f%%'%(fn_per[-1]), 'Lines %0.2f%%'%(ln_per[-1])), loc=3)
        ind = numpy.arange(len(dates))
        lims = xlim()
        xlim((lims[0]-0.5, lims[1]+0.5))
        xticks(ind, [x[0].replace(' ', '\n') for x in dates], rotation=60)
        lims = ylim()
#        ylim((int(lims[0]), int(lims[1])+1))
        ylim((0,100))
        ylabel('coverage in %')
        title(options.label)
        axhline(80, color='green', lw=2, alpha=0.5)
        axhline(40, color='red', lw=2, alpha=0.5)
#        fill_between(xlim(), 0, 30, facecolor='red', alpha=0.3)
#        fill_between(xlim(), 80, 100, facecolor='green', alpha=0.3)


        savefig(options.graph, transparent=False)
        close()

conn.close()