FnStreamTest.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace GuzzleHttp\Tests\Stream;
  3. use BadMethodCallException;
  4. use GuzzleHttp\Stream\Stream;
  5. use GuzzleHttp\Stream\FnStream;
  6. use PHPUnit\Framework\TestCase;
  7. /**
  8. * @covers GuzzleHttp\Stream\FnStream
  9. */
  10. class FnStreamTest extends TestCase
  11. {
  12. public function testThrowsWhenNotImplemented()
  13. {
  14. $this->expectException(BadMethodCallException::class);
  15. $this->expectExceptionMessage('seek() is not implemented in the FnStream');
  16. (new FnStream([]))->seek(1);
  17. }
  18. public function testProxiesToFunction()
  19. {
  20. $s = new FnStream([
  21. 'read' => function ($len) {
  22. $this->assertEquals(3, $len);
  23. return 'foo';
  24. },
  25. ]);
  26. $this->assertEquals('foo', $s->read(3));
  27. }
  28. public function testCanCloseOnDestruct()
  29. {
  30. $called = false;
  31. $s = new FnStream([
  32. 'close' => function () use (&$called) {
  33. $called = true;
  34. },
  35. ]);
  36. unset($s);
  37. $this->assertTrue($called);
  38. }
  39. /**
  40. * @doesNotPerformAssertions
  41. */
  42. public function testDoesNotRequireClose()
  43. {
  44. $s = new FnStream([]);
  45. unset($s);
  46. }
  47. public function testDecoratesStream()
  48. {
  49. $a = Stream::factory('foo');
  50. $b = FnStream::decorate($a, []);
  51. $this->assertEquals(3, $b->getSize());
  52. $this->assertEquals($b->isWritable(), true);
  53. $this->assertEquals($b->isReadable(), true);
  54. $this->assertEquals($b->isSeekable(), true);
  55. $this->assertEquals($b->read(3), 'foo');
  56. $this->assertEquals($b->tell(), 3);
  57. $this->assertEquals($a->tell(), 3);
  58. $this->assertEmpty($b->read(1));
  59. $this->assertEquals($b->eof(), true);
  60. $this->assertEquals($a->eof(), true);
  61. $b->seek(0);
  62. $this->assertEquals('foo', (string) $b);
  63. $b->seek(0);
  64. $this->assertEquals('foo', $b->getContents());
  65. $this->assertEquals($a->getMetadata(), $b->getMetadata());
  66. $b->seek(0, SEEK_END);
  67. $b->write('bar');
  68. $this->assertEquals('foobar', (string) $b);
  69. $this->assertIsResource($b->detach());
  70. $b->close();
  71. }
  72. public function testDecoratesWithCustomizations()
  73. {
  74. $called = false;
  75. $a = Stream::factory('foo');
  76. $b = FnStream::decorate($a, [
  77. 'read' => function ($len) use (&$called, $a) {
  78. $called = true;
  79. return $a->read($len);
  80. }
  81. ]);
  82. $this->assertEquals('foo', $b->read(3));
  83. $this->assertTrue($called);
  84. }
  85. }