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

SystemTestCase.php « TestCase « Framework « PHPUnit « tests - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8a3f92918823f21ae7d982b6f6d01d433ec9d847 (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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
<?php
/**
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik\Tests\Framework\TestCase;

use Exception;
use Piwik\ArchiveProcessor\Rules;
use Piwik\Common;
use Piwik\Config;
use Piwik\Container\StaticContainer;
use Piwik\DataTable;
use Piwik\DataTable\Manager;
use Piwik\Date;
use Piwik\Db;
use Piwik\DbHelper;
use Piwik\Http;
use Piwik\Period;
use Piwik\Plugin\ProcessedMetric;
use Piwik\ReportRenderer;
use Piwik\Site;
use Piwik\Tests\Framework\Constraint\ResponseCode;
use Piwik\Tests\Framework\Constraint\HttpResponseText;
use Piwik\Tests\Framework\Mock\File as MockFileMethods;
use Piwik\Tests\Framework\TestRequest\ApiTestConfig;
use Piwik\Tests\Framework\TestRequest\Collection;
use Piwik\Tests\Framework\TestRequest\Response;
use Piwik\Log;
use PHPUnit\Framework\TestCase;
use Piwik\Tests\Framework\Fixture;
use Piwik\Translation\Translator;
use Piwik\Url;

/**
 * Base class for System tests.
 *
 * Provides helpers to track data and then call API get* methods to check outputs automatically.
 *
 * @since 2.8.0
 */
abstract class SystemTestCase extends TestCase
{
    /**
     * Identifies the last language used in an API/Controller call.
     *
     * @var string
     */
    protected $lastLanguage;

    protected $missingExpectedFiles = array();
    protected $comparisonFailures = array();

    /**
     * @var Fixture
     */
    public static $fixture;

    public function setGroups(array $groups): void
    {
        $pluginName = explode('\\', get_class($this));
        if (!empty($pluginName[2]) && !empty($pluginName[1]) && $pluginName[1] === 'Plugins') {
            // we assume \Piwik\Plugins\PluginName nanmespace...
            if (!in_array($pluginName[2], $groups, true)) {
                $groups[] = $pluginName[2];
            }
        }

        parent::setGroups($groups);
    }

    public static function setUpBeforeClass(): void
    {
        Log::debug("Setting up " . get_called_class());

        // NOTE: it is important to reference this class in a test framework class like Fixture so the mocks
        // will be loaded before any testable classed load, otherwise some tests may fail w/o any obvious reason.
        // (the actual reason being )
        MockFileMethods::reset();

        if (!isset(static::$fixture)) {
            $fixture = new Fixture();
        } else {
            $fixture = static::$fixture;
        }

        $fixture->testCaseClass = get_called_class();

        if (!array_key_exists('loadRealTranslations', $fixture->extraTestEnvVars)) {
            $fixture->extraTestEnvVars['loadRealTranslations'] = true; // load real translations by default for system tests
        }

        $fixture->extraDefinitions = static::provideContainerConfigBeforeClass();

        try {
            $fixture->performSetUp();
        } catch (Exception $e) {
            static::fail("Failed to setup fixture: " . $e->getMessage() . "\n" . $e->getTraceAsString());
        }
    }

    public static function tearDownAfterClass(): void
    {
        Log::debug("Tearing down " . get_called_class());

        if (!isset(static::$fixture)) {
            $fixture = new Fixture();
        } else {
            $fixture = static::$fixture;
        }

        $fixture->performTearDown();
    }

    /**
     * Returns true if continuous integration running this request
     * Useful to exclude tests which may fail only on this setup
     */
    public static function isTravisCI()
    {
        $travis = getenv('TRAVIS');
        return !empty($travis);
    }

    public static function isMysqli()
    {
        return getenv('MYSQL_ADAPTER') == 'MYSQLI';
    }

    /**
     * Return 4 Api Urls for testing scheduled reports :
     * - one in HTML format with all available reports
     * - one in PDF format with all available reports
     * - two in SMS (one for each available report: MultiSites.getOne & MultiSites.getAll)
     *
     * @param string $dateTime eg '2010-01-01 12:34:56'
     * @param string $period eg 'day', 'week', 'month', 'year'
     * @return array
     */
    protected static function getApiForTestingScheduledReports($dateTime, $period)
    {
        $apiCalls = array();

        // HTML Scheduled Report
        array_push(
            $apiCalls,
            array(
                'ScheduledReports.generateReport',
                array(
                    'testSuffix'             => '_schedrep_html_tables_only',
                    'date'                   => $dateTime,
                    'periods'                => array($period),
                    'format'                 => 'original',
                    'fileExtension'          => 'html',
                    'otherRequestParameters' => array(
                        'idReport'     => 1,
                        'reportFormat' => ReportRenderer::HTML_FORMAT,
                        'outputType'   => \Piwik\Plugins\ScheduledReports\API::OUTPUT_RETURN,
                        'serialize' => 0,
                    )
                )
            )
        );

        // CSV Scheduled Report
        array_push(
            $apiCalls,
            array(
                'ScheduledReports.generateReport',
                array(
                    'testSuffix'             => '_schedrep_in_csv',
                    'date'                   => $dateTime,
                    'periods'                => array($period),
                    'format'                 => 'original',
                    'fileExtension'          => 'csv',
                    'otherRequestParameters' => array(
                        'idReport'     => 1,
                        'reportFormat' => ReportRenderer::CSV_FORMAT,
                        'outputType'   => \Piwik\Plugins\ScheduledReports\API::OUTPUT_RETURN,
                        'serialize' => 0,
                    )
                )
            )
        );

        // TSV Scheduled Report
        array_push(
            $apiCalls,
            array(
                'ScheduledReports.generateReport',
                array(
                    'testSuffix'             => '_schedrep_in_tsv',
                    'date'                   => $dateTime,
                    'periods'                => array($period),
                    'format'                 => 'original',
                    'fileExtension'          => 'tsv',
                    'otherRequestParameters' => array(
                        'idReport'     => 1,
                        'reportFormat' => ReportRenderer::TSV_FORMAT,
                        'outputType'   => \Piwik\Plugins\ScheduledReports\API::OUTPUT_RETURN,
                        'serialize' => 0,
                    )
                )
            )
        );

        if (Fixture::canImagesBeIncludedInScheduledReports()) {
            // PDF Scheduled Report
            // tests/PHPUnit/System/processed/test_ecommerceOrderWithItems_scheduled_report_in_pdf_tables_only__ScheduledReports.generateReport_week.original.pdf
            array_push(
                $apiCalls,
                array(
                     'ScheduledReports.generateReport',
                     array(
                         'testSuffix'             => '_schedrep_in_pdf_tables_only',
                         'date'                   => $dateTime,
                         'periods'                => array($period),
                         'format'                 => 'original',
                         'fileExtension'          => 'pdf',
                         'otherRequestParameters' => array(
                             'idReport'     => 1,
                             'reportFormat' => ReportRenderer::PDF_FORMAT,
                             'outputType'   => \Piwik\Plugins\ScheduledReports\API::OUTPUT_RETURN,
                             'serialize' => 0,
                         )
                     )
                )
            );
        }

        // SMS Scheduled Report, one site
        array_push(
            $apiCalls,
            array(
                 'ScheduledReports.generateReport',
                 array(
                     'testSuffix'             => '_schedrep_via_sms_one_site',
                     'date'                   => $dateTime,
                     'periods'                => array($period),
                     'format'                 => 'original',
                     'fileExtension'          => 'sms.txt',
                     'otherRequestParameters' => array(
                         'idReport'   => 2,
                         'outputType' => \Piwik\Plugins\ScheduledReports\API::OUTPUT_RETURN,
                         'serialize' => 0,
                     )
                 )
            )
        );

        // SMS Scheduled Report, all sites
        array_push(
            $apiCalls,
            array(
                 'ScheduledReports.generateReport',
                 array(
                     'testSuffix'             => '_schedrep_via_sms_all_sites',
                     'date'                   => $dateTime,
                     'periods'                => array($period),
                     'format'                 => 'original',
                     'fileExtension'          => 'sms.txt',
                     'otherRequestParameters' => array(
                         'idReport'   => 3,
                         'outputType' => \Piwik\Plugins\ScheduledReports\API::OUTPUT_RETURN,
                         'serialize' => 0,
                     )
                 )
            )
        );

        if (Fixture::canImagesBeIncludedInScheduledReports()) {
            // HTML Scheduled Report with images
            array_push(
                $apiCalls,
                array(
                     'ScheduledReports.generateReport',
                     array(
                         'testSuffix'             => '_schedrep_html_tables_and_graph',
                         'date'                   => $dateTime,
                         'periods'                => array($period),
                         'format'                 => 'original',
                         'fileExtension'          => 'html',
                         'otherRequestParameters' => array(
                             'idReport'     => 4,
                             'reportFormat' => ReportRenderer::HTML_FORMAT,
                             'outputType'   => \Piwik\Plugins\ScheduledReports\API::OUTPUT_RETURN,
                             'serialize' => 0,
                         )
                     )
                )
            );

            // mail report with one row evolution based png graph
            array_push(
                $apiCalls,
                array(
                     'ScheduledReports.generateReport',
                     array(
                         'testSuffix'             => '_schedrep_html_row_evolution_graph',
                         'date'                   => $dateTime,
                         'periods'                => array($period),
                         'format'                 => 'original',
                         'fileExtension'          => 'html',
                         'otherRequestParameters' => array(
                             'idReport'     => 5,
                             'outputType'   => \Piwik\Plugins\ScheduledReports\API::OUTPUT_RETURN,
                             'serialize' => 0,
                         )
                     )
                )
            );

            // row evolution w/ custom previousN
            array_push(
                $apiCalls,
                array(
                    'ScheduledReports.generateReport',
                    array(
                        'testSuffix'             => '_schedrep_html_row_evolution_prevCustomN',
                        'date'                   => $dateTime,
                        'periods'                => array($period),
                        'format'                 => 'original',
                        'fileExtension'          => 'html',
                        'otherRequestParameters' => array(
                            'idReport'     => 6,
                            'outputType'   => \Piwik\Plugins\ScheduledReports\API::OUTPUT_RETURN,
                            'serialize' => 0,
                        )
                    )
                )
            );

            // row evolution w/ each in period
            array_push(
                $apiCalls,
                array(
                    'ScheduledReports.generateReport',
                    array(
                        'testSuffix'             => '_schedrep_html_row_evolution_overEach',
                        'date'                   => $dateTime,
                        'periods'                => array($period),
                        'format'                 => 'original',
                        'fileExtension'          => 'html',
                        'otherRequestParameters' => array(
                            'idReport'     => 7,
                            'outputType'   => \Piwik\Plugins\ScheduledReports\API::OUTPUT_RETURN,
                            'serialize' => 0,
                        )
                    )
                )
            );
        }

        return $apiCalls;
    }

    /**
     * While {@link runApiTests()} lets you run test for many API methods at once this one tests only one specific
     * API method and it goes via HTTP. While the other method lets you test only some methods starting with 'get'
     * this one lets you actually test any API method.
     */
    protected function runAnyApiTest($apiMethod, $apiId, $requestParams, $options = array())
    {
        $requestParams['module'] = 'API';
        if (empty($requestParams['format'])) {
            $requestParams['format'] = 'XML';
        }
        $requestParams['method'] = $apiMethod;

        $apiId = $apiMethod . '_' . $apiId . '.' . strtolower($requestParams['format']);
        $testName = 'test_' . static::getOutputPrefix();

        if (!empty($options['testSuffix'])) {
            $testName .= '_' . $options['testSuffix'];
        }

        list($processedFilePath, $expectedFilePath) =
            $this->getProcessedAndExpectedPaths($testName, $apiId, $format = null, $compareAgainst = false);

        if (!array_key_exists('token_auth', $requestParams)) {
            $requestParams['token_auth'] = Fixture::getTokenAuth();
        }

        $response = $this->getResponseFromHttpAPI($requestParams);
        $processedResponse = new Response($response, $options, $requestParams);

        if (empty($compareAgainst)) {
            $processedResponse->save($processedFilePath);
        }

        $response = $processedResponse->getResponseText();
        if (strpos($response, '<?xml') === 0) {
            $this->assertValidXML($response);
        }

        try {
            $expectedResponse = Response::loadFromFile($expectedFilePath, $options, $requestParams);
        } catch (Exception $ex) {
            $this->handleMissingExpectedFile($expectedFilePath, $processedResponse);
            return;
        }

        try {
            $errorMessage = get_class($this) . ": Differences with expected in '$processedFilePath'";
            Response::assertEquals($expectedResponse, $processedResponse, $errorMessage);
        } catch (Exception $ex) {
            $this->comparisonFailures[] = $ex;
        }

        $this->printApiTestFailures();
    }

    protected function assertValidXML($xml)
    {
        libxml_use_internal_errors(true);
        $sxe = simplexml_load_string($xml);

        if ($sxe === false) {
            $errors = [];
            foreach (libxml_get_errors() as $error) {
                $errors[] = trim($error->message) . ' @' . $error->line . ':' . $error->column;
            }
            static::fail('Response is no valid xml: ' . implode("\n", $errors));
        }

        libxml_clear_errors();
    }

    /**
     * @param $requestUrl
     * @return string
     * @throws Exception
     */
    protected function getResponseFromHttpAPI($requestUrl)
    {
        $queryString = Url::getQueryStringFromParameters($requestUrl);
        $hostAndPath = Fixture::getTestRootUrl();
        $url = $hostAndPath . '?' . $queryString;
        $response = Http::sendHttpRequest($url, $timeout = 300);
        return $response;
    }

    protected function _testApiUrl($testName, $apiId, $requestUrl, $compareAgainst, $params = array())
    {
        Manager::getInstance()->deleteAll(); // clearing the datatable cache here GREATLY speeds up system tests on travis CI

        list($processedFilePath, $expectedFilePath) =
            $this->getProcessedAndExpectedPaths($testName, $apiId, $format = null, $compareAgainst);

        $originalGET = $_GET;
        $_GET = $requestUrl;
        unset($_GET['serialize']);

        $onlyCheckUnserialize = !empty($params['onlyCheckUnserialize']);

        $processedResponse = Response::loadFromApi($params, $requestUrl, $normailze = !$onlyCheckUnserialize);
        if (empty($compareAgainst)) {
            $processedResponse->save($processedFilePath);
        }

        $response = $processedResponse->getResponseText();
        if (strpos($response, '<?xml') === 0) {
            $this->assertValidXML($response);
        }

        if ($onlyCheckUnserialize) {
            if (empty($response) || is_numeric($response)) {
                return; // pass
            }

            // check the data can be successfully unserialized, nothing else
            try {
                $unserialized = Common::safe_unserialize($response, [
                    DataTable::class,
                    DataTable\Simple::class,
                    DataTable\Row::class,
                    DataTable\Map::class,
                    Site::class,
                    Date::class,
                    Period::class,
                    Period\Day::class,
                    Period\Week::class,
                    Period\Month::class,
                    Period\Year::class,
                    Period\Range::class,
                    ProcessedMetric::class,
                ], true);

                self::assertTrue($unserialized !== false, "Unknown serialization error.");
            } catch (\Exception $ex) {
                $this->comparisonFailures[] = new \Exception("Processed response in '$processedFilePath' could not be unserialized: " . $ex->getMessage());
            }
            return;
        }

        $_GET = $originalGET;

        try {
            $expectedResponse = Response::loadFromFile($expectedFilePath, $params, $requestUrl);
        } catch (Exception $ex) {
            $this->handleMissingExpectedFile($expectedFilePath, $processedResponse);
            return;
        }

        try {
            $errorMessage = get_class($this) . ": Differences with expected in '$processedFilePath'";
            Response::assertEquals($expectedResponse, $processedResponse, $errorMessage);
        } catch (Exception $ex) {
            $this->comparisonFailures[] = $ex;
        }
    }

    private function handleMissingExpectedFile($expectedFilePath, Response $processedResponse)
    {
        $this->missingExpectedFiles[] = $expectedFilePath;

        print("The expected file is not found at '$expectedFilePath'. The Processed response was:");
        print("\n----------------------------\n\n");
        var_dump($processedResponse->getResponseText());
        print("\n----------------------------\n");
    }

    public static function assertApiResponseHasNoError($response)
    {
        if(!is_string($response)) {
            $response = json_encode($response);
        }
        self::assertTrue(stripos($response, 'error') === false, "error in $response");
        self::assertTrue(stripos($response, 'exception') === false, "exception in $response");
    }

    protected static function getProcessedAndExpectedDirs()
    {
        $path = static::getPathToTestDirectory();
        $processedPath = $path . '/processed/';

        if (!is_dir($processedPath)) {
            mkdir($processedPath, $mode = 0777, $recursive = true);
        }

        if (!is_writable($processedPath)) {
            self::fail('To run the tests, you need to give write permissions to the following directory (create it if '
                      . 'it doesn\'t exist).<code><br/>mkdir ' . $processedPath . '<br/>chmod 777 ' . $processedPath
                      . '</code><br/>');
        }

        return array($processedPath, $path . '/expected/');
    }

    protected function getProcessedAndExpectedPaths($testName, $testId, $format = null, $compareAgainst = false)
    {
        $filenameSuffix = '__' . $testId;
        if ($format) {
            $filenameSuffix .= ".$format";
        }

        $processedFilename = $testName . $filenameSuffix;

        $expectedFilename = $compareAgainst ? ('test_' . $compareAgainst) : $testName;
        $expectedFilename .= $filenameSuffix;

        list($processedDir, $expectedDir) = static::getProcessedAndExpectedDirs();

        return array($processedDir . $processedFilename, $expectedDir . $expectedFilename);
    }

    /**
     * Returns an array describing the API methods to call & compare with
     * expected output.
     *
     * The returned array must be of the following format:
     * <code>
     * array(
     *     array('SomeAPI.method', array('testOption1' => 'value1', 'testOption2' => 'value2'),
     *     array(array('SomeAPI.method', 'SomeOtherAPI.method'), array(...)),
     *     .
     *     .
     *     .
     * )
     * </code>
     *
     * Valid test options are described in the ApiTestConfig class docs.
     *
     * All test options are optional, except 'idSite' & 'date'.
     */
    public function getApiForTesting()
    {
        return array();
    }

    /**
     * Gets the string prefix used in the name of the expected/processed output files.
     */
    public static function getOutputPrefix()
    {
        $parts = explode("\\", get_called_class());
        $result = end($parts);
        $result = str_replace('Test_Piwik_Integration_', '', $result);
        return $result;
    }

    /**
     * Assert that the response of an API method call is the same as the contents in an
     * expected file.
     *
     * @param string $api ie, `"DevicesDetection.getBrowsers"`
     * @param array $queryParams Query parameters to send to the API.
     */
    public function assertApiResponseEqualsExpected($apiMethod, $queryParams)
    {
        $this->runApiTests($apiMethod, array(
            'idSite' => $queryParams['idSite'],
            'date' => $queryParams['date'],
            'periods' => $queryParams['period'],
            'format' => isset($queryParams['format']) ? $queryParams['format'] : 'xml',
            'testSuffix' => '_' . $this->getName(), // TODO: instead of using a test suffix, the whole file name should just be the test method
            'otherRequestParameters' => $queryParams
        ));
    }

    /**
     * Runs API tests.
     */
    protected function runApiTests($api, $params)
    {
        $testConfig = new ApiTestConfig($params);

        $testName = 'test_' . static::getOutputPrefix();
        $this->missingExpectedFiles = array();
        $this->comparisonFailures = array();

        if ($testConfig->disableArchiving) {
            Rules::$archivingDisabledByTests = true;
            Config::getInstance()->General['browser_archiving_disabled_enforce'] = 1;
        } else {
            Rules::$archivingDisabledByTests = false;
            Config::getInstance()->General['browser_archiving_disabled_enforce'] = 0;
        }

        if ($testConfig->language) {
            $this->changeLanguage($testConfig->language);
        }

        $testRequests = $this->getTestRequestsCollection($api, $testConfig, $api);

        foreach ($testRequests->getRequestUrls() as $apiId => $requestUrl) {
            $this->_testApiUrl($testName . $testConfig->testSuffix, $apiId, $requestUrl, $testConfig->compareAgainst, $params);
        }

        // change the language back to en
        if ($this->lastLanguage != 'en') {
            $this->changeLanguage('en');
        }

        $this->printApiTestFailures();

        return count($this->comparisonFailures) == 0;
    }

    private function printApiTestFailures()
    {
        if (!empty($this->missingExpectedFiles)) {
            $expectedDir = dirname(reset($this->missingExpectedFiles));
            $this->fail(" ERROR: Could not find expected API output '"
                . implode("', '", $this->missingExpectedFiles)
                . "'. For new tests, to pass the test, you can copy files from the processed/ directory into"
                . " $expectedDir  after checking that the output is valid. %s ");
        }

        // Display as one error all sub-failures
        if (!empty($this->comparisonFailures)) {
            $this->printComparisonFailures();
            throw reset($this->comparisonFailures);
        }
    }

    protected function getTestRequestsCollection($api, $testConfig, $apiToCall)
    {
       return new Collection($api, $testConfig, $apiToCall);
    }

    private function printComparisonFailures()
    {
        $messages = '';
        foreach ($this->comparisonFailures as $index => $failure) {
            $msg = $failure->getMessage();
            $msg = strtok($msg, "\n");
            $messages .= "\n#" . ($index + 1) . ": " . $msg;
        }
        $messages .= " \n ";

        print($messages);
    }

    /**
     * changing the language within one request is a bit fancy
     * in order to keep the core clean, we need a little hack here
     *
     * @param string $langId
     */
    protected function changeLanguage($langId)
    {
        if ($this->lastLanguage != $langId) {
            $_GET['language'] = $langId;
            /** @var Translator $translator */
            $translator = StaticContainer::get('Piwik\Translation\Translator');
            $translator->setCurrentLanguage($langId);
        }

        $this->lastLanguage = $langId;
    }

    /**
     * Path where expected/processed output files are stored.
     */
    public static function getPathToTestDirectory()
    {
        $up = DIRECTORY_SEPARATOR . '..';

        return dirname(__FILE__) . $up . $up . DIRECTORY_SEPARATOR . 'System';
    }

    /**
     * Returns an array associating table names w/ lists of row data.
     *
     * @return array
     */
    protected static function getDbTablesWithData()
    {
        $result = array();
        $tables = Db::fetchAll('SHOW TABLES'); // tests should be in a clean database, so we can just get all tables
        if (!empty($tables)) {
            $tables = array_column($tables, key($tables[0]));
        }
        foreach ($tables as $tableName) {
            $result[$tableName] = Db::fetchAll("SELECT * FROM `$tableName`");
        }
        return $result;
    }

    /**
     * Truncates all tables then inserts the data in $tables into each
     * mapped table.
     *
     * @param array $tables Array mapping table names with arrays of row data.
     */
    protected static function restoreDbTables($tables)
    {
        $db = Db::fetchOne("SELECT DATABASE()");
        if (empty($db)) {
            Db::exec("USE " . Config::getInstance()->database_tests['dbname']);
        }

        DbHelper::truncateAllTables();

        // insert data
        $archiveTables = Db::fetchAll("SHOW TABLES LIKE '%archive_%'");
        if (!empty($archiveTables)) {
            $archiveTables = array_column($archiveTables, key($archiveTables[0]));
        }
        foreach ($tables as $table => $rows) {
            // create table if it's an archive table
            if (strpos($table, 'archive_') !== false && !in_array($table, $archiveTables)) {
                $tableType = strpos($table, 'archive_numeric') !== false ? 'archive_numeric' : 'archive_blob';

                $createSql = DbHelper::getTableCreateSql($tableType);
                $createSql = str_replace(Common::prefixTable($tableType), $table, $createSql);
                Db::query($createSql);
            }

            if (empty($rows)) {
                continue;
            }

            foreach ($rows as $row) {
                $rowsSql = array();
                $bind = array();

                $values = array();
                foreach ($row as $value) {
                    if (is_null($value)) {
                        $values[] = 'NULL';
                    } else {
                        // is_numeric cannot be used here since some strings will look like floating point numbers (eg 3e456)
                        $isNumeric = preg_match('/^\d+(\.\d+)?$/', $value);
                        if ($isNumeric) {
                            $values[] = $value;
                        } else if (!ctype_print($value)) {
                            $values[] = "x'" . bin2hex($value) . "'";
                        } else {
                            $values[] = "?";
                            $bind[] = $value;
                        }
                    }
                }

                $rowsSql[] = "(" . implode(',', $values) . ")";

                $sql = "INSERT INTO `$table` VALUES " . implode(',', $rowsSql);
                try {
                    Db::query($sql, $bind);
                } catch( Exception $e) {
                    throw new Exception("error while inserting $sql into $table the data. SQl data: " . var_export($sql, true) . ", Bind array: " . var_export($bind, true) . ". Erorr was -> " . $e->getMessage());
                }

            }

        }
    }

    /**
     * Drops all archive tables.
     */
    public static function deleteArchiveTables()
    {
        DbHelper::deleteArchiveTables();
    }

    public function assertNotDbConnectionCreated($message = 'A database connection was created but should not.')
    {
        self::assertFalse(Db::hasDatabaseObject(), $message);
        self::assertFalse(Db::hasReaderDatabaseObject(), $message);
    }

    public function assertDbConnectionCreated($message = 'A database connection was not created but should.')
    {
        self::assertTrue(Db::hasDatabaseObject(), $message);
    }

    /**
     * Use this method to return custom container configuration that you want to apply for the tests.
     * This configuration will override Fixture config.
     *
     * @return array
     */
    public static function provideContainerConfigBeforeClass()
    {
        return array();
    }
}

SystemTestCase::$fixture = new \Piwik\Tests\Framework\Fixture();