lib/gitlab/qa/report/results_in_testcases.rb



# frozen_string_literal: true

module Gitlab
  module QA
    module Report
      # Uses the API to create or update GitLab test cases with the results of tests from RSpec report files.
      class ResultsInTestCases < ReportAsIssue
        attr_reader :issue_type, :gitlab

        include ResultsReporterShared

        def initialize(**kwargs)
          super
          @issue_type = 'test_case'
        end

        def find_or_create_testcase(test)
          find_testcase(test) || create_issue(test)
        end

        def add_issue_link_to_testcase(testcase, issue, test)
          results_section = testcase.description.include?(TEST_CASE_RESULTS_SECTION_TEMPLATE) ? '' : TEST_CASE_RESULTS_SECTION_TEMPLATE

          gitlab.edit_issue(iid: testcase.iid, options: { description: (testcase.description + results_section + "\n\n#{issue.web_url}") })
          # We are using test.testcase for the url here instead of testcase.web_url since it has the updated test case path
          puts "Added results issue #{issue.web_url} link to test case #{test.testcase}"
        end

        def update_testcase(testcase, test)
          puts "Test case labels updated." if update_labels(testcase, test)
        end

        private

        def find_testcase(test)
          testcase = find_testcase_by_iid(test)

          if testcase
            testcase = update_issue_title(testcase, test) if issue_title_needs_updating?(testcase, test)
          else
            testcase = find_issue(test)
          end

          testcase
        end

        def find_testcase_by_iid(test)
          iid = testcase_iid_from_url(test.testcase)

          return unless iid

          find_issue_by_iid(iid)
        end

        def testcase_iid_from_url(url)
          return warn(%(\nPlease update #{url} to test case url")) if url&.include?('/-/issues/')

          url && url.split('/').last.to_i
        end

        def new_issue_description(test)
          "#{super}#{TEST_CASE_RESULTS_SECTION_TEMPLATE}"
        end
      end
    end
  end
end