Skip to content

Commit

Permalink
Add test to demonstrate tagging fallback.
Browse files Browse the repository at this point in the history
Typo fix.

Fix issues in test.

Update test code.
  • Loading branch information
steve-gray committed Jan 30, 2018
1 parent 31878d4 commit e7fec90
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions bson/compatability_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package bson_test

import (
"github.com/globalsign/mgo/bson"
. "gopkg.in/check.v1"
)

type mixedTagging struct {
First string
Second string `bson:"second_field"`
Third string `json:"third_field"`
Fourth string `bson:"fourth_field" json:"alternate"`
}

// TestTaggingFallback checks that tagging fallback can be used/works as expected.
func (s *S) TestTaggingFallback(c *C) {
initial := &mixedTagging{
First: "One",
Second: "Two",
Third: "Three",
Fourth: "Four",
}

// Take only testing.T, leave only footprints.
initialState := bson.JSONTagFallbackState()
defer bson.SetJSONTagFallback(initialState)

// Marshal with the new mode applied.
bson.SetJSONTagFallback(true)
bson, errBSON := bson.Marshal(initial)
c.Assert(errBSON, IsNil)

// Unmarshal into a generic map so that we can pick up the actual field names
// selected.
target := make(map[string]string)
errUnmarshal := bson.Unmarshal(bson, target)
c.Assert(errUnmarshal, IsNil)

// No tag, so standard naming
_, firstExists := target["first"]
c.Assert(firstExists, Exists, true)

// Just a BSON tag
_, secondExists := target["second_field"]
c.Assert(secondExists, Exists, true)

// Just a JSON tag
_, thirdExists := target["third_field"]
c.Assert(thirdExists, Exists, true)

// Should marshal 4th as fourth_field (since we have both tags)
_, fourthExists := target["fourth_field"]
c.Assert(fourthExists, Exists, true)
}

0 comments on commit e7fec90

Please sign in to comment.