From aca3cc009062e53eb793ee8427e4b5ab53b3e00e Mon Sep 17 00:00:00 2001 From: yatesliang Date: Mon, 25 Sep 2023 00:24:02 -0700 Subject: [PATCH] test: unit test for testing KindUnexpected case in Mongo query function (#1883) --- pkg/storage/mongo/mongo_test.go | 48 +++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/pkg/storage/mongo/mongo_test.go b/pkg/storage/mongo/mongo_test.go index 7e2a31e75..7f52f2522 100644 --- a/pkg/storage/mongo/mongo_test.go +++ b/pkg/storage/mongo/mongo_test.go @@ -3,6 +3,9 @@ package mongo import ( "bytes" "context" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" "io" "os" "testing" @@ -97,6 +100,51 @@ func TestQueryKindNotFoundErrorCases(t *testing.T) { require.Equal(t, errors.KindNotFound, errors.Kind(err)) } } + +func TestQueryKindUnexpectedErrorCases(t *testing.T) { + // Prepare error documents + // If there is any error in preparation phase, skip this test + ctx := context.Background() + mongoStorage := getStorage(t) + uri := os.Getenv("ATHENS_MONGO_STORAGE_URL") + client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) + if err != nil { + t.SkipNow() + } + defer client.Disconnect(ctx) + coll := client.Database("athens").Collection("modules") + errDocs := []struct { + Module string `bson:"module"` + Version string `bson:"version"` + Mod interface{} `bson:"mod"` + Info interface{} `bson:"info"` + }{ + {"model1", "v1.1.1", 12345678, "error document with integer mod"}, + {"model2", "v2.0.0", true, "error document with boolean mod"}, + } + // In case some docs were inserted into the collection before, using upsert instead. + for _, errDoc := range errDocs { + filter := bson.D{{"module", errDoc.Module}, {"version", errDoc.Version}} + update := bson.D{{"$set", bson.D{{"mod", errDoc.Mod}, {"info", errDoc.Info}}}} + opts := options.Update().SetUpsert(true).SetBypassDocumentValidation(true) + _, err = coll.UpdateOne(ctx, filter, update, opts) + if err != nil { + t.SkipNow() + } + } + testCases := []struct { + modName string + version string + }{ + {"model1", "v1.1.1"}, // test case: decode integer to []byte + {"model2", "v2.0.0"}, // test case: decode boolean to []byte + } + for _, test := range testCases { + _, err := query(ctx, mongoStorage, test.modName, test.version) + require.Error(t, err) + require.Equal(t, errors.KindUnexpected, errors.Kind(err)) + } +} func TestNewStorageWithDefaultOverrides(t *testing.T) { url := os.Getenv("ATHENS_MONGO_STORAGE_URL")