Skip to content

Commit a4853ff

Browse files
chore(internal): add more streamHandler tests (#404)
1 parent 62a5c1d commit a4853ff

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

openai-java-core/src/test/kotlin/com/openai/core/handlers/StreamHandlerTest.kt

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,42 @@ import com.openai.core.http.HttpResponse
55
import com.openai.errors.OpenAIIoException
66
import java.io.IOException
77
import java.io.InputStream
8+
import kotlin.streams.asSequence
89
import kotlin.test.Test
910
import org.assertj.core.api.Assertions.assertThat
1011
import org.junit.jupiter.api.assertThrows
1112

1213
internal class StreamHandlerTest {
1314

15+
@Test
16+
fun streamHandler_splitsStreamOnNewlines() {
17+
val handler = streamHandler { _, lines -> yieldAll(lines) }
18+
val streamResponse = handler.handle(httpResponse("a\nbb\nccc\ndddd".byteInputStream()))
19+
20+
val lines = streamResponse.stream().asSequence().toList()
21+
22+
assertThat(lines).containsExactly("a", "bb", "ccc", "dddd")
23+
}
24+
25+
@Test
26+
fun streamHandler_whenClosedEarly_stopsYielding() {
27+
val handler = streamHandler { _, lines -> yieldAll(lines) }
28+
val streamResponse = handler.handle(httpResponse("a\nbb\nccc\ndddd".byteInputStream()))
29+
30+
val lines =
31+
streamResponse
32+
.stream()
33+
.asSequence()
34+
.onEach {
35+
if (it == "bb") {
36+
streamResponse.close()
37+
}
38+
}
39+
.toList()
40+
41+
assertThat(lines).containsExactly("a", "bb")
42+
}
43+
1444
@Test
1545
fun streamHandler_whenReaderThrowsIOException_wrapsException() {
1646
val handler = streamHandler<String> { _, lines -> lines.forEach {} }

0 commit comments

Comments
 (0)