Created
April 13, 2012 07:37
-
-
Save egonelbre/2374904 to your computer and use it in GitHub Desktop.
golang scope function test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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