github.com/honeycombio/honeytail@v1.9.0/parsers/mongodb/queryshape/shape_test.go (about)

     1  package queryshape_test
     2  
     3  import (
     4  	"fmt"
     5  	"path/filepath"
     6  	"reflect"
     7  	"runtime"
     8  	"strings"
     9  	"testing"
    10  
    11  	"github.com/honeycombio/honeytail/parsers/mongodb/logparser"
    12  	"github.com/honeycombio/honeytail/parsers/mongodb/queryshape"
    13  )
    14  
    15  func testQueryStringShape(t *testing.T, queryString, queryShape string) {
    16  	q, err := logparser.ParseQuery(queryString)
    17  	testOK(t, err)
    18  	testEquals(t, queryshape.GetQueryShape(q), queryShape)
    19  }
    20  
    21  func TestSortedKeys(t *testing.T) {
    22  	testQueryStringShape(t, "{ b: 1, c: 2, a: 3 }", `{ "a": 1, "b": 1, "c": 1 }`)
    23  }
    24  
    25  func TestFlattenedSlice(t *testing.T) {
    26  	testQueryStringShape(t, "{ $in: [1, 2, 3] }", `{ "$in": 1 }`)
    27  }
    28  
    29  // helper function
    30  func testEquals(t testing.TB, actual, expected interface{}, msg ...string) {
    31  	if !reflect.DeepEqual(actual, expected) {
    32  		message := strings.Join(msg, ", ")
    33  		_, file, line, _ := runtime.Caller(2)
    34  
    35  		t.Errorf(
    36  			"%s:%d: %s -- actual(%T): %v, expected(%T): %v",
    37  			filepath.Base(file),
    38  			line,
    39  			message,
    40  			testDeref(actual),
    41  			testDeref(actual),
    42  			testDeref(expected),
    43  			testDeref(expected),
    44  		)
    45  	}
    46  }
    47  
    48  func testDeref(v interface{}) interface{} {
    49  	switch t := v.(type) {
    50  	case *string:
    51  		return fmt.Sprintf("*(%v)", *t)
    52  	case *int64:
    53  		return fmt.Sprintf("*(%v)", *t)
    54  	case *float64:
    55  		return fmt.Sprintf("*(%v)", *t)
    56  	case *bool:
    57  		return fmt.Sprintf("*(%v)", *t)
    58  	default:
    59  		return v
    60  	}
    61  }
    62  
    63  func testOK(t testing.TB, err error, msg ...string) {
    64  	if err != nil {
    65  		message := strings.Join(msg, ", ")
    66  		_, file, line, _ := runtime.Caller(2)
    67  
    68  		t.Errorf("%s:%d: %s -- unexpected error: %s",
    69  			filepath.Base(file),
    70  			line,
    71  			message,
    72  			err.Error(),
    73  		)
    74  	}
    75  }