|
| 1 | +// Copyright (C) MongoDB, Inc. 2025-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 | +//go:build mongointernal |
| 8 | + |
| 9 | +package integration |
| 10 | + |
| 11 | +import ( |
| 12 | + "context" |
| 13 | + "testing" |
| 14 | + |
| 15 | + "go.mongodb.org/mongo-driver/v2/bson" |
| 16 | + "go.mongodb.org/mongo-driver/v2/internal/assert" |
| 17 | + "go.mongodb.org/mongo-driver/v2/internal/integration/mtest" |
| 18 | + "go.mongodb.org/mongo-driver/v2/internal/require" |
| 19 | + "go.mongodb.org/mongo-driver/v2/mongo" |
| 20 | + "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" |
| 21 | +) |
| 22 | + |
| 23 | +func TestNewSessionWithID(t *testing.T) { |
| 24 | + mt := mtest.New(t) |
| 25 | + |
| 26 | + mt.Run("can be used to pass a specific session ID to CRUD commands", func(mt *mtest.T) { |
| 27 | + mt.Parallel() |
| 28 | + |
| 29 | + // Create a session ID document, which is a BSON document with field |
| 30 | + // "id" containing a 16-byte UUID (binary subtype 4). |
| 31 | + sessionID := bson.Raw(bsoncore.NewDocumentBuilder(). |
| 32 | + AppendBinary("id", 4, []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}). |
| 33 | + Build()) |
| 34 | + |
| 35 | + sess := mongo.NewSessionWithID(mt.Client, sessionID) |
| 36 | + |
| 37 | + ctx := mongo.NewSessionContext(context.Background(), sess) |
| 38 | + _, err := mt.Coll.InsertOne(ctx, bson.D{{"foo", "bar"}}) |
| 39 | + require.NoError(mt, err) |
| 40 | + |
| 41 | + evt := mt.GetStartedEvent() |
| 42 | + val, err := evt.Command.LookupErr("lsid") |
| 43 | + require.NoError(mt, err, "lsid should be present in the command document") |
| 44 | + |
| 45 | + doc, ok := val.DocumentOK() |
| 46 | + require.True(mt, ok, "lsid should be a document") |
| 47 | + |
| 48 | + assert.Equal(mt, sessionID, doc) |
| 49 | + }) |
| 50 | + |
| 51 | + mt.Run("EndSession panics", func(mt *mtest.T) { |
| 52 | + mt.Parallel() |
| 53 | + |
| 54 | + sessionID := bson.Raw(bsoncore.NewDocumentBuilder(). |
| 55 | + AppendBinary("id", 4, []byte{}). |
| 56 | + Build()) |
| 57 | + sess := mongo.NewSessionWithID(mt.Client, sessionID) |
| 58 | + |
| 59 | + // Use a defer-recover block to catch the expected panic and assert that |
| 60 | + // the recovered error is not nil. |
| 61 | + defer func() { |
| 62 | + err := recover() |
| 63 | + assert.NotNil(mt, err, "expected panic error to not be nil") |
| 64 | + }() |
| 65 | + |
| 66 | + sess.EndSession(context.Background()) |
| 67 | + |
| 68 | + // We expect that calling EndSession on a Session returned by |
| 69 | + // NewSessionWithID panics. This code will only be reached if EndSession |
| 70 | + // doesn't panic. |
| 71 | + t.Errorf("expected EndSession to panic") |
| 72 | + }) |
| 73 | +} |
0 commit comments