Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
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/>.
16
 
17
/**
18
 * Data generators for acceptance testing.
19
 *
20
 * @package   core
21
 * @category  test
22
 * @copyright 2012 David Monllaó
23
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
27
 
28
require_once(__DIR__ . '/../../behat/behat_base.php');
29
 
30
use Behat\Gherkin\Node\TableNode as TableNode;
31
use Behat\Behat\Tester\Exception\PendingException as PendingException;
32
 
33
/**
34
 * Class to set up quickly a Given environment.
35
 *
36
 * The entry point is the Behat steps:
37
 *     the following "entity types" exist:
38
 *       | test | data |
39
 *
40
 * Entity type will either look like "users" or "activities" for core entities, or
41
 * "mod_forum > subscription" or "core_message > message" for entities belonging
42
 * to components.
43
 *
44
 * Generally, you only need to specify properties relevant to your test,
45
 * and everything else gets set to sensible defaults.
46
 *
47
 * The actual generation of entities is done by {@link behat_generator_base}.
48
 * There is one subclass for each component, e.g. {@link behat_core_generator}
49
 * or {@link behat_mod_quiz_generator}. To see the types of entity
50
 * that can be created for each component, look at the arrays returned
51
 * by the get_creatable_entities() method in each class.
52
 *
53
 * @package   core
54
 * @category  test
55
 * @copyright 2012 David Monllaó
56
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
57
 */
58
class behat_data_generators extends behat_base {
59
 
60
    /**
61
     * Convert legacy entity names to the new component-specific form.
62
     *
63
     * In the past, there was no support for plugins, and everything that
64
     * could be created was handled by the core generator. Now, we can
65
     * support plugins, and so some thing should probably be moved.
66
     *
67
     * For example, in the future we should probably add
68
     * 'message contacts' => 'core_message > contact'] to
69
     * this array, and move generation of message contact
70
     * from core to core_message.
71
     *
72
     * @var array old entity type => new entity type.
73
     */
74
    protected $movedentitytypes = [
75
    ];
76
 
77
    /**
78
     * Creates the specified elements.
79
     *
80
     * See the class comment for an overview.
81
     *
82
     * @Given /^the following "(?P<element_string>(?:[^"]|\\")*)" exist:$/
83
     *
84
     * @param string    $entitytype The name of the type entity to add
85
     * @param TableNode $data
86
     */
1441 ariadna 87
    #[\core\attribute\example('And the following "activities" exist:
88
        | activity | name              | intro           | course   | idnumber | section | visible |
89
        | assign   | Activity sample 1 | Test assignment | C1       | sample1  | 1       | 1       |
90
        | assign   | Activity sample 2 | Test assignment | C1       | sample2  | 1       | 0       |')]
1 efrain 91
    public function the_following_entities_exist($entitytype, TableNode $data) {
92
        if (isset($this->movedentitytypes[$entitytype])) {
93
            $entitytype = $this->movedentitytypes[$entitytype];
94
        }
95
        list($component, $entity) = $this->parse_entity_type($entitytype);
96
        $this->get_instance_for_component($component)->generate_items($entity, $data);
97
    }
98
 
99
    /**
100
     * Create multiple entities of one entity type.
101
     *
102
     * @Given :count :entitytype exist with the following data:
103
     *
104
     * @param   string $entitytype The name of the type entity to add
105
     * @param   int $count
106
     * @param   TableNode $data
107
     */
1441 ariadna 108
    #[\core\attribute\example('And "5" "course enrolments" exist with the following data:
109
        | user   | student[count] |
110
        | course | C1             |
111
        | role   | student        |')]
1 efrain 112
    public function the_following_repeated_entities_exist(string $entitytype, int $count, TableNode $data): void {
113
        $rows = $data->getRowsHash();
114
 
115
        $tabledata = [array_keys($rows)];
116
        for ($current = 1; $current < $count + 1; $current++) {
117
            $rowdata = [];
118
            foreach ($rows as $fieldname => $fieldtemplate) {
119
                $rowdata[$fieldname] = str_replace('[count]', $current, $fieldtemplate);
120
            }
121
            $tabledata[] = $rowdata;
122
        }
123
 
124
        if (isset($this->movedentitytypes[$entitytype])) {
125
            $entitytype = $this->movedentitytypes[$entitytype];
126
        }
127
        list($component, $entity) = $this->parse_entity_type($entitytype);
128
        $this->get_instance_for_component($component)->generate_items($entity, new TableNode($tabledata), false);
129
    }
130
 
131
    /**
132
     * Creates the specified (singular) element.
133
     *
134
     * See the class comment for an overview.
135
     *
136
     * @Given the following :entitytype exists:
137
     *
138
     * @param string    $entitytype The name of the type entity to add
139
     * @param TableNode $data
140
     */
1441 ariadna 141
    #[\core\attribute\example('And the following "course" exists:
142
        | fullname         | Course test |
143
        | shortname        | C1          |
144
        | category         | 0           |
145
        | numsections      | 3           |
146
        | initsections     | 1           |')]
1 efrain 147
    public function the_following_entity_exists($entitytype, TableNode $data) {
148
        if (isset($this->movedentitytypes[$entitytype])) {
149
            $entitytype = $this->movedentitytypes[$entitytype];
150
        }
151
        list($component, $entity) = $this->parse_entity_type($entitytype);
152
        $this->get_instance_for_component($component)->generate_items($entity, $data, true);
153
    }
154
 
155
    /**
156
     * Parse a full entity type like 'users' or 'mod_forum > subscription'.
157
     *
158
     * E.g. parsing 'course' gives ['core', 'course'] and
159
     * parsing 'core_message > message' gives ['core_message', 'message'].
160
     *
161
     * @param string $entitytype the entity type
162
     * @return string[] with two elements, component and entity type.
163
     */
164
    protected function parse_entity_type(string $entitytype): array {
165
        $dividercount = substr_count($entitytype, ' > ');
166
        if ($dividercount === 0) {
167
            return ['core', $entitytype];
168
        } else if ($dividercount === 1) {
169
            list($component, $type) = explode(' > ', $entitytype);
170
            if ($component === 'core') {
171
                throw new coding_exception('Do not specify the component "core > ..." for entity types.');
172
            }
173
            return [$component, $type];
174
        } else {
175
            throw new coding_exception('The entity type must be in the form ' .
176
                    '"{entity-type}" for core entities, or "{component} > {entity-type}" ' .
177
                    'for entities belonging to other components. ' .
178
                    'For example "users" or "mod_forum > subscriptions".');
179
        }
180
    }
181
 
182
    /**
183
     * Get an instance of the appropriate subclass of this class for a given component.
184
     *
185
     * @param string $component The name of the component to generate entities for.
186
     * @return behat_generator_base the subclass of this class for the requested component.
187
     */
188
    protected function get_instance_for_component(string $component): behat_generator_base {
189
        global $CFG;
190
 
191
        // Ensure the generator class is loaded.
192
        require_once($CFG->libdir . '/behat/classes/behat_generator_base.php');
193
        if ($component === 'core') {
194
            $lib = $CFG->libdir . '/behat/classes/behat_core_generator.php';
195
        } else {
196
            $dir = core_component::get_component_directory($component);
197
            $lib = $dir . '/tests/generator/behat_' . $component . '_generator.php';
198
            if (!$dir || !is_readable($lib)) {
199
                throw new coding_exception("Component {$component} does not support " .
200
                        "behat generators yet. Missing {$lib}.");
201
            }
202
        }
203
        require_once($lib);
204
 
205
        // Create an instance.
206
        $componentclass = "behat_{$component}_generator";
207
        if (!class_exists($componentclass)) {
208
            throw new PendingException($component .
209
                    ' does not yet support the Behat data generator mechanism. Class ' .
210
                    $componentclass . ' not found in file ' . $lib . '.');
211
        }
212
        $instance = new $componentclass($component);
213
        return $instance;
214
    }
215
 
216
    /**
217
     * Get all entities that can be created in all components using the_following_entities_exist()
218
     *
219
     * @return array
220
     * @throws coding_exception
221
     */
222
    public function get_all_entities(): array {
223
        global $CFG;
224
        // Ensure the generator class is loaded.
225
        require_once($CFG->libdir . '/behat/classes/behat_generator_base.php');
226
        $componenttypes = core_component::get_component_list();
227
        $coregenerator = $this->get_instance_for_component('core');
228
        $pluginswithentities = ['core' => array_keys($coregenerator->get_available_generators())];
229
        foreach ($componenttypes as $components) {
230
            foreach ($components as $component => $componentdir) {
231
                try {
232
                    $plugingenerator = $this->get_instance_for_component($component);
233
                    $entities = array_keys($plugingenerator->get_available_generators());
234
                    if (!empty($entities)) {
235
                        $pluginswithentities[$component] = $entities;
236
                    }
237
                } catch (Exception $e) {
238
                    // The component has no generator, skip it.
239
                    continue;
240
                }
241
            }
242
        }
243
        return $pluginswithentities;
244
    }
245
 
246
    /**
247
     * Get the required fields for a specific creatable entity.
248
     *
249
     * @param string $entitytype
250
     * @return mixed
251
     * @throws coding_exception
252
     */
253
    public function get_entity(string $entitytype): array {
254
        [$component, $entity] = $this->parse_entity_type($entitytype);
255
        $generator = $this->get_instance_for_component($component);
256
        $entities = $generator->get_available_generators();
257
        if (!array_key_exists($entity, $entities)) {
258
            throw new coding_exception('No generator for ' . $entity . ' in component ' . $component);
259
        }
260
        return $entities[$entity];
261
    }
262
}