1
0

JSONResponseTest.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace Test\AppFramework\Http;
  8. use OCP\AppFramework\Http;
  9. use OCP\AppFramework\Http\JSONResponse;
  10. class JSONResponseTest extends \Test\TestCase {
  11. /**
  12. * @var JSONResponse
  13. */
  14. private $json;
  15. protected function setUp(): void {
  16. parent::setUp();
  17. $this->json = new JSONResponse();
  18. }
  19. public function testHeader() {
  20. $headers = $this->json->getHeaders();
  21. $this->assertEquals('application/json; charset=utf-8', $headers['Content-Type']);
  22. }
  23. public function testSetData() {
  24. $params = ['hi', 'yo'];
  25. $this->json->setData($params);
  26. $this->assertEquals(['hi', 'yo'], $this->json->getData());
  27. }
  28. public function testSetRender() {
  29. $params = ['test' => 'hi'];
  30. $this->json->setData($params);
  31. $expected = '{"test":"hi"}';
  32. $this->assertEquals($expected, $this->json->render());
  33. }
  34. /**
  35. * @return array
  36. */
  37. public function renderDataProvider() {
  38. return [
  39. [
  40. ['test' => 'hi'], '{"test":"hi"}',
  41. ],
  42. [
  43. ['<h1>test' => '<h1>hi'], '{"\u003Ch1\u003Etest":"\u003Ch1\u003Ehi"}',
  44. ],
  45. ];
  46. }
  47. /**
  48. * @dataProvider renderDataProvider
  49. * @param array $input
  50. * @param string $expected
  51. */
  52. public function testRender(array $input, $expected) {
  53. $this->json->setData($input);
  54. $this->assertEquals($expected, $this->json->render());
  55. }
  56. public function testRenderWithNonUtf8Encoding() {
  57. $this->expectException(\JsonException::class);
  58. $this->expectExceptionMessage('Malformed UTF-8 characters, possibly incorrectly encoded');
  59. $params = ['test' => hex2bin('e9')];
  60. $this->json->setData($params);
  61. $this->json->render();
  62. }
  63. public function testConstructorAllowsToSetData() {
  64. $data = ['hi'];
  65. $code = 300;
  66. $response = new JSONResponse($data, $code);
  67. $expected = '["hi"]';
  68. $this->assertEquals($expected, $response->render());
  69. $this->assertEquals($code, $response->getStatus());
  70. }
  71. public function testChainability() {
  72. $params = ['hi', 'yo'];
  73. $this->json->setData($params)
  74. ->setStatus(Http::STATUS_NOT_FOUND);
  75. $this->assertEquals(Http::STATUS_NOT_FOUND, $this->json->getStatus());
  76. $this->assertEquals(['hi', 'yo'], $this->json->getData());
  77. }
  78. }