FileFormTest.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace AlibabaCloud\Tea\FileForm\Tests;
  3. use AlibabaCloud\Tea\FileForm\FileForm;
  4. use AlibabaCloud\Tea\FileForm\FileForm\FileField;
  5. use AlibabaCloud\Tea\FileForm\FileFormStream;
  6. use GuzzleHttp\Psr7\Stream;
  7. use PHPUnit\Framework\TestCase;
  8. /**
  9. * @internal
  10. * @coversNothing
  11. */
  12. class FileFormTest extends TestCase
  13. {
  14. public function testFileFromStream()
  15. {
  16. $boundary = FileForm::getBoundary();
  17. $stream = FileForm::toFileForm([], $boundary);
  18. $this->assertTrue($stream instanceof FileFormStream);
  19. $stream->write($boundary);
  20. $this->assertTrue(\strlen($boundary) === $stream->getSize());
  21. }
  22. public function testSet()
  23. {
  24. $fileField = new FileField([
  25. 'filename' => 'fake filename',
  26. 'contentType' => 'content type',
  27. 'content' => null,
  28. ]);
  29. $this->assertEquals('fake filename', $fileField->filename);
  30. $this->assertEquals('content type', $fileField->contentType);
  31. }
  32. public function testRead()
  33. {
  34. $fileField = new FileField();
  35. $fileField->filename = 'haveContent';
  36. $fileField->contentType = 'contentType';
  37. $fileField->content = new Stream(fopen('data://text/plain;base64,' . base64_encode('This is file test. This sentence must be long'), 'r'));
  38. $fileFieldNoContent = new FileField();
  39. $fileFieldNoContent->filename = 'noContent';
  40. $fileFieldNoContent->contentType = 'contentType';
  41. $fileFieldNoContent->content = null;
  42. $map = [
  43. 'key' => 'value',
  44. 'testKey' => 'testValue',
  45. 'haveFile' => $fileField,
  46. 'noFile' => $fileFieldNoContent,
  47. ];
  48. $stream = FileForm::toFileForm($map, 'testBoundary');
  49. $result = $stream->getContents();
  50. $target = "--testBoundary\r\nContent-Disposition: form-data; name=\"key\"\r\n\r\nvalue\r\n--testBoundary\r\nContent-Disposition: form-data; name=\"testKey\"\r\n\r\ntestValue\r\n--testBoundary\r\nContent-Disposition: form-data; name=\"haveFile\"; filename=\"haveContent\"\r\nContent-Type: contentType\r\n\r\nThis is file test. This sentence must be long\r\n--testBoundary--\r\n";
  51. $this->assertEquals($target, $result);
  52. }
  53. public function testReadFile()
  54. {
  55. $fileField = new FileField();
  56. $fileField->filename = 'composer.json';
  57. $fileField->contentType = 'application/json';
  58. $fileField->content = new Stream(fopen(__DIR__ . '/../composer.json', 'r'));
  59. $map = [
  60. 'name' => 'json_file',
  61. 'type' => 'application/json',
  62. 'json_file' => $fileField,
  63. ];
  64. $boundary = FileForm::getBoundary();
  65. $fileStream = FileForm::toFileForm($map, $boundary);
  66. $this->assertTrue(false !== strpos($fileStream->getContents(), 'json_file'));
  67. }
  68. }