github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/base/toqtype/toqtype_test.go (about)

     1  package toqtype
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/google/go-cmp/cmp"
     7  )
     8  
     9  type simpleObject struct {
    10  	Fruit string
    11  	Num   int
    12  }
    13  
    14  type invalidObject struct {
    15  	Bad func()
    16  	Num int
    17  }
    18  
    19  func TestStructToMap(t *testing.T) {
    20  	s := simpleObject{Fruit: "apple", Num: 4}
    21  	val, err := StructToMap(s)
    22  	if err != nil {
    23  		t.Fatal(err)
    24  	}
    25  	expect := map[string]interface{}{
    26  		"Fruit": "apple",
    27  		"Num":   4.0,
    28  	}
    29  	if diff := cmp.Diff(expect, val); diff != "" {
    30  		t.Errorf("StructToMap (-want +got):\n%s", diff)
    31  	}
    32  }
    33  
    34  func TestStructToMapInvalid(t *testing.T) {
    35  	s := invalidObject{Bad: func() {}, Num: 4}
    36  	_, err := StructToMap(s)
    37  	if err == nil {
    38  		t.Fatal("expected error, did not get one")
    39  	}
    40  	expect := "json: unsupported type: func()"
    41  	if err.Error() != expect {
    42  		t.Fatalf("error mismatch, expected: %s, got: %s", expect, err.Error())
    43  	}
    44  }
    45  
    46  func TestMustParseJSONAsArray(t *testing.T) {
    47  	val := MustParseJSONAsArray("[1,2,3]")
    48  	expect := []interface{}{1.0, 2.0, 3.0}
    49  	if diff := cmp.Diff(expect, val); diff != "" {
    50  		t.Errorf("MustParseJsonAsArray (-want +got):\n%s", diff)
    51  	}
    52  }
    53  
    54  func TestMustParseCsvAsArray(t *testing.T) {
    55  	val := MustParseCsvAsArray("1,2\n3,4\n")
    56  	expect := []interface{}{
    57  		[]string{"1", "2"},
    58  		[]string{"3", "4"},
    59  	}
    60  	if diff := cmp.Diff(expect, val); diff != "" {
    61  		t.Errorf("MustParseCsvAsArray (-want +got):\n%s", diff)
    62  	}
    63  }