aboutsummaryrefslogtreecommitdiffstats
path: root/tests/lib/AppFramework/Http/JSONResponseTest.php
blob: bacc59993488c67996a816a01b15f73b1573e7c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php

/**
 * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace Test\AppFramework\Http;

use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;

class JSONResponseTest extends \Test\TestCase {
	/**
	 * @var JSONResponse
	 */
	private $json;

	protected function setUp(): void {
		parent::setUp();
		$this->json = new JSONResponse();
	}


	public function testHeader() {
		$headers = $this->json->getHeaders();
		$this->assertEquals('application/json; charset=utf-8', $headers['Content-Type']);
	}


	public function testSetData() {
		$params = ['hi', 'yo'];
		$this->json->setData($params);

		$this->assertEquals(['hi', 'yo'], $this->json->getData());
	}


	public function testSetRender() {
		$params = ['test' => 'hi'];
		$this->json->setData($params);

		$expected = '{"test":"hi"}';

		$this->assertEquals($expected, $this->json->render());
	}

	/**
	 * @return array
	 */
	public function renderDataProvider() {
		return [
			[
				['test' => 'hi'], '{"test":"hi"}',
			],
			[
				['<h1>test' => '<h1>hi'], '{"\u003Ch1\u003Etest":"\u003Ch1\u003Ehi"}',
			],
		];
	}

	/**
	 * @dataProvider renderDataProvider
	 * @param array $input
	 * @param string $expected
	 */
	public function testRender(array $input, $expected) {
		$this->json->setData($input);
		$this->assertEquals($expected, $this->json->render());
	}


	public function testRenderWithNonUtf8Encoding() {
		$this->expectException(\JsonException::class);
		$this->expectExceptionMessage('Malformed UTF-8 characters, possibly incorrectly encoded');

		$params = ['test' => hex2bin('e9')];
		$this->json->setData($params);
		$this->json->render();
	}

	public function testConstructorAllowsToSetData() {
		$data = ['hi'];
		$code = 300;
		$response = new JSONResponse($data, $code);

		$expected = '["hi"]';
		$this->assertEquals($expected, $response->render());
		$this->assertEquals($code, $response->getStatus());
	}

	public function testChainability() {
		$params = ['hi', 'yo'];
		$this->json->setData($params)
			->setStatus(Http::STATUS_NOT_FOUND);

		$this->assertEquals(Http::STATUS_NOT_FOUND, $this->json->getStatus());
		$this->assertEquals(['hi', 'yo'], $this->json->getData());
	}
}