Module: ClientApi

Included in:
Api, Request
Defined in:
lib/client-api/base.rb,
lib/client-api/request.rb,
lib/client-api/version.rb,
lib/client-api/settings.rb,
lib/client-api/validator.rb

Defined Under Namespace

Classes: Api, Request

Constant Summary collapse

VERSION =
"0.4.1".freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.configurationObject



9
10
11
# File 'lib/client-api/settings.rb', line 9

def self.configuration
  RSpec.configuration
end

.configureObject



3
4
5
6
7
# File 'lib/client-api/settings.rb', line 3

def self.configure
  RSpec.configure do |config|
    yield config
  end
end

Instance Method Details

#base_urlObject



13
14
15
# File 'lib/client-api/settings.rb', line 13

def base_url
  ClientApi.configuration.base_url || ''
end

#basic_authObject



21
22
23
# File 'lib/client-api/settings.rb', line 21

def basic_auth
  ClientApi.configuration.basic_auth || ''
end

#datatype(type, value) ⇒ Object



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/client-api/validator.rb', line 296

def datatype(type, value)
  if (type.downcase == 'string') || (type.downcase.== 'str')
    String
  elsif (type.downcase.== 'integer') || (type.downcase.== 'int')
    Integer
  elsif (type.downcase == 'symbol') || (type.downcase == 'sym')
    Symbol
  elsif (type.downcase == 'array') || (type.downcase == 'arr')
    Array
  elsif (type.downcase == 'object') || (type.downcase == 'obj')
    Object
  elsif (type.downcase == 'boolean') || (type.downcase == 'bool')
    value === true ? TrueClass : FalseClass
  elsif (type.downcase == 'falseclass') || (type.downcase == 'false')
    FalseClass
  elsif (type.downcase == 'trueclass') || (type.downcase == 'true')
    TrueClass
  elsif type.downcase == 'float'
    Float
  elsif type.downcase == 'hash'
    Hash
  elsif type.downcase == 'complex'
    Complex
  elsif type.downcase == 'rational'
    Rational
  elsif type.downcase == 'fixnum'
    Fixnum
  elsif type.downcase == 'bignum'
    Bignum
  else
  end
end

#deep_traverse(hash, &block) ⇒ Object



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/client-api/validator.rb', line 401

def deep_traverse(hash, &block)
  stack = hash.map {|k, v| [[k], v]}

  while not stack.empty?
    key, value = stack.pop
    yield(key, value)
    if value.is_a? Hash
      value.each do |k, v|
        if v.is_a?(String) then
          if v.empty? then
            v = ""
          end
        end
        stack.push [key.dup << k, v]
      end
    end
  end
end

#headersObject



17
18
19
# File 'lib/client-api/settings.rb', line 17

def headers
  ClientApi.configuration.headers || ''
end

#is_num?(str) ⇒ Boolean

Returns:

  • (Boolean)


329
330
331
332
333
334
335
# File 'lib/client-api/validator.rb', line 329

def is_num?(str)
  if Float(str)
    true
  end
rescue ArgumentError, TypeError
  false
end

#json_outputObject



25
26
27
# File 'lib/client-api/settings.rb', line 25

def json_output
  ClientApi.configuration.json_output || ''
end

#payload(args) ⇒ Object Also known as: schema_from_json



122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/client-api/base.rb', line 122

def payload(args)
  if args['type'].nil?
    JSON.parse(File.read(args))
  else
    case args['type'].downcase
    when 'multipart/form-data', 'application/x-www-form-urlencoded'
      args
    else
      raise "invalid body type | try: payload('./data/request/file.png', 'multipart/form-data')"
    end
  end
end

#time_outObject



29
30
31
# File 'lib/client-api/settings.rb', line 29

def time_out
  ClientApi.configuration.time_out || 60
end

#url_generator(url) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/client-api/base.rb', line 135

def url_generator(url)
  begin
    if url.count == 2
      raise('":url"'.green + ' field is missing in url'.red) if url[:url].nil?
      raise('":query"'.green + ' field is missing in url'.red) if url[:query].nil?

      query = url[:url].include?('?') ? [url[:url]] : [url[:url].concat('?')]

      url[:query].map do |val|
        query <<  val[0].to_s + "=" + val[1].gsub(' ','%20') + "&"
      end
      return query.join.delete_suffix('&')
    end
  rescue ArgumentError
    url
  end
end

#validate(res, *options) ⇒ Object



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
# File 'lib/client-api/validator.rb', line 5

def validate(res, *options)

  # noinspection RubyScope
  options.map do |data|
    raise('"key": ""'.green + ' field is missing'.red) if data[:key].nil?
    raise('Need at least one field to validate'.green) if data[:value].nil? && data[:type].nil? && data[:size].nil? && data[:empty].nil? && data[:has_key].nil?

    data.keys.map do |val|
      raise "invalid key: " + "#{val}".green unless [:key, :operator, :value, :type, :size, :has_key, :empty].include? val
    end

    value ||= data[:value]
    operator ||= (data[:operator] || '==').downcase
    type ||= data[:type]
    size ||= data[:size]
    empty ||= data[:empty]
    has_key ||= data[:has_key]

    @resp = JSON.parse(res.to_json)
    key = data[:key].split("->")

    @err_method = []

    key.map do |method|
      method = method.to_i if is_num?(method)
      @err_method = @err_method << method

      begin
        if (method.is_a? Integer) && (has_key != nil)
          @valid_key = false
        elsif (!method.is_a? Integer) && (has_key != nil)
          @valid_key = @resp.has_key? method
        elsif (method.is_a? Integer) && has_key.nil?
          raise %[key: ]+ %[#{@err_method.join('->')}].green + %[ does not exist! please check the key once again].red if ((@resp.class != Array) || (method.to_i >= @resp.count))
        elsif (method.is_a? String) && has_key.nil?
          raise %[key: ]+ %[#{@err_method.join('->')}].green + %[ does not exist! please check the key once again].red if !@resp.include?(method)
        end
        @resp = @resp.send(:[], method)
      rescue NoMethodError
        raise %[key: ]+ %[#{@err_method.join('->')}].green + %[ does not exist! please check the key once again].red if has_key.nil?
      end
    end

    case operator
    when '=', '==', 'eql', 'eql?', 'equal', 'equal?'
      # has key validation
      validate_key(@valid_key, has_key, data) if has_key != nil

      # value validation
      expect(value).to eq(@resp), lambda {"[key]: \"#{data[:key]}\"".blue + "\n  didn't match \n[value]: \"#{data[:value]}\"\n"} if value != nil

      # datatype validation
      if (type == 'boolean') || (type == 'bool')
        expect(%w[TrueClass, FalseClass].any? {|bool| bool.include? @resp.class.to_s}).to eq(true), lambda {"[key]: \"#{data[:key]}\"".blue + "\n  datatype shouldn't be \n[type]: \"#{data[:type]}\"\n"}
      elsif ((type != 'boolean') || (type != 'bool')) && (type != nil)
        expect(datatype(type, value)).to eq(@resp.class), lambda {"[key]: \"#{data[:key]}\"".blue + "\n  datatype shouldn't be \n[type]: \"#{data[:type]}\"\n"}
      end

      # size validation
      validate_size(size, data) if size != nil

      # is empty validation
      validate_empty(empty, data) if empty != nil

    when '!', '!=', '!eql', '!eql?', 'not eql', 'not equal', '!equal?'
      # has key validation
      validate_key(@valid_key, has_key, data) if has_key != nil

      # value validation
      expect(value).not_to eq(@resp), lambda {"[key]: \"#{data[:key]}\"".blue + "\n  didn't match \n[value]: \"#{data[:value]}\"\n"} if value != nil

      # datatype validation
      if (type == 'boolean') || (type == 'bool')
        expect(%w[TrueClass, FalseClass].any? {|bool| bool.include? @resp.class.to_s}).not_to eq(true), lambda {"[key]: \"#{data[:key]}\"".blue + "\n  datatype shouldn't be \n[type]: \"#{data[:type]}\"\n"}
      elsif ((type != 'boolean') || (type != 'bool')) && (type != nil)
        expect(datatype(type, value)).not_to eq(@resp.class), lambda {"[key]: \"#{data[:key]}\"".blue + "\n  datatype shouldn't be \n[type]: \"#{data[:type]}\"\n"}
      end

      # size validation
      if size != nil
        begin
          expect(size).not_to eq(@resp.count), lambda {"[key]: \"#{data[:key]}\"".blue + "\n" + "size shouldn't match" + "\n\n" + "[   actual size   ]: #{@resp.count}" + "\n" + "[size not expected]: #{size}".green}
        rescue NoMethodError
          expect(size).not_to eq(0), lambda {"[key]: \"#{data[:key]}\"".blue + "\n" + "size shouldn't match" + "\n\n" + "[   actual size   ]: 0" + "\n" + "[size not expected]: #{size}".green}
        rescue ArgumentError
          expect(size).not_to eq(0), lambda {"[key]: \"#{data[:key]}\"".blue + "\n" + "size shouldn't match" + "\n\n" + "[   actual size   ]: 0" + "\n" + "[size not expected]: #{size}".green}
        end
      end

      # is empty validation
      validate_empty(empty, data) if empty != nil

    when '>', '>=', '<', '<=', 'greater than', 'greater than or equal to', 'less than', 'less than or equal to', 'lesser than', 'lesser than or equal to'
      message = 'is not greater than (or) equal to' if operator == '>=' || operator == 'greater than or equal to'
      message = 'is not greater than' if operator == '>' || operator == 'greater than'
      message = 'is not lesser than (or) equal to' if operator == '<=' || operator == 'less than or equal to'
      message = 'is not lesser than' if operator == '<' || operator == 'less than' || operator == 'lesser than'

      # has key validation
      validate_key(@valid_key, has_key, data) if has_key != nil

      # value validation
      expect(@resp.to_i.public_send(operator, value)).to eq(true), "[key]: \"#{data[:key]}\"".blue + "\n  #{message} \n[value]: \"#{data[:value]}\"\n" if value != nil

      # datatype validation
      expect(datatype(type, value)).to eq(@resp.class), lambda {"[key]: \"#{data[:key]}\"".blue + "\n  datatype shouldn't be \n[type]: \"#{data[:type]}\"\n"} if type != nil

      # size validation
      if size != nil
        begin
          expect(@resp.count.to_i.public_send(operator, size)).to eq(true), lambda {"[key]: \"#{data[:key]}\"".blue + "\n" + "#{message} #{size}" + "\n\n" + "[ actual size ]: #{@resp.count}" + "\n" + "expected size to be #{operator} #{size}".green}
        rescue NoMethodError
          expect(0.public_send(operator, size)).to eq(true), lambda {"[key]: \"#{data[:key]}\"".blue + "\n" + "#{message} #{size}" + "\n\n" + "[ actual size ]: 0" + "\n" + "expected size to be #{operator} #{size}".green}
        rescue ArgumentError
          expect(0.public_send(operator, size)).to eq(true), lambda {"[key]: \"#{data[:key]}\"".blue + "\n" + "#{message} #{size}" + "\n\n" + "[ actual size ]: 0" + "\n" + "expected size to be #{operator} #{size}".green}
        end
      end

      # is empty validation
      validate_empty(empty, data) if empty != nil

    when 'contains', 'has', 'contains?', 'has?', 'include', 'include?'
      # has key validation
      validate_key(@valid_key, has_key, data) if has_key != nil

      # value validation
      expect(@resp.to_s).to include(value.to_s), lambda {"[key]: \"#{data[:key]} => #{@resp}\"".blue + "\n  not contains \n[value]: \"#{data[:value]}\"\n"} if value != nil

      # datatype validation
      if (type == 'boolean') || (type == 'bool')
        expect(%w[TrueClass, FalseClass].any? {|bool| bool.include? @resp.class.to_s}).to eq(true), lambda {"[key]: \"#{data[:key]}\"".blue + "\n  datatype shouldn't be \n[type]: \"#{data[:type]}\"\n"}
      elsif ((type != 'boolean') || (type != 'bool')) && (type != nil)
        expect(datatype(type, value)).to eq(@resp.class), lambda {"[key]: \"#{data[:key]}\"".blue + "\n  datatype shouldn't be \n[type]: \"#{data[:type]}\"\n"}
      end

      # size validation
      if size != nil
        begin
          expect(@resp.count.to_s).to include(size.to_s), lambda {"[key]: \"#{data[:key]} => #{@resp}\"".blue + "\n"+ "size not contains #{size}"+ "\n\n" + "[ actual size ]: #{@resp.count}" + "\n" + "expected size to contain: #{size}".green}
        rescue NoMethodError
          expect(0.to_s).to include(size.to_s), lambda {"[key]: \"#{data[:key]} => #{@resp}\"".blue + "\n"+ "size not contains #{size}"+ "\n\n" + "[ actual size ]: 0" + "\n" + "expected size to contain: #{size}".green}
        rescue ArgumentError
          expect(0.to_s).to include(size.to_s), lambda {"[key]: \"#{data[:key]} => #{@resp}\"".blue + "\n"+ "size not contains #{size}"+ "\n\n" + "[ actual size ]: 0" + "\n" + "expected size to contain: #{size}".green}
        end
      end

      # is empty validation
      validate_empty(empty, data) if empty != nil

    when 'not contains', '!contains', 'not include', '!include'
      # has key validation
      validate_key(@valid_key, has_key, data) if has_key != nil

      # value validation
      expect(@resp.to_s).not_to include(value.to_s), lambda {"[key]: \"#{data[:key]} => #{@resp}\"".blue + "\n  should not contain \n[value]: \"#{data[:value]}\"\n"} if value != nil

      # datatype validation
      if (type == 'boolean') || (type == 'bool')
        expect(%w[TrueClass, FalseClass].any? {|bool| bool.include? @resp.class.to_s}).not_to eq(true), lambda {"[key]: \"#{data[:key]}\"".blue + "\n  datatype shouldn't be \n[type]: \"#{data[:type]}\"\n"}
      elsif ((type != 'boolean') || (type != 'bool')) && (type != nil)
        expect(datatype(type, value)).not_to eq(@resp.class), lambda {"[key]: \"#{data[:key]}\"".blue + "\n  datatype shouldn't be \n[type]: \"#{data[:type]}\"\n"}
      end

      # size validation
      if size != nil
        begin
          expect(@resp.count.to_s).not_to include(size.to_s), lambda {"[key]: \"#{data[:key]} => #{@resp}\"".blue + "\n"+ "size should not contain #{size}"+ "\n\n" + "[ actual size ]: #{@resp.count}" + "\n" + "expected size not to contain: #{size}".green}
        rescue NoMethodError
          expect(0.to_s).not_to include(size.to_s), lambda {"[key]: \"#{data[:key]} => #{@resp}\"".blue + "\n"+ "size should not contain #{size}"+ "\n\n" + "[ actual size ]: 0" + "\n" + "expected size not to contain: #{size}".green}
        rescue ArgumentError
          expect(0.to_s).not_to include(size.to_s), lambda {"[key]: \"#{data[:key]} => #{@resp}\"".blue + "\n"+ "size should not contain #{size}"+ "\n\n" + "[ actual size ]: 0" + "\n" + "expected size not to contain: #{size}".green}
        end
      end

      # is empty validation
      validate_empty(empty, data) if empty != nil

    else
      raise('operator not matching')
    end

  end

end

#validate_empty(empty, data) ⇒ Object



244
245
246
247
248
249
250
251
252
253
# File 'lib/client-api/validator.rb', line 244

def validate_empty(empty, data)
  case empty
  when true
    expect(@resp.nil?).to eq(empty), lambda {"[key]: \"#{data[:key]}\"".blue + "\n is not empty"+"\n"} if [Integer, TrueClass, FalseClass, Float].include? @resp.class
    expect(@resp.empty?).to eq(empty), lambda {"[key]: \"#{data[:key]}\"".blue + "\n is not empty"+"\n"} if [String, Hash, Array].include? @resp.class
  when false
    expect(@resp.nil?).to eq(empty), lambda {"[key]: \"#{data[:key]}\"".blue + "\n is empty"+"\n"} if [Integer, TrueClass, FalseClass, Float].include? @resp.class
    expect(@resp.empty?).to eq(empty), lambda {"[key]: \"#{data[:key]}\"".blue + "\n is empty"+"\n"} if [String, Hash, Array].include? @resp.class
  end
end

#validate_headers(res, *options) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/client-api/validator.rb', line 271

def validate_headers(res, *options)
  options.map do |data|
    raise('key is not given!') if data[:key].nil?
    raise('operator is not given!') if data[:operator].nil?
    raise('value is not given!') if data[:value].nil?

    @resp_header = JSON.parse(res.to_json)

    key = data[:key]
    value = data[:value]
    operator = data[:operator]

    case operator
    when '=', '==', 'eql?', 'equal', 'equal?'
      expect(value).to eq(@resp_header[key][0]), lambda {"\"#{key}\" => \"#{value}\"".blue + "\n  didn't match \n\"#{key}\" => \"#{@resp_header[key][0]}\"\n"}

    when '!', '!=', '!eql?', 'not equal', '!equal?'
      expect(value).not_to eq(@resp_header[key][0]), lambda {"\"#{key}\" => \"#{value}\"".blue + "\n  shouldn't match \n\"#{key}\" => \"#{@resp_header[key][0]}\"\n"}

    else
      raise('operator not matching')
    end
  end
end

#validate_json(actual, expected) ⇒ Object



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/client-api/validator.rb', line 337

def validate_json(actual, expected)
  param1 = JSON.parse(actual.to_json)
  param2 = JSON.parse(expected.to_json)

  @actual_key, @actual_value = [], []
  deep_traverse(param2) do |path, value|
    if !value.is_a?(Hash)
      key_path = path.map! {|k| k}
      @actual_key << key_path.join("->").to_s
      @actual_value << value
    end
  end

  Hash[@actual_key.zip(@actual_value)].map do |data|
    @resp = param1
    key = data[0].split("->")

    key.map do |method|
      method = method.to_i if is_num?(method)
      @resp = @resp.send(:[], method)
    end

    value = data[1]
    @assert, @final_assert, @overall = [], [], []

    if !value.is_a?(Array)
      expect(value).to eq(@resp)
    else
      @resp.each_with_index do |resp, i|
        value.to_a.each_with_index do |val1, j|
          val1.to_a.each_with_index do |val2, k|
            if resp.to_a.include? val2
              @assert << true
            else
              @assert << false
            end
          end
          @final_assert << @assert
          @assert = []

          if @resp.count == @final_assert.count
            @final_assert.each_with_index do |result, i|
              if result.count(true) == val1.count
                @overall << true
                break
              elsif @final_assert.count == i+1
                expect(value).to eq(@resp)
              end
            end
            @final_assert = []
          end

        end
      end

      if @overall.count(true) == value.count
      else
        expect(value).to eq(@resp)
      end

    end
  end
end

#validate_key(valid_key, has_key, data) ⇒ Object



255
256
257
258
259
260
261
262
263
264
# File 'lib/client-api/validator.rb', line 255

def validate_key(valid_key, has_key, data)
  case valid_key
  when true
    expect(valid_key).to eq(true), lambda {"[key]: \"#{data[:key]}\"".blue + "\n does not exist"+"\n"} if has_key == true
    expect(valid_key).to eq(false), lambda {"[key]: \"#{data[:key]}\"".blue + "\n does exist"+"\n"} if has_key == false
  when false
    expect(@resp.nil?).to eq(false), lambda {"[key]: \"#{data[:key]}\"".blue + "\n does not exist"+"\n"} if has_key == true
    expect(@resp.nil?).to eq(true), lambda {"[key]: \"#{data[:key]}\"".blue + "\n does exist"+"\n"} if has_key == false
  end
end

#validate_list(res, *options) ⇒ Object



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
# File 'lib/client-api/validator.rb', line 190

def validate_list(res, *options)
  options.map do |data|

    raise('"sort": ""'.green + ' field is missing'.red) if data[:sort].nil?

    sort ||= data[:sort]
    unit ||= data[:unit].split("->")

    @value = []
    @resp = JSON.parse(res.to_json)

    key = data[:key].split("->")

    key.map do |method|
      @resp = @resp.send(:[], method)
    end

    @cls = []
    @resp.map do |val|
      unit.map do |list|
        val = val.send(:[], list)
      end
      @value << val
      begin
        @cls << (val.scan(/^\d+$/).any? ? Integer : val.class)
      rescue NoMethodError
        @cls << val.class
      end
    end

    @value =
        if @cls.all? {|e| e == Integer}
          @value.map(&:to_i)
        elsif (@cls.all? {|e| e == String}) || (@cls.include? String)
          @value.map(&:to_s)
        else
          @value
        end
    expect(@value).to eq(@value.sort) if sort == 'ascending'
    expect(@value).to eq(@value.sort.reverse) if sort == 'descending'

  end
end

#validate_schema(param1, param2) ⇒ Object



266
267
268
269
# File 'lib/client-api/validator.rb', line 266

def validate_schema(param1, param2)
  expected_schema = JSON::Validator.validate(param1, param2)
  expect(expected_schema).to eq(true)
end

#validate_size(size, data) ⇒ Object



234
235
236
237
238
239
240
241
242
# File 'lib/client-api/validator.rb', line 234

def validate_size(size, data)
  begin
    expect(size).to eq(@resp.count), lambda {"[key]: \"#{data[:key]}\"".blue + "\n" + "size didn't match" + "\n\n" + "[ actual size ]: #{@resp.count}" + "\n" + "[expected size]: #{size}".green}
  rescue NoMethodError
    expect(size).to eq(0), lambda {"[key]: \"#{data[:key]}\"".blue + "\n" + "size didn't match" + "\n\n" + "[ actual size ]: 0" + "\n" + "[expected size]: #{size}".green}
  rescue ArgumentError
    expect(size).to eq(0), lambda {"[key]: \"#{data[:key]}\"".blue + "\n" + "size didn't match" + "\n\n" + "[ actual size ]: 0" + "\n" + "[expected size]: #{size}".green}
  end
end