gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cache
  4. import (
  5. "context"
  6. "testing"
  7. "time"
  8. "code.gitea.io/gitea/modules/test"
  9. "github.com/stretchr/testify/assert"
  10. )
  11. func TestWithCacheContext(t *testing.T) {
  12. ctx := WithCacheContext(t.Context())
  13. c := GetContextCache(ctx)
  14. v, _ := c.Get("empty_field", "my_config1")
  15. assert.Nil(t, v)
  16. const field = "system_setting"
  17. v, _ = c.Get(field, "my_config1")
  18. assert.Nil(t, v)
  19. c.Put(field, "my_config1", 1)
  20. v, _ = c.Get(field, "my_config1")
  21. assert.NotNil(t, v)
  22. assert.Equal(t, 1, v.(int))
  23. c.Delete(field, "my_config1")
  24. c.Delete(field, "my_config2") // remove a non-exist key
  25. v, _ = c.Get(field, "my_config1")
  26. assert.Nil(t, v)
  27. vInt, err := GetWithContextCache(ctx, field, "my_config1", func(context.Context, string) (int, error) {
  28. return 1, nil
  29. })
  30. assert.NoError(t, err)
  31. assert.Equal(t, 1, vInt)
  32. v, _ = c.Get(field, "my_config1")
  33. assert.EqualValues(t, 1, v)
  34. defer test.MockVariableValue(&timeNow, func() time.Time {
  35. return time.Now().Add(5 * time.Minute)
  36. })()
  37. v, _ = c.Get(field, "my_config1")
  38. assert.Nil(t, v)
  39. }