summaryrefslogtreecommitdiff
path: root/scripts/pipeline/create_test_failure_issues.rb
blob: 6312d39276029d88079b38888ac42155791abe0e (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
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
#!/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).comment_or_create(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', 'failure::flaky-test'].freeze

  def initialize(options)
    @project = options.delete(:project)
    @api_token = options.delete(:api_token)
  end

  def comment_or_create(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

  def find(failed_test, existing_issues = [])
    failed_test_issue_title = failed_test_issue_title(failed_test)
    issue_from_existing_issues = existing_issues.find { |issue| issue.title == failed_test_issue_title }
    issue_from_issue_tracker = FindIssues
      .new(project: project, api_token: api_token)
      .execute(state: 'opened', search: failed_test_issue_title)
      .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)
    new_issue_description = "#{existing_issue.description}\n- #{failed_test['job_url']} (#{ENV['CI_PIPELINE_URL']})"
    UpdateIssue
      .new(project: project, api_token: api_token)
      .execute(existing_issue.iid, description: new_issue_description)
    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)
    }

    CreateIssue.new(project: project, api_token: api_token).execute(payload).tap do |issue|
      puts "[CreateTestFailureIssue] Created issue '#{issue.title}': #{issue.web_url}!"
    end
  end

  private

  attr_reader :project, :api_token

  def failed_test_id(failed_test)
    Digest::SHA256.hexdigest(search_safe(failed_test['name']))[0...12]
  end

  def failed_test_issue_title(failed_test)
    title = "#{failed_test['file']} - ID: #{failed_test_id(failed_test)}"

    raise "Title is too long!" if title.size > MAX_TITLE_LENGTH

    title
  end

  def failed_test_issue_description(failed_test)
    <<~DESCRIPTION
    ### Full description

    `#{search_safe(failed_test['name'])}`

    ### File path

    `#{failed_test['file']}`

    <!-- Don't add anything after the report list since it's updated automatically -->
    ### Reports

    - #{failed_test['job_url']} (#{ENV['CI_PIPELINE_URL']})
    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