tree_test.go 2.0 KB
package domain

import (
	"encoding/json"
	"github.com/stretchr/testify/assert"
	"strconv"
	"testing"
)

func Test_Tree(t *testing.T) {
	table := []struct {
		Input  []TreeNode
		Text   string
		Except []string
	}{
		{
			Input: []TreeNode{&st{Id: 1, Pid: 0}, &st{Id: 2, Pid: 1}, &st{Id: 3, Pid: 1}, &st{Id: 4, Pid: 1}, &st{Id: 5, Pid: 3}, &st{Id: 6, Pid: 5}, &st{Id: 7, Pid: 5}},
			Text: `
树形结构:	 
	 1
2    3    4
     5
    6 7 
`,
			Except: []string{"5", "6", "7"},
		},
	}

	for i := range table {
		tree := NewTrees(table[i].Input)
		out := tree.AllChildNodes(&st{Id: 5, Pid: 3})
		var res []string
		for i := range out {
			res = append(res, out[i].ID())
		}
		assert.Equal(t, res, table[i].Except)
	}
}

type st struct {
	Id  int
	Pid int
}

func (t *st) PID() string {
	return strconv.Itoa(t.Pid)
}
func (t *st) ID() string {
	return strconv.Itoa(t.Id)
}

func TestInt64String(t *testing.T) {
	type value struct {
		Value Int64String `json:"v"`
	}
	jsonData := `{"v":1}`
	var v = value{}
	if err := json.Unmarshal([]byte(jsonData), &v); err != nil {
		assert.Error(t, err)
	}
	assert.Equal(t, v.Value, Int64String(1))
	if data, err := json.Marshal(v); err != nil {
		assert.Error(t, err)
	} else {
		t.Log(string(data))
	}
}

func TestStringInt64(t *testing.T) {
	type value struct {
		Value StringInt64 `json:"v"`
	}
	jsonData := `{"v":"1"}`
	var v = value{}
	if err := json.Unmarshal([]byte(jsonData), &v); err != nil {
		assert.Error(t, err)
	}
	assert.Equal(t, StringInt64(1), v.Value)
	if data, err := json.Marshal(v); err != nil {
		assert.Error(t, err)
	} else {
		t.Log(string(data))
	}
}

func TestStringInt64_Array(t *testing.T) {
	type value struct {
		Value []StringInt64 `json:"v"`
	}
	jsonData := `{"v":["1","2","3"]}`
	var v = value{}
	if err := json.Unmarshal([]byte(jsonData), &v); err != nil {
		assert.Error(t, err)
	}
	assert.Equal(t, []StringInt64{StringInt64(1), StringInt64(2), StringInt64(3)}, v.Value)
	if data, err := json.Marshal(v); err != nil {
		assert.Error(t, err)
	} else {
		t.Log(string(data))
	}
}