aboutsummaryrefslogtreecommitdiffstats
path: root/tests/unit/Module/TestCase.php
blob: 2959eab79f29e04079e7a10dc4995658fa0ed03c (plain) (blame)
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
<?php

namespace Zotlabs\Tests\Unit\Module;

class TestCase extends \Zotlabs\Tests\Unit\UnitTestCase {

	// Import PHPMock methods into this class
	use \phpmock\phpunit\PHPMock;

	/**
	 * Emulate a GET request.
	 *
	 * @param string $uri	The URI to request. Typically this will be the module
	 *						name, followed by any req args separated by slashes.
	 *
	 * @param array $query	Assciative array of query args, with the parameters
	 *						as keys.
	 */
	protected function get(string $uri, array $query = []): void {
		$_GET['q'] = $uri;

		if (!empty($query)) {
			$_GET = array_merge($_GET, $query);
		}

		$_SERVER['REQUEST_METHOD'] = 'GET';
		$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
		$_SERVER['QUERY_STRING'] = "q={$uri}";
		$_REQUEST = $_GET;

		\App::init();
		\App::$page['content'] = '';

		$router = new \Zotlabs\Web\Router();
		$router->Dispatch();
	}

	/**
	 * Helper to simplify asserting contents in the rendered page.
	 *
	 * @param string $needle	The expected string to find.
	 */
	protected function assertPageContains(string $needle): void {
		$this->assertStringContainsString($needle, \App::$page['content']);
	}

	/**
	 * Stub out the `killme` function.
	 *
	 * Usefule for modules that call this function directly.
	 *
	 * Instead of calling exit, the stub will throw a `KillmeException`,
	 * that can be caught by the test code to regain control after request
	 * processing is terminated.
	 */
	protected function stub_killme(): void {
		$killme_stub = $this->getFunctionMock('Zotlabs\Module', 'killme');
		$killme_stub
			->expects($this->once())
			->willReturnCallback(
				function () {
					throw new KillmeException();
				}
			);
	}

	protected function stub_goaway(): void {
		$goaway_stub = $this->getFunctionMock('Zotlabs\Module', 'goaway');
		$goaway_stub
			->expects($this->once())
			->willReturnCallback(
				function (string $uri) {
					throw new RedirectException($uri);
				}
			);
	}

	protected function expectRedirectTo(string $destination): void {
		$this->stub_goaway();
		$this->expectException(RedirectException::class);
		$this->expectExceptionMessage($destination);
	}
}

/**
 * Exception class for killme stub
 */
class KillmeException extends \Exception {}

/**
 * Exception class for goaway stub.
 *
 * Takes the goaway uri as an arg, and makes it available as
 * the public `$uri` member variable.
 */
class RedirectException extends \Exception {
	function __construct(string $uri) {
		parent::__construct($uri);
	}
}