Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ServeStaticFileTest.php « Integration « PHPUnit « tests - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bdf288efd4b746860a23eb3b4e4ca9522378f0f3 (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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
<?php
/**
 * This php file is used to unit test Piwik::serverStaticFile()
 * Unit tests for this method should normally be located in /tests/core/Piwik.test.php
 * To make a comprehensive test suit for Piwik::serverStaticFile() (ie. being able to test combinations of request
 * headers, being able to test response headers and so on) we need to simulate static file requests in a controlled
 * environment
 * The php code which simulates requests using Piwik::serverStaticFile() is provided in the same file (ie. this one)
 * as the unit testing code for Piwik::serverStaticFile()
 * This decision has a structural impact on the usual unit test file structure
 * serverStaticFile.test.php has been created to avoid making too many modifications to /tests/core/Piwik.test.php
 */

// This is Piwik logo, the static file used in this test suit

// TODO this is an integration or system test! not a unit test

use Piwik\ProxyHttp;
use Piwik\SettingsServer;
use Piwik\Tests\Framework\Fixture;

define("TEST_FILE_LOCATION", realpath(dirname(__FILE__) . "/../../resources/lipsum.txt"));
define("TEST_FILE_CONTENT_TYPE", "text/plain");

// Defines http request parameters
define("FILE_MODE_REQUEST_VAR", "fileMode");
define("SRV_MODE_REQUEST_VAR", "serverMode");
define("ZLIB_OUTPUT_REQUEST_VAR", "zlibOutput");

/**
 * These constants define the mode in which this php file is used :
 * - for unit testing Piwik::serverStaticFile() or
 * - as a static file server
 */
define("STATIC_SERVER_MODE", "staticServerMode");
define("UNIT_TEST_MODE", "unitTestMode");

// These constants define which action will be performed by the static server.
define("NULL_FILE_SRV_MODE", "nullFile");
define("GHOST_FILE_SRV_MODE", "ghostFile");
define("TEST_FILE_SRV_MODE", "testFile");
define("PARTIAL_TEST_FILE_SRV_MODE", "partialTestFile");
define("WHOLE_TEST_FILE_WITH_RANGE_SRV_MODE", "wholeTestFileWithRange");

define("PARTIAL_BYTE_START", 1204);
define("PARTIAL_BYTE_END", 14724);

// If the static file server has not been requested, the standard unit test case class is defined
class Test_Piwik_ServeStaticFile extends PHPUnit_Framework_TestCase
{
    public function tearDown()
    {
        parent::tearDown();
        chmod(TEST_FILE_LOCATION, 0644);
    }

    /**
     * Test that php compression isn't enabled ... otherwise, lots of tests will fail
     *
     * @group Core
     */
    public function test_phpOutputCompression()
    {
        $this->assertFalse(ProxyHttp::isPhpOutputCompressed());
    }

    /**
     * Checks that "HTTP/1.0 404 Not Found" is returned when Piwik::serverStaticFile is called with a null file
     *
     * @group Core
     */
    public function test_nullFile()
    {
        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getNullFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_exec($curlHandle);
        $responseInfo = curl_getinfo($curlHandle);
        curl_close($curlHandle);

        $this->assertEquals($responseInfo["http_code"], 404);
    }

    /**
     * Checks that "HTTP/1.0 404 Not Found" is returned when Piwik::serverStaticFile is called with a non existing file
     *
     *
     * @group Core
     */
    public function test_ghostFile()
    {
        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getGhostFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_exec($curlHandle);
        $responseInfo = curl_getinfo($curlHandle);
        curl_close($curlHandle);

        $this->assertEquals($responseInfo["http_code"], 404);
    }

    /**
     * Checks that "HTTP/1.0 505 Internal server error" is returned when Piwik::serverStaticFile is called with a
     * non-readable file
     *
     * @group Core
     */
    public function test_nonReadableFile()
    {
        /**
         * This test would fail on a windows environment because it is not possible to remove reading rights on a
         * windows file using PHP.
         */
        if (SettingsServer::isWindows()) {
            return;
        }

        // Setting mode so the testing file is non-readable
        chmod(TEST_FILE_LOCATION, 0200);

        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $url = $this->getTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_exec($curlHandle);
        $responseInfo = curl_getinfo($curlHandle);
        curl_close($curlHandle);

        // Restoring file mode
        chmod(TEST_FILE_LOCATION, 0644);

        $this->assertEquals($responseInfo["http_code"], 505);
    }

    /**
     * Context :
     *  - First access to test file
     *  - zlib.output_compression = 0
     *  - no compression
     * Expected :
     *  - file is send back without compression
     *  - cache control headers are correctly set
     *
     * @group Core
     */
    public function test_firstAccessNoCompression()
    {
        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_HEADER, true);
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        $fullResponse = curl_exec($curlHandle);
        $responseInfo = curl_getinfo($curlHandle);
        curl_close($curlHandle);

        // Tests returned code equals 200
        $this->assertEquals(200, $responseInfo["http_code"]);

        // Tests content type
        $this->assertContains(TEST_FILE_CONTENT_TYPE, $responseInfo["content_type"]);

        // Tests no compression has been applied
        $this->assertNull($this->getContentEncodingValue($fullResponse));

        // Tests returned size
        $this->assertEquals(filesize(TEST_FILE_LOCATION), $responseInfo["size_download"]);

        // Tests if returned modified date is correctly set
        $this->assertEquals(gmdate('D, d M Y H:i:s', filemtime(TEST_FILE_LOCATION)) . ' GMT',
            $this->getLastModifiedValue($fullResponse));

        // Tests if cache control headers are correctly set
        $this->assertEquals("public, must-revalidate", $this->getCacheControlValue($fullResponse));
        $pragma = $this->getPragma($fullResponse);
        $this->assertTrue($pragma == null || $pragma == 'Pragma:');
        $expires = $this->getExpires($fullResponse);
        $this->assertTrue(strtotime($expires) > time() + 99 * 86400);
    }

    /**
     * Context :
     *  - Second access to test file
     *  - If-Modified-Since set to test file modification date
     * Expected :
     *  - "HTTP/1.1 304 Not Modified" sent back to client
     *
     * @group Core
     */
    public function test_secondAccessNoCompression()
    {
        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_TIMECONDITION, 1);
        curl_setopt($curlHandle, CURLOPT_TIMEVALUE, filemtime(TEST_FILE_LOCATION));
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_exec($curlHandle);
        $responseInfo = curl_getinfo($curlHandle);
        curl_close($curlHandle);

        $this->assertEquals($responseInfo["http_code"], 304);
    }

    /**
     * Context :
     *  - Second access to test file
     *  - If-Modified-Since set to test file modification date minus 1 second
     * Expected :
     *  - http return code 200 sent back to client
     *
     * @group Core
     */
    public function test_secondAccessNoCompressionExpiredFile()
    {
        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_TIMECONDITION, 1);
        curl_setopt($curlHandle, CURLOPT_TIMEVALUE, filemtime(TEST_FILE_LOCATION) - 1);
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_exec($curlHandle);
        $responseInfo = curl_getinfo($curlHandle);
        curl_close($curlHandle);

        $this->assertEquals($responseInfo["http_code"], 200);
    }

    /**
     * Context :
     *  - First access to file
     *  - zlib output compression is on
     * Expected :
     *  - the response has to be readable, it tests the proxy doesn't compress the file when compression
     *      is enabled in php.
     *
     * @group Core
     */
    public function test_responseReadableWithPhpCompression()
    {
        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->setZlibOutputRequest(($this->getTestFileSrvModeUrl())));

        // The "" parameter sets all compatible content encodings
        curl_setopt($curlHandle, CURLOPT_ENCODING, "");
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        $fullResponse = curl_exec($curlHandle);
        curl_close($curlHandle);

        // Tests response content, it has to be equal to the test file. If not equal, double compression occurred
        $this->assertEquals($fullResponse, file_get_contents(TEST_FILE_LOCATION));
    }

    /**
     * Context :
     *  - First access to file
     *  - Content-Encoding: deflate
     * Expected :
     *  - the response has to be readable
     *  - the compression method used must be gzdeflate and not gzcompression to be IE compatible
     *
     * @group Core
     */
    public function test_deflateCompression()
    {
        $this->removeCompressedFiles();

        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate");
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        $fullResponse = curl_exec($curlHandle);
        curl_close($curlHandle);

        // Tests response content, it has to be equal to the test file
        $this->assertEquals($fullResponse, file_get_contents(TEST_FILE_LOCATION));

        // Tests deflate compression has been used
        $deflateFileLocation = $this->getCompressedFileLocation() . ".deflate";
        $this->assertTrue(file_exists($deflateFileLocation));

        // Tests gzdeflate has been used for IE compatibility
        $this->assertEquals(gzinflate(file_get_contents($deflateFileLocation)), file_get_contents(TEST_FILE_LOCATION));

        $this->removeCompressedFiles();
    }

    /**
     * Context :
     *  - First access to file
     *  - Content-Encoding: gzip
     * Expected :
     *  - the response has to be readable
     *  - the compression method used is gzip
     *
     * @group Core
     */
    public function test_gzipCompression()
    {
        $this->removeCompressedFiles();

        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_ENCODING, "gzip");
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        $fullResponse = curl_exec($curlHandle);
        curl_close($curlHandle);

        // Tests response content, it has to be equal to the test file
        $this->assertEquals($fullResponse, file_get_contents(TEST_FILE_LOCATION));

        // Tests gzip compression has been used
        $gzipFileLocation = $this->getCompressedFileLocation() . ".gz";
        $this->assertTrue(file_exists($gzipFileLocation));

        $this->removeCompressedFiles();
    }

    /**
     * Context :
     *  - First access to file
     *  - Content-Encoding: deflate
     *  - Repeat twice
     * Expected :
     *  - the compressed file cache mechanism works file, ie. the .deflate file is not generated twice
     *
     * @group Core
     */
    public function test_compressionCache()
    {
        $this->removeCompressedFiles();
        $deflateFileLocation = $this->getCompressedFileLocation() . ".deflate";

        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate");
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_exec($curlHandle);
        curl_close($curlHandle);

        $firstAccessModificationTime = filemtime($deflateFileLocation);

        // Requests made to the static file have to be executed at different times for the test to be valid.
        sleep(1);

        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate");
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_exec($curlHandle);
        curl_close($curlHandle);

        // Tests the .deflate file has not been generated twice
        clearstatcache();
        $this->assertEquals($firstAccessModificationTime, filemtime($deflateFileLocation));

        $this->removeCompressedFiles();
    }

    /**
     * Context :
     *  - First access to file
     *  - Content-Encoding: deflate
     *  - Repeat twice, in between: update the modification date of the test file
     * Expected :
     *  - the test file has been updated, the cached compressed file should be regenerated
     *
     * @group Core
     */
    public function test_compressionCacheInvalidation()
    {
        $this->removeCompressedFiles();
        $deflateFileLocation = $this->getCompressedFileLocation() . ".deflate";

        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate");
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_exec($curlHandle);
        curl_close($curlHandle);

        $firstAccessModificationTime = filemtime($deflateFileLocation);

        // Requests made to the static file have to be executed at different times for the test to be valid.
        sleep(1);

        // We update the test file modification date
        touch(TEST_FILE_LOCATION);

        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate");
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_exec($curlHandle);
        curl_close($curlHandle);

        clearstatcache();
        $this->assertNotEquals($firstAccessModificationTime, filemtime($deflateFileLocation));

        $this->removeCompressedFiles();
    }

    /**
     * @group Core
     */
    public function test_partialFileServeNoCompression()
    {
        $this->removeCompressedFiles();

        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getPartialTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        $partialResponse = curl_exec($curlHandle);
        $responseInfo = curl_getinfo($curlHandle);
        curl_close($curlHandle);

        clearstatcache();

        // check no compressed files created
        $this->assertFalse(file_exists($this->getCompressedFileLocation() . ".deflate"));
        $this->assertFalse(file_exists($this->getCompressedFileLocation() . ".gz"));

        // check $partialResponse
        $this->assertEquals(PARTIAL_BYTE_END - PARTIAL_BYTE_START, $responseInfo["size_download"]);

        $expectedPartialContents = substr(file_get_contents(TEST_FILE_LOCATION), PARTIAL_BYTE_START,
            PARTIAL_BYTE_END - PARTIAL_BYTE_START);
        $this->assertEquals($expectedPartialContents, $partialResponse);
    }

    /**
     * @group Core
     * @group TestToExec
     */
    public function test_partialFileServeWithCompression()
    {
        $this->removeCompressedFiles();

        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getPartialTestFileSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate");
        $partialResponse = curl_exec($curlHandle);
        curl_getinfo($curlHandle);
        curl_close($curlHandle);

        clearstatcache();

        // check the correct compressed file is created
        $this->assertTrue(file_exists($this->getCompressedFileLocation() . '.' . PARTIAL_BYTE_START . '.' . PARTIAL_BYTE_END . ".deflate"));
        $this->assertFalse(file_exists($this->getCompressedFileLocation() . ".gz"));

        // check $partialResponse
        $expectedPartialContents = substr(file_get_contents(TEST_FILE_LOCATION), PARTIAL_BYTE_START,
            PARTIAL_BYTE_END - PARTIAL_BYTE_START);
        $this->assertEquals($expectedPartialContents, $partialResponse);

        $this->removeCompressedFiles();
    }

    /**
     * @group Core
     */
    public function test_wholeFileServeWithByteRange()
    {
        $this->removeCompressedFiles();

        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $this->getWholeTestFileWithRangeSrvModeUrl());
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlHandle, CURLOPT_ENCODING, "deflate");
        $fullResponse = curl_exec($curlHandle);
        curl_getinfo($curlHandle);
        curl_close($curlHandle);

        clearstatcache();

        // check the correct compressed file is created
        $this->assertTrue(file_exists($this->getCompressedFileLocation() . ".deflate"));
        $this->assertFalse(file_exists($this->getCompressedFileLocation() . ".gz"));

        // check $fullResponse
        $this->assertEquals(file_get_contents(TEST_FILE_LOCATION), $fullResponse);

        $this->removeCompressedFiles();
    }

    /**
     * Helper methods
     */
    private function getStaticSrvUrl()
    {
        $url = Fixture::getRootUrl();
        $url .= '/tests/resources/';

        return $url . "staticFileServer.php?" . FILE_MODE_REQUEST_VAR . "=" . STATIC_SERVER_MODE .
            "&" . SRV_MODE_REQUEST_VAR . "=";
    }

    private function getNullFileSrvModeUrl()
    {
        return $this->getStaticSrvUrl() . NULL_FILE_SRV_MODE;
    }

    private function getGhostFileSrvModeUrl()
    {
        return $this->getStaticSrvUrl() . GHOST_FILE_SRV_MODE;
    }

    private function getTestFileSrvModeUrl()
    {
        return $this->getStaticSrvUrl() . TEST_FILE_SRV_MODE;
    }

    private function getPartialTestFileSrvModeUrl()
    {
        return $this->getStaticSrvUrl() . PARTIAL_TEST_FILE_SRV_MODE;
    }

    private function getWholeTestFileWithRangeSrvModeUrl()
    {
        return $this->getStaticSrvUrl() . WHOLE_TEST_FILE_WITH_RANGE_SRV_MODE;
    }

    private function setZlibOutputRequest($url)
    {
        return $url . "&" . ZLIB_OUTPUT_REQUEST_VAR . "=1";
    }

    private function getContentEncodingValue($fullResponse)
    {
        preg_match_all('/Content-Encoding:[\s*]([[:print:]]*)/', $fullResponse, $matches);

        if (isset($matches[1][0])) {
            return $matches[1][0];
        }

        return null;
    }

    private function getCacheControlValue($fullResponse)
    {
        preg_match_all('/Cache-Control:[\s*]([[:print:]]*)/', $fullResponse, $matches);

        if (isset($matches[1][0])) {
            return $matches[1][0];
        }

        return null;
    }

    private function getPragma($fullResponse)
    {
        preg_match_all('/(Pragma:[[:print:]]*)/', $fullResponse, $matches);

        if (isset($matches[1][0])) {
            return trim($matches[1][0]);
        }

        return null;
    }

    private function getExpires($fullResponse)
    {
        preg_match_all('/Expires: ([[:print:]]*)/', $fullResponse, $matches);

        if (isset($matches[1][0])) {
            return trim($matches[1][0]);
        }

        return null;
    }

    private function getLastModifiedValue($fullResponse)
    {
        preg_match_all('/Last-Modified:[\s*]([[:print:]]*)/', $fullResponse, $matches);

        if (isset($matches[1][0])) {
            return $matches[1][0];
        }

        return null;
    }

    private function getCompressedFileLocation()
    {
        return \Piwik\AssetManager::getInstance()->getAssetDirectory() . '/' . basename(TEST_FILE_LOCATION);
    }

    private function removeCompressedFiles()
    {
        @unlink($this->getCompressedFileLocation() . ".deflate");
        @unlink($this->getCompressedFileLocation() . ".gz");
    }
}