...

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

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

     1  // Copyright (C) MongoDB, Inc. 2022-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 bson
     8  
     9  import (
    10  	"testing"
    11  
    12  	"go.mongodb.org/mongo-driver/bson/bsoncodec"
    13  	"go.mongodb.org/mongo-driver/internal/assert"
    14  )
    15  
    16  type inputArgs struct {
    17  	Name string
    18  	Val  *float64
    19  }
    20  
    21  type outputArgs struct {
    22  	Name string
    23  	Val  *int64
    24  }
    25  
    26  func TestTruncation(t *testing.T) {
    27  	t.Run("truncation", func(t *testing.T) {
    28  		inputName := "truncation"
    29  		inputVal := 4.7892
    30  
    31  		input := inputArgs{Name: inputName, Val: &inputVal}
    32  		ec := bsoncodec.EncodeContext{Registry: DefaultRegistry}
    33  
    34  		doc, err := MarshalWithContext(ec, &input)
    35  		assert.Nil(t, err)
    36  
    37  		var output outputArgs
    38  		dc := bsoncodec.DecodeContext{
    39  			Registry: DefaultRegistry,
    40  			Truncate: true,
    41  		}
    42  
    43  		err = UnmarshalWithContext(dc, doc, &output)
    44  		assert.Nil(t, err)
    45  
    46  		assert.Equal(t, inputName, output.Name)
    47  		assert.Equal(t, int64(inputVal), *output.Val)
    48  	})
    49  	t.Run("no truncation", func(t *testing.T) {
    50  		inputName := "no truncation"
    51  		inputVal := 7.382
    52  
    53  		input := inputArgs{Name: inputName, Val: &inputVal}
    54  		ec := bsoncodec.EncodeContext{Registry: DefaultRegistry}
    55  
    56  		doc, err := MarshalWithContext(ec, &input)
    57  		assert.Nil(t, err)
    58  
    59  		var output outputArgs
    60  		dc := bsoncodec.DecodeContext{
    61  			Registry: DefaultRegistry,
    62  			Truncate: false,
    63  		}
    64  
    65  		// case throws an error when truncation is disabled
    66  		err = UnmarshalWithContext(dc, doc, &output)
    67  		assert.NotNil(t, err)
    68  	})
    69  }
    70  

View as plain text