github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/easy/ezmap/map_test.go (about)

     1  package ezmap
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  	"github.com/stretchr/testify/require"
     8  	"gopkg.in/yaml.v3"
     9  )
    10  
    11  func TestMap(t *testing.T) {
    12  	t.Run("zero map", func(t *testing.T) {
    13  		var m Map
    14  		val1, exists1 := m.Get("abc")
    15  		assert.False(t, exists1)
    16  		assert.Nil(t, val1)
    17  		assert.Nil(t, m.GetOr("abc", nil))
    18  		assert.Panics(t, func() { _ = m.MustGet("abc") })
    19  
    20  		m.Set("abc", "abc")
    21  		val2, exists2 := m.Get("abc")
    22  		assert.True(t, exists2)
    23  		assert.Equal(t, "abc", val2)
    24  	})
    25  
    26  	t.Run("Merge", func(t *testing.T) {
    27  		m1 := Map{"abc": 123}
    28  		var m2 Map
    29  		m2.Merge(m1)
    30  		require.NotNil(t, m2)
    31  		assert.Equal(t, 123, m2.GetOr("abc", 0))
    32  	})
    33  }
    34  
    35  func TestYAMLMarshaling(t *testing.T) {
    36  	s := `
    37  servers:
    38    - ports: [ 80, ]
    39      server_names:
    40        - "www.example1.com"
    41        - "www.example2.com"
    42      services:
    43        - "serviceName1"
    44    - ports: [ 80, 81 ]
    45      server_names:
    46        - "api.example1.com"
    47      services:
    48        - "serviceName2"
    49  `
    50  	var m Map
    51  	err := yaml.Unmarshal([]byte(s), &m)
    52  	require.Nil(t, err)
    53  
    54  	services, ok := m.GetSlice("servers").([]any)
    55  	require.True(t, ok)
    56  	assert.Len(t, services, 2)
    57  	assert.Equal(t, 80, services[0].(map[string]any)["ports"].([]any)[0])
    58  	assert.Equal(t, 81, services[1].(map[string]any)["ports"].([]any)[1])
    59  	assert.Equal(t, "serviceName2", services[1].(map[string]any)["services"].([]any)[0])
    60  }