cleanup.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package framework
  2. import (
  3. "sync"
  4. )
  5. // CleanupActionHandle is an integer pointer type for handling cleanup action
  6. type CleanupActionHandle *int
  7. type cleanupFuncHandle struct {
  8. actionHandle CleanupActionHandle
  9. actionHook func()
  10. }
  11. var (
  12. cleanupActionsLock sync.Mutex
  13. cleanupHookList = []cleanupFuncHandle{}
  14. )
  15. // AddCleanupAction installs a function that will be called in the event of the
  16. // whole test being terminated. This allows arbitrary pieces of the overall
  17. // test to hook into SynchronizedAfterSuite().
  18. // The hooks are called in last-in-first-out order.
  19. func AddCleanupAction(fn func()) CleanupActionHandle {
  20. p := CleanupActionHandle(new(int))
  21. cleanupActionsLock.Lock()
  22. defer cleanupActionsLock.Unlock()
  23. c := cleanupFuncHandle{actionHandle: p, actionHook: fn}
  24. cleanupHookList = append([]cleanupFuncHandle{c}, cleanupHookList...)
  25. return p
  26. }
  27. // RemoveCleanupAction removes a function that was installed by
  28. // AddCleanupAction.
  29. func RemoveCleanupAction(p CleanupActionHandle) {
  30. cleanupActionsLock.Lock()
  31. defer cleanupActionsLock.Unlock()
  32. for i, item := range cleanupHookList {
  33. if item.actionHandle == p {
  34. cleanupHookList = append(cleanupHookList[:i], cleanupHookList[i+1:]...)
  35. break
  36. }
  37. }
  38. }
  39. // RunCleanupActions runs all functions installed by AddCleanupAction. It does
  40. // not remove them (see RemoveCleanupAction) but it does run unlocked, so they
  41. // may remove themselves.
  42. func RunCleanupActions() {
  43. list := []func(){}
  44. func() {
  45. cleanupActionsLock.Lock()
  46. defer cleanupActionsLock.Unlock()
  47. for _, p := range cleanupHookList {
  48. list = append(list, p.actionHook)
  49. }
  50. }()
  51. // Run unlocked.
  52. for _, fn := range list {
  53. fn()
  54. }
  55. }