FnStreamTest.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace RingCentral\Tests\Psr7;
  3. use RingCentral\Psr7;
  4. use RingCentral\Psr7\FnStream;
  5. /**
  6. * @covers RingCentral\Psr7\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. $stream = new FnStream(array());
  17. $stream->seek(1);
  18. }
  19. public function testProxiesToFunction()
  20. {
  21. $self = $this;
  22. $s = new FnStream(array(
  23. 'read' => function ($len) use ($self) {
  24. $self->assertEquals(3, $len);
  25. return 'foo';
  26. }
  27. ));
  28. $this->assertEquals('foo', $s->read(3));
  29. }
  30. public function testCanCloseOnDestruct()
  31. {
  32. $called = false;
  33. $s = new FnStream(array(
  34. 'close' => function () use (&$called) {
  35. $called = true;
  36. }
  37. ));
  38. unset($s);
  39. $this->assertTrue($called);
  40. }
  41. public function testDoesNotRequireClose()
  42. {
  43. $s = new FnStream(array());
  44. unset($s);
  45. }
  46. public function testDecoratesStream()
  47. {
  48. $a = Psr7\stream_for('foo');
  49. $b = FnStream::decorate($a, array());
  50. $this->assertEquals(3, $b->getSize());
  51. $this->assertEquals($b->isWritable(), true);
  52. $this->assertEquals($b->isReadable(), true);
  53. $this->assertEquals($b->isSeekable(), true);
  54. $this->assertEquals($b->read(3), 'foo');
  55. $this->assertEquals($b->tell(), 3);
  56. $this->assertEquals($a->tell(), 3);
  57. $this->assertSame('', $a->read(1));
  58. $this->assertEquals($b->eof(), true);
  59. $this->assertEquals($a->eof(), true);
  60. $b->seek(0);
  61. $this->assertEquals('foo', (string) $b);
  62. $b->seek(0);
  63. $this->assertEquals('foo', $b->getContents());
  64. $this->assertEquals($a->getMetadata(), $b->getMetadata());
  65. $b->seek(0, SEEK_END);
  66. $b->write('bar');
  67. $this->assertEquals('foobar', (string) $b);
  68. $this->assertInternalType('resource', $b->detach());
  69. $b->close();
  70. }
  71. public function testDecoratesWithCustomizations()
  72. {
  73. $called = false;
  74. $a = Psr7\stream_for('foo');
  75. $b = FnStream::decorate($a, array(
  76. 'read' => function ($len) use (&$called, $a) {
  77. $called = true;
  78. return $a->read($len);
  79. }
  80. ));
  81. $this->assertEquals('foo', $b->read(3));
  82. $this->assertTrue($called);
  83. }
  84. }