single_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package testdata
  2. import (
  3. "context"
  4. "errors"
  5. "testing"
  6. )
  7. func TestSingleCache(t *testing.T) {
  8. d := New()
  9. meta := &Article{ID: 1}
  10. getFromCache := func(c context.Context, id int64) (*Article, error) { return meta, nil }
  11. notGetFromCache := func(c context.Context, id int64) (*Article, error) { return nil, errors.New("err") }
  12. getFromSource := func(c context.Context, id int64) (*Article, error) { return meta, nil }
  13. notGetFromSource := func(c context.Context, id int64) (*Article, error) { return meta, errors.New("err") }
  14. addToCache := func(c context.Context, id int64, values *Article) error { return nil }
  15. // get from cache
  16. _singleCacheFunc = getFromCache
  17. _singleRawFunc = notGetFromSource
  18. _singleAddCacheFunc = addToCache
  19. res, err := d.Article(context.TODO(), 1)
  20. if err != nil {
  21. t.Fatalf("err should be nil, get: %v", err)
  22. }
  23. if res.ID != 1 {
  24. t.Fatalf("id should be 1")
  25. }
  26. // get from source
  27. _singleCacheFunc = notGetFromCache
  28. _singleRawFunc = getFromSource
  29. res, err = d.Article(context.TODO(), 1)
  30. if err != nil {
  31. t.Fatalf("err should be nil, get: %v", err)
  32. }
  33. if res.ID != 1 {
  34. t.Fatalf("id should be 1")
  35. }
  36. // with null cache
  37. nullCache := &Article{ID: -1}
  38. getNullFromCache := func(c context.Context, id int64) (*Article, error) { return nullCache, nil }
  39. _singleCacheFunc = getNullFromCache
  40. _singleRawFunc = notGetFromSource
  41. res, err = d.Article(context.TODO(), 1)
  42. if err != nil {
  43. t.Fatalf("err should be nil, get: %v", err)
  44. }
  45. if res != nil {
  46. t.Fatalf("res should be nil")
  47. }
  48. }