File: copier_tags_test.go

package info (click to toggle)
golang-github-jinzhu-copier 0.3.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 156 kB
  • sloc: makefile: 2
file content (106 lines) | stat: -rw-r--r-- 1,997 bytes parent folder | download
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package copier_test

import (
	"testing"

	"github.com/jinzhu/copier"
)

type EmployeeTags struct {
	Name    string `copier:"must"`
	DOB     string
	Address string
	ID      int `copier:"-"`
}

type User1 struct {
	Name    string
	DOB     string
	Address string
	ID      int
}

type User2 struct {
	DOB     string
	Address string
	ID      int
}

func TestCopyTagIgnore(t *testing.T) {
	employee := EmployeeTags{ID: 100}
	user := User1{Name: "Dexter Ledesma", DOB: "1 November, 1970", Address: "21 Jump Street", ID: 12345}
	copier.Copy(&employee, user)
	if employee.ID == user.ID {
		t.Error("Was not expected to copy IDs")
	}
	if employee.ID != 100 {
		t.Error("Original ID was overwritten")
	}
}

func TestCopyTagMust(t *testing.T) {
	employee := &EmployeeTags{}
	user := &User2{DOB: "1 January 1970"}
	defer func() {
		if r := recover(); r == nil {
			t.Error("Expected a panic.")
		}
	}()
	copier.Copy(employee, user)
}

func TestCopyTagFieldName(t *testing.T) {
	t.Run("another name field copy", func(t *testing.T) {
		type SrcTags struct {
			FieldA string
			FieldB string `copier:"Field2"`
			FieldC string `copier:"FieldTagMatch"`
		}

		type DestTags struct {
			Field1 string `copier:"FieldA"`
			Field2 string
			Field3 string `copier:"FieldTagMatch"`
		}

		dst := &DestTags{}
		src := &SrcTags{
			FieldA: "FieldA->Field1",
			FieldB: "FieldB->Field2",
			FieldC: "FieldC->Field3",
		}
		err := copier.Copy(dst, src)
		if err != nil {
			t.Fatal(err)
		}

		if dst.Field1 != src.FieldA {
			t.Error("Field1 no copy")
		}
		if dst.Field2 != src.FieldB {
			t.Error("Field2 no copy")
		}
		if dst.Field3 != src.FieldC {
			t.Error("Field3 no copy")
		}
	})

	t.Run("validate error flag name", func(t *testing.T) {
		type SrcTags struct {
			field string
		}

		type DestTags struct {
			Field1 string `copier:"field"`
		}

		dst := &DestTags{}
		src := &SrcTags{
			field: "field->Field1",
		}
		err := copier.Copy(dst, src)
		if err == nil {
			t.Fatal("must validate error")
		}
	})
}