Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is a simple script used calculate average spec files running time across multiple builds using Knapsack API. It requires that the KNAPSACK_API_TOKEN variable is set. It runs by default for the last 10 builds, but you can customize it passing the number of builds you want as an argument. Lastly, it returns a specs.txt file with the average t…
# frozen_string_literal: true
require 'httparty'
REQUESTED_BUILDS = ARGV[0].to_i || 10
SPEC_FILES = {}
def get(url, options = {})
headers = {
'cache-control': 'no-cache',
'KNAPSACK-PRO-TEST-SUITE-TOKEN': ENV['KNAPSACK_API_TOKEN']
}
response = HTTParty.get(url, headers: headers, query: options, format: :plain)
JSON.parse(response, symbolize_names: true)
end
def ci_build_list
@ci_build_list ||= get('https://api.knapsackpro.com/v1/builds').take(REQUESTED_BUILDS)
end
def ci_build(ci_build_token)
get("https://api.knapsackpro.com/v1/builds/#{ci_build_token}")
end
def build_data(ci_build_token)
ci_build(ci_build_token).dig(:build_subsets)&.each do |build_subset|
build_subset.dig(:test_files)&.each do |test_file|
spec_file_data(test_file)
end
end
end
def spec_file_data(test_file)
file_name = test_file.dig(:path)&.to_sym
file_execution_time = test_file.dig(:time_execution)&.to_f
return if file_name.nil? || file_execution_time.nil?
spec_file_data = SPEC_FILES.dig(file_name)
if spec_file_data.nil?
SPEC_FILES[file_name] = {
total_executions: 1,
total_execution_time: file_execution_time
}
else
spec_file_data[:total_execution_time] += file_execution_time
spec_file_data[:total_executions] += 1
end
end
def calculate_average_times
ci_build_list.each do |ci_build|
build_data(ci_build.dig(:id))
end
SPEC_FILES.each do |_key, file|
file_total_execution_time = file[:total_execution_time]
file_total_executions = file[:total_executions]
file[:average_execution_time] = file_total_execution_time / file_total_executions
end
end
def sorted_specs_by_time
SPEC_FILES.sort_by{ |_file_name, file_data| -file_data[:average_execution_time] }
end
def print_specs_info
calculate_average_times
File.open('specs.txt', 'w') do |file|
sorted_specs_by_time.each do |spec_data|
file.write("#{spec_data.first} - Average time: #{spec_data.last[:average_execution_time]}\n")
end
end
end
print_specs_info
@ArturT

This comment has been minimized.

ArturT commented May 28, 2018

Thanks for the script! Here is the article describing how to use Knapsack Pro API to fetch data. I added there the link to your gist :)
http://docs.knapsackpro.com/2018/how-to-export-test-suite-timing-data-from-knapsack-pro-api

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment