local_ctx_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package local_ctx
  2. import (
  3. "context"
  4. "testing"
  5. )
  6. type tester struct {
  7. t *testing.T
  8. ctx *LocalCtx
  9. }
  10. func TestLocalCtx(t *testing.T) {
  11. sf := &tester{
  12. t: t,
  13. }
  14. sf.new()
  15. sf.set()
  16. sf.get()
  17. sf.del()
  18. sf.done()
  19. }
  20. // Ожидает отмены контекста
  21. func (sf *tester) done() {
  22. sf.t.Log("done")
  23. _ = sf.ctx.Size()
  24. go sf.ctx.Cancel()
  25. sf.ctx.Done()
  26. }
  27. // Удаляет несуществующий ключ из локального контекста
  28. func (sf *tester) del() {
  29. sf.t.Log("del")
  30. sf.ctx.Del("123")
  31. sf.ctx.Del("count")
  32. }
  33. // Возвращает хранимое значение
  34. func (sf *tester) get() {
  35. sf.t.Log("get")
  36. val := sf.ctx.Get("count")
  37. count := val.Val().(int)
  38. if count == 15 {
  39. return
  40. }
  41. }
  42. // Устанавливает значение
  43. func (sf *tester) set() {
  44. sf.t.Log("set")
  45. sf.ctx.Set("count", 5, "test_val")
  46. sf.ctx.Set("count", 15, "test_val1")
  47. }
  48. // Создание нового локального контекста
  49. func (sf *tester) new() {
  50. sf.t.Log("new")
  51. sf.newBad1()
  52. sf.newGood1()
  53. }
  54. func (sf *tester) newGood1() {
  55. sf.t.Log("newGood1")
  56. ctx := context.Background()
  57. sf.ctx = NewLocalCtx(ctx).(*LocalCtx)
  58. _ = sf.ctx.Log()
  59. if lst := sf.ctx.SortedList(); lst == nil {
  60. sf.t.Fatalf("newGood1(): lst==nil")
  61. }
  62. if ctx := sf.ctx.Ctx(); ctx == nil {
  63. sf.t.Fatalf("newGood1(): ctx==nil")
  64. }
  65. }
  66. // Нет контекста ядра
  67. func (sf *tester) newBad1() {
  68. sf.t.Log("newBad1")
  69. defer func() {
  70. if _panic := recover(); _panic == nil {
  71. sf.t.Fatalf("newBad1(): panic==nil")
  72. }
  73. }()
  74. var ctx context.Context
  75. sf.ctx = NewLocalCtx(ctx).(*LocalCtx)
  76. }