Browse Source

Merge pull request #395 from probkiizokna/fix_list_unmarshaling

Fix list unmarshaling
Chris Bannister 10 năm trước cách đây
mục cha
commit
5baef3037c
2 tập tin đã thay đổi với 54 bổ sung3 xóa
  1. 1 3
      marshal.go
  2. 53 0
      marshal_test.go

+ 1 - 3
marshal.go

@@ -952,10 +952,8 @@ func unmarshalList(info TypeInfo, data []byte, value interface{}) error {
 			if rv.Len() != n {
 				return unmarshalErrorf("unmarshal list: array with wrong size")
 			}
-		} else if rv.Cap() < n {
-			rv.Set(reflect.MakeSlice(t, n, n))
 		} else {
-			rv.SetLen(n)
+			rv.Set(reflect.MakeSlice(t, n, n))
 		}
 		for i := 0; i < n; i++ {
 			if len(data) < 2 {

+ 53 - 0
marshal_test.go

@@ -657,6 +657,59 @@ func TestMarshalVarint(t *testing.T) {
 	}
 }
 
+func equalStringSlice(leftList, rightList []string) bool {
+	if len(leftList) != len(rightList) {
+		return false
+	}
+	for index := range leftList {
+		if rightList[index] != leftList[index] {
+			return false
+		}
+	}
+	return true
+}
+
+func TestMarshalList(t *testing.T) {
+	typeInfo := CollectionType {
+		NativeType: NativeType { proto: 2, typ: TypeList },
+		Elem: NativeType{ proto: 2, typ: TypeVarchar },
+	}
+
+	sourceLists := [][]string {
+		[]string{ "valueA" },
+		[]string{ "valueA", "valueB" },
+		[]string{ "valueB" },
+	}
+
+	listDatas := [][]byte{}
+
+	for _, list := range sourceLists {
+		listData, marshalErr := Marshal(typeInfo, list)
+		if nil != marshalErr {
+			t.Errorf("Error marshal %+v of type %+v: %s", list, typeInfo, marshalErr)
+		}
+		listDatas = append(listDatas, listData)
+	}
+
+	outputLists := [][]string{}
+
+	var outputList []string
+
+	for _, listData := range listDatas {
+		if unmarshalErr := Unmarshal(typeInfo, listData, &outputList); nil != unmarshalErr {
+			t.Error(unmarshalErr)
+		}
+		outputLists = append(outputLists, outputList)
+	}
+
+	for index, sourceList := range sourceLists {
+		outputList := outputLists[index]
+		if !equalStringSlice(sourceList, outputList) {
+			t.Errorf("Lists %+v not equal to lists %+v, but should", sourceList, outputList)
+		}
+	}
+}
+
 type CustomString string
 
 func (c CustomString) MarshalCQL(info TypeInfo) ([]byte, error) {