saga_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package test
  2. import (
  3. "errors"
  4. "fmt"
  5. "git.sxidc.com/service-supports/dapr_api/saga"
  6. "git.sxidc.com/service-supports/dapr_api/state"
  7. "testing"
  8. "time"
  9. )
  10. func TestSagaOK(t *testing.T) {
  11. stateAPI := state.NewAPI(daprHttpPort, 10*time.Second)
  12. defer state.DestroyAPI(stateAPI)
  13. saga.Init(stateAPI, stateStoreName, "sage_test")
  14. defer saga.Destroy()
  15. orchestrator := saga.GetInstance().BuildOrchestrator("test-ok", 5*time.Second).
  16. AddStep(&saga.Step{
  17. StepFunc: func() error {
  18. fmt.Println("one")
  19. return nil
  20. },
  21. StepRollbackFunc: func() error {
  22. fmt.Println("one rollback")
  23. return nil
  24. },
  25. }).
  26. AddStep(&saga.Step{
  27. StepFunc: func() error {
  28. fmt.Println("two")
  29. return nil
  30. },
  31. StepRollbackFunc: func() error {
  32. fmt.Println("two rollback")
  33. return nil
  34. },
  35. }).
  36. AddStep(&saga.Step{
  37. StepFunc: func() error {
  38. fmt.Println("three")
  39. return nil
  40. },
  41. StepRollbackFunc: nil,
  42. }).
  43. Output(func() (interface{}, error) {
  44. return "ok result", nil
  45. })
  46. result, err := orchestrator.Run()
  47. if err != nil {
  48. t.Fatal(err)
  49. }
  50. fmt.Println("Result:", result)
  51. }
  52. func TestSagaRollback(t *testing.T) {
  53. stateAPI := state.NewAPI(daprHttpPort, 10*time.Second)
  54. defer state.DestroyAPI(stateAPI)
  55. saga.Init(stateAPI, stateStoreName, "sage_test")
  56. defer saga.Destroy()
  57. orchestrator := saga.GetInstance().BuildOrchestrator("test-rollback", 5*time.Second).
  58. AddStep(&saga.Step{
  59. StepFunc: func() error {
  60. fmt.Println("one")
  61. return nil
  62. },
  63. StepRollbackFunc: func() error {
  64. fmt.Println("one rollback")
  65. return nil
  66. },
  67. }).
  68. AddStep(&saga.Step{
  69. StepFunc: func() error {
  70. fmt.Println("two")
  71. return nil
  72. },
  73. StepRollbackFunc: func() error {
  74. fmt.Println("two rollback")
  75. return nil
  76. },
  77. }).
  78. AddStep(&saga.Step{
  79. StepFunc: func() error {
  80. fmt.Println("three")
  81. return nil
  82. },
  83. StepRollbackFunc: nil,
  84. }).
  85. AddStep(&saga.Step{
  86. StepFunc: func() error {
  87. return errors.New("four error")
  88. },
  89. StepRollbackFunc: nil,
  90. }).
  91. Output(func() (interface{}, error) {
  92. return "should not come here", nil
  93. })
  94. result, err := orchestrator.Run()
  95. if err != nil {
  96. t.Fatal(err)
  97. }
  98. fmt.Println("Result:", result)
  99. time.Sleep(1 * time.Second)
  100. }