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.
7 # The default HTML output is appropriate for use with Gitlab CI.
8 # You can override it with a command-line argument.
16 YAML_PATH = "../adventure.yaml"
17 HTML_TEMPLATE_PATH = "../templates/coverage_dungeon.html.tpl"
18 DEFAULT_HTML_OUTPUT_PATH = "../coverage/adventure.yaml.html"
20 STDOUT_REPORT_CATEGORY = " {name:.<19}: {percent:5.1f}% covered ({covered} of {total})\n"
22 HTML_SUMMARY_ROW = '''
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>
31 HTML_CATEGORY_SECTION = '''
39 HTML_CATEGORY_HEADER = '''
41 <td class="tableHead" width="60%" colspan="{colspan}">{label}</td>
46 HTML_CATEGORY_HEADER_CELL = '<td class="tableHead" width="15%">{}</td>\n'
48 HTML_CATEGORY_COVERAGE_CELL = '<td class="{}"> </td>\n'
50 HTML_CATEGORY_ROW = '''
52 <td class="coverFile" colspan="{colspan}">{id}</td>
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
62 if needle == None or needle == "" or needle == "NO_MESSAGE":
63 # if needle is empty, assume we're going to find an empty string
66 needle_san = re.escape(needle) \
67 .replace("\\n", "\n") \
68 .replace("\\t", "\t") \
69 .replace("\%S", ".*") \
70 .replace("\%s", ".*") \
71 .replace("\%d", ".*") \
74 return re.search(needle_san, haystack)
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}
86 if report["messages"][name]["covered"] != True and search(desc, text):
87 report["messages"][name]["covered"] = True
88 report["covered"] += 1
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}
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
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"]
111 if name not in report["messages"]:
112 report["messages"][name] = {"question" : False, "hint": False}
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
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}
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
135 def threshold_coverage(classes, text, report):
136 # works for class thresholds and turn threshold, which have a "message"
138 for name, item in enumerate(classes):
139 if name not in report["messages"]:
140 report["messages"][name] = {"covered" : "False"}
142 if report["messages"][name]["covered"] != True and search(item["message"], text):
143 report["messages"][name]["covered"] = True
144 report["covered"] += 1
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}
151 if report["messages"][name]["covered"] != True and search(message, text):
152 report["messages"][name]["covered"] = True
153 report["covered"] += 1
155 def actions_coverage(items, text, report):
157 for name, item in items:
158 if name not in report["messages"]:
159 report["messages"][name] = {"covered" : False}
161 if report["messages"][name]["covered"] != True and search(item["message"], text):
162 report["messages"][name]["covered"] = True
163 report["covered"] += 1
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
169 for name in db.keys():
170 # initialize each catagory
172 "name" : name, # convenience for string formatting
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 actions_coverage(db["actions"], chk, report["actions"])
186 threshold_coverage(db["classes"], chk, report["classes"])
187 threshold_coverage(db["turn_thresholds"], chk, report["turn_thresholds"])
191 if __name__ == "__main__":
194 with open(YAML_PATH, "r") as f:
197 print('ERROR: could not load {} ({}})'.format(YAML_PATH, e.strerror))
200 # get contents of all the check files
201 check_file_contents = []
202 for filename in os.listdir(TEST_DIR):
203 if filename.endswith(".chk"):
204 with open(filename, "r") as f:
205 check_file_contents.append(f.read())
207 # run coverage analysis report on dungeon database
208 report = coverage_report(db, check_file_contents)
210 # render report output
213 summary_stdout = "adventure.yaml coverage rate:\n"
214 for name, category in sorted(report.items()):
215 # ignore categories with zero entries
216 if category["total"] > 0:
217 # Calculate percent coverage
218 category["percent"] = (category["covered"] / float(category["total"])) * 100
220 # render section header
221 cat_messages = sorted(category["messages"].items())
222 cat_keys = cat_messages[0][1].keys()
224 colspan = 10 - len(cat_keys)
226 headers_html += HTML_CATEGORY_HEADER_CELL.format(key)
227 category_html = HTML_CATEGORY_HEADER.format(colspan=colspan, label=category["name"], cells=headers_html)
229 # render message coverage row
230 for message_id, covered in cat_messages:
231 category_html_row = ""
232 for key, value in covered.items():
233 category_html_row += HTML_CATEGORY_COVERAGE_CELL.format("uncovered" if value != True else "covered")
234 category_html += HTML_CATEGORY_ROW.format(id=message_id,colspan=colspan, cells=category_html_row)
235 categories_html += HTML_CATEGORY_SECTION.format(id=name, rows=category_html)
237 # render category summaries
238 summary_stdout += STDOUT_REPORT_CATEGORY.format(**category)
239 summary_html += HTML_SUMMARY_ROW.format(**category)
241 # output some quick report stats
242 print(summary_stdout)
244 if len(sys.argv) > 1:
245 html_output_path = sys.argv[1]
247 html_output_path = DEFAULT_HTML_OUTPUT_PATH
251 with open(HTML_TEMPLATE_PATH, "r") as f:
252 # read in HTML template
253 html_template = f.read()
255 print('ERROR: reading HTML report template failed ({})'.format(e.strerror))
258 # parse template with report and write it out
260 with open(html_output_path, "w") as f:
261 f.write(html_template.format(categories=categories_html, summary=summary_html))
263 print('ERROR: writing HTML report failed ({})'.format(e.strerror))