Skip to content

Instantly share code, notes, and snippets.

@egonelbre
Created April 13, 2012 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egonelbre/2374904 to your computer and use it in GitHub Desktop.
Save egonelbre/2374904 to your computer and use it in GitHub Desktop.
golang scope function test
package main
import "errors"
func actionOk() (int, error) {
return 1, nil
}
func actionErr() (int, error) {
return 0, errors.New("err")
}
type action func() (int, error)
func scope(err error, rollback func(), cleanup func()) {
if err == nil {
cleanup()
} else {
rollback()
}
}
func rollback(err error, f func()) {
if err != nil {
f()
}
}
func cleanup(err error, f func()) {
if err == nil {
f()
}
}
func testScope(first action, second action) {
var err error
_, err = first()
defer scope(err,
func() { println(" rollback: first ") },
func() { println(" cleanup: first ") })
_, err = second()
defer scope(err,
func() { println(" rollback: second ") },
func() { println(" cleanup: second ") })
}
func testSeparate(first action, second action) {
var err error
_, err = first()
defer rollback(err, func() { println(" rollback: first ") })
defer cleanup(err, func() { println(" cleanup: first ") })
_, err = second()
defer rollback(err, func() { println(" rollback: second ") })
defer cleanup(err, func() { println(" cleanup: second ") })
}
func runTest(test func(action, action)) {
println("Running test: OK, OK")
test(actionOk, actionOk)
println("Running test: OK, ERR")
test(actionOk, actionErr)
println("Running test: ERR, OK")
test(actionErr, actionOk)
println("Running test: ERR, ERR")
test(actionErr, actionErr)
}
func main() {
println("--------------------------")
println("testing scope function")
runTest(testScope)
println("--------------------------")
println("testing separate functions")
runTest(testSeparate)
println()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment