You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

context_committer_test.go 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package db // it's not db_test, because this file is for testing the private type halfCommitter
  4. import (
  5. "fmt"
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. )
  9. type MockCommitter struct {
  10. wants []string
  11. gots []string
  12. }
  13. func NewMockCommitter(wants ...string) *MockCommitter {
  14. return &MockCommitter{
  15. wants: wants,
  16. }
  17. }
  18. func (c *MockCommitter) Commit() error {
  19. c.gots = append(c.gots, "commit")
  20. return nil
  21. }
  22. func (c *MockCommitter) Close() error {
  23. c.gots = append(c.gots, "close")
  24. return nil
  25. }
  26. func (c *MockCommitter) Assert(t *testing.T) {
  27. assert.Equal(t, c.wants, c.gots, "want operations %v, but got %v", c.wants, c.gots)
  28. }
  29. func Test_halfCommitter(t *testing.T) {
  30. /*
  31. Do something like:
  32. ctx, committer, err := db.TxContext(db.DefaultContext)
  33. if err != nil {
  34. return nil
  35. }
  36. defer committer.Close()
  37. // ...
  38. if err != nil {
  39. return nil
  40. }
  41. // ...
  42. return committer.Commit()
  43. */
  44. testWithCommitter := func(committer Committer, f func(committer Committer) error) {
  45. if err := f(&halfCommitter{committer: committer}); err == nil {
  46. committer.Commit()
  47. }
  48. committer.Close()
  49. }
  50. t.Run("commit and close", func(t *testing.T) {
  51. mockCommitter := NewMockCommitter("commit", "close")
  52. testWithCommitter(mockCommitter, func(committer Committer) error {
  53. defer committer.Close()
  54. return committer.Commit()
  55. })
  56. mockCommitter.Assert(t)
  57. })
  58. t.Run("rollback and close", func(t *testing.T) {
  59. mockCommitter := NewMockCommitter("close", "close")
  60. testWithCommitter(mockCommitter, func(committer Committer) error {
  61. defer committer.Close()
  62. if true {
  63. return fmt.Errorf("error")
  64. }
  65. return committer.Commit()
  66. })
  67. mockCommitter.Assert(t)
  68. })
  69. t.Run("close and commit", func(t *testing.T) {
  70. mockCommitter := NewMockCommitter("close", "close")
  71. testWithCommitter(mockCommitter, func(committer Committer) error {
  72. committer.Close()
  73. committer.Commit()
  74. return fmt.Errorf("error")
  75. })
  76. mockCommitter.Assert(t)
  77. })
  78. }