local_ctx_test.go 1.8 KB

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