|
13 | 13 | use chillerlan\HTTP\Utils\StreamUtil;
|
14 | 14 | use InvalidArgumentException;
|
15 | 15 | use PHPUnit\Framework\TestCase;
|
| 16 | +use RuntimeException; |
16 | 17 | use function fclose;
|
17 | 18 | use function fopen;
|
18 | 19 | use function stream_get_meta_data;
|
| 20 | +use function strlen; |
19 | 21 | use function substr;
|
20 |
| -use function var_dump; |
21 | 22 |
|
22 | 23 | /**
|
23 | 24 | *
|
@@ -85,4 +86,55 @@ public function testGetContentsFromUnreadableStream():void{
|
85 | 86 | $this::assertNull(StreamUtil::getContents($stream));
|
86 | 87 | }
|
87 | 88 |
|
| 89 | + public function testCopyToStream():void{ |
| 90 | + $content = 'teststream'; |
| 91 | + |
| 92 | + $streamA = $this->streamFactory->createStream($content); |
| 93 | + $streamB = $this->streamFactory->createStream(); |
| 94 | + |
| 95 | + $bytesRead = StreamUtil::copyToStream($streamA, $streamB); |
| 96 | + |
| 97 | + $this::assertSame(strlen($content), $bytesRead); |
| 98 | + $this::assertSame($content, (string)$streamB); // -> "teststream" |
| 99 | + } |
| 100 | + |
| 101 | + public function testCopyToStreamWithMaxlength():void{ |
| 102 | + $content = 'teststream'; |
| 103 | + $maxlength = 4; |
| 104 | + |
| 105 | + $streamA = $this->streamFactory->createStream($content); |
| 106 | + $streamB = $this->streamFactory->createStream(); |
| 107 | + |
| 108 | + $bytesRead = StreamUtil::copyToStream($streamA, $streamB, $maxlength); |
| 109 | + |
| 110 | + $this::assertSame($maxlength, $bytesRead); |
| 111 | + $this::assertSame(substr($content, 0, $maxlength), (string)$streamB); // -> "test" |
| 112 | + } |
| 113 | + |
| 114 | + public function testCopyToStreamFromCurrentPosition():void{ |
| 115 | + $content = 'teststream'; |
| 116 | + $position = 4; |
| 117 | + |
| 118 | + $streamA = $this->streamFactory->createStream($content); |
| 119 | + $streamB = $this->streamFactory->createStream(); |
| 120 | + |
| 121 | + $streamA->seek($position); |
| 122 | + $pos = $streamA->tell(); |
| 123 | + |
| 124 | + $bytesRead = StreamUtil::copyToStream($streamA, $streamB); |
| 125 | + |
| 126 | + $this::assertSame((strlen($content) - $pos), $bytesRead); |
| 127 | + $this::assertSame(substr($content, $position), (string)$streamB); // -> "stream" |
| 128 | + } |
| 129 | + |
| 130 | + public function testCopyToStreamException():void{ |
| 131 | + $this->expectException(RuntimeException::class); |
| 132 | + $this->expectExceptionMessage('$source must be readable and $destination must be writable'); |
| 133 | + |
| 134 | + $streamA = $this->streamFactory->createStreamFromResource(fopen(__DIR__.'/fopen-test.txt', 'a')); |
| 135 | + $streamB = $this->streamFactory->createStream(); |
| 136 | + |
| 137 | + StreamUtil::copyToStream($streamA, $streamB); |
| 138 | + } |
| 139 | + |
88 | 140 | }
|
0 commit comments