FnStreamTest.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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->assertEquals($b->eof(), true);
  56. $this->assertEquals($a->eof(), true);
  57. $b->seek(0);
  58. $this->assertEquals('foo', (string) $b);
  59. $b->seek(0);
  60. $this->assertEquals('foo', $b->getContents());
  61. $this->assertEquals($a->getMetadata(), $b->getMetadata());
  62. $b->seek(0, SEEK_END);
  63. $b->write('bar');
  64. $this->assertEquals('foobar', (string) $b);
  65. $this->assertInternalType('resource', $b->detach());
  66. $b->close();
  67. }
  68. public function testDecoratesWithCustomizations()
  69. {
  70. $called = false;
  71. $a = Stream::factory('foo');
  72. $b = FnStream::decorate($a, [
  73. 'read' => function ($len) use (&$called, $a) {
  74. $called = true;
  75. return $a->read($len);
  76. }
  77. ]);
  78. $this->assertEquals('foo', $b->read(3));
  79. $this->assertTrue($called);
  80. }
  81. }