@@ -15,6 +15,7 @@ import (
15
15
"time"
16
16
17
17
"go.mongodb.org/mongo-driver/bson"
18
+ "go.mongodb.org/mongo-driver/bson/primitive"
18
19
"go.mongodb.org/mongo-driver/event"
19
20
"go.mongodb.org/mongo-driver/internal/testutil/assert"
20
21
"go.mongodb.org/mongo-driver/internal/testutil/israce"
@@ -248,6 +249,48 @@ func TestGridFS(x *testing.T) {
248
249
})
249
250
}
250
251
})
252
+ mt .Run ("chunk size determined by files collection document" , func (mt * mtest.T ) {
253
+ // Test that the chunk size for a file download is determined by the chunkSize field in the files
254
+ // collection document, not the bucket's chunk size.
255
+
256
+ bucket , err := gridfs .NewBucket (mt .DB )
257
+ assert .Nil (mt , err , "NewBucket error: %v" , err )
258
+ defer func () { _ = bucket .Drop () }()
259
+
260
+ fileData := []byte ("hello world" )
261
+ uploadOpts := options .GridFSUpload ().SetChunkSizeBytes (4 )
262
+ fileID , err := bucket .UploadFromStream ("file" , bytes .NewReader (fileData ), uploadOpts )
263
+ assert .Nil (mt , err , "UploadFromStream error: %v" , err )
264
+
265
+ // If the bucket's chunk size was used, this would error because the actual chunk size is 4 and the bucket
266
+ // chunk size is 255 KB.
267
+ var downloadBuffer bytes.Buffer
268
+ _ , err = bucket .DownloadToStream (fileID , & downloadBuffer )
269
+ assert .Nil (mt , err , "DownloadToStream error: %v" , err )
270
+
271
+ downloadedBytes := downloadBuffer .Bytes ()
272
+ assert .Equal (mt , fileData , downloadedBytes , "expected bytes %s, got %s" , fileData , downloadedBytes )
273
+ })
274
+ mt .Run ("error if files collection document does not have a chunkSize field" , func (mt * mtest.T ) {
275
+ // Test that opening a download returns ErrMissingChunkSize if the files collection document has no
276
+ // chunk size field.
277
+
278
+ oid := primitive .NewObjectID ()
279
+ filesDoc := bson.D {
280
+ {"_id" , oid },
281
+ {"length" , 10 },
282
+ {"filename" , "filename" },
283
+ }
284
+ _ , err := mt .DB .Collection ("fs.files" ).InsertOne (mtest .Background , filesDoc )
285
+ assert .Nil (mt , err , "InsertOne error for files collection: %v" , err )
286
+
287
+ bucket , err := gridfs .NewBucket (mt .DB )
288
+ assert .Nil (mt , err , "NewBucket error: %v" , err )
289
+ defer func () { _ = bucket .Drop () }()
290
+
291
+ _ , err = bucket .OpenDownloadStream (oid )
292
+ assert .Equal (mt , gridfs .ErrMissingChunkSize , err , "expected error %v, got %v" , gridfs .ErrMissingChunkSize , err )
293
+ })
251
294
})
252
295
253
296
mt .RunOpts ("bucket collection accessors" , noClientOpts , func (mt * mtest.T ) {
0 commit comments