multi_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package testdata
  2. import (
  3. "context"
  4. "errors"
  5. "testing"
  6. )
  7. func TestMultiCache(t *testing.T) {
  8. id := int64(1)
  9. d := New()
  10. meta := map[int64]*Article{id: {ID: id}}
  11. getsFromCache := func(c context.Context, keys []int64) (map[int64]*Article, error) { return meta, nil }
  12. notGetsFromCache := func(c context.Context, keys []int64) (map[int64]*Article, error) { return nil, errors.New("err") }
  13. // 缓存返回了部分数据
  14. partFromCache := func(c context.Context, keys []int64) (map[int64]*Article, error) { return meta, errors.New("err") }
  15. getsFromSource := func(c context.Context, keys []int64) (map[int64]*Article, error) { return meta, nil }
  16. notGetsFromSource := func(c context.Context, keys []int64) (map[int64]*Article, error) {
  17. return meta, errors.New("err")
  18. }
  19. addToCache := func(c context.Context, values map[int64]*Article) error { return nil }
  20. // gets from cache
  21. _multiCacheFunc = getsFromCache
  22. _multiRawFunc = notGetsFromSource
  23. _multiAddCacheFunc = addToCache
  24. res, err := d.Articles(context.TODO(), []int64{id})
  25. if err != nil {
  26. t.Fatalf("err should be nil, get: %v", err)
  27. }
  28. if res[1].ID != 1 {
  29. t.Fatalf("id should be 1")
  30. }
  31. // get from source
  32. _multiCacheFunc = notGetsFromCache
  33. _multiRawFunc = getsFromSource
  34. res, err = d.Articles(context.TODO(), []int64{id})
  35. if err != nil {
  36. t.Fatalf("err should be nil, get: %v", err)
  37. }
  38. if res[1].ID != 1 {
  39. t.Fatalf("id should be 1")
  40. }
  41. // 缓存失败 返回部分数据 回源也失败的情况
  42. _multiCacheFunc = partFromCache
  43. _multiRawFunc = notGetsFromSource
  44. res, err = d.Articles(context.TODO(), []int64{id})
  45. if err == nil {
  46. t.Fatalf("err should be nil, get: %v", err)
  47. }
  48. if res[1].ID != 1 {
  49. t.Fatalf("id should be 1")
  50. }
  51. // with null cache
  52. nullCache := &Article{ID: -1}
  53. getNullFromCache := func(c context.Context, keys []int64) (map[int64]*Article, error) {
  54. return map[int64]*Article{id: nullCache}, nil
  55. }
  56. _multiCacheFunc = getNullFromCache
  57. _multiRawFunc = notGetsFromSource
  58. res, err = d.Articles(context.TODO(), []int64{id})
  59. if err != nil {
  60. t.Fatalf("err should be nil, get: %v", err)
  61. }
  62. if res[id] != nil {
  63. t.Fatalf("res should be nil")
  64. }
  65. }