lib/gitlab/qa/scenario/test/sanity/version.rb



# frozen_string_literal: true

require 'json'
require 'net/http'
require 'cgi'
require 'time'

module Gitlab
  module QA
    module Scenario
      module Test
        module Sanity
          # This test checks that the sha_version of a GitLab was authored in
          # the window defined by the `weekday_hours` method.
          # We perform a single API call to get the commit
          class Version < Scenario::Template
            SOURCE_MAP = {
              'git@dev.gitlab.org:gitlab/gitlab-ee.git' => {
                host: 'dev.gitlab.org',
                project: 'gitlab/gitlab-ee'
              },
              'git@dev.gitlab.org:gitlab/gitlabhq.git' => {
                host: 'dev.gitlab.org',
                project: 'gitlab/gitlabhq'
              },
              'git@gitlab.com:gitlab-org/gitlab.git' => {
                host: 'gitlab.com',
                project: 'gitlab-org/gitlab'
              },
              'git@gitlab.com:gitlab-org/gitlab-foss.git' => {
                host: 'gitlab.com',
                project: 'gitlab-org/gitlab-foss'
              }
            }.freeze

            def perform(release = 'ce')
              version = Component::Gitlab.perform do |gitlab|
                gitlab.release = release
                gitlab.act do
                  pull
                  rails_version
                end
              end

              project = SOURCE_MAP[version[:source]][:project]
              host = SOURCE_MAP[version[:source]][:host]
              sha = version[:sha]
              commit = api_commit_detail(host, project, sha)

              if commit_within_hours?(commit['created_at'], weekday_hours(commit['created_at']))
                puts "Found commit #{sha} in recent history of #{project} on #{host}"
              else
                puts "Did not find #{sha} in recent history of #{project} on #{host}"
                exit 1
              end
            end

            private

            def weekday_hours(date_string)
              case Date.parse(date_string).wday
                # Sunday
              when 0
                48
                # Monday
              when 1
                72
              else
                24
              end
            end

            def commit_within_hours?(commit_time_string, hours)
              Time.at(Time.parse(commit_time_string).utc).to_datetime > Time.at((Time.now - (hours * 60 * 60)).utc).to_datetime
            end

            def api_commit_detail(host, project, sha)
              url = "https://#{host}/api/v4/projects/#{CGI.escape(project)}/repository/commits/#{sha}"

              if host == 'dev.gitlab.org'
                Runtime::Env.require_qa_dev_access_token!

                url = "#{url}?private_token=#{Runtime::Env.qa_dev_access_token}"
              end

              JSON.parse(Net::HTTP.get(URI(url)))
            end
          end
        end
      end
    end
  end
end