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
197
198
199
200
201
202
203
204
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
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
260
261
262
263
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'optparse'
require 'json'
require 'httparty'
require_relative '../api/create_issue'
require_relative '../api/find_issues'
require_relative '../api/update_issue'
class CreateTestFailureIssues
DEFAULT_OPTIONS = {
project: nil,
tests_report_file: 'tests_report.json',
issue_json_folder: 'tmp/issues/'
}.freeze
def initialize(options)
@options = options
end
def execute
puts "[CreateTestFailureIssues] No failed tests!" if failed_tests.empty?
failed_tests.each_with_object([]) do |failed_test, existing_issues|
CreateTestFailureIssue.new(options.dup).upsert(failed_test, existing_issues).tap do |issue|
existing_issues << issue
File.write(File.join(options[:issue_json_folder], "issue-#{issue.iid}.json"), JSON.pretty_generate(issue.to_h))
end
end
end
private
attr_reader :options
def failed_tests
@failed_tests ||=
if File.exist?(options[:tests_report_file])
JSON.parse(File.read(options[:tests_report_file]))
else
puts "[CreateTestFailureIssues] #{options[:tests_report_file]} doesn't exist!"
[]
end
end
end
class CreateTestFailureIssue
MAX_TITLE_LENGTH = 255
WWW_GITLAB_COM_SITE = 'https://about.gitlab.com'
WWW_GITLAB_COM_GROUPS_JSON = "#{WWW_GITLAB_COM_SITE}/groups.json".freeze
WWW_GITLAB_COM_CATEGORIES_JSON = "#{WWW_GITLAB_COM_SITE}/categories.json".freeze
FEATURE_CATEGORY_METADATA_REGEX = /(?<=feature_category: :)\w+/
DEFAULT_LABELS = ['type::maintenance', 'test'].freeze
def self.server_host
@server_host ||= ENV.fetch('CI_SERVER_HOST', 'gitlab.com')
end
def self.project_path
@project_path ||= ENV.fetch('CI_PROJECT_PATH', 'gitlab-org/gitlab')
end
def self.file_base_url
@file_base_url ||= "https://#{server_host}/#{project_path}/-/blob/master/"
end
def self.report_item_regex
@report_item_regex ||= %r{^1\. \d{4}-\d{2}-\d{2}: https://#{server_host}/#{project_path}/-/jobs/.+$}
end
def initialize(options)
@project = options.delete(:project)
@api_token = options.delete(:api_token)
end
def upsert(failed_test, existing_issues = [])
existing_issue = find(failed_test, existing_issues)
if existing_issue
update_reports(existing_issue, failed_test)
existing_issue
else
create(failed_test)
end
end
private
attr_reader :project, :api_token
def find(failed_test, existing_issues = [])
test_hash = failed_test_hash(failed_test)
issue_from_existing_issues = existing_issues.find { |issue| issue.title.include?(test_hash) }
issue_from_issue_tracker = FindIssues
.new(project: project, api_token: api_token)
.execute(state: :opened, search: test_hash, in: :title, per_page: 1)
.first
existing_issue = issue_from_existing_issues || issue_from_issue_tracker
return unless existing_issue
puts "[CreateTestFailureIssue] Found issue '#{existing_issue.title}': #{existing_issue.web_url}!"
existing_issue
end
def update_reports(existing_issue, failed_test)
# We count the number of existing reports.
reports_count = existing_issue.description
.scan(self.class.report_item_regex)
.size.to_i + 1
# We include the number of reports in the header, for visibility.
issue_description = existing_issue.description.sub(/^### Reports.*$/, "### Reports (#{reports_count})")
# We add the current failure to the list of reports.
issue_description = "#{issue_description}\n#{report_list_item(failed_test)}"
UpdateIssue
.new(project: project, api_token: api_token)
.execute(
existing_issue.iid,
description: issue_description,
weight: reports_count
)
puts "[CreateTestFailureIssue] Added a report in '#{existing_issue.title}': #{existing_issue.web_url}!"
end
def create(failed_test)
payload = {
title: failed_test_issue_title(failed_test),
description: failed_test_issue_description(failed_test),
labels: failed_test_issue_labels(failed_test),
weight: 1
}
CreateIssue.new(project: project, api_token: api_token).execute(payload).tap do |issue|
puts "[CreateTestFailureIssue] Created issue '#{issue.title}': #{issue.web_url}!"
end
end
def failed_test_hash(failed_test)
Digest::SHA256.hexdigest(failed_test['file'] + failed_test['name'])[0...12]
end
def failed_test_issue_title(failed_test)
title = "#{failed_test['file']} [test-hash:#{failed_test_hash(failed_test)}]"
raise "Title is too long!" if title.size > MAX_TITLE_LENGTH
title
end
def test_file_link(failed_test)
"[`#{failed_test['file']}`](#{self.class.file_base_url}#{failed_test['file']})"
end
def report_list_item(failed_test)
"1. #{Time.new.utc.strftime('%F')}: #{failed_test['job_url']} (#{ENV['CI_PIPELINE_URL']})"
end
def failed_test_issue_description(failed_test)
<<~DESCRIPTION
### Test description
`#{search_safe(failed_test['name'])}`
### Test file path
#{test_file_link(failed_test)}
<!-- Don't add anything after the report list since it's updated automatically -->
### Reports (1)
#{report_list_item(failed_test)}
DESCRIPTION
end
def failed_test_issue_labels(failed_test)
labels = DEFAULT_LABELS + category_and_group_labels_for_test_file(failed_test['file'])
# make sure we don't spam people who are notified to actual labels
labels.map { |label| "wip-#{label}" }
end
def category_and_group_labels_for_test_file(test_file)
feature_categories = File.open(File.expand_path(File.join('..', '..', test_file), __dir__))
.read
.scan(FEATURE_CATEGORY_METADATA_REGEX)
category_labels = feature_categories.filter_map { |category| categories_mapping.dig(category, 'label') }.uniq
groups = feature_categories.filter_map { |category| categories_mapping.dig(category, 'group') }
group_labels = groups.map { |group| groups_mapping.dig(group, 'label') }.uniq
(category_labels + [group_labels.first]).compact
end
def categories_mapping
@categories_mapping ||= self.class.fetch_json(WWW_GITLAB_COM_CATEGORIES_JSON)
end
def groups_mapping
@groups_mapping ||= self.class.fetch_json(WWW_GITLAB_COM_GROUPS_JSON)
end
def search_safe(value)
value.delete('"')
end
def self.fetch_json(json_url)
json = with_retries { HTTParty.get(json_url, format: :plain) } # rubocop:disable Gitlab/HTTParty
JSON.parse(json)
end
def self.with_retries(attempts: 3)
yield
rescue Errno::ECONNRESET, OpenSSL::SSL::SSLError, Net::OpenTimeout
retry if (attempts -= 1) > 0
raise
end
private_class_method :with_retries
end
if $PROGRAM_NAME == __FILE__
options = CreateTestFailureIssues::DEFAULT_OPTIONS.dup
OptionParser.new do |opts|
opts.on("-p", "--project PROJECT", String,
"Project where to create the issue (defaults to " \
"`#{CreateTestFailureIssues::DEFAULT_OPTIONS[:project]}`)") do |value|
options[:project] = value
end
opts.on("-r", "--tests-report-file file_path", String,
"Path to a JSON file which contains the current pipeline's tests report (defaults to " \
"`#{CreateTestFailureIssues::DEFAULT_OPTIONS[:tests_report_file]}`)"
) do |value|
options[:tests_report_file] = value
end
opts.on("-f", "--issues-json-folder file_path", String,
"Path to a folder where to save the issues JSON data (defaults to " \
"`#{CreateTestFailureIssues::DEFAULT_OPTIONS[:issue_json_folder]}`)") do |value|
options[:issue_json_folder] = value
end
opts.on("-t", "--api-token API_TOKEN", String,
"A valid Project token with the `Reporter` role and `api` scope to create the issue") do |value|
options[:api_token] = value
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
end.parse!
CreateTestFailureIssues.new(options).execute
end
|