Skip to content

Commit 992fa34

Browse files
Robert Guorozza
authored andcommitted
Reader type enforcement
Enforces getBsonType() only gets called when state is TYPE in the BsonDocumentReader. This ensures the DocumentReader, BinaryReader and JsonReader behave the same way.
1 parent e6df2b0 commit 992fa34

2 files changed

Lines changed: 42 additions & 1 deletion

File tree

bson/src/main/org/bson/BsonDocumentReader.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,10 @@ public BsonType readBsonType() {
169169
return getCurrentBsonType();
170170
}
171171

172+
if (getState() != State.TYPE) {
173+
throwInvalidState("ReadBSONType", State.TYPE);
174+
}
175+
172176
switch (getContext().getContextType()) {
173177
case ARRAY:
174178
currentValue = getContext().getNextValue();

bson/src/test/org/bson/BsonDocumentReaderSpecification.groovy

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,20 @@ package org.bson
1919
import org.bson.codecs.BsonDocumentCodec
2020
import org.bson.codecs.DecoderContext
2121
import org.bson.types.ObjectId
22+
import spock.lang.Shared
2223
import spock.lang.Specification
2324

2425
class BsonDocumentReaderSpecification extends Specification {
26+
27+
@Shared BsonDocument nullDoc
28+
29+
def setup() {
30+
nullDoc = new BsonDocument([
31+
new BsonElement('null', new BsonNull())
32+
])
33+
}
34+
35+
2536
def 'should read all types'() {
2637
given:
2738
def doc = new BsonDocument(
@@ -50,13 +61,39 @@ class BsonDocumentReaderSpecification extends Specification {
5061
new BsonElement('document', new BsonDocument('a', new BsonInt32(1)))
5162
])
5263

53-
5464
when:
5565
def decodedDoc = new BsonDocumentCodec().decode(new BsonDocumentReader(doc), DecoderContext.builder().build())
5666

5767
then:
5868
decodedDoc == doc
5969
}
6070

71+
def 'should fail, ReadBSONType can only be called when State is TYPE, not VALUE'() {
72+
given:
73+
def reader = new BsonDocumentReader(nullDoc)
74+
75+
when:
76+
reader.readStartDocument()
77+
reader.readBsonType()
78+
reader.readName()
79+
reader.readBsonType()
80+
81+
then:
82+
thrown(BsonInvalidOperationException)
83+
}
84+
85+
def 'should fail, ReadBSONType can only be called when State is TYPE, not NAME'() {
86+
given:
87+
def reader = new BsonDocumentReader(nullDoc)
88+
89+
when:
90+
reader.readStartDocument()
91+
reader.readBsonType()
92+
reader.readBsonType()
93+
94+
then:
95+
thrown(BsonInvalidOperationException)
96+
}
97+
6198

6299
}

0 commit comments

Comments
 (0)