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 :)

# gem install observr
#
# run:
# observr autotest.rb
#
# nice to have (for displaying icons in the notification):
# ~/.config/autotest/success.png
# ~/.config/autotest/fail.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.start_with?('--- FAIL') || l.include?('_test.go:')
      failure_lines << l[4..-1]
    end
  end

  if failure_lines.empty?
    notify "PASS", "", "success.png", 1000
  else
    notify_failed "Failure", failure_lines.join("\r")
  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, "fail.png", show
end

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