atexit_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package atexit
  15. import (
  16. "testing"
  17. )
  18. func TestAtExit(t *testing.T) {
  19. t.Run("empty reason", func(t *testing.T) {
  20. func() {
  21. defer func() {
  22. val := recover()
  23. if val == nil {
  24. t.Errorf("should panic")
  25. }
  26. }()
  27. Register(ExitHandler{})
  28. }()
  29. })
  30. t.Run("empty func", func(t *testing.T) {
  31. func() {
  32. defer func() {
  33. val := recover()
  34. if val == nil {
  35. t.Errorf("should panic")
  36. }
  37. }()
  38. Register(ExitHandler{
  39. Reason: "have reason",
  40. })
  41. }()
  42. })
  43. t.Run("order & prio", func(t *testing.T) {
  44. verdict := ""
  45. handler := func(eh ExitHandler) { verdict += eh.Reason }
  46. Register(ExitHandler{
  47. Prio: 2,
  48. Reason: "2",
  49. Func: handler,
  50. })
  51. Register(ExitHandler{
  52. Prio: 0,
  53. Reason: "0",
  54. Func: handler,
  55. })
  56. Register(ExitHandler{
  57. Prio: 0,
  58. Reason: "1",
  59. Func: handler,
  60. })
  61. Handle()
  62. Handle()
  63. if verdict != "012" {
  64. t.Errorf("expecting %q, got %q", "012", verdict)
  65. }
  66. })
  67. }