WaitGroupTest.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. declare(strict_types=1);
  3. namespace tests;
  4. use PHPUnit\Framework\TestCase;
  5. use Workerman\Coroutine;
  6. use Workerman\Timer;
  7. use Workerman\Coroutine\WaitGroup;
  8. /**
  9. * Class WaitGroupTest
  10. *
  11. * Tests for the Fiber WaitGroup implementation.
  12. */
  13. class WaitGroupTest extends TestCase
  14. {
  15. public function testWaitWaitGroupDone()
  16. {
  17. $waitGroup = new WaitGroup();
  18. $this->assertEquals(0, $waitGroup->count());
  19. $results = [0];
  20. $this->assertTrue($waitGroup->add());
  21. Coroutine::create(function () use ($waitGroup, &$results) {
  22. try {
  23. Timer::sleep(0.1);
  24. $results[] = 1;
  25. } finally {
  26. $this->assertTrue($waitGroup->done());
  27. }
  28. });
  29. $this->assertTrue($waitGroup->add());
  30. Coroutine::create(function () use ($waitGroup, &$results) {
  31. try {
  32. Timer::sleep(0.2);
  33. $results[] = 2;
  34. } finally {
  35. $this->assertTrue($waitGroup->done());
  36. }
  37. });
  38. $this->assertTrue($waitGroup->add());
  39. Coroutine::create(function () use ($waitGroup, &$results) {
  40. try {
  41. Timer::sleep(0.3);
  42. $results[] = 3;
  43. } finally {
  44. $this->assertTrue($waitGroup->done());
  45. }
  46. });
  47. $this->assertTrue($waitGroup->wait());
  48. $this->assertEquals(0, $waitGroup->count(), 'WaitGroup count should be 0 after wait is called.');
  49. $this->assertEquals([0, 1, 2, 3], $results, 'All coroutines should have been executed.');
  50. }
  51. }