...

Source file src/go.mongodb.org/mongo-driver/mongo/bson_helpers_test.go

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

     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 mongo
     8  
     9  import (
    10  	"testing"
    11  
    12  	"go.mongodb.org/mongo-driver/bson"
    13  	"go.mongodb.org/mongo-driver/internal/assert"
    14  )
    15  
    16  // compare expected and actual BSON documents. comparison succeeds if actual contains each element in expected.
    17  func compareDocuments(t *testing.T, expected, actual bson.Raw) {
    18  	t.Helper()
    19  
    20  	eElems, err := expected.Elements()
    21  	assert.Nil(t, err, "error getting expected elements: %v", err)
    22  
    23  	for _, e := range eElems {
    24  		eKey := e.Key()
    25  		aVal, err := actual.LookupErr(eKey)
    26  		assert.Nil(t, err, "key %s not found in result", e.Key())
    27  		compareBsonValues(t, eKey, e.Value(), aVal)
    28  	}
    29  }
    30  
    31  func numberFromValue(t *testing.T, val bson.RawValue) int64 {
    32  	switch val.Type {
    33  	case bson.TypeInt32:
    34  		return int64(val.Int32())
    35  	case bson.TypeInt64:
    36  		return val.Int64()
    37  	case bson.TypeDouble:
    38  		return int64(val.Double())
    39  	default:
    40  		t.Fatalf("unexpected type for number: %v", val.Type)
    41  	}
    42  
    43  	return 0
    44  }
    45  
    46  func compareNumberValues(t *testing.T, key string, expected, actual bson.RawValue) {
    47  	eInt := numberFromValue(t, expected)
    48  	aInt := numberFromValue(t, actual)
    49  	assert.Equal(t, eInt, aInt, "value mismatch for key %s; expected %v, got %v", key, expected, actual)
    50  }
    51  
    52  // compare BSON values and fail if they are not equal. the key parameter is used for error strings.
    53  // if the expected value is a numeric type (int32, int64, or double) and the value is 42, the function only asserts that
    54  // the actual value is non-null.
    55  func compareBsonValues(t *testing.T, key string, expected, actual bson.RawValue) {
    56  	t.Helper()
    57  
    58  	switch expected.Type {
    59  	case bson.TypeInt32, bson.TypeInt64, bson.TypeDouble:
    60  		compareNumberValues(t, key, expected, actual)
    61  	case bson.TypeEmbeddedDocument:
    62  		compareDocuments(t, expected.Document(), actual.Document())
    63  	case bson.TypeArray:
    64  		compareDocuments(t, expected.Array(), actual.Array())
    65  	default:
    66  		assert.Equal(t, expected.Value, actual.Value,
    67  			"value mismatch for key %v; expected %v, got %v", key, expected.Value, actual.Value)
    68  	}
    69  }
    70  

View as plain text