...

Source file src/go.mongodb.org/mongo-driver/internal/codecutil/encoding_test.go

Documentation: go.mongodb.org/mongo-driver/internal/codecutil

     1  // Copyright (C) MongoDB, Inc. 2023-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  package codecutil
     8  
     9  import (
    10  	"io"
    11  	"testing"
    12  
    13  	"go.mongodb.org/mongo-driver/bson"
    14  	"go.mongodb.org/mongo-driver/bson/bsoncodec"
    15  	"go.mongodb.org/mongo-driver/bson/bsonrw"
    16  	"go.mongodb.org/mongo-driver/internal/assert"
    17  	"go.mongodb.org/mongo-driver/internal/require"
    18  )
    19  
    20  func testEncFn(t *testing.T) EncoderFn {
    21  	t.Helper()
    22  
    23  	return func(w io.Writer) (*bson.Encoder, error) {
    24  		rw, err := bsonrw.NewBSONValueWriter(w)
    25  		require.NoError(t, err, "failed to construct BSONValue writer")
    26  
    27  		enc, err := bson.NewEncoder(rw)
    28  		require.NoError(t, err, "failed to construct encoder")
    29  
    30  		return enc, nil
    31  	}
    32  }
    33  
    34  func TestMarshalValue(t *testing.T) {
    35  	t.Parallel()
    36  
    37  	tests := []struct {
    38  		name     string
    39  		val      interface{}
    40  		registry *bsoncodec.Registry
    41  		encFn    EncoderFn
    42  		want     string
    43  		wantErr  error
    44  	}{
    45  		{
    46  			name:    "empty",
    47  			val:     nil,
    48  			want:    "",
    49  			wantErr: ErrNilValue,
    50  			encFn:   testEncFn(t),
    51  		},
    52  		{
    53  			name:  "bson.D",
    54  			val:   bson.D{{"foo", "bar"}},
    55  			want:  `{"foo": "bar"}`,
    56  			encFn: testEncFn(t),
    57  		},
    58  		{
    59  			name:  "map",
    60  			val:   map[string]interface{}{"foo": "bar"},
    61  			want:  `{"foo": "bar"}`,
    62  			encFn: testEncFn(t),
    63  		},
    64  		{
    65  			name:  "struct",
    66  			val:   struct{ Foo string }{Foo: "bar"},
    67  			want:  `{"foo": "bar"}`,
    68  			encFn: testEncFn(t),
    69  		},
    70  		{
    71  			name:  "non-document type",
    72  			val:   "foo: bar",
    73  			want:  `"foo: bar"`,
    74  			encFn: testEncFn(t),
    75  		},
    76  	}
    77  
    78  	for _, test := range tests {
    79  		test := test
    80  
    81  		t.Run(test.name, func(t *testing.T) {
    82  			t.Parallel()
    83  
    84  			value, err := MarshalValue(test.val, test.encFn)
    85  
    86  			assert.Equal(t, test.wantErr, err, "expected and actual error do not match")
    87  			assert.Equal(t, test.want, value.String(), "expected and actual comments are different")
    88  		})
    89  	}
    90  }
    91  

View as plain text