Skip to content

Instantly share code, notes, and snippets.

@yloiseau
Created September 1, 2014 17:39
Show Gist options
  • Save yloiseau/7212fc97a23155a444c5 to your computer and use it in GitHub Desktop.
Save yloiseau/7212fc97a23155a444c5 to your computer and use it in GitHub Desktop.
Try on a unit test golo mini framework

the unit test framework itself

module gololang.unittest

struct TestCase = {
  desc,
  verbose,
  failed,
  errors,
  tests
}

augment gololang.unittest.types.TestCase {

  function printTestDesc = |this, desc| { 
    if this: verbose() { print("\n* " + desc + "...\t\t") }
  }

  function printDesc = |this| {
    if this: verbose() { println("== %s": format(this: desc())) }
  }

  function printOk = |this| {
    if this: verbose() {
      print("[OK]")
    } else {
      print(".") 
    }
  }

  function printFailed = |this, err| {
    if this: verbose() { 
      println("[Failed]")
      println(err)
    } else { 
      print("F") 
    }
  }

  function printErr = |this, err| {
    if this: verbose() {
      println("[Error]")
      println(err)
    } else {
      print("E") 
    }
  }

  function printRunResult = |this| {
    println("\n--------")
    println("Run: %s tests, %s failed, %s errors": format(
      this:tests():size(),
      this:failed():size(),
      this:errors():size()))
  }

  function run = |this| {
    this: printDesc()
    this: tests(): each(|t| {
      this: runTest(t: get(0), t: get(1))
    })
    this: printRunResult()
  }

  function runTest = |this, message, func| {
    this: printTestDesc(message)
    try {
      func()
      this: printOk()
    } catch (e) { case {
      when e oftype AssertionError.class { 
        this: printFailed(e)
        this: failed(): add(e)
      }
      otherwise { 
        this: printErr(e)
        this: errors(): add(e)
      }
    }}
  }

  function Test = |this, desc| -> |func| {
    this:tests():add([desc, {require(func(), desc)}])
    return this
  }
  
}

function tester = |desc| -> TestCase(desc, false, set[], set[], set[])

The code to test

module MyModule

function foo = -> "foo"

The tests

module MyModuleTest

import gololang.unittest

import MyModule

function main = |args| {
  tester("Testing MyModule"):verbose(true):
    Test("foo must return foo")(-> foo() == "foo"):
    Test("success")(-> true):
    Test("will fail")(-> false):
    Test("will err")(-> raise("an error occured")):
    Test("success")(-> true):
  run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment