Module: TestJoska

Defined in:
lib/test_joska.rb,
lib/test_joska/builder.rb,
lib/test_joska/version.rb

Defined Under Namespace

Modules: Boolean Classes: Error

Constant Summary collapse

VERSION =
"1.3.25"
@@raise_on_error =
true
@@verbose =
false
@@URL =
nil
@@HEAD =
nil
@@standard_endpoint =
""
@@standard_header =
""
@@internal_log =
""
@@url_log =
""
@@has_token =
false
@@min_price_flat =
0.10
@@min_price_percent =
0.001

Instance Method Summary collapse

Instance Method Details

#arrayKeyRemover(object, key) ⇒ Object



416
417
418
419
420
421
422
423
424
# File 'lib/test_joska/builder.rb', line 416

def arrayKeyRemover(object, key)
 
  res = []
 
  object.each do |obj| res.push(keyRemover(obj, key)) end
 
  return res
 
end

#checkFloat(value) ⇒ Object



305
306
307
308
309
# File 'lib/test_joska/builder.rb', line 305

def checkFloat value 

  true if Float value rescue false

end

#comparePrice(price1, price2, type1, type2) ⇒ Object



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/test_joska/builder.rb', line 260

def comparePrice(price1, price2, type1, type2)

  range = price1.abs * @@min_price_percent > @@min_price_flat ? price1.abs * @@min_price_percent : @@min_price_flat

  if !(price1.abs-range...price1.abs+range).include?(price2.abs)

    error_message = "Diferença de preço encontrada (#{type1} - #{type2})\n#{type1}: R$#{price1} / #{type2}: R$#{price2}"

    raise error_message if @@raise_on_error

    jskLog(error_message) 

  end

end

#compareType(value, type, name) ⇒ Object



277
278
279
280
281
282
283
# File 'lib/test_joska/builder.rb', line 277

def compareType(value, type, name)

  return if type == Boolean && (value.is_a?(TrueClass) || value.is_a?(FalseClass))

  raise "Variavel #{name} retornou com tipo diferente de #{type}\n(#{value.class}: #{value})" if !value.is_a?(type)

end

#compareValues(value1, value2, message, type1, type2) ⇒ Object



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/test_joska/builder.rb', line 286

def compareValues(value1, value2, message, type1, type2)

  if value1 != value2

    value1 = "null" if value1 == nil

    value2 = "null" if value2 == nil

    error_message = "Conflito: #{message}  (#{type1} - #{type2})\n#{type1}: #{value1} /  #{type2}: #{value2}"

    raise error_message if @@raise_on_error

    jskLog(error_message)

  end

end

#customRequest(method, product, path, query, payload = nil, header = nil, endpoint = nil) ⇒ Object



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
# File 'lib/test_joska/builder.rb', line 106

def customRequest(method, product, path, query, payload=nil, header=nil, endpoint=nil)

  endpoint = @@standard_endpoint if !endpoint

  header = @@standard_header if !header

  url = "#{URL[product]["base"][endpoint]}#{path}"

  if query

    query.keys.each do |key| url = "#{url}#{key}=#{query[key]}&" end

    url.chomp!('&')

  end

  res = ""
  
  p url if @@verbose

  begin

    RestClient::Request.execute(method: method, url: url, headers: header, payload: payload, timeout: 90) do |response| res = response end

  rescue StandardError => error 
    
    res = error 
  
  end

  return res

end

#genericComparator(object1, object2, context, type1, type2, remove = nil) ⇒ Object



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
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
# File 'lib/test_joska/builder.rb', line 312

def genericComparator(object1, object2, context, type1 , type2, remove=nil)

  if remove.kind_of?(Array)

    object1 = genericKeyRemover(object1, remove)

    object2 = genericKeyRemover(object2, remove)

  end

  if object1.is_a?(Hash) && object2.is_a?(Hash)

    compareValues(object1.keys.count, object2.keys.count, "#{context}_keyCount", type1, type2)

    (object1.keys | object2.keys).each do |key|

      genericComparator(object1[key], object2[key], "#{context}_#{key}", type1, type2)

    end

  elsif object1.is_a?(Array) && object2.is_a?(Array)

    if object1.count != object2.count

      genericComparator(object1[0], object2[0], "#{context}_arrayElement", type1, type2) if object1[0] && object2[0] 

      return compareValues(object1.count, object2.count, "#{context}_arrayCount", type1, type2)

    end

    array_count = 0

    while array_count < object1.count do

      genericComparator(object1[array_count], object2[array_count], "#{context}_arrayElement", type1, type2)

      array_count += 1

    end

  elsif (checkFloat(object1) && checkFloat(object2)) && (object1.to_s.include?(".") || object2.to_s.include?("."))

    comparePrice(object1.to_f, object2.to_f, "#{type1}_#{context}", "#{type2}_#{context}")

  elsif context.split("_").last.include?("Token")

    object1 = rateTokenBuilder(object1) if object1.kind_of?(String)

    object2 = rateTokenBuilder(object2) if object2.kind_of?(String)

    genericComparator(object1, object2, "#{context}_decoded", type1, type2)

  else

    compareValues(object1, object2, context, type1, type2)

  end

end

#genericKeyRemover(object, keys) ⇒ Object



380
381
382
383
384
385
386
387
388
# File 'lib/test_joska/builder.rb', line 380

def genericKeyRemover(object, keys)
 
  raise "Metodo aceita apenas arrays como chave" if !keys.kind_of?(Array)
 
  keys.each do |key| object = keyRemover(object, key) end
 
  return object
 
end

#jskClearLogObject



88
89
90
91
92
# File 'lib/test_joska/builder.rb', line 88

def jskClearLog

  @@internal_log = ""

end

#jskClearUrlLogObject



100
101
102
103
104
# File 'lib/test_joska/builder.rb', line 100

def jskClearUrlLog

  @@url_log = ""

end

#jskGetLogObject



74
75
76
77
78
# File 'lib/test_joska/builder.rb', line 74

def jskGetLog

  return @@internal_log

end

#jskGetUrlLogObject



94
95
96
97
98
# File 'lib/test_joska/builder.rb', line 94

def jskGetUrlLog

  return @@url_log

end

#jskLog(message) ⇒ Object



80
81
82
83
84
85
86
# File 'lib/test_joska/builder.rb', line 80

def jskLog(message)

  p message if @@verbose

  @@internal_log = "#{@@internal_log}#{message}\n"

end

#jskRoomBuilder(rooms) ⇒ Object



373
374
375
376
377
# File 'lib/test_joska/builder.rb', line 373

def jskRoomBuilder(rooms)

  return rooms.gsub(",", "%2C").gsub("+", "%2B")

end

#jskSetup(options) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/test_joska/builder.rb', line 50

def jskSetup(options)

  @@raise_on_error = options["raise_on_error"] if options["raise_on_error"] != nil

  @@verbose = options["verbose"] if options["verbose"] != nil

  @@URL = options["url_parts"] if options["url_parts"] != nil

  @@HEAD = options["headers"] if options["headers"] != nil

  @@standard_endpoint = options["standard_endpoint"] if options["standard_endpoint"] != nil

  @@standard_header = @@HEAD[options["standard_header_name"]] if options["standard_header_name"] != nil

  @@standard_header = options["standard_header"] if options["standard_header"] != nil

  @@has_token = options["has_token"] if options["has_token"] != nil

  @@min_price_flat = options["min_price_flat"] if options["min_price_flat"] != nil

  @@min_price_percent = options["min_price_percent"] if options["min_price_percent"] != nil

end

#jskSlackExcelSender(options) ⇒ Object



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
# File 'lib/test_joska/builder.rb', line 450

def jskSlackExcelSender(options)

  name = options["name"]

  project = options["project"]

  project_type = options["project_type"]

  environment = options["environment"]

  additional_info = options["additional_info"]

  report_path = options["report_path"]

  slack_url = options["slack_url"]

  send_server = options["send_server"]

  send_slack = options["send_slack"]

  send_excel = options["send_excel"]

  rep_id = 0

  slack_payload = {}

  excel_payload = {}

  t = Time.now

  generated_report_path = "#{report_path}/report_#{project}_#{project_type}_#{environment} #{t.strftime('%d_%m_%y %H_%M_%S')}" 

  options = {
    input_path: report_path,
    report_path: generated_report_path,
    report_types: [:html],
    report_title: "Report: #{project} #{project_type} #{environment}",
    additional_info: additional_info
  }

  ReportBuilder.build_report options

  if send_server

    p "Enviando para o servidor..."

    file_to_transfer = "#{generated_report_path}.html"
  
    zipfile_name = "#{report_path}/mandar.zip"
  
    File.delete(zipfile_name) if File.exist?(zipfile_name)
  
    Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
  
      file_to_transfer = file_to_transfer.split('/').last
  
      zipfile.add(file_to_transfer, File.join(report_path, file_to_transfer))
  
    end
  
    file_to_send = File.new(zipfile_name, 'rb')
  
    payload = {
      :report => file_to_send,
      :usr => name,
      :project => "#{project}_#{project_type}",
      :env => environment,
      :simple => true
    }
  
    url = "http://corp-report01.compute.br-sao-1.cvccorp.cloud:4444"  
  
    repId = ""
  
    RestClient::Request.execute(method: 'post', url: "#{url}/generate", payload: payload) do |response| 

      repId = response.body

    end
  
    if repId.to_i == 0
  
      p "Deu algum problema no servidor"

    end

  end

  if send_slack || send_excel

    rep = JSON.parse(File.read("#{report_path}/report.json"))

    scn_status = {}

    step_status = {}

    scn_status["success"] = 0

    excel_report = []

    rep.each do |esq|

      esq["elements"].each do |scn|

        cur_scn = "success" if scn["type"] == "scenario"

        excel_scenario = {
          "Produto"=> project,
          "Cenário"=> esq["name"],
          "Status"=> "passed",
          "Erro"=> nil,
          "Data"=> t.strftime('%d/%m/%y'),
          "Ambiente"=> environment,
          "Tipo"=> project_type,
          "Hora"=> t.strftime('%H:%M:%S')
        }

        scn["steps"].each do |step|

          if cur_scn == "success" && step["result"]["status"] != "passed"

            excel_scenario["Status"] = step["result"]["status"]

            excel_scenario["Erro"] = step["result"]["error_message"].split("\n").first.split("(RuntimeError)").first if step["result"]["error_message"]
          
            cur_scn = step["result"]["status"] 

          end

          step_status[step["result"]["status"]] ? step_status[step["result"]["status"]] += 1 : step_status[step["result"]["status"]] = 1

        end

        excel_report.push(excel_scenario) if scn["keyword"] != "Contexto"

        scn_status[cur_scn] ? scn_status[cur_scn] += 1 : scn_status[cur_scn] = 1 if cur_scn

      end

    end

    not_passed = 0

    slack_title = "Teste de #{project} #{project_type} no ambiente #{environment} concluido"

    slack_msg = "Cenários: "

    scn_status.keys. each do |key| 
      
      slack_msg = "#{slack_msg}#{key} : #{scn_status[key]} / "  
      
      not_passed += scn_status[key] if key != "success"
    
    end

    slack_msg.chomp!("/ ")

    slack_msg = "#{slack_msg}\nSteps: "

    step_status.keys. each do |key| slack_msg = "#{slack_msg}#{key} : #{step_status[key]} / "  end

    slack_msg.chomp!("/ ")

    total = not_passed + scn_status["success"]

    green = (255*scn_status["success"]/total).to_s(16).upcase

    green = "0#{green}" if green.length == 1

    red = (255*not_passed/total).to_s(16).upcase

    red = "0#{red}" if red.length == 1

    slack_color = "##{red}#{green}00"

    link = nil

    link = "#{url}/#{name}/#{project}_#{project_type}/#{environment}/#{repId}" if repId.to_i != 0

    slack_payload = {
      "attachments" => [
        {
          "color": slack_color,
          "title": slack_title,
          "title_link": link,
          "text": slack_msg
        }
      ]
    }.to_json

    excel_payload = {"scenarios"=>excel_report}

  end

  if send_slack

    p "Enviando para o slack..."

    RestClient::Request.execute(method: "post", url: slack_url, payload: slack_payload)

  end

  if send_excel

    p "Envidando para o excel..."

    excel_url = "http://corp-report01.compute.br-sao-1.cvccorp.cloud:8080/upload" 

    p RestClient::Request.execute(method: "post", url: excel_url, payload: excel_payload) 

  end

end

#jskUrlBuilder(product, type, details, endpoint) ⇒ Object



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
233
234
235
236
237
238
# File 'lib/test_joska/builder.rb', line 198

def jskUrlBuilder(product, type, details, endpoint)

  raise "URL_parts não configurada" if !@@URL

  details = "" if !details

  details = [details] if !details.kind_of?(Array)

  url = @@URL[product]["base"][endpoint]

  if !@@URL[product]["path"][type].kind_of?(Array)

    return "#{url}#{@@URL[product]["path"][type]}#{details[0]}"

  else

    query_pos = 0

    @@URL[product]["path"][type].each do |query|

      if details[query_pos] && details[query_pos] != ""

        query = query[0] if query.kind_of?(Array)

        url = "#{url}#{query}#{details[query_pos]}"

      else

        query.kind_of?(Array) ? url = "#{url}#{query[0]}#{query[1]}" : url = "#{url}#{query}"

      end

      query_pos += 1

    end

    return url

  end

end

#jskValuesObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/test_joska/builder.rb', line 32

def jskValues
  p "Raise on error: #{@@raise_on_error}" 
  p ""
  p "Verbose: #{@@verbose}"
  p ""
  p "Url parts: #{@@URL}"
  p ""
  p "Headers: #{@@HEAD}"
  p ""
  p "Standard endpoint: #{@@standard_endpoint}"
  p ""
  p "Standard header: #{@@standard_header}"
  p ""
  p "Internal log: #{@@internal_log}"
  p ""
  p "Url log: #{@@url_log}"
end

#keyRemover(object, key) ⇒ Object



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/test_joska/builder.rb', line 391

def keyRemover(object, key)

  return arrayKeyRemover(object, key) if object.kind_of?(Array)

  object = object.except
 
  key = key.split("|")
 
  if !object[key.first] || key.count == 1
 
    object = object.except(key.first)
 
  else
 
    object[key.first] = rateTokenBuilder(object[key.first]) if key.first.include?("Token") && object[key.first].kind_of?(String)
 
    object[key.first] = object[key.first].kind_of?(Array) ? arrayKeyRemover(object[key.first], key.drop(1).join("|")) : keyRemover(object[key.first], key.drop(1).join("|"))
 
  end
 
  return object
 
end

#rateTokenBuilder(rateToken) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/test_joska/builder.rb', line 240

def rateTokenBuilder(rateToken)

  token_decoded = Base64.decode64(rateToken).gsub(" ", "").gsub("/>", "").gsub("<rateToken", "").gsub("=", "").split('"')

  built_token = {}

  cur_part = 0

  while cur_part < token_decoded.count do

    built_token[token_decoded[cur_part]] = token_decoded[cur_part + 1]

    cur_part += 2

  end

  built_token

end

#request(method, product, type, details = nil, payload = nil, header = nil, endpoint = nil) ⇒ Object



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
# File 'lib/test_joska/builder.rb', line 140

def request(method, product, type, details=nil, payload=nil, header=nil, endpoint=nil)

  raise "URL_parts não configurada" if !@@URL

  endpoint = @@standard_endpoint if !endpoint

  url = jskUrlBuilder(product, type, details, endpoint)

  header = @@standard_header if !header

  header = @@HEAD[header] if header.kind_of?(String)

  payload = payload.to_json if payload

  res = ""

  p url if @@verbose

  @@url_log = "#{@@url_log}\n#{method} #{type}: #{url}"

  @@url_log = "#{@@url_log}\nPayload: #{payload}" if payload && type != "login"

  RestClient::Request.execute(method: method, url: url, headers: header, payload: payload, timeout: 90) do |response|

    res_message = response

    if response.code != 200

      begin

        res_message = JSON.parse(res_message)

      rescue

        p "Não possível converter para json"

      end
    
      raise "Erro no serviço #{type}, codigo: #{response.code} \nURL: #{url} \nResposta: #{res_message}" 

    end

    res = response

  end

  begin

    return JSON.parse(res)

  rescue

    raise "Problema em converter a resposta #{res}" if res != ""

  end

end