Proyectos de Subversion Moodle

Rev

Rev 11 | Mostrar el archivo completo | | | Autoría | Ultima modificación | Ver Log |

Rev 11 Rev 1441
Línea 14... Línea 14...
14
// You should have received a copy of the GNU General Public License
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
Línea 16... Línea 16...
16
 
16
 
17
use core\di;
17
use core\di;
-
 
18
use core\hook;
-
 
19
use core\http_client;
-
 
20
use GuzzleHttp\Handler\MockHandler;
-
 
21
use GuzzleHttp\HandlerStack;
-
 
22
use GuzzleHttp\Middleware;
-
 
23
use PHPUnit\Framework\Attributes\After;
Línea 18... Línea 24...
18
use core\hook;
24
use PHPUnit\Framework\Attributes\Before;
19
 
25
 
20
/**
26
/**
21
 * Advanced PHPUnit test case customised for Moodle.
27
 * Advanced PHPUnit test case customised for Moodle.
Línea 40... Línea 46...
40
     * Constructs a test case with the given name.
46
     * Constructs a test case with the given name.
41
     *
47
     *
42
     * Note: use setUp() or setUpBeforeClass() in your test cases.
48
     * Note: use setUp() or setUpBeforeClass() in your test cases.
43
     *
49
     *
44
     * @param string $name
50
     * @param string $name
45
     * @param array  $data
-
 
46
     * @param string $dataName
-
 
47
     */
51
     */
48
    final public function __construct($name = null, array $data = [], $dataname = '') {
52
    final public function __construct(string $name) {
49
        parent::__construct($name, $data, $dataname);
53
        parent::__construct($name);
Línea 50... Línea 54...
50
 
54
 
51
        $this->setBackupGlobals(false);
-
 
52
        $this->setBackupStaticAttributes(false);
55
        $this->setBackupGlobals(false);
53
        $this->setPreserveGlobalState(false);
56
        $this->setPreserveGlobalState(false);
Línea 54... Línea -...
54
    }
-
 
55
 
-
 
56
    /**
57
    }
57
     * Runs the bare test sequence.
58
 
58
     */
59
    #[Before]
Línea 59... Línea 60...
59
    final public function runBare(): void {
60
    final public function setup_test_environment(): void {
60
        global $CFG, $DB;
61
        global $CFG, $DB;
61
 
62
 
62
        if (phpunit_util::$lastdbwrites != $DB->perf_get_writes()) {
63
        if (phpunit_util::$lastdbwrites != $DB->perf_get_writes()) {
63
            // This happens when previous test does not reset, we can not use transactions.
64
            // This happens when previous test does not reset, we can not use transactions.
64
            $this->testdbtransaction = null;
65
            $this->testdbtransaction = null;
65
        } else if ($DB->get_dbfamily() === 'postgres' || $DB->get_dbfamily() === 'mssql') {
66
        } else if ($DB->get_dbfamily() === 'postgres' || $DB->get_dbfamily() === 'mssql') {
Línea 66... Línea -...
66
            // Database must allow rollback of DDL, so no mysql here.
-
 
67
            $this->testdbtransaction = $DB->start_delegated_transaction();
67
            // Database must allow rollback of DDL, so no mysql here.
68
        }
-
 
69
 
-
 
70
        try {
-
 
71
            $this->setCurrentTimeStart();
-
 
72
            parent::runBare();
-
 
73
        } catch (Exception $ex) {
-
 
74
            $e = $ex;
68
            $this->testdbtransaction = $DB->start_delegated_transaction();
75
        } catch (Throwable $ex) {
-
 
76
            // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
-
 
77
            $e = $ex;
-
 
Línea -... Línea 69...
-
 
69
        }
-
 
70
 
-
 
71
        $this->setCurrentTimeStart();
78
        } finally {
72
    }
79
            // Reset global state after test and test failure.
73
 
80
            $CFG = phpunit_util::get_global_backup('CFG');
74
    #[After]
Línea 81... Línea -...
81
            $DB = phpunit_util::get_global_backup('DB');
-
 
82
 
75
    final public function teardown_test_environment(): void {
83
            // We need to reset the autoloader.
76
        global $CFG, $DB;
84
            \core_component::reset();
-
 
85
        }
-
 
Línea 86... Línea 77...
86
 
77
        // Reset global state after test and test failure.
87
        if (isset($e)) {
78
        $CFG = phpunit_util::get_global_backup('CFG');
88
            // Cleanup after failed expectation.
79
        $DB = phpunit_util::get_global_backup('DB');
89
            self::resetAllData();
80
 
Línea 141... Línea 132...
141
            }
132
            }
142
        }
133
        }
143
    }
134
    }
Línea 144... Línea 135...
144
 
135
 
145
    /**
-
 
146
     * @deprecated since Moodle 3.10 - See MDL-67673 and MDL-64600 for more info.
-
 
147
     */
-
 
148
    protected function createXMLDataSet() {
-
 
149
        throw new coding_exception(__FUNCTION__ . '() is deprecated. Please use dataset_from_files() instead.');
-
 
150
    }
-
 
151
 
-
 
152
    /**
-
 
153
     * @deprecated since Moodle 3.10 - See MDL-67673 and MDL-64600 for more info.
-
 
154
     */
-
 
155
    protected function createCsvDataSet() {
-
 
156
        throw new coding_exception(__FUNCTION__ . '() is deprecated. Please use dataset_from_files() instead.');
-
 
157
    }
-
 
158
 
-
 
159
    /**
-
 
160
     * @deprecated since Moodle 3.10 - See MDL-67673 and MDL-64600 for more info.
-
 
161
     */
-
 
162
    protected function createArrayDataSet() {
-
 
163
        throw new coding_exception(__FUNCTION__ . '() is deprecated. Please use dataset_from_array() instead.');
-
 
164
    }
-
 
165
 
-
 
166
    /**
-
 
167
     * @deprecated since Moodle 3.10 - See MDL-67673 and MDL-64600 for more info.
-
 
168
     */
-
 
169
    protected function loadDataSet() {
-
 
170
        throw new coding_exception(__FUNCTION__ . '() is deprecated. Please use dataset->to_database() instead.');
-
 
171
    }
-
 
172
 
-
 
173
    /**
136
    /**
174
     * Creates a new dataset from CVS/XML files.
137
     * Creates a new dataset from CVS/XML files.
175
     *
138
     *
176
     * This method accepts an array of full paths to CSV or XML files to be loaded
139
     * This method accepts an array of full paths to CSV or XML files to be loaded
177
     * into the dataset. For CSV files, the name of the table which the file belongs
140
     * into the dataset. For CSV files, the name of the table which the file belongs
Línea 185... Línea 148...
185
     * @since Moodle 3.10
148
     * @since Moodle 3.10
186
     *
149
     *
187
     * @param array $files full paths to CSV or XML files to load.
150
     * @param array $files full paths to CSV or XML files to load.
188
     * @return phpunit_dataset
151
     * @return phpunit_dataset
189
     */
152
     */
190
    protected function dataset_from_files(array $files) {
153
    protected static function dataset_from_files(array $files) {
191
        // We ignore $delimiter, $enclosure and $escape, use the default ones in your fixtures.
154
        // We ignore $delimiter, $enclosure and $escape, use the default ones in your fixtures.
192
        $dataset = new phpunit_dataset();
155
        $dataset = new phpunit_dataset();
193
        $dataset->from_files($files);
156
        $dataset->from_files($files);
194
        return $dataset;
157
        return $dataset;
195
    }
158
    }
Línea 202... Línea 165...
202
     * @param string $content contents (CSV or XML) to load.
165
     * @param string $content contents (CSV or XML) to load.
203
     * @param string $type format of the content to be loaded (csv or xml).
166
     * @param string $type format of the content to be loaded (csv or xml).
204
     * @param string $table name of the table which the file belongs to (only for CSV files).
167
     * @param string $table name of the table which the file belongs to (only for CSV files).
205
     * @return phpunit_dataset
168
     * @return phpunit_dataset
206
     */
169
     */
207
    protected function dataset_from_string(string $content, string $type, ?string $table = null) {
170
    protected static function dataset_from_string(string $content, string $type, ?string $table = null) {
208
        $dataset = new phpunit_dataset();
171
        $dataset = new phpunit_dataset();
209
        $dataset->from_string($content, $type, $table);
172
        $dataset->from_string($content, $type, $table);
210
        return $dataset;
173
        return $dataset;
211
    }
174
    }
Línea 216... Línea 179...
216
     * @since Moodle 3.10
179
     * @since Moodle 3.10
217
     *
180
     *
218
     * @param array $data array of tables, see {@see phpunit_dataset::from_array()} for supported formats.
181
     * @param array $data array of tables, see {@see phpunit_dataset::from_array()} for supported formats.
219
     * @return phpunit_dataset
182
     * @return phpunit_dataset
220
     */
183
     */
221
    protected function dataset_from_array(array $data) {
184
    protected static function dataset_from_array(array $data) {
222
        $dataset = new phpunit_dataset();
185
        $dataset = new phpunit_dataset();
223
        $dataset->from_array($data);
186
        $dataset->from_array($data);
224
        return $dataset;
187
        return $dataset;
225
    }
188
    }
Línea 601... Línea 564...
601
     *
564
     *
602
     * @param string $path
565
     * @param string $path
603
     * @param bool $https true if https required
566
     * @param bool $https true if https required
604
     * @return string url
567
     * @return string url
605
     */
568
     */
606
    public function getExternalTestFileUrl($path, $https = false) {
569
    public static function getExternalTestFileUrl(
-
 
570
        string $path,
-
 
571
        bool $https = false,
-
 
572
    ): string {
607
        $path = ltrim($path, '/');
573
        $path = ltrim($path, '/');
608
        if ($path) {
574
        if ($path) {
609
            $path = '/' . $path;
575
            $path = "/{$path}";
610
        }
576
        }
611
        if ($https) {
577
        if ($https) {
612
            if (defined('TEST_EXTERNAL_FILES_HTTPS_URL')) {
578
            if (defined('TEST_EXTERNAL_FILES_HTTPS_URL')) {
613
                if (!TEST_EXTERNAL_FILES_HTTPS_URL) {
579
                if (!TEST_EXTERNAL_FILES_HTTPS_URL) {
614
                    $this->markTestSkipped('Tests using external https test files are disabled');
580
                    self::markTestSkipped('Tests using external https test files are disabled');
615
                }
581
                }
616
                return TEST_EXTERNAL_FILES_HTTPS_URL . $path;
582
                return TEST_EXTERNAL_FILES_HTTPS_URL . $path;
617
            }
583
            }
618
            return 'https://download.moodle.org/unittest' . $path;
584
            return "https://download.moodle.org/unittest{$path}";
619
        }
585
        }
Línea 620... Línea 586...
620
 
586
 
621
        if (defined('TEST_EXTERNAL_FILES_HTTP_URL')) {
587
        if (defined('TEST_EXTERNAL_FILES_HTTP_URL')) {
622
            if (!TEST_EXTERNAL_FILES_HTTP_URL) {
588
            if (!TEST_EXTERNAL_FILES_HTTP_URL) {
623
                $this->markTestSkipped('Tests using external http test files are disabled');
589
                self::markTestSkipped('Tests using external http test files are disabled');
624
            }
590
            }
625
            return TEST_EXTERNAL_FILES_HTTP_URL . $path;
591
            return TEST_EXTERNAL_FILES_HTTP_URL . $path;
626
        }
592
        }
627
        return 'http://download.moodle.org/unittest' . $path;
593
        return "http://download.moodle.org/unittest{$path}";
Línea 628... Línea 594...
628
    }
594
    }
629
 
595
 
630
    /**
596
    /**
Línea 689... Línea 655...
689
 
655
 
690
        if (!empty($matchuserid)) {
656
        if (!empty($matchuserid)) {
691
            $params['userid'] = $matchuserid;
657
            $params['userid'] = $matchuserid;
Línea 692... Línea 658...
692
        }
658
        }
693
 
659
 
Línea 694... Línea 660...
694
        $lock = $this->createMock(\core\lock\lock::class);
660
        $lock = $this->createStub(\core\lock\lock::class);
695
        $cronlock = $this->createMock(\core\lock\lock::class);
661
        $cronlock = $this->createStub(\core\lock\lock::class);
696
 
662
 
697
        $tasks = $DB->get_recordset('task_adhoc', $params);
663
        $tasks = $DB->get_recordset('task_adhoc', $params);
Línea 776... Línea 742...
776
     * Please note that tests calling this method must be run in separate isolation mode.
742
     * Please note that tests calling this method must be run in separate isolation mode.
777
     * Please avoid using this if at all possible.
743
     * Please avoid using this if at all possible.
778
     *
744
     *
779
     * @param string $plugintype The name of the plugintype
745
     * @param string $plugintype The name of the plugintype
780
     * @param string $path The path to the plugintype's root
746
     * @param string $path The path to the plugintype's root
-
 
747
     * @param bool $deprecated whether to add the plugintype as a deprecated plugin type.
781
     */
748
     */
782
    protected function add_mocked_plugintype(
749
    protected function add_mocked_plugintype(
783
        string $plugintype,
750
        string $plugintype,
784
        string $path,
751
        string $path,
-
 
752
        bool $deprecated = false,
785
    ): void {
753
    ): void {
786
        require_phpunit_isolation();
754
        require_phpunit_isolation();
Línea 787... Línea 755...
787
 
755
 
-
 
756
        $mockedcomponent = new \ReflectionClass(\core_component::class);
788
        $mockedcomponent = new \ReflectionClass(\core_component::class);
757
        $propertyname = $deprecated ? 'deprecatedplugintypes' : 'plugintypes';
Línea 789... Línea 758...
789
        $plugintypes = $mockedcomponent->getStaticPropertyValue('plugintypes');
758
        $plugintypes = $mockedcomponent->getStaticPropertyValue($propertyname);
790
 
759
 
791
        if (array_key_exists($plugintype, $plugintypes)) {
760
        if (array_key_exists($plugintype, $plugintypes)) {
Línea 792... Línea 761...
792
            throw new \coding_exception("The plugintype '{$plugintype}' already exists.");
761
            throw new \coding_exception("The plugintype '{$plugintype}' already exists.");
793
        }
762
        }
Línea 794... Línea 763...
794
 
763
 
795
        $plugintypes[$plugintype] = $path;
764
        $plugintypes[$plugintype] = $path;
Línea 796... Línea 765...
796
        $mockedcomponent->setStaticPropertyValue('plugintypes', $plugintypes);
765
        $mockedcomponent->setStaticPropertyValue($propertyname, $plugintypes);
Línea 829... Línea 798...
829
        $mockedcomponent->setStaticPropertyValue('plugins', $plugins);
798
        $mockedcomponent->setStaticPropertyValue('plugins', $plugins);
830
        $this->resetDebugging();
799
        $this->resetDebugging();
831
    }
800
    }
Línea 832... Línea 801...
832
 
801
 
833
    /**
802
    /**
834
     * Convenience method to load a fixture from a component's fixture directory.
803
     * Convenience method to get the path to a fixture.
835
     *
804
     *
836
     * @param string $component
805
     * @param string $component
837
     * @param string $path
806
     * @param string $path
838
     * @throws coding_exception
807
     * @throws coding_exception
839
     */
808
     */
840
    protected static function load_fixture(
809
    protected static function get_fixture_path(
841
        string $component,
810
        string $component,
842
        string $path,
811
        string $path,
843
    ): void {
812
    ): string {
844
        $fullpath = sprintf(
813
        return sprintf(
845
            "%s/tests/fixtures/%s",
814
            "%s/tests/fixtures/%s",
846
            \core_component::get_component_directory($component),
815
            \core_component::get_component_directory($component),
847
            $path,
816
            $path,
848
        );
-
 
849
        if (!file_exists($fullpath)) {
-
 
850
            throw new \coding_exception("Fixture file not found: $fullpath");
817
        );
Línea -... Línea 818...
-
 
818
    }
-
 
819
 
-
 
820
    /**
-
 
821
     * Convenience method to load a fixture from a component's fixture directory.
-
 
822
     *
-
 
823
     * @param string $component
-
 
824
     * @param string $path
-
 
825
     * @throws coding_exception
-
 
826
     */
-
 
827
    protected static function load_fixture(
-
 
828
        string $component,
851
        }
829
        string $path,
852
 
830
    ): void {
853
        global $ADMIN;
831
        global $ADMIN;
854
        global $CFG;
832
        global $CFG;
855
        global $DB;
833
        global $DB;
Línea 859... Línea 837...
859
        global $PAGE;
837
        global $PAGE;
860
        global $SESSION;
838
        global $SESSION;
861
        global $COURSE;
839
        global $COURSE;
862
        global $SITE;
840
        global $SITE;
Línea -... Línea 841...
-
 
841
 
-
 
842
        $fullpath = static::get_fixture_path($component, $path);
-
 
843
 
-
 
844
        if (!file_exists($fullpath)) {
-
 
845
            throw new \coding_exception("Fixture file not found: $fullpath");
-
 
846
        }
863
 
847
 
864
        require_once($fullpath);
848
        require_once($fullpath);
-
 
849
    }
-
 
850
 
-
 
851
    /**
-
 
852
     * Get a mocked HTTP Client, inserting it into the Dependency Injector.
-
 
853
     *
-
 
854
     * @param array|null $history An array which will contain the Request/Response history of the HTTP client
-
 
855
     * @return array Containing the client, the mock, and the history
-
 
856
     */
-
 
857
    protected function get_mocked_http_client(
-
 
858
        ?array &$history = null,
-
 
859
    ): array {
-
 
860
        $mock = new MockHandler([]);
-
 
861
        $handlerstack = HandlerStack::create($mock);
-
 
862
 
-
 
863
        if ($history !== null) {
-
 
864
            $historymiddleware = Middleware::history($history);
-
 
865
            $handlerstack->push($historymiddleware);
-
 
866
        }
-
 
867
        $client = new http_client(['handler' => $handlerstack]);
-
 
868
 
-
 
869
        di::set(http_client::class, $client);
-
 
870
 
-
 
871
        return [
-
 
872
            'client' => $client,
-
 
873
            'mock' => $mock,
-
 
874
            'handlerstack' => $handlerstack,
-
 
875
        ];
-
 
876
    }
-
 
877
 
-
 
878
    /**
-
 
879
     * Get a copy of the mocked string manager.
-
 
880
     *
-
 
881
     * @return \core\tests\mocking_string_manager
-
 
882
     */
-
 
883
    protected function get_mocked_string_manager(): \core\tests\mocking_string_manager {
-
 
884
        global $CFG;
-
 
885
 
-
 
886
        $this->resetAfterTest();
-
 
887
        $CFG->config_php_settings['customstringmanager'] = \core\tests\mocking_string_manager::class;
-
 
888
 
-
 
889
        return get_string_manager(true);
865
    }
890
    }