...

Source file src/go.mongodb.org/mongo-driver/bson/bsoncodec/string_codec_test.go

Documentation: go.mongodb.org/mongo-driver/bson/bsoncodec

     1  // Copyright (C) MongoDB, Inc. 2017-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 bsoncodec
     8  
     9  import (
    10  	"reflect"
    11  	"testing"
    12  
    13  	"go.mongodb.org/mongo-driver/bson/bsonoptions"
    14  	"go.mongodb.org/mongo-driver/bson/bsonrw/bsonrwtest"
    15  	"go.mongodb.org/mongo-driver/bson/bsontype"
    16  	"go.mongodb.org/mongo-driver/bson/primitive"
    17  	"go.mongodb.org/mongo-driver/internal/assert"
    18  )
    19  
    20  func TestStringCodec(t *testing.T) {
    21  	t.Run("ObjectIDAsHex", func(t *testing.T) {
    22  		oid := primitive.NewObjectID()
    23  		byteArray := [12]byte(oid)
    24  		reader := &bsonrwtest.ValueReaderWriter{BSONType: bsontype.ObjectID, Return: oid}
    25  		testCases := []struct {
    26  			name   string
    27  			opts   *bsonoptions.StringCodecOptions
    28  			hex    bool
    29  			result string
    30  		}{
    31  			{"default", bsonoptions.StringCodec(), true, oid.Hex()},
    32  			{"true", bsonoptions.StringCodec().SetDecodeObjectIDAsHex(true), true, oid.Hex()},
    33  			{"false", bsonoptions.StringCodec().SetDecodeObjectIDAsHex(false), false, string(byteArray[:])},
    34  		}
    35  		for _, tc := range testCases {
    36  			t.Run(tc.name, func(t *testing.T) {
    37  				stringCodec := NewStringCodec(tc.opts)
    38  
    39  				actual := reflect.New(reflect.TypeOf("")).Elem()
    40  				err := stringCodec.DecodeValue(DecodeContext{}, reader, actual)
    41  				assert.Nil(t, err, "StringCodec.DecodeValue error: %v", err)
    42  
    43  				actualString := actual.Interface().(string)
    44  				assert.Equal(t, tc.result, actualString, "Expected string %v, got %v", tc.result, actualString)
    45  			})
    46  		}
    47  	})
    48  }
    49  

View as plain text