maputils_test.go 995 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package maputils
  2. import "testing"
  3. func TestGetValueByPath(t *testing.T) {
  4. testMap := map[string]any{
  5. "foo1": map[string]any{
  6. "foo1_sub": []any{
  7. "value1", 2,
  8. },
  9. },
  10. }
  11. value, err := GetValueByPath(testMap, "foo1.foo1_sub.[0]")
  12. if err != nil {
  13. t.Fatal(err)
  14. }
  15. if value.(string) != "value1" {
  16. t.Fatal("值不一致")
  17. }
  18. value, err = GetValueByPath(testMap, "foo1.foo1_sub.[1]")
  19. if err != nil {
  20. t.Fatal(err)
  21. }
  22. if value.(int) != 2 {
  23. t.Fatal("值不一致")
  24. }
  25. }
  26. func TestGetValueByKey(t *testing.T) {
  27. testMap := map[string]any{
  28. "foo1": map[string]any{
  29. "foo1_sub": []any{
  30. "value1", 2,
  31. },
  32. },
  33. }
  34. foo1Map, ok := GetValueByKey[string, map[string]any](testMap, "foo1")
  35. if !ok {
  36. t.Fatal("取foo1值失败")
  37. }
  38. foo1Sub, ok := GetValueByKey[string, []any](foo1Map, "foo1_sub")
  39. if !ok {
  40. t.Fatal("取foo1Sub值失败")
  41. }
  42. if foo1Sub[0].(string) != "value1" {
  43. t.Fatal("值不一致")
  44. }
  45. if foo1Sub[1].(int) != 2 {
  46. t.Fatal("值不一致")
  47. }
  48. }