FnStreamTest.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace GuzzleHttp\Tests\Stream;
  3. use GuzzleHttp\Stream\Stream;
  4. use GuzzleHttp\Stream\FnStream;
  5. /**
  6. * @covers GuzzleHttp\Stream\FnStream
  7. */
  8. class FnStreamTest extends \PHPUnit_Framework_TestCase
  9. {
  10. /**
  11. * @expectedException \BadMethodCallException
  12. * @expectedExceptionMessage seek() is not implemented in the FnStream
  13. */
  14. public function testThrowsWhenNotImplemented()
  15. {
  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. public function testDoesNotRequireClose()
  40. {
  41. $s = new FnStream([]);
  42. unset($s);
  43. }
  44. public function testDecoratesStream()
  45. {
  46. $a = Stream::factory('foo');
  47. $b = FnStream::decorate($a, []);
  48. $this->assertEquals(3, $b->getSize());
  49. $this->assertEquals($b->isWritable(), true);
  50. $this->assertEquals($b->isReadable(), true);
  51. $this->assertEquals($b->isSeekable(), true);
  52. $this->assertEquals($b->read(3), 'foo');
  53. $this->assertEquals($b->tell(), 3);
  54. $this->assertEquals($a->tell(), 3);
  55. $this->assertEmpty($b->read(1));
  56. $this->assertEquals($b->eof(), true);
  57. $this->assertEquals($a->eof(), true);
  58. $b->seek(0);
  59. $this->assertEquals('foo', (string) $b);
  60. $b->seek(0);
  61. $this->assertEquals('foo', $b->getContents());
  62. $this->assertEquals($a->getMetadata(), $b->getMetadata());
  63. $b->seek(0, SEEK_END);
  64. $b->write('bar');
  65. $this->assertEquals('foobar', (string) $b);
  66. $this->assertInternalType('resource', $b->detach());
  67. $b->close();
  68. }
  69. public function testDecoratesWithCustomizations()
  70. {
  71. $called = false;
  72. $a = Stream::factory('foo');
  73. $b = FnStream::decorate($a, [
  74. 'read' => function ($len) use (&$called, $a) {
  75. $called = true;
  76. return $a->read($len);
  77. }
  78. ]);
  79. $this->assertEquals('foo', $b->read(3));
  80. $this->assertTrue($called);
  81. }
  82. }