@@ -241,17 +241,45 @@ public function testConnectionException()
241241 public function testMaxAwaitTimeMS ()
242242 {
243243 $ this ->collection = new Collection ($ this ->manager , $ this ->getDatabaseName (), $ this ->getCollectionName ());
244- $ maxAwaitTimeMS = 10 ;
244+ /* On average, an acknowledged write takes about 20 ms to appear in a
245+ * change stream on the server so we'll use a higher maxAwaitTimeMS to
246+ * ensure we see the write. */
247+ $ maxAwaitTimeMS = 100 ;
245248 $ changeStreamResult = $ this ->collection ->watch ([], ['maxAwaitTimeMS ' => $ maxAwaitTimeMS ]);
246249
247- /* Make sure we await results for at least maxAwaitTimeMS, since no new
248- * documents should be inserted to wake up the server's command thread.
249- * Also ensure that we don't wait too long (server default is one
250- * second). */
250+ /* The initial change stream is empty so we should expect a delay when
251+ * we call rewind, since it issues a getMore. Expect to wait at least
252+ * maxAwaitTimeMS, since no new documents should be inserted to wake up
253+ * the server's query thread. Also ensure we don't wait too long (server
254+ * default is one second). */
251255 $ startTime = microtime (true );
252256 $ changeStreamResult ->rewind ();
253- $ this ->assertGreaterThanOrEqual ($ maxAwaitTimeMS * 0.001 , microtime (true ) - $ startTime );
254- $ this ->assertLessThan (0.5 , microtime (true ) - $ startTime );
255- }
257+ $ duration = microtime (true ) - $ startTime ;
258+ $ this ->assertGreaterThanOrEqual ($ maxAwaitTimeMS * 0.001 , $ duration );
259+ $ this ->assertLessThan (0.5 , $ duration );
260+
261+ $ this ->assertFalse ($ changeStreamResult ->valid ());
262+
263+ /* Advancing again on a change stream will issue a getMore, so we should
264+ * expect a delay again. */
265+ $ startTime = microtime (true );
266+ $ changeStreamResult ->next ();
267+ $ duration = microtime (true ) - $ startTime ;
268+ $ this ->assertGreaterThanOrEqual ($ maxAwaitTimeMS * 0.001 , $ duration );
269+ $ this ->assertLessThan (0.5 , $ duration );
270+
271+ $ this ->assertFalse ($ changeStreamResult ->valid ());
256272
273+ /* After inserting a document, the change stream will not issue a
274+ * getMore so we should not expect a delay. */
275+ $ result = $ this ->collection ->insertOne (['_id ' => 1 ]);
276+ $ this ->assertInstanceOf ('MongoDB\InsertOneResult ' , $ result );
277+ $ this ->assertSame (1 , $ result ->getInsertedCount ());
278+
279+ $ startTime = microtime (true );
280+ $ changeStreamResult ->next ();
281+ $ duration = microtime (true ) - $ startTime ;
282+ $ this ->assertLessThan ($ maxAwaitTimeMS * 0.001 , $ duration );
283+ $ this ->assertTrue ($ changeStreamResult ->valid ());
284+ }
257285}
0 commit comments