File: reflect_test.go

package info (click to toggle)
golang-github-maxatome-go-testdeep 1.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,416 kB
  • sloc: perl: 1,012; yacc: 130; makefile: 2
file content (80 lines) | stat: -rw-r--r-- 1,864 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) 2020-2022, Maxime Soulé
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.

package types_test

import (
	"reflect"
	"testing"

	"github.com/maxatome/go-testdeep/internal/test"
	"github.com/maxatome/go-testdeep/internal/types"
)

func TestIsStruct(t *testing.T) {
	s := struct{}{}
	ps := &s
	pps := &ps
	m := map[string]struct{}{}

	for i, test := range []struct {
		val any
		ok  bool
	}{
		{val: s, ok: true},
		{val: ps, ok: true},
		{val: pps, ok: true},
		{val: &pps, ok: true},
		{val: m, ok: false},
		{val: &m, ok: false},
	} {
		if types.IsStruct(reflect.TypeOf(test.val)) != test.ok {
			t.Errorf("#%d IsStruct() mismatch as ≠ %t", i, test.ok)
		}
	}
}

func TestIsTypeOrConvertible(t *testing.T) {
	type MyInt int

	ok, convertible := types.IsTypeOrConvertible(reflect.ValueOf(123), reflect.TypeOf(123))
	test.IsTrue(t, ok)
	test.IsFalse(t, convertible)

	ok, convertible = types.IsTypeOrConvertible(reflect.ValueOf(123), reflect.TypeOf(123.45))
	test.IsTrue(t, ok)
	test.IsTrue(t, convertible)

	ok, convertible = types.IsTypeOrConvertible(reflect.ValueOf(123), reflect.TypeOf(MyInt(123)))
	test.IsTrue(t, ok)
	test.IsTrue(t, convertible)

	ok, convertible = types.IsTypeOrConvertible(reflect.ValueOf("xx"), reflect.TypeOf(123))
	test.IsFalse(t, ok)
	test.IsFalse(t, convertible)
}

func TestKindType(t *testing.T) {
	for _, tc := range []struct {
		val      any
		expected string
	}{
		{nil, "nil"},
		{42, "int"},
		{(*int)(nil), "*int"},
		{(*[]int)(nil), "*slice (*[]int type)"},
		{(***int)(nil), "***int"},
	} {
		vval := reflect.ValueOf(tc.val)
		name := "nil"
		if tc.val != nil {
			name = vval.Type().String()
		}
		t.Run(name, func(t *testing.T) {
			test.EqualStr(t, types.KindType(vval), tc.expected)
		})
	}
}