November 22, 2018

Golang Automatic Test Execution

This script acts as a watcher for your golang files and runs tests automatically on every *.go file save.

Should work with linux & osx, displays notifications :)

setup:

# gem install observr
#
# run:
# observr autotest.rb
#
# nice to have (for displaying icons in the notification):
# ~/.config/autotest/success.png
# ~/.config/autotest/failure.png
#
# use 'brew install terminal-notifier', Mac

require 'rbconfig'

watch '^*.go' do |match|
    run_tests unless /vendor/.match(match[0])
end

def run_tests
  clear_console

  result = `go test .`
  puts result

  failure_lines = []
  lines = result.split("\n")
  lines.each do |l|
    if l.include?(": FAIL: ") || l.include?("Expected: ") || l.include?("Actual: ")
      failure_lines << l.strip!
    end
  end

  if lines.last(1)[0].match(/^ok/)
    notify "PASS", "", "success.png", 1000
  else
    notify_failed "Failure", failure_lines.join("\n")
  end
end

def notify title, msg, img, show_time
  images_dir='~/.config/autotest'

  cmd = "notify-send -t #{show_time} '#{title}' '#{msg}' -i #{images_dir}/#{img};" if RbConfig::CONFIG["arch"].include? "linux"

  if RbConfig::CONFIG["arch"].include? "darwin"
    show_time /= 1000
    cmd = "terminal-notifier -timeout #{show_time} -title '#{title}' -message '#{msg}' -appIcon #{images_dir}/#{img};"
  end
  system(cmd)
end

def notify_failed cmd, result, show = 3000
  notify "#{cmd}", result, "failure.png", show
end

def clear_console
  puts "\e[H\e[2J"  #clear console
end