@@ -10,6 +10,7 @@ import (
1010 "context"
1111 "testing"
1212
13+ "go.mongodb.org/mongo-driver/v2/bson"
1314 "go.mongodb.org/mongo-driver/v2/event"
1415 "go.mongodb.org/mongo-driver/v2/internal/assert"
1516 "go.mongodb.org/mongo-driver/v2/internal/integtest"
@@ -109,3 +110,71 @@ func TestGridFS(t *testing.T) {
109110 }
110111 })
111112}
113+
114+ func TestGridFSFile_UnmarshalBSON (t * testing.T ) {
115+ if testing .Short () {
116+ t .Skip ("skipping integration test in short mode" )
117+ }
118+
119+ cs := integtest .ConnString (t )
120+
121+ clientOpts := options .Client ().
122+ ApplyURI (cs .Original ).
123+ SetReadPreference (readpref .Primary ()).
124+ SetWriteConcern (writeconcern .Majority ()).
125+ // Connect to a single host. For sharded clusters, this will pin to a single mongos, which avoids
126+ // non-deterministic versioning errors in the server. This has no effect for replica sets because the driver
127+ // will discover the other hosts during SDAM checks.
128+ SetHosts (cs .Hosts [:1 ])
129+
130+ integtest .AddTestServerAPIVersion (clientOpts )
131+
132+ client , err := Connect (clientOpts )
133+ require .NoError (t , err )
134+
135+ defer func () {
136+ err := client .Disconnect (context .Background ())
137+ require .NoError (t , err )
138+ }()
139+
140+ // Get the database and create a GridFS bucket
141+ db := client .Database ("gridfs_test_db" )
142+
143+ // Drop the collection
144+ err = db .Collection ("myfiles.files" ).Drop (context .Background ())
145+ require .NoError (t , err )
146+
147+ err = db .Collection ("myfiles.chunks" ).Drop (context .Background ())
148+ require .NoError (t , err )
149+
150+ bucket := db .GridFSBucket (options .GridFSBucket ().SetName ("myfiles" ))
151+
152+ // Data to upload
153+ fileName := "example-file.txt"
154+ fileContent := []byte ("Hello GridFS! This is a test file." )
155+
156+ // Upload data into GridFS
157+ uploadStream , err := bucket .OpenUploadStream (context .Background (), fileName )
158+ require .NoError (t , err )
159+
160+ _ , err = uploadStream .Write (fileContent )
161+ require .NoError (t , err )
162+
163+ uploadStream .Close ()
164+
165+ // Verify the file metadata
166+ fileCursor , err := bucket .Find (context .Background (), bson.D {})
167+ require .NoError (t , err )
168+
169+ for fileCursor .Next (context .Background ()) {
170+ var file GridFSFile
171+ err := fileCursor .Decode (& file )
172+ require .NoError (t , err )
173+
174+ assert .NotNil (t , file .ID )
175+ assert .Equal (t , int64 (34 ), file .Length )
176+ assert .Equal (t , int32 (261120 ), file .ChunkSize )
177+ assert .NotNil (t , file .UploadDate )
178+ assert .Equal (t , fileName , file .Name )
179+ }
180+ }
0 commit comments