|
| 1 | +package bson_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/globalsign/mgo/bson" |
| 5 | + . "gopkg.in/check.v1" |
| 6 | +) |
| 7 | + |
| 8 | +type mixedTagging struct { |
| 9 | + First string |
| 10 | + Second string `bson:"second_field"` |
| 11 | + Third string `json:"third_field"` |
| 12 | + Fourth string `bson:"fourth_field" json:"alternate"` |
| 13 | +} |
| 14 | + |
| 15 | +// TestTaggingFallback checks that tagging fallback can be used/works as expected. |
| 16 | +func (s *S) TestTaggingFallback(c *C) { |
| 17 | + initial := &mixedTagging{ |
| 18 | + First: "One", |
| 19 | + Second: "Two", |
| 20 | + Third: "Three", |
| 21 | + Fourth: "Four", |
| 22 | + } |
| 23 | + |
| 24 | + // Take only testing.T, leave only footprints. |
| 25 | + initialState := bson.JSONTagFallbackState() |
| 26 | + defer bson.SetJSONTagFallback(initialState) |
| 27 | + |
| 28 | + // Marshal with the new mode applied. |
| 29 | + bson.SetJSONTagFallback(true) |
| 30 | + bsonState, errBSON := bson.Marshal(initial) |
| 31 | + c.Assert(errBSON, IsNil) |
| 32 | + |
| 33 | + // Unmarshal into a generic map so that we can pick up the actual field names |
| 34 | + // selected. |
| 35 | + target := make(map[string]string) |
| 36 | + errUnmarshal := bson.Unmarshal(bsonState, target) |
| 37 | + c.Assert(errUnmarshal, IsNil) |
| 38 | + |
| 39 | + // No tag, so standard naming |
| 40 | + _, firstExists := target["first"] |
| 41 | + c.Assert(firstExists, Equals, true) |
| 42 | + |
| 43 | + // Just a BSON tag |
| 44 | + _, secondExists := target["second_field"] |
| 45 | + c.Assert(secondExists, Equals, true) |
| 46 | + |
| 47 | + // Just a JSON tag |
| 48 | + _, thirdExists := target["third_field"] |
| 49 | + c.Assert(thirdExists, Equals, true) |
| 50 | + |
| 51 | + // Should marshal 4th as fourth_field (since we have both tags) |
| 52 | + _, fourthExists := target["fourth_field"] |
| 53 | + c.Assert(fourthExists, Equals, true) |
| 54 | +} |
0 commit comments