github.com/angryronald/go-kit@v0.0.0-20240505173814-ff2bd9c79dbf/cast/object.transformer_test.go (about)

     1  package cast
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"testing"
     7  
     8  	"github.com/google/uuid"
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func TestTransformObject(t *testing.T) {
    13  	// Define sample input and output structs
    14  	type SourceStruct struct {
    15  		Field1 string `json:"field1"`
    16  		Field2 int    `json:"field2"`
    17  	}
    18  
    19  	type ResultStruct struct {
    20  		Field1 string `json:"field1"`
    21  		Field2 int    `json:"field2"`
    22  	}
    23  
    24  	// Create a sample source object
    25  	source := SourceStruct{
    26  		Field1: "value1",
    27  		Field2: 42,
    28  	}
    29  
    30  	// Create a result object with the same structure
    31  	var result ResultStruct
    32  
    33  	// Test TransformObject function
    34  	err := TransformObject(source, &result)
    35  	if err != nil {
    36  		t.Errorf("TransformObject returned an error: %v", err)
    37  	}
    38  
    39  	// Check if the result matches the expected output
    40  	expectedResult := ResultStruct{
    41  		Field1: "value1",
    42  		Field2: 42,
    43  	}
    44  
    45  	if !reflect.DeepEqual(result, expectedResult) {
    46  		t.Errorf("TransformObject result doesn't match the expected result.")
    47  	}
    48  }
    49  
    50  func TestFromBytes(t *testing.T) {
    51  	// Define a sample JSON
    52  	jsonData := []byte(`{"Field1": "value1", "Field2": 42}`)
    53  
    54  	// Create a result struct
    55  	var result struct {
    56  		Field1 string `json:"Field1"`
    57  		Field2 int    `json:"Field2"`
    58  	}
    59  
    60  	// Test FromBytes function
    61  	err := FromBytes(jsonData, &result)
    62  	if err != nil {
    63  		t.Errorf("FromBytes returned an error: %v", err)
    64  	}
    65  
    66  	// Check if the result matches the expected output
    67  	expectedResult := struct {
    68  		Field1 string `json:"Field1"`
    69  		Field2 int    `json:"Field2"`
    70  	}{
    71  		Field1: "value1",
    72  		Field2: 42,
    73  	}
    74  
    75  	if !reflect.DeepEqual(result, expectedResult) {
    76  		t.Errorf("FromBytes result doesn't match the expected result.")
    77  	}
    78  }
    79  
    80  func TestToBytes(t *testing.T) {
    81  	// Define a sample struct
    82  	data := struct {
    83  		Field1 string `json:"Field1"`
    84  		Field2 int    `json:"Field2"`
    85  	}{
    86  		Field1: "value1",
    87  		Field2: 42,
    88  	}
    89  
    90  	// Test ToBytes function
    91  	jsonData, err := ToBytes(data)
    92  	if err != nil {
    93  		t.Errorf("ToBytes returned an error: %v", err)
    94  	}
    95  
    96  	// Check if the JSON data matches the expected JSON
    97  	expectedJSON := []byte(`{"Field1":"value1","Field2":42}`)
    98  
    99  	if !reflect.DeepEqual(jsonData, expectedJSON) {
   100  		t.Errorf("ToBytes result doesn't match the expected JSON data.")
   101  	}
   102  }
   103  
   104  func TestInterfacePointerArrayToInterfaceArray(t *testing.T) {
   105  	var a interface{} = 1
   106  	var b interface{} = "hello"
   107  	var c interface{} = 3.14
   108  
   109  	// Create a sample input slice of pointers to interfaces
   110  	input := []*interface{}{&a, &b, &c}
   111  
   112  	// Call the function to be tested
   113  	output := InterfacePointerArrayToInterfaceArray(input)
   114  
   115  	// Expected output (converted to []interface{})
   116  	expected := []interface{}{
   117  		1,
   118  		"hello",
   119  		3.14,
   120  	}
   121  
   122  	// Compare the actual and expected output
   123  	if !reflect.DeepEqual(output, expected) {
   124  		t.Errorf("Expected %v, but got %v", expected, output)
   125  	}
   126  }
   127  
   128  func TestStructPointerArrayToInterfaceArray(t *testing.T) {
   129  	// Create a sample input slice of pointers to interfaces
   130  	type AStruct struct {
   131  		val interface{}
   132  	}
   133  	var input []*AStruct
   134  	var a interface{} = 1
   135  	var b interface{} = "hello"
   136  	var c interface{} = 3.14
   137  	input = append(input, &AStruct{val: a})
   138  	input = append(input, &AStruct{val: b})
   139  	input = append(input, &AStruct{val: c})
   140  
   141  	// Call the function to be tested
   142  	output := StructPointerArrayToInterfaceArray(input)
   143  
   144  	// Expected output (converted to []interface{})
   145  	expected := []interface{}{
   146  		AStruct{val: a},
   147  		AStruct{val: b},
   148  		AStruct{val: c},
   149  	}
   150  
   151  	// Compare the actual and expected output
   152  	if !reflect.DeepEqual(output, expected) {
   153  		t.Errorf("Expected %v, but got %v", expected, output)
   154  	}
   155  }
   156  
   157  func TestStructPointerArrayToInterfacePointerArray(t *testing.T) {
   158  	// Create a sample input slice of pointers to interfaces
   159  	type AStruct struct {
   160  		val interface{}
   161  	}
   162  	var input []*AStruct
   163  	var a interface{} = 1
   164  	var b interface{} = "hello"
   165  	var c interface{} = 3.14
   166  	ap := &AStruct{val: a}
   167  	bp := &AStruct{val: b}
   168  	cp := &AStruct{val: c}
   169  	input = append(input, ap)
   170  	input = append(input, bp)
   171  	input = append(input, cp)
   172  
   173  	// Call the function to be tested
   174  	output := StructPointerArrayToInterfacePointerArray(input)
   175  
   176  	// Expected output (converted to []interface{})
   177  	expected := []interface{}{
   178  		ap,
   179  		bp,
   180  		cp,
   181  	}
   182  
   183  	// Compare the actual and expected output
   184  	if !reflect.DeepEqual(output, expected) {
   185  		t.Errorf("Expected %v, but got %v", expected, output)
   186  	}
   187  }
   188  
   189  func TestInterfaceArrayToPointerArray(t *testing.T) {
   190  	// Define a slice of structs
   191  	type Person struct {
   192  		Name string
   193  		Age  int
   194  	}
   195  
   196  	people := []Person{
   197  		{"Alice", 30},
   198  		{"Bob", 25},
   199  	}
   200  
   201  	// Convert []Person to []*Person using the function
   202  	pointerArray := InterfaceArrayToPointerArray(people)
   203  
   204  	// Assert that the result is of the correct type ([]*Person)
   205  	assert.NotNil(t, pointerArray)
   206  	assert.Equal(t, reflect.SliceOf(reflect.PtrTo(reflect.TypeOf(Person{}))), reflect.TypeOf(pointerArray))
   207  
   208  	// Access the converted data
   209  	peoplePointer := pointerArray.([]*Person)
   210  
   211  	// Check the contents of the converted data
   212  	assert.Len(t, peoplePointer, len(people))
   213  	assert.Equal(t, "Alice", peoplePointer[0].Name)
   214  	assert.Equal(t, 30, peoplePointer[0].Age)
   215  	assert.Equal(t, "Bob", peoplePointer[1].Name)
   216  	assert.Equal(t, 25, peoplePointer[1].Age)
   217  }
   218  
   219  func TestStructToPointer(t *testing.T) {
   220  	// Create an instance of the Person struct
   221  	type Person struct {
   222  		Name string
   223  		Age  int
   224  	}
   225  	person := Person{Name: "Alice", Age: 30}
   226  
   227  	// Convert the Person object to a pointer
   228  	ptrPerson := ToPointerObject(person)
   229  
   230  	// Assert that the result is a pointer to Person
   231  	if reflect.TypeOf(ptrPerson).Elem() != reflect.TypeOf(Person{}) {
   232  		t.Errorf("Expected a pointer to Person, but got %T", ptrPerson)
   233  	}
   234  
   235  	// Access the converted data
   236  	convertedPerson, ok := ptrPerson.(*Person)
   237  	if !ok {
   238  		t.Errorf("Failed to assert the type to *Person")
   239  	}
   240  
   241  	// Check the field values
   242  	if convertedPerson.Name != person.Name || convertedPerson.Age != person.Age {
   243  		t.Errorf("Field values do not match: %+v", convertedPerson)
   244  	}
   245  }
   246  
   247  func TestStructToPointerWithOtherStruct(t *testing.T) {
   248  	// Test with a different struct type
   249  	otherStruct := struct {
   250  		Name string
   251  		Age  int
   252  	}{Name: "Bob", Age: 25}
   253  
   254  	ptrStruct := ToPointerObject(otherStruct)
   255  
   256  	// Assert that the result is a pointer to the correct struct type
   257  	if reflect.TypeOf(ptrStruct).Elem() != reflect.TypeOf(otherStruct) {
   258  		t.Errorf("Expected a pointer to %T, but got %T", otherStruct, ptrStruct)
   259  	}
   260  
   261  	// Check the field values
   262  	if !reflect.DeepEqual(ptrStruct, &otherStruct) {
   263  		t.Errorf("Field values do not match: %+v", ptrStruct)
   264  	}
   265  }
   266  
   267  func TestStructToPointerWithNonStruct(t *testing.T) {
   268  	// Test with a non-struct type (int)
   269  	i := 42
   270  	ptr := ToPointerObject(i)
   271  
   272  	// Assert that the result is nil because it's not a struct
   273  	if reflect.TypeOf(ptr).Elem() != reflect.TypeOf(&i).Elem() {
   274  		t.Errorf("Expected a pointer object, but got %+v", ptr)
   275  	}
   276  }
   277  
   278  func TestObjectToStructPointerSlice(t *testing.T) {
   279  	type SampleStruct struct {
   280  		Name string
   281  		Age  int
   282  	}
   283  
   284  	// Create an instance of a struct.
   285  	obj := &SampleStruct{
   286  		Name: "Alice",
   287  		Age:  30,
   288  	}
   289  
   290  	// Call the function to create a slice of struct pointers.
   291  	pointerSlice := ObjectToStructPointerSlice(obj)
   292  
   293  	// Assert that the result is a slice.
   294  	if reflect.TypeOf(pointerSlice).Kind() != reflect.Slice {
   295  		t.Errorf("Expected result to be a slice, got %v", reflect.TypeOf(pointerSlice).Kind())
   296  	}
   297  
   298  	// Convert the interface back to a slice of struct pointers.
   299  	result := pointerSlice.([]*SampleStruct)
   300  
   301  	// Assert that the result slice has one element.
   302  	if len(result) != 1 {
   303  		t.Errorf("Expected result slice to have 1 element, got %d", len(result))
   304  	}
   305  
   306  	// Access the first element in the result slice.
   307  	firstElement := result[0]
   308  
   309  	// Assert that the values match.
   310  	expectedName := "Alice"
   311  	expectedAge := 30
   312  
   313  	if firstElement.Name != expectedName {
   314  		t.Errorf("Expected Name: %s, got Name: %s", expectedName, firstElement.Name)
   315  	}
   316  
   317  	if firstElement.Age != expectedAge {
   318  		t.Errorf("Expected Age: %d, got Age: %d", expectedAge, firstElement.Age)
   319  	}
   320  }
   321  
   322  func TestToString(t *testing.T) {
   323  	// Test cases for different data types.
   324  	sampleUUID := uuid.New()
   325  	type StringInEnum string
   326  	const thisIsString StringInEnum = "this is string value"
   327  	testCases := []struct {
   328  		input    interface{}
   329  		expected string
   330  		err      error
   331  	}{
   332  		// Valid cases
   333  		{"Hello, World!", "Hello, World!", nil},
   334  		{42, "42", nil},
   335  		{int64(12345), "12345", nil},
   336  		{3.14159, "3.141590", nil},
   337  		{sampleUUID, sampleUUID.String(), nil},
   338  		// Unsupported data type
   339  		{thisIsString, "this is string value", nil},
   340  	}
   341  
   342  	for _, tc := range testCases {
   343  		t.Run(fmt.Sprintf("%v", tc.input), func(t *testing.T) {
   344  			result, err := ToString(tc.input)
   345  
   346  			if err == nil && tc.err != nil {
   347  				t.Errorf("Expected error: %v, but got no error", tc.err)
   348  			} else if err != nil && tc.err == nil {
   349  				t.Errorf("Expected no error, but got error: %v", err)
   350  			} else if err != nil && tc.err != nil && err.Error() != tc.err.Error() {
   351  				t.Errorf("Expected error: %v, but got error: %v", tc.err, err)
   352  			}
   353  
   354  			if result != tc.expected {
   355  				t.Errorf("Expected result: %v, but got: %v", tc.expected, result)
   356  			}
   357  		})
   358  	}
   359  }
   360  
   361  // func TestConvertSliceOfPointersToArrayOfInterfaces(t *testing.T) {
   362  // 	type Person struct {
   363  // 		Name string
   364  // 		Age  int
   365  // 	}
   366  
   367  // 	// Create a slice of struct pointers.
   368  // 	pointerSlice := []*Person{
   369  // 		{Name: "Alice", Age: 30},
   370  // 		{Name: "Bob", Age: 25},
   371  // 	}
   372  
   373  // 	// Convert the slice of pointers to a slice of interfaces.
   374  // 	interfaceSlice := ConvertSliceOfPointersToArrayOfInterfaces(pointerSlice)
   375  
   376  // 	// Check if the result is a slice of interfaces.
   377  // 	if reflect.TypeOf(interfaceSlice).Kind() != reflect.Slice {
   378  // 		t.Errorf("Expected result to be a slice, but got %v", reflect.TypeOf(interfaceSlice))
   379  // 	}
   380  
   381  // 	// Check the length of the result.
   382  // 	if len(interfaceSlice.([]interface{})) != len(pointerSlice) {
   383  // 		t.Errorf("Expected result length to be %d, but got %d", len(pointerSlice), len(interfaceSlice.([]interface{})))
   384  // 	}
   385  
   386  // 	// Check the types of elements in the result.
   387  // 	for _, elem := range interfaceSlice.([]interface{}) {
   388  // 		if reflect.TypeOf(elem).Kind() != reflect.Ptr {
   389  // 			t.Errorf("Expected element type to be a pointer, but got %v", reflect.TypeOf(elem))
   390  // 		}
   391  // 		if reflect.TypeOf(elem).Elem() != reflect.TypeOf(&Person{}) {
   392  // 			t.Errorf("Expected element type to be *Person, but got %v", reflect.TypeOf(elem).Elem())
   393  // 		}
   394  // 	}
   395  
   396  // 	// Check the values of elements in the result.
   397  // 	for i, elem := range interfaceSlice.([]interface{}) {
   398  // 		personPointer := elem.(*Person) // Assert back to the struct pointer type
   399  // 		expectedPerson := pointerSlice[i]
   400  
   401  // 		if personPointer.Name != expectedPerson.Name || personPointer.Age != expectedPerson.Age {
   402  // 			t.Errorf("Expected element at index %d to have values %v, but got %v", i, expectedPerson, personPointer)
   403  // 		}
   404  // 	}
   405  // }