Repository: fxamacker/cbor
Pull request #480 (2024-01-30 04:37:55)

Fix EncOption/DecOption unset fields on mode regurgitation.
<!--
Thank you for your interest in contributing to fxamacker/cbor!
-->

### Description

I noticed that DefaultMapType didn't survive the trip from DecOptions to DecMode and back. There are existing roundtrip tests for both DecOptions/DecMode and EncOptions/EncMode, but they also depend on being updated when new options are added. I've updated the existing tests so that they fail unless all fields have been set to a non-zero value, and set the fields that were missing in the implementation of EncOptions() and DecOptions(). Hopefully the updated tests will make it easy to avoid the same mistake in the future.

<!-- For code contributions, please complete all the items below this line. -->
<!-- For documentation-only contributions, please delete everything below this line. -->

#### PR Was Proposed and Welcomed in Currently Open Issue

- [ ] This PR was proposed and welcomed by maintainer(s) in issue #___
- [ ] Closes or Updates Issue #___

#### Checklist (for code PR only, ignore for docs PR)

- [x] Include unit tests that cover the new code
- [x] Pass all unit tests 
- [x] Pass all 18 ci linters (golint, gosec, staticcheck, etc.)
- [x] Sign each commit with your real name and email.  
      Last line of each commit message should be in this format:  
      Signed-off-by: Firstname Lastname <firstname.lastname@example.com>
- [x] Certify the Developer's Certificate of Origin 1.1
      (see next section).

#### Certify the Developer's Certificate of Origin 1.1

- [x] By marking this item as completed, I certify 
      the Developer Certificate of Origin 1.1.

```
Developer Certificate of Origin
Version 1.1

Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA

Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
```




Patch:
diff --git a/decode.go b/decode.go
index 015ac9d..5986d06 100644
--- a/decode.go
+++ b/decode.go
@@ -741,6 +741,7 @@ func (dm *decMode) DecOptions() DecOptions {
 		IntDec:                dm.intDec,
 		MapKeyByteString:      dm.mapKeyByteString,
 		ExtraReturnErrors:     dm.extraReturnErrors,
+		DefaultMapType:        dm.defaultMapType,
 		UTF8:                  dm.utf8,
 		FieldNameMatching:     dm.fieldNameMatching,
 		BigIntDec:             dm.bigIntDec,
diff --git a/encode.go b/encode.go
index 087f95f..86cc47a 100644
--- a/encode.go
+++ b/encode.go
@@ -643,6 +643,7 @@ func (em *encMode) EncOptions() EncOptions {
 		Time:          em.time,
 		TimeTag:       em.timeTag,
 		IndefLength:   em.indefLength,
+		NilContainers: em.nilContainers,
 		TagsMd:        em.tagsMd,
 		OmitEmpty:     em.omitEmpty,
 		String:        em.stringType,


Test patch:
diff --git a/decode_test.go b/decode_test.go
index 99265b6..92cb675 100644
--- a/decode_test.go
+++ b/decode_test.go
@@ -4861,16 +4861,30 @@ func TestUnmarshalToNotNilInterface(t *testing.T) {
 
 func TestDecOptions(t *testing.T) {
 	opts1 := DecOptions{
-		DupMapKey:         DupMapKeyEnforcedAPF,
-		TimeTag:           DecTagRequired,
-		MaxNestedLevels:   100,
-		MaxArrayElements:  102,
-		MaxMapPairs:       101,
-		IndefLength:       IndefLengthForbidden,
-		TagsMd:            TagsForbidden,
-		IntDec:            IntDecConvertSigned,
-		ExtraReturnErrors: ExtraDecErrorUnknownField,
-		UTF8:              UTF8DecodeInvalid,
+		DupMapKey:             DupMapKeyEnforcedAPF,
+		TimeTag:               DecTagRequired,
+		MaxNestedLevels:       100,
+		MaxArrayElements:      102,
+		MaxMapPairs:           101,
+		IndefLength:           IndefLengthForbidden,
+		TagsMd:                TagsForbidden,
+		IntDec:                IntDecConvertSigned,
+		MapKeyByteString:      MapKeyByteStringForbidden,
+		ExtraReturnErrors:     ExtraDecErrorUnknownField,
+		DefaultMapType:        reflect.TypeOf(map[string]interface{}(nil)),
+		UTF8:                  UTF8DecodeInvalid,
+		FieldNameMatching:     FieldNameMatchingCaseSensitive,
+		BigIntDec:             BigIntDecodePointer,
+		DefaultByteStringType: reflect.TypeOf(""),
+		ByteStringToString:    ByteStringToStringAllowed,
+		FieldNameByteString:   FieldNameByteStringAllowed,
+	}
+	ov := reflect.ValueOf(opts1)
+	for i := 0; i < ov.NumField(); i++ {
+		fv := ov.Field(i)
+		if fv.IsZero() {
+			t.Errorf("options field %q is unset or set to the zero value for its type", ov.Type().Field(i).Name)
+		}
 	}
 	dm, err := opts1.DecMode()
 	if err != nil {
@@ -4878,7 +4892,7 @@ func TestDecOptions(t *testing.T) {
 	} else {
 		opts2 := dm.DecOptions()
 		if !reflect.DeepEqual(opts1, opts2) {
-			t.Errorf("DecOptions->DecMode->DecOptions returned different values: %v, %v", opts1, opts2)
+			t.Errorf("DecOptions->DecMode->DecOptions returned different values: %#v, %#v", opts1, opts2)
 		}
 	}
 }
diff --git a/encode_test.go b/encode_test.go
index 516a248..bb4bdad 100644
--- a/encode_test.go
+++ b/encode_test.go
@@ -3623,6 +3623,23 @@ func TestEncModeInvalidBigIntConvertMode(t *testing.T) {
 	}
 }
 
+func TestEncOptionsTagsForbidden(t *testing.T) {
+	// It's not valid to set both TagsMd and TimeTag to a non-zero value in the same EncOptions,
+	// so this exercises the options-mode-options roundtrip for non-zero TagsMd.
+	opts1 := EncOptions{
+		TagsMd: TagsForbidden,
+	}
+	em, err := opts1.EncMode()
+	if err != nil {
+		t.Errorf("EncMode() returned an error %v", err)
+	} else {
+		opts2 := em.EncOptions()
+		if !reflect.DeepEqual(opts1, opts2) {
+			t.Errorf("EncOptions->EncMode->EncOptions returned different values: %#v, %#v", opts1, opts2)
+		}
+	}
+}
+
 func TestEncOptions(t *testing.T) {
 	opts1 := EncOptions{
 		Sort:          SortBytewiseLexical,
@@ -3633,8 +3650,25 @@ func TestEncOptions(t *testing.T) {
 		Time:          TimeRFC3339Nano,
 		TimeTag:       EncTagRequired,
 		IndefLength:   IndefLengthForbidden,
-		NilContainers: NilContainerAsNull,
+		NilContainers: NilContainerAsEmpty,
 		TagsMd:        TagsAllowed,
+		OmitEmpty:     OmitEmptyGoValue,
+		String:        StringToByteString,
+		FieldName:     FieldNameToByteString,
+	}
+	ov := reflect.ValueOf(opts1)
+	for i := 0; i < ov.NumField(); i++ {
+		fv := ov.Field(i)
+		if fv.IsZero() {
+			fn := ov.Type().Field(i).Name
+			if fn == "TagsMd" {
+				// Roundtripping non-zero values for TagsMd is tested separately
+				// since the non-zero value (TagsForbidden) is incompatible with the
+				// non-zero value for other options (e.g. TimeTag).
+				continue
+			}
+			t.Errorf("options field %q is unset or set to the zero value for its type", fn)
+		}
 	}
 	em, err := opts1.EncMode()
 	if err != nil {
@@ -3642,7 +3676,7 @@ func TestEncOptions(t *testing.T) {
 	} else {
 		opts2 := em.EncOptions()
 		if !reflect.DeepEqual(opts1, opts2) {
-			t.Errorf("EncOptions->EncMode->EncOptions returned different values: %v, %v", opts1, opts2)
+			t.Errorf("EncOptions->EncMode->EncOptions returned different values: %#v, %#v", opts1, opts2)
 		}
 	}
 }