Completed
Push — 3 ( 1d0cff...2b4954 )
by Damian
13:47
created

HTTPTest::testAddCacheHeaders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 51
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 39
nc 2
nop 0
dl 0
loc 51
rs 9.4109
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Tests the {@link HTTP} class
4
 *
5
 * @package framework
6
 * @subpackage tests
7
 */
8
class HTTPTest extends FunctionalTest {
9
10
	public function setUp()
11
	{
12
		parent::setUp();
13
		// Remove dev-only config
14
		Config::inst()->remove('HTTP', 'disable_http_cache');
15
		HTTPCacheControl::reset();
16
	}
17
18
	public function testAddCacheHeaders() {
19
		$body = "<html><head></head><body><h1>Mysite</h1></body></html>";
20
		$response = new SS_HTTPResponse($body, 200);
21
		HTTPCacheControl::singleton()->publicCache();
22
		HTTP::set_cache_age(30);
23
		HTTP::add_cache_headers($response);
24
		$this->assertNotEmpty($response->getHeader('Cache-Control'));
25
26
		// Ensure cache headers are set correctly when disabled via config (e.g. when dev)
27
		Config::inst()->update('HTTP', 'disable_http_cache', true);
28
		HTTPCacheControl::reset();
29
		HTTPCacheControl::singleton()->publicCache();
30
		HTTP::set_cache_age(30);
31
		$response = new SS_HTTPResponse($body, 200);
32
		HTTP::add_cache_headers($response);
33
		$this->assertContains('no-cache', $response->getHeader('Cache-Control'));
34
		$this->assertContains('no-store', $response->getHeader('Cache-Control'));
35
		$this->assertContains('must-revalidate', $response->getHeader('Cache-Control'));
36
37
		// Ensure max-age setting is respected in production.
38
		Config::inst()->remove('HTTP', 'disable_http_cache');
39
		HTTPCacheControl::reset();
40
		HTTPCacheControl::singleton()->publicCache();
41
		HTTP::set_cache_age(30);
42
		$response = new SS_HTTPResponse($body, 200);
43
		HTTP::add_cache_headers($response);
44
		$this->assertContains('max-age=30', $response->getHeader('Cache-Control'));
45
		$this->assertNotContains('max-age=0', $response->getHeader('Cache-Control'));
46
47
		// Still "live": Ensure header's aren't overridden if already set (using purposefully different values).
48
		$headers = array(
49
			'Vary' => '*',
50
			'Pragma' => 'no-cache',
51
			'Cache-Control' => 'max-age=0, no-cache, no-store',
52
		);
53
		HTTPCacheControl::reset();
54
		HTTPCacheControl::singleton()->publicCache();
55
		HTTP::set_cache_age(30);
56
		$response = new SS_HTTPResponse($body, 200);
57
		foreach($headers as $name => $value) {
58
			$response->addHeader($name, $value);
59
		}
60
61
		// Expect a warning if the header is already set
62
		$this->setExpectedException(
63
			'PHPUnit_Framework_Error_Warning',
64
			'Cache-Control header has already been set. '
65
			. 'Please use HTTPCacheControl API to set caching options instead.'
66
		);
67
		HTTP::add_cache_headers($response);
68
	}
69
70
    public function testConfigVary() {
71
		$body = "<html><head></head><body><h1>Mysite</h1></body></html>";
72
		$response = new SS_HTTPResponse($body, 200);
73
		HTTP::set_cache_age(30);
74
		HTTP::add_cache_headers($response);
75
76
		$v = $response->getHeader('Vary');
77
		$this->assertNotEmpty($v);
78
79
		$this->assertContains("X-Forwarded-Protocol", $v);
80
		$this->assertContains("X-Requested-With", $v);
81
		$this->assertNotContains("Cookie", $v);
82
		$this->assertNotContains("User-Agent", $v);
83
		$this->assertNotContains("Accept", $v);
84
85
		Config::inst()->update('HTTP', 'vary', '');
86
		HTTPCacheControl::reset();
87
88
		$response = new SS_HTTPResponse($body, 200);
89
		HTTP::add_cache_headers($response);
90
91
		$v = $response->getHeader('Vary');
92
		$this->assertEmpty($v);
93
	}
94
95
	/**
96
	 * Tests {@link HTTP::getLinksIn()}
97
	 */
98
	public function testGetLinksIn() {
99
		$content = '
100
			<h2><a href="/">My Cool Site</a></h2>
101
102
			<p>
103
				A boy went <a href="home/">home</a> to see his <span><a href="mother/">mother</a></span>. This
104
				involved a short <a href="$Journey">journey</a>, as well as some <a href="space travel">space travel</a>
105
				and <a href=unquoted>unquoted</a> events, as well as a <a href=\'single quote\'>single quote</a> from
106
				his <a href="/father">father</a>.
107
			</p>
108
109
			<p>
110
				There were also some elements with extra <a class=attribute href=\'attributes\'>attributes</a> which
111
				played a part in his <a href=journey"extra id="JourneyLink">journey</a>. HE ALSO DISCOVERED THE
112
				<A HREF="CAPS LOCK">KEY</a>. Later he got his <a href="quotes \'mixed\' up">mixed up</a>.
113
			</p>
114
		';
115
116
		$expected = array (
117
			'/', 'home/', 'mother/', '$Journey', 'space travel', 'unquoted', 'single quote', '/father', 'attributes',
118
			'journey', 'CAPS LOCK', 'quotes \'mixed\' up'
119
		);
120
121
		$result = HTTP::getLinksIn($content);
122
123
		// Results don't neccesarily come out in the order they are in the $content param.
124
		sort($result);
125
		sort($expected);
126
127
		$this->assertTrue(is_array($result));
128
		$this->assertEquals($expected, $result, 'Test that all links within the content are found.');
129
	}
130
131
	/**
132
	 * Tests {@link HTTP::setGetVar()}
133
	 */
134
	public function testSetGetVar() {
0 ignored issues
show
Coding Style introduced by
testSetGetVar uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
135
		// Hackery to work around volatile URL formats in test invocation,
136
		// and the inability of Director::absoluteBaseURL() to produce consistent URLs.
137
		$origURI = $_SERVER['REQUEST_URI'];
138
		$_SERVER['REQUEST_URI'] = 'relative/url/';
139
				$this->assertContains(
140
			'relative/url/?foo=bar',
141
			HTTP::setGetVar('foo', 'bar'),
142
			'Omitting a URL falls back to current URL'
143
		);
144
		$_SERVER['REQUEST_URI'] = $origURI;
145
146
		$this->assertEquals(
147
			'relative/url?foo=bar',
148
			HTTP::setGetVar('foo', 'bar', 'relative/url'),
149
			'Relative URL without existing query params');
150
151
		$this->assertEquals(
152
			'relative/url?baz=buz&amp;foo=bar',
153
			HTTP::setGetVar('foo', 'bar', '/relative/url?baz=buz'),
154
			'Relative URL with existing query params, and new added key'
155
		);
156
157
		$this->assertEquals(
158
			'http://test.com/?foo=new&amp;buz=baz',
159
			HTTP::setGetVar('foo', 'new', 'http://test.com/?foo=old&buz=baz'),
160
			'Absolute URL without path and multipe existing query params, overwriting an existing parameter'
161
		);
162
163
		$this->assertContains(
164
			'http://test.com/?foo=new',
165
			HTTP::setGetVar('foo', 'new', 'http://test.com/?foo=&foo=old'),
166
			'Absolute URL and empty query param'
167
		);
168
		// http_build_query() escapes angular brackets, they should be correctly urldecoded by the browser client
169
		$this->assertEquals(
170
			'http://test.com/?foo%5Btest%5D=one&amp;foo%5Btest%5D=two',
171
			HTTP::setGetVar('foo[test]', 'two', 'http://test.com/?foo[test]=one'),
172
			'Absolute URL and PHP array query string notation'
173
		);
174
175
		$urls = array(
176
			'http://www.test.com:8080',
177
			'http://test.com:3000/',
178
			'http://test.com:3030/baz/',
179
			'http://baz:[email protected]',
180
			'http://[email protected]/',
181
			'http://baz:[email protected]:8080',
182
			'http://[email protected]:8080'
183
		);
184
185
		foreach($urls as $testURL) {
186
			$this->assertEquals(
187
				$testURL .'?foo=bar',
188
				HTTP::setGetVar('foo', 'bar', $testURL),
189
				'Absolute URL and Port Number'
190
			);
191
		}
192
	}
193
194
	/**
195
	 * Test that the the get_mime_type() works correctly
196
	 *
197
	 */
198
	public function testGetMimeType() {
199
		$this->assertEquals('text/plain', HTTP::get_mime_type(FRAMEWORK_DIR.'/tests/control/files/file.csv'));
200
		$this->assertEquals('image/gif', HTTP::get_mime_type(FRAMEWORK_DIR.'/tests/control/files/file.gif'));
201
		$this->assertEquals('text/html', HTTP::get_mime_type(FRAMEWORK_DIR.'/tests/control/files/file.html'));
202
		$this->assertEquals('image/jpeg', HTTP::get_mime_type(FRAMEWORK_DIR.'/tests/control/files/file.jpg'));
203
		$this->assertEquals('image/jpeg', HTTP::get_mime_type(FRAMEWORK_DIR.'/tests/control/files/upperfile.JPG'));
204
		$this->assertEquals('image/png', HTTP::get_mime_type(FRAMEWORK_DIR.'/tests/control/files/file.png'));
205
		$this->assertEquals('image/vnd.adobe.photoshop',
206
			HTTP::get_mime_type(FRAMEWORK_DIR.'/tests/control/files/file.psd'));
207
		$this->assertEquals('audio/x-wav', HTTP::get_mime_type(FRAMEWORK_DIR.'/tests/control/files/file.wav'));
208
	}
209
210
	/**
211
	 * Test that absoluteURLs correctly transforms urls within CSS to absolute
212
	 */
213
	public function testAbsoluteURLsCSS() {
214
		$this->withBaseURL('http://www.silverstripe.org/', function($test){
215
216
			// background-image
217
			// Note that using /./ in urls is absolutely acceptable
218
			$test->assertEquals(
219
				'<div style="background-image: url(\'http://www.silverstripe.org/./images/mybackground.gif\');">'.
220
				'Content</div>',
221
				HTTP::absoluteURLs('<div style="background-image: url(\'./images/mybackground.gif\');">Content</div>')
222
			);
223
224
			// background
225
			$test->assertEquals(
226
				'<div style="background: url(\'http://www.silverstripe.org/images/mybackground.gif\');">Content</div>',
227
				HTTP::absoluteURLs('<div style="background: url(\'images/mybackground.gif\');">Content</div>')
228
			);
229
230
			// list-style-image
231
			$test->assertEquals(
232
				'<div style=\'background: url(http://www.silverstripe.org/list.png);\'>Content</div>',
233
				HTTP::absoluteURLs('<div style=\'background: url(list.png);\'>Content</div>')
234
			);
235
236
			// list-style
237
			$test->assertEquals(
238
				'<div style=\'background: url("http://www.silverstripe.org/./assets/list.png");\'>Content</div>',
239
				HTTP::absoluteURLs('<div style=\'background: url("./assets/list.png");\'>Content</div>')
240
			);
241
		});
242
	}
243
244
	/**
245
	 * Test that absoluteURLs correctly transforms urls within html attributes to absolute
246
	 */
247
	public function testAbsoluteURLsAttributes() {
248
		$this->withBaseURL('http://www.silverstripe.org/', function($test){
249
			//empty links
250
			$test->assertEquals(
251
				'<a href="http://www.silverstripe.org/">test</a>',
252
				HTTP::absoluteURLs('<a href="">test</a>')
253
			);
254
255
			$test->assertEquals(
256
				'<a href="http://www.silverstripe.org/">test</a>',
257
				HTTP::absoluteURLs('<a href="/">test</a>')
258
			);
259
260
			//relative
261
			$test->assertEquals(
262
				'<a href="http://www.silverstripe.org/">test</a>',
263
				HTTP::absoluteURLs('<a href="./">test</a>')
264
			);
265
			$test->assertEquals(
266
				'<a href="http://www.silverstripe.org/">test</a>',
267
				HTTP::absoluteURLs('<a href=".">test</a>')
268
			);
269
270
			// links
271
			$test->assertEquals(
272
				'<a href=\'http://www.silverstripe.org/blog/\'>SS Blog</a>',
273
				HTTP::absoluteURLs('<a href=\'/blog/\'>SS Blog</a>')
274
			);
275
276
			// background
277
			// Note that using /./ in urls is absolutely acceptable
278
			$test->assertEquals(
279
				'<div background="http://www.silverstripe.org/./themes/silverstripe/images/nav-bg-repeat-2.png">'.
280
				'SS Blog</div>',
281
				HTTP::absoluteURLs('<div background="./themes/silverstripe/images/nav-bg-repeat-2.png">SS Blog</div>')
282
			);
283
284
			//check dot segments
285
			// Assumption: dots are not removed
286
				//if they were, the url should be: http://www.silverstripe.org/abc
287
			$test->assertEquals(
288
				'<a href="http://www.silverstripe.org/test/page/../../abc">Test</a>',
289
				HTTP::absoluteURLs('<a href="test/page/../../abc">Test</a>')
290
			);
291
292
			// image
293
			$test->assertEquals(
294
				'<img src=\'http://www.silverstripe.org/themes/silverstripe/images/logo-org.png\' />',
295
				HTTP::absoluteURLs('<img src=\'themes/silverstripe/images/logo-org.png\' />')
296
			);
297
298
			// link
299
			$test->assertEquals(
300
				'<link href=http://www.silverstripe.org/base.css />',
301
				HTTP::absoluteURLs('<link href=base.css />')
302
			);
303
		});
304
	}
305
306
	/**
307
	 * 	Make sure URI schemes are not rewritten
308
	 */
309
	public function testURISchemes() {
310
		$this->withBaseURL('http://www.silverstripe.org/', function($test){
311
312
			// mailto
313
			$test->assertEquals(
314
				'<a href=\'mailto:[email protected]\'>Email Us</a>',
315
				HTTP::absoluteURLs('<a href=\'mailto:[email protected]\'>Email Us</a>'),
316
				'Email links are not rewritten'
317
			);
318
319
			// data uri
320
			$test->assertEquals(
321
				'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38'.
322
				'GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />',
323
				HTTP::absoluteURLs('<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH'.
324
					'ElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />'),
325
				'Data URI links are not rewritten'
326
			);
327
328
			// call
329
			$test->assertEquals(
330
				'<a href="callto:12345678" />',
331
				HTTP::absoluteURLs('<a href="callto:12345678" />'),
332
				'Call to links are not rewritten'
333
			);
334
		});
335
	}
336
337
}
338