YAML coverage generator minor cleanup
[open-adventure.git] / tests / coverage_dungeon.py
1 #!/usr/bin/env python
2
3 # This is the open-adventure dungeon text coverage report generator. It
4 # consumes a YAML description of the dungeon and determines whether the
5 # various strings contained are present within the test check files.
6 #
7 # The default HTML output is appropriate for use with Gitlab CI.
8 # You can override it with a command-line argument.
9
10 import os
11 import sys
12 import yaml
13 import re
14
15 TEST_DIR = "."
16 YAML_PATH = "../adventure.yaml"
17 HTML_TEMPLATE_PATH = "coverage_dungeon.html.tpl"
18 DEFAULT_HTML_OUTPUT_PATH = "../coverage/adventure.yaml.html"
19
20 STDOUT_REPORT_CATEGORY = "  {name:.<19}: {percent:5.1f}% covered ({covered} of {total})\n"
21
22 HTML_SUMMARY_ROW = '''
23     <tr>
24         <td class="headerItem"><a href="#{name}">{name}:</a></td>
25         <td class="headerCovTableEntry">{total}</td>
26         <td class="headerCovTableEntry">{covered}</td>
27         <td class="headerCovTableEntry">{percent:.1f}%</td>
28     </tr>
29 '''
30
31 HTML_CATEGORY_SECTION = '''
32     <tr id="{id}"></tr>
33     {rows}
34     <tr>
35         <td>&nbsp;</td>
36     </tr>
37 '''
38
39 HTML_CATEGORY_HEADER = '''
40     <tr>
41         <td class="tableHead" width="60%" colspan="{colspan}">{label}</td>
42         {cells}
43     </tr>
44 '''
45
46 HTML_CATEGORY_HEADER_CELL = '<td class="tableHead" width="15%">{}</td>\n'
47
48 HTML_CATEGORY_COVERAGE_CELL = '<td class="{}">&nbsp;</td>\n'
49
50 HTML_CATEGORY_ROW = '''
51     <tr>
52         <td class="coverFile" colspan="{colspan}">{id}</td>
53         {cells}
54     </tr>
55 '''
56
57 def search(needle, haystack):
58     # Search for needle in haystack, first escaping needle for regex, then
59     # replacing %s, %d, etc. with regex wildcards, so the variable messages
60     # within the dungeon definition will actually match
61         
62     if needle == None or needle == "" or needle == "NO_MESSAGE":
63         # if needle is empty, assume we're going to find an empty string
64         return True
65     
66     needle_san = re.escape(needle) \
67              .replace("\\n", "\n") \
68              .replace("\\t", "\t") \
69              .replace("\%S", ".*") \
70              .replace("\%s", ".*") \
71              .replace("\%d", ".*") \
72              .replace("\%V", ".*")
73
74     return re.search(needle_san, haystack)
75
76 def obj_coverage(objects, text, report):
77     # objects have multiple descriptions based on state
78     for i, objouter in enumerate(objects):
79         (obj_name, obj) = objouter
80         if obj["descriptions"]:
81             for j, desc in enumerate(obj["descriptions"]):
82                 name = "{}[{}]".format(obj_name, j)
83                 if name not in report["messages"]:
84                     report["messages"][name] = {"covered" : False}
85                     report["total"] += 1
86                 if report["messages"][name]["covered"] != True and search(desc, text):
87                     report["messages"][name]["covered"] = True
88                     report["covered"] += 1
89
90 def loc_coverage(locations, text, report):
91     # locations have a long and a short description, that each have to
92     # be checked seperately
93     for name, loc in locations:
94         desc = loc["description"]
95         if name not in report["messages"]:
96             report["messages"][name] = {"long" : False, "short": False}
97             report["total"] += 2
98         if report["messages"][name]["long"] != True and search(desc["long"], text):
99             report["messages"][name]["long"] = True
100             report["covered"] += 1
101         if report["messages"][name]["short"] != True and search(desc["short"], text):
102             report["messages"][name]["short"] = True
103             report["covered"] += 1
104
105 def hint_coverage(obituaries, text, report):
106     # hints have a "question" where the hint is offered, followed
107     # by the actual hint if the player requests it
108     for i, hintouter in enumerate(obituaries):
109         hint = hintouter["hint"]
110         name = hint["name"]
111         if name not in report["messages"]:
112             report["messages"][name] = {"question" : False, "hint": False}
113             report["total"] += 2
114         if report["messages"][name]["question"] != True and search(hint["question"], text):
115             report["messages"][name]["question"] = True
116             report["covered"] += 1
117         if report["messages"][name]["hint"] != True and search(hint["hint"], text):
118             report["messages"][name]["hint"] = True
119             report["covered"] += 1
120
121 def obit_coverage(obituaries, text, report):
122     # obituaries have a "query" where it asks the player for a resurrection,
123     # followed by a snarky comment if the player says yes
124     for name, obit in enumerate(obituaries):
125         if name not in report["messages"]:
126             report["messages"][name] = {"query" : False, "yes_response": False}
127             report["total"] += 2
128         if report["messages"][name]["query"] != True and search(obit["query"], text):
129             report["messages"][name]["query"] = True
130             report["covered"] += 1
131         if report["messages"][name]["yes_response"] != True and search(obit["yes_response"], text):
132             report["messages"][name]["yes_response"] = True
133             report["covered"] += 1
134
135 def threshold_coverage(classes, text, report):
136     # works for class thresholds and turn threshold, which have a "message"
137     # property
138     for name, item in enumerate(classes):
139         if name not in report["messages"]:
140             report["messages"][name] = {"covered" : "False"}
141             report["total"] += 1
142         if report["messages"][name]["covered"] != True and search(item["message"], text):
143             report["messages"][name]["covered"] = True
144             report["covered"] += 1
145
146 def arb_coverage(arb_msgs, text, report):
147     for name, message in arb_msgs:
148         if name not in report["messages"]:
149             report["messages"][name] = {"covered" : False}
150             report["total"] += 1
151         if report["messages"][name]["covered"] != True and search(message, text):
152             report["messages"][name]["covered"] = True
153             report["covered"] += 1
154
155 def specials_actions_coverage(items, text, report):
156     # works for actions or specials
157     for name, item in items:
158         if name not in report["messages"]:
159             report["messages"][name] = {"covered" : False}
160             report["total"] += 1
161         if report["messages"][name]["covered"] != True and search(item["message"], text):
162             report["messages"][name]["covered"] = True
163             report["covered"] += 1
164
165 def coverage_report(db, check_file_contents):
166     # Create report for each catagory, including total items,  number of items
167     # covered, and a list of the covered messages
168     report = {}
169     for name in db.keys():
170         # initialize each catagory
171         report[name] = {
172             "name" : name, # convenience for string formatting
173             "total" : 0,
174             "covered" : 0,
175             "messages" : {}
176         }
177
178     # search for each message in ever test check file
179     for chk in check_file_contents:
180         arb_coverage(db["arbitrary_messages"], chk, report["arbitrary_messages"])
181         hint_coverage(db["hints"], chk, report["hints"])
182         loc_coverage(db["locations"], chk, report["locations"])
183         obit_coverage(db["obituaries"], chk, report["obituaries"])
184         obj_coverage(db["objects"], chk, report["objects"])
185         specials_actions_coverage(db["actions"], chk, report["actions"])
186         specials_actions_coverage(db["specials"], chk, report["specials"])
187         threshold_coverage(db["classes"], chk, report["classes"])
188         threshold_coverage(db["turn_thresholds"], chk, report["turn_thresholds"])
189
190     return report
191
192 if __name__ == "__main__":
193     # load DB
194     try:
195         with open(YAML_PATH, "r") as f:
196             db = yaml.load(f)
197     except IOError as e:
198         print('ERROR: could not load {} ({}})'.format(YAML_PATH, e.strerror))
199         exit(-1)
200
201     # get contents of all the check files
202     check_file_contents = []
203     for filename in os.listdir(TEST_DIR):
204         if filename.endswith(".chk"):
205             with open(filename, "r") as f:
206                 check_file_contents.append(f.read())
207
208     # run coverage analysis report on dungeon database
209     report = coverage_report(db, check_file_contents)
210
211     # render report output
212     categories_html = ""
213     summary_html = ""
214     summary_stdout = "adventure.yaml coverage rate:\n"
215     for name, category in sorted(report.items()):
216         # ignore categories with zero entries
217         if category["total"] > 0:
218             # Calculate percent coverage
219             category["percent"] = (category["covered"] / float(category["total"])) * 100
220
221             # render section header
222             cat_messages = sorted(category["messages"].items())
223             cat_keys = cat_messages[0][1].keys()
224             headers_html = ""
225             colspan = 10 - len(cat_keys)
226             for key in cat_keys:
227                 headers_html += HTML_CATEGORY_HEADER_CELL.format(key)
228             category_html = HTML_CATEGORY_HEADER.format(colspan=colspan, label=category["name"], cells=headers_html)
229
230             # render message coverage row
231             for message_id, covered in cat_messages:
232                 category_html_row = ""
233                 for key, value in covered.items():
234                     category_html_row += HTML_CATEGORY_COVERAGE_CELL.format("uncovered" if value != True else "covered")
235                 category_html += HTML_CATEGORY_ROW.format(id=message_id,colspan=colspan, cells=category_html_row)
236             categories_html += HTML_CATEGORY_SECTION.format(id=name, rows=category_html)
237
238             # render category summaries
239             summary_stdout += STDOUT_REPORT_CATEGORY.format(**category)
240             summary_html += HTML_SUMMARY_ROW.format(**category)
241
242     # output some quick report stats
243     print(summary_stdout)
244
245     if len(sys.argv) > 1:
246         html_output_path = sys.argv[1]
247     else:
248         html_output_path = DEFAULT_HTML_OUTPUT_PATH
249
250     # render HTML report
251     try:
252         with open(HTML_TEMPLATE_PATH, "r") as f:
253             # read in HTML template
254             html_template = f.read()
255     except IOError as e:
256         print('ERROR: reading HTML report template failed ({})'.format(e.strerror))
257         exit(-1)
258
259     # parse template with report and write it out
260     try:
261         with open(html_output_path, "w") as f:
262             f.write(html_template.format(categories=categories_html, summary=summary_html))
263     except IOError as e:
264         print('ERROR: writing HTML report failed ({})'.format(e.strerror))