Skip to content

Commit

Permalink
Rewrite behat tests to be more efficient.
Browse files Browse the repository at this point in the history
  • Loading branch information
timhunt committed May 23, 2019
1 parent beb035c commit 3e06b7b
Show file tree
Hide file tree
Showing 9 changed files with 331 additions and 169 deletions.
2 changes: 1 addition & 1 deletion addcategory.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@

if ($data = $mform->get_data()) {
if ($isadding) {
$DB->insert_record('report_customsql_categories', $data, true);
$DB->insert_record('report_customsql_categories', $data);
} else {
$updrec = new stdClass();
$updrec->id = $data->id;
Expand Down
2 changes: 1 addition & 1 deletion categoryadd_form.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class report_customsql_addcategory_form extends moodleform {
// Form definition.
public function definition() {
global $CFG, $DB;
$mform =& $this->_form;
$mform = $this->_form;
$categoryid = $this->_customdata['categoryid'];

$editoroptions = array();
Expand Down
13 changes: 6 additions & 7 deletions edit_form.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ public function definition() {

$mform = $this->_form;

$categoryoptions = report_customsql_category_options();
$mform->addElement('select', 'categoryid', get_string('category', 'report_customsql'),
$categoryoptions);
$catdefault = isset($categoryoptions[1]) ? 1 : key($categoryoptions);
$mform->setDefault('categoryid', $catdefault);

$mform->addElement('text', 'displayname', get_string('displayname', 'report_customsql'));
$mform->addRule('displayname', get_string('displaynamerequired', 'report_customsql'),
'required', null, 'client');
Expand Down Expand Up @@ -113,13 +119,6 @@ public function definition() {
$mform->disabledIf('emailwhat', 'runable', 'eq', 'manual');
$mform->setType('emailto', PARAM_RAW);

// Add new category selection.
$categoryoptions = report_customsql_category_options();
$mform->addElement('select', 'categoryid', get_string('selectcategory', 'report_customsql'),
$categoryoptions);
$catdefault = isset($categoryoptions[1]) ? 1 : key($categoryoptions);
$mform->setDefault('categoryid', $catdefault);

$this->add_action_buttons();
}

Expand Down
10 changes: 5 additions & 5 deletions lang/en/report_customsql.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
$string['availablereports'] = 'On-demand queries';
$string['availableto'] = 'Available to {$a}.';
$string['backtoreportlist'] = 'Back to the list of queries';
$string['category'] = 'Category';
$string['categorycontent'] = '({$a->manual} on-demand, {$a->daily} daily, {$a->weekly} weekly, {$a->monthly} monthly)';
$string['categoryexists'] = 'Category names must be unique, this name already exists';
$string['categorynamex'] = 'Category name: {$a}';
Expand All @@ -54,19 +55,19 @@
$string['delete'] = 'Delete';
$string['deleteareyousure'] = 'Are you sure you want to delete this query?';
$string['deletecategoryareyousure'] = '<p>Are you sure you want to delete this category? </p><p>It cannot contain any queries.</p>';
$string['deletecategoryx'] = 'Delete category \'{$a}\'';
$string['deletecategoryyesno'] = '<p>Are you really sure you want to delete this category? </p>';
$string['deletethiscategory'] = 'Delete this category';
$string['deletethisreport'] = 'Delete this query';
$string['deletereportx'] = 'Delete query \'{$a}\'';
$string['description'] = 'Description';
$string['displayname'] = 'Query name';
$string['displaynamex'] = 'Query name: {$a}';
$string['displaynamerequired'] = 'You must enter a query name';
$string['downloadthisreportascsv'] = 'Download these results as CSV';
$string['edit'] = 'Add/Edit';
$string['editcategory'] = 'Update category';
$string['editcategoryx'] = 'Edit category \'{$a}\'';
$string['editingareport'] = 'Editing an ad-hoc database query';
$string['editthiscategory'] = 'Edit this category';
$string['editthisreport'] = 'Edit this query';
$string['editreportx'] = 'Edit query \'{$a}\'';
$string['emailnumberofrows'] = 'Just the number of rows and the link';
$string['emailresults'] = 'Put the results in the email body';
$string['emailink'] = 'To access the report, click this link: {$a}';
Expand Down Expand Up @@ -138,7 +139,6 @@
$string['requireint'] = 'Integer required';
$string['runable'] = 'Run';
$string['runablex'] = 'Run: {$a}';
$string['selectcategory'] = 'Select category for this report';
$string['schedulednote'] = 'These queries are automatically run on the first day of each week or month, to report on the previous week or month. These links let you view the results that has already been accumulated.';
$string['scheduledqueries'] = 'Scheduled queries';
$string['typeofresult'] = 'Type of result';
Expand Down
6 changes: 3 additions & 3 deletions locallib.php
Original file line number Diff line number Diff line change
Expand Up @@ -338,10 +338,10 @@ function report_customsql_print_reports_for($reports, $type) {
$capabilities[$report->capability]),
array('class' => 'admin_note')).' '.
html_writer::tag('a', $imgedit,
array('title' => get_string('editthisreport', 'report_customsql'),
'href' => report_customsql_url('edit.php?id='.$report->id))).' '.
['title' => get_string('editreportx', 'report_customsql', format_string($report->displayname)),
'href' => report_customsql_url('edit.php?id='.$report->id)]) . ' ' .
html_writer::tag('a', $imgdelete,
array('title' => get_string('deletethisreport', 'report_customsql'),
array('title' => get_string('deletereportx', 'report_customsql', format_string($report->displayname)),
'href' => report_customsql_url('delete.php?id='.$report->id)));
}
echo html_writer::end_tag('p');
Expand Down
19 changes: 9 additions & 10 deletions manage.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,19 +44,18 @@
if (!empty($categories)) {
foreach ($categories as $category) {
echo html_writer::start_tag('div');
$imgedit = $OUTPUT->pix_icon('t/edit', get_string('edit'));
echo ' ' . html_writer::tag('span', $category->name . ' ', array('class' => 'report_customsql')) .
html_writer::tag('a', $imgedit,
array('title' => get_string('editthiscategory', 'report_customsql'),

echo ' ' . html_writer::tag('span', format_string($category->name) . ' ', array('class' => 'report_customsql')) .
html_writer::tag('a', $OUTPUT->pix_icon('t/edit', get_string('edit')),
array('title' => get_string('editcategoryx', 'report_customsql', format_string($category->name)),
'href' => report_customsql_url('addcategory.php?id=' . $category->id)));
if ($category->id != 1 &&
!$queries = $DB->get_records('report_customsql_queries',
array('categoryid' => $category->id))) {
$imgdelete = $OUTPUT->pix_icon('t/delete', get_string('delete'));
echo ' ' . html_writer::tag('a', $imgdelete,
array('title' => get_string('deletethiscategory', 'report_customsql'),

if ($category->id != 1 && !$DB->record_exists('report_customsql_queries', ['categoryid' => $category->id])) {
echo ' ' . html_writer::tag('a', $OUTPUT->pix_icon('t/delete', get_string('delete')),
array('title' => get_string('deletecategoryx', 'report_customsql', format_string($category->name)),
'href' => report_customsql_url('categorydelete.php?id=' . $category->id)));
}

echo html_writer::end_tag('div');
}
}
Expand Down
218 changes: 218 additions & 0 deletions tests/behat/behat_report_customsql.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

/**
* Behat steps for the custom SQL report.
*
* All these steps include the phrase 'custom SQL report'.
*
* @package report_customsql
* @copyright 2019 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

// NOTE: no MOODLE_INTERNAL test because this file is required by Behat.

require_once(__DIR__ . '/../../../../lib/behat/behat_base.php');

use Behat\Gherkin\Node\PyStringNode as PyStringNode;
use Behat\Gherkin\Node\TableNode;


/**
* Behat steps for the the custom SQL report.
*
* All these steps include the phrase 'custom SQL report'.
*/
class behat_report_customsql extends behat_base {

/**
* Create a new report in the database.
*
* For example
* Given the following custom sql report exists:
* | name | Test report |
* | querysql | SELECT * FROM {config} |
* | category | Miscellaneous |
*
* if present, category name is looked up in the database to get the id.
* @Given /^the following custom sql report exists:$/
* @param TableNode $data Supplied data
*/
public function the_following_custom_sql_report_exists(TableNode $data) {
global $DB;
$report = $data->getRowsHash();

// Report name.
if (isset($report['name'])) {
$report['displayname'] = $report['name'];
unset($report['name']);
} else {
throw new Exception('A report name must be given.');
}

// Description (defaults to blank).
if (!isset($report['description'])) {
$report['description'] = '';
}
if (!isset($report['descriptionformat'])) {
$report['descriptionformat'] = FORMAT_HTML;
}

// Query SQL.
if (!isset($report['querysql'])) {
throw new Exception('The report SQL must be given as querysql.');
}

// Category.
if (isset($report['category'])) {
$report['categoryid'] = $this->get_category_id_by_name($report['category']);
unset($report['category']);
} else {
$report['categoryid'] = $this->get_category_id_by_name(
get_string('defaultcategory', 'report_customsql'));
}

// Capability.
if (isset($report['capability']) &&
!in_array($report['capability'], report_customsql_capability_options())) {
throw new Exception('Capability ' . $report['capability'] . ' is not a valid choice.');
} else {
$report['capability'] = 'moodle/site:config';
}

// Capability.
if (isset($report['runable']) &&
!in_array($report['runable'], report_customsql_runable_options())) {
throw new Exception('Invalid runable value ' . $report['capability'] . '.');
} else {
$report['runable'] = 'manual';
}

$DB->insert_record('report_customsql_queries', (object) $report);
}

/**
* Create a new report in the database.
*
* For example
* Given the custom sql report "Test report" exists with SQL:
* """
* SELECT *
* FROM {config}
* """
*
* Creates a report in the default category with long SQL.
*
* @Given /^the custom sql report "(?P<REPORT_NAME>[^"]*)" exists with SQL:$/
* @param string $reportname the name of the report to go to.
* @param PyStringNode $querysql The query SQL
*/
public function the_custom_sql_report_x_exists(string $reportname, PyStringNode $querysql) {
global $DB;
$report = [
'displayname' => $reportname,
'description' => '',
'descriptionformat' => FORMAT_HTML,
'querysql' => (string)$querysql,
'categoryid' => $this->get_category_id_by_name(
get_string('defaultcategory', 'report_customsql')),
'capability' => 'moodle/site:config',
'runable' => 'manual',
];

$DB->insert_record('report_customsql_queries', (object) $report);
}

/**
* Create a new report category in the database.
*
* @Given /^the custom sql report category "(?P<CATEGORY_NAME>[^"]*)" exists:$/
* @param string $name the name of the category to create.
*/
public function the_custom_sql_report_cateogry_exists(string $name) {
global $DB;
$DB->insert_record('report_customsql_categories', (object) ['name' => $name]);
}

/**
* Views a report.
*
* Goes straight to the URL $CFG->wwwroot/report/customsql/view.php?id=123
*
* @When /^I view the "(?P<REPORT_NAME>[^"]*)" custom sql report$/
* @param string $reportname the name of the report to go to.
*/
public function i_view_the_x_custom_sql_report(string $reportname) {
$report = $this->get_report_by_name($reportname);
$this->getSession()->visit($this->locate_path('/report/customsql/view.php?id=' . $report->id));
}

/**
* Simulates going directly to a report with certain parameters in the URL.
*
* For example:
* When I view the "Frog" custom sql report with these URL parameters:
* | frogname | freddy |
* | colour | green |
* this goes to the URL $CFG->wwwroot/report/customsql/view.php?id=123&frogname=freddy&colour=green.
*
* @When /^I view the "(?P<REPORT_NAME>[^"]*)" custom sql report with these URL parameters:$/
* @param string $reportname the name of the report to go to.
* @param TableNode $data two columns, name and value, params to add to the URL.
*/
public function i_view_the_x_custom_sql_report_with_these_url_parameters(string $reportname, TableNode $data) {
$report = $this->get_report_by_name($reportname);

$queryparams = ['id=' . $report->id];
foreach ($data->getRows() as $rowdata) {
if (count($rowdata) != 2) {
throw new Exception('Table of params must have two values in each row, query parameter name and value.');
}

$name = clean_param($rowdata[0], PARAM_ALPHANUMEXT);
if ($name !== $rowdata[0]) {
throw new Exception('Parameter names must match PARAM_ALPHANUMEXT.');
}
$queryparams[] = $name . '=' . urlencode($rowdata[1]);
}

$this->getSession()->visit($this->locate_path('/report/customsql/view.php?id=' .
implode('&', $queryparams)));
}

/**
* Find a report by name and get all the details.
*
* @param string $reportname the report name to find.
* @return stdClass the report data
*/
protected function get_report_by_name(string $reportname): stdClass {
global $DB;
return $DB->get_record('report_customsql_queries', ['displayname' => $reportname], '*', MUST_EXIST);
}

/**
* Find a category by name and return its id.
*
* @param string $name the category name to find.
* @return int the category id.
*/
protected function get_category_id_by_name(string $name): int {
global $DB;
return $DB->get_field('report_customsql_categories', 'id', ['name' => $name], MUST_EXIST);
}
}
Loading

0 comments on commit 3e06b7b

Please sign in to comment.