Skip to content

Instantly share code, notes, and snippets.

@brokenthumbs
Last active December 16, 2015 07:19
Show Gist options
  • Save brokenthumbs/5398225 to your computer and use it in GitHub Desktop.
Save brokenthumbs/5398225 to your computer and use it in GitHub Desktop.
Normalize all JUnit formatted .xml files in the specified folder
def normalize_xml(folder)
xml_files = []
Dir.entries(folder).each do |element|
xml_files << "#{folder}/#{element}" if element.end_with?(".xml")
end
merged_files = {}
xml_files.each do |xml_file|
merged_files[xml_file] = []
file = File.new(xml_file)
number = 1
result = ""
file.each_line do |line|
if line.start_with? "<?xml"
if !result.empty?
new_file_name = xml_file.gsub(".xml", ".#{number}.xml")
merged_files[xml_file] << new_file_name
new_file = File.new(new_file_name, "w")
new_file.write(result)
new_file.close
number += 1
end
result = ""
end
result << line
end
new_file_name = xml_file.gsub(".xml", ".#{number}.xml")
merged_files[xml_file] << new_file_name
new_file = File.new(new_file_name, "w")
new_file.write(result)
new_file.close
File.delete(xml_file)
end
merged_files.each do |merged_file, files_to_merge|
errors = 0
failures = 0
skipped = 0
tests = 0
time = 0
cases = []
files_to_merge.each do |file|
# Add up the attributes
temp = File.new(file)
xdoc = Nokogiri::XML(temp)
xdoc.css("testsuite").each do |element|
errors += element.attr("errors").to_i
failures += element.attr("failures").to_i
skipped += element.attr("skipped").to_i
tests += element.attr("tests").to_i
time += element.attr("time").to_f
end
# Collect the test cases
xdoc.css("testcase").each do |element|
cases << element.to_s
end
File.delete(file)
end
# Write the final merged results.xml
results = File.new(merged_file, "w")
results.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
results.write("<testsuite errors=\"#{errors}\" failures=\"#{failures}\" skipped=\"#{skipped}\" tests=\"#{tests}\" time=\"#{time}\">\n")
results.write(" <properties/>\n")
cases.each { |tc| results.write(" #{tc}\n") }
results.write("</testsuite>")
results.close
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment