summaryrefslogtreecommitdiff
path: root/qa/qa/runtime/api.rb
blob: a2b4210f91075a1f1e7d9cf0e11eb479077f461a (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
require 'faraday'

module QA
  module Runtime
    class API
      ##
      # GET an endpoint that belongs to a GitLab instance under a given address
      #
      # Example:
      #
      # get(:gitlab, api('/users', personal_access_token: 'something'))
      # get(:gitlab, api('/users', personal_access_token: 'something'), username: value, ...)
      # get('http://gitlab.example', '/api/v4/users?private_token=something')
      #
      # In case of an address that is a symbol we will try to guess address
      # based on `Runtime::Scenario#something_address`.
      def self.get(address, page, *args)
        page = self.add_query_values(page, args)
        response = Faraday.get(API::Session.new(address, page).address)
        json = response.status == 200 ? JSON.parse(response.body) : nil
        return response, json
      end

      def self.version
        'v4'
      end

      def self.add_query_values(path, args)
        if args.any?
          query_string = Hash(*args).map { |key, value| "#{key}=#{value}" }.join('&')

          if query_string
            path << (path.index('?') ? '&' : '?')
            path << query_string
          end
        end
        path
      end

      class Session
        def initialize(instance, page = nil)
          @instance = instance
          @address = host + (page.is_a?(String) ? page : page&.path)
        end

        def host
          @instance.is_a?(Symbol) ? Runtime::Scenario.send("#{@instance}_address") : @instance.to_s
        end

        def address
          @address
        end
      end
    end
  end
end