Commit cad79fa6 authored by Abbassy's avatar Abbassy
Browse files

Update plugin to latest code and package

parent 7b9a500c
# Backup files
*.tar.gz
dta_backup_*.tar.gz
# IDE files
.vscode/
.idea/
*.swp
*.swo
*~
# OS files
.DS_Store
Thumbs.db
# Temporary files
*.tmp
*.log
# You can override the included template(s) by including variable overrides
# SAST customization: https://docs.gitlab.com/ee/user/application_security/sast/#customizing-the-sast-settings
# Secret Detection customization: https://docs.gitlab.com/ee/user/application_security/secret_detection/#customizing-settings
# Dependency Scanning customization: https://docs.gitlab.com/ee/user/application_security/dependency_scanning/#customizing-the-dependency-scanning-settings
# Container Scanning customization: https://docs.gitlab.com/ee/user/application_security/container_scanning/#customizing-the-container-scanning-settings
# Note that environment variables can be set in several places
# See https://docs.gitlab.com/ee/ci/variables/#cicd-variable-precedence
# moodle-assignsubmission_dta/.gitlab-ci.yml
stages:
- trigger
trigger_cota_pipeline:
stage: trigger
rules:
- changes:
- dta/**
script:
- apk add --no-cache curl jq bash
- echo "🔄 Detected changes in DTA — triggering CoTA/cota-infra pipeline via API..."
- |
curl -X POST \
-F token=$COTA_INFRA_TRIGGER_TOKEN \
-F ref=master \
https://transfer.hft-stuttgart.de/gitlab/api/v4/projects/645/trigger/pipeline
# Changelog - DTA Plugin v2.1.0
## [v2.1.0] - 2025-10-29
### Added
- **More Details Button**: Replaced magnifying glass icon with modern "More Details" button
- **Colored Test Labels**: Added color-coded labels for test results:
- 🟢 Green for successful tests
- 🟡 Yellow for compilation errors
- 🔴 Red for failed tests
- **Smart Competency Filtering**: Hide competencies with 0% values, only show those with actual progress
- **Enhanced Button Styling**: Button now matches Moodle's "Grade" button style and alignment
- **Robust Parameter Handling**: Improved cmid parameter detection for better reliability
### Fixed
- **File Include Path**: Fixed `DtaResult.php` → `dta_result.php` case sensitivity issue
- **Property Name Mismatch**: Corrected camelCase vs lowercase property names in dta_result class
- **View.php Parameter Handling**: Made cmid optional with intelligent fallback detection
- **German Comments**: Translated all German comments to English for better maintainability
### Improved
- **UI/UX**: Better visual hierarchy and user experience
- **Code Quality**: Cleaner, more maintainable code structure
- **Error Handling**: More robust error handling and fallback mechanisms
- **Performance**: Optimized rendering and caching
### Technical Details
- **Files Modified**:
- `classes/view.php` - Main view logic and parameter handling
- `classes/dta_view_submission_utils.php` - Submission summary generation
- `styles.css` - Enhanced styling and button design
- `locallib.php` - Disabled default magnifying glass
- **Templates**: All Mustache templates remain unchanged
- **Database**: No schema changes required
- **Compatibility**: Fully compatible with existing Moodle installations
### Installation
1. Upload all files to `/mod/assign/submission/dta/`
2. Run `php admin/cli/purge_caches.php`
3. No database upgrade required
### Rollback
To rollback to previous version:
```bash
git checkout v2.0.0
./upload_to_docker.sh
```
---
**Status**: ✅ Production Ready
**Tested**: ✅ All functionality verified
**Documentation**: ✅ Complete
This diff is collapsed.
This diff is collapsed.
No preview for this file type
<?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/>.
/**
* Callback endpoint for receiving test results from the DTA backend.
*
* @package assignsubmission_dta
* @copyright 2023 Your Name
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define('NO_MOODLE_COOKIES', true);
require_once(__DIR__ . '/../../../../config.php');
require_once(__DIR__ . '/classes/dta_db_utils.php');
require_once(__DIR__ . '/classes/models/dta_result_summary.php');
require_once(__DIR__ . '/classes/models/dta_recommendation.php');
// Only accept POST requests.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
// Get the raw POST data.
$json = file_get_contents('php://input');
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON']);
exit;
}
// Extract required parameters.
$assignmentid = isset($data['assignmentId']) ? (int)$data['assignmentId'] : 0;
$submissionid = isset($data['submissionId']) ? (int)$data['submissionId'] : 0;
if ($assignmentid <= 0 || $submissionid <= 0) {
http_response_code(400);
echo json_encode(['error' => 'Missing or invalid assignmentId or submissionId']);
exit;
}
try {
// Decode the response JSON into class instances.
$resultsummary = \assignsubmission_dta\models\dta_result_summary::assignsubmission_dta_decode_json($json);
$recommendations = \assignsubmission_dta\models\dta_recommendation::assignsubmission_dta_decode_json_recommendations($json);
// Store results in database.
\assignsubmission_dta\dta_db_utils::assignsubmission_dta_store_result_summary_to_database(
$assignmentid,
$submissionid,
$resultsummary
);
\assignsubmission_dta\dta_db_utils::assignsubmission_dta_store_recommendations_to_database(
$assignmentid,
$submissionid,
$recommendations
);
http_response_code(200);
echo json_encode(['status' => 'success']);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
<?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/>.
/**
* utility class for DTA submission plugin result display
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
class view_submission_utils {
/**
* Broadly used in logic, parametrized for easier change.
*/
const COMPONENT_NAME = "assignsubmission_dta";
/**
* generates a short summary html
*
* @param int $assignmentid assignment
* @param int $submissionid submission to create a report for
* @return string html
*/
public static function generatesummaryhtml(
int $assignmentid,
int $submissionid
): string {
// Fetch data.
$summary = DbUtils::getResultSummaryFromDatabase($assignmentid, $submissionid);
$html = "";
// Calculate success rate, if no unknown result states or compilation errors.
$successrate = "?";
if ($summary->unknownCount() == 0 && $summary->compilationErrorCount() == 0) {
$successrate = round(($summary->successfulCount() / $summary->resultCount()) * 100, 2 );
}
// Generate html.
$html .= $summary->successfulCount() . "/";
$html .= ($summary->compilationErrorCount() == 0 && $summary->unknownCount() == 0)
? $summary->resultCount() . " (" . $successrate . "%)"
: "?";
$html .= get_string("tests_successful", self::COMPONENT_NAME) . "<br />";
if ($summary->compilationErrorCount() > 0) {
$html .= $summary->compilationErrorCount() . get_string("compilation_errors", self::COMPONENT_NAME) . "<br />";
}
if ($summary->unknownCount() > 0) {
$html .= $summary->unknownCount() . get_string("unknown_state", self::COMPONENT_NAME) . "<br />";
}
$showncompetencies = explode(";", $summary->successfultestcompetencies);
$overallcompetencies = explode(";", $summary->overalltestcompetencies);
$tmp = "";
for ($index = 0, $size = count($showncompetencies); $index < $size; $index++) {
$shown = $showncompetencies[$index];
$comp = $overallcompetencies[$index];
// If the competency was actually assessed by the assignment and tests, add a summary entry.
if ($shown != "0") {
$tmp .= get_string("comp" . $index, self::COMPONENT_NAME) .
" " . 100 * floatval($shown) / floatval($comp) . "% " . "<br />";
}
}
$html .= get_string("success_competencies", self::COMPONENT_NAME) . "<br />" . $tmp . "<br />";
return html_writer::div($html, "dtaSubmissionSummary");
}
/**
* generates detailed view html
*
* @param int $assignmentid assignment
* @param int $submissionid submission to create a report for
*/
public static function generatedetailhtml(
int $assignmentid,
int $submissionid
): string {
// Fetch data.
$summary = DbUtils::getResultSummaryFromDatabase($assignmentid, $submissionid);
$html = "";
// Define a few css classes and prepare html attribute arrays to beautify the output.
$tableheaderrowattributes = ["class" => "dtaTableHeaderRow"];
$tablerowattributes = ["class" => "dtaTableRow"];
$resultrowattributes = $tablerowattributes;
$unknownattributes = 'dtaResultUnknown';
$successattributes = 'dtaResultSuccess';
$failureattributes = 'dtaResultFailure';
$compilationerrorattributes = 'dtaResultCompilationError';
// Summary table.
$tmp = "";
$tmp .= html_writer::tag("th", get_string("summary", self::COMPONENT_NAME), ["class" => "dtaTableHeader"]);
$tmp .= html_writer::empty_tag("th", ["class" => "dtaTableHeader"]);
$header = html_writer::tag("tr", $tmp, $tableheaderrowattributes);
$header = html_writer::tag("thead", $header);
$body = "";
$tmp = "";
$attributes = ["class" => "dtaTableData"];
$tmp .= html_writer::tag(
"td",
get_string("total_items", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$summary->resultCount(),
$attributes);
$resultrowattributes = $tablerowattributes;
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes;
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag("td", get_string("tests_successful", self::COMPONENT_NAME), $attributes);
$tmp .= html_writer::tag( "td", $summary->successfulCount(), $attributes);
$resultrowattributes = $tablerowattributes;
$successrate = "?";
if ($summary->unknownCount() > 0 || $summary->compilationErrorCount() > 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes;
} else {
$successrate = round(($summary->successfulCount() / $summary->resultCount()) * 100, 2 );
if ($successrate < 50) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $compilationerrorattributes;
} else if ($successrate < 75) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $failureattributes;
} else {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes;
}
}
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag("td", get_string("failures", self::COMPONENT_NAME), $attributes);
$tmp .= html_writer::tag("td", $summary->failedCount(), $attributes);
$resultrowattributes = $tablerowattributes;
if ($summary->failedCount() > 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $failureattributes;
} else {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes;
}
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag("td", get_string("compilation_errors", self::COMPONENT_NAME), $attributes);
$tmp .= html_writer::tag("td", $summary->compilationErrorCount(), $attributes);
$resultrowattributes = $tablerowattributes;
if ($summary->compilationErrorCount() > 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $compilationerrorattributes;
} else {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes;
}
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag("td", get_string("unknown_state", self::COMPONENT_NAME), $attributes);
$tmp .= html_writer::tag("td", $summary->unknownCount(), $attributes);
$resultrowattributes = $tablerowattributes;
if ($summary->unknownCount() > 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes;
} else {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes;
}
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag("td", html_writer::tag("b", get_string("success_rate", self::COMPONENT_NAME)), $attributes);
$tmp .= html_writer::tag(
"td",
html_writer::tag("b", $summary->successfulCount()
. "/" . (($summary->compilationErrorCount() == 0 && $summary->unknownCount() == 0) ? $summary->resultCount()
. " (" . $successrate . "%)"
: "?")),
$attributes);
$resultrowattributes = $tablerowattributes;
if ($summary->unknownCount() > 0 || $summary->compilationErrorCount() > 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes;
} else {
if ($successrate < 50) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $compilationerrorattributes;
} else if ($successrate < 75) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $failureattributes;
} else {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes;
}
}
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$body = html_writer::tag("tbody", $body);
$table = html_writer::tag("table", $header . $body, ["class" => "dtaTable"]);
$html .= $table;
// Add empty div for spacing between summary and compentency table.
$html .= html_writer::empty_tag("div", ["class" => "dtaSpacer"]);
// Competency assessment table.
$body = "";
$tmp = "";
$tmp .= html_writer::tag("th", get_string("competencies", self::COMPONENT_NAME), ["class" => "dtaTableHeader"]);
$tmp .= html_writer::empty_tag("th", ["class" => "dtaTableHeader"]);
$header = html_writer::tag("tr", $tmp, $tableheaderrowattributes);
$header = html_writer::tag("thead", $header);
$showncompetencies = explode(";", $summary->successfultestcompetencies);
$overallcompetencies = explode(";", $summary->overalltestcompetencies);
for ($index = 0, $size = count($overallcompetencies); $index < $size; $index++) {
$comp = $overallcompetencies[$index];
$shown = $showncompetencies[$index];
// If the competency was actually assessed by the assignment and tests, add a row in the table.
if ($comp != "0") {
// New copy of base attributes array.
$resultrowattributes = $tablerowattributes;
$tmp = "";
$tmp .= html_writer::tag("td", get_string("comp" . $index, self::COMPONENT_NAME), $resultrowattributes);
$tmp .= html_writer::tag("td", 100 * floatval($shown) / floatval($comp) . "% " .
"(" . $shown . " / " . $comp . ")", $resultrowattributes);
$tmp .= html_writer::tag("td", get_string("comp_expl" . $index, self::COMPONENT_NAME), $resultrowattributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
}
}
$body = html_writer::tag("tbody", $body);
$html .= html_writer::tag("table", $header . $body, ["class" => "dtaTable"]);
// Add empty div for spacing between competency and details table.
$html .= html_writer::empty_tag("div", ["class" => "dtaSpacer"]);
// Details table.
$tmp = "";
$tmp .= html_writer::tag("th", get_string("details", self::COMPONENT_NAME), ["class" => "dtaTableHeader"]);
$tmp .= html_writer::empty_tag("th", ["class" => "dtaTableHeader"]);
$header = html_writer::tag("tr", $tmp, $tableheaderrowattributes);
$header = html_writer::tag("thead", $header);
$body = "";
$spacerrow = null;
foreach ($summary->results as $r) {
// Add spacer first if not null.
if (!is_null($spacerrow)) {
$body .= $spacerrow;
}
// New copy of base attributes array.
$resultrowattributes = $tablerowattributes;
// Check which css class to add for the colored left-border according to resuls state.
if ($r->state == 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultUnknown';
} else if ($r->state == 1) {
$resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultSuccess';
} else if ($r->state == 2) {
$resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultFailure';
} else if ($r->state == 3) {
$resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultCompilationError';
}
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("package_name", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->packagename,
$attributes);
$tmp .= html_writer::tag(
"td",
get_string("unit_name", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->classname,
$attributes);
$tmp .= html_writer::tag(
"td",
get_string("test_name", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->name,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("status", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
DtaResult::getStateName($r->state),
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
// If state is something different than successful, show additional rows.
if ($r->state != 1) {
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("failure_type", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->failureType,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("failure_reason", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->failureReason,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
// Only show line, column and position if they have useful values.
if (!is_null($r->lineNumber) && $r->lineNumber > 0) {
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("line_no", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->lineNumber,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
}
if (!is_null($r->columnNumber) && $r->columnNumber > 0) {
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("col_no", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->columnNumber,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
}
if (!is_null($r->position) && $r->position > 0) {
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("pos", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->position,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
}
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("stacktrace", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
html_writer::tag("details", $r->stacktrace, ["class" => "dtaStacktraceDetails"]),
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
}
// Set spacerrow value if null for next round separation.
if (is_null($spacerrow)) {
$spacerrow = html_writer::empty_tag("tr", ["class" => "dtaTableSpacer"]);
}
}
$html .= html_writer::tag("table", $header . $body, ["class" => "dtaTable"]);
// Wrap generated html into final div.
$html = html_writer::div($html, "dtaSubmissionDetails");
return $html;
}
}
......@@ -194,9 +194,6 @@ class dta_db_utils {
): void {
global $DB;
// Debug output (you can remove or adapt this if unneeded).
debugging('Recommendations array: ' . json_encode($recommendations));
// If recommendations already exist, delete old values beforehand.
$existingrecords = $DB->get_records(
'assignsubmission_dta_recommendations',
......@@ -224,13 +221,8 @@ class dta_db_utils {
$recommendation->assignment_id = $assignmentid;
$recommendation->submission_id = $submissionid;
debugging('Inserting new recommendation record: ' . json_encode($recommendation));
// Insert the recommendation into the database.
$DB->insert_record('assignsubmission_dta_recommendations', $recommendation);
} else {
// Handle the case where $recommendation is not a dta_recommendation instance.
debugging('Invalid recommendation object encountered.');
}
}
}
......
......@@ -74,7 +74,7 @@ class dta_view_submission_utils {
}
// More Details Button - Always show at the top, get cmid from assignment context
global $PAGE, $COURSE;
global $PAGE, $COURSE, $OUTPUT;
// Try multiple methods to get cmid
$cmid = 0;
......@@ -102,7 +102,20 @@ class dta_view_submission_utils {
]);
}
$html .= '<a href="' . $detailurl->out() . '" class="dtaMoreDetailsButton">More Details</a>';
// Use direct button link with same styling as Grade button (blue, full width)
$buttontext = get_string('view_dta_report', self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME);
if (empty($buttontext)) {
$buttontext = 'More Details';
}
// Create a simple link button styled like Moodle's Grade button
$html .= \html_writer::link(
$detailurl,
$buttontext,
array(
'class' => 'btn btn-primary dta-view-report-button',
'style' => 'width: 100%; display: block; text-align: center;'
)
);
// 5) Test results with colored labels
$html .= '<div class="dtaTestResults">';
......@@ -594,7 +607,7 @@ class dta_view_submission_utils {
get_string('failure_type', self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME),
$attributes
);
$tmp .= \html_writer::tag('td', $r->failureType, $attributes);
$tmp .= \html_writer::tag('td', isset($r->failureType) ? $r->failureType : '', $attributes);
$body .= \html_writer::tag('tr', $tmp, $resultrowattributes);
$tmp = '';
......@@ -603,10 +616,10 @@ class dta_view_submission_utils {
get_string('failure_reason', self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME),
$attributes
);
$tmp .= \html_writer::tag('td', $r->failureReason, $attributes);
$tmp .= \html_writer::tag('td', isset($r->failureReason) ? $r->failureReason : '', $attributes);
$body .= \html_writer::tag('tr', $tmp, $resultrowattributes);
if (!is_null($r->lineNumber) && $r->lineNumber > 0) {
if (isset($r->lineNumber) && !is_null($r->lineNumber) && $r->lineNumber > 0) {
$tmp = '';
$tmp .= \html_writer::tag(
'td',
......@@ -617,7 +630,7 @@ class dta_view_submission_utils {
$body .= \html_writer::tag('tr', $tmp, $resultrowattributes);
}
if (!is_null($r->columnNumber) && $r->columnNumber > 0) {
if (isset($r->columnNumber) && !is_null($r->columnNumber) && $r->columnNumber > 0) {
$tmp = '';
$tmp .= \html_writer::tag(
'td',
......@@ -628,7 +641,7 @@ class dta_view_submission_utils {
$body .= \html_writer::tag('tr', $tmp, $resultrowattributes);
}
if (!is_null($r->position) && $r->position > 0) {
if (isset($r->position) && !is_null($r->position) && $r->position > 0) {
$tmp = '';
$tmp .= \html_writer::tag(
'td',
......
......@@ -79,13 +79,6 @@ class grade_summary_helper {
$result['successrate_percent'] = 0.0;
}
// Only set grade to 0 if there are more than 1 compilation errors.
if ($result['compilationerrors'] > 1) {
$result['test_score'] = 0.0;
$result['finalgrade'] = 0.0;
return $result;
}
// Calculate test score (0-100%).
if ($result['totaltests'] > 0) {
$result['test_score'] = ($result['successcount'] / $result['totaltests']) * 100.0;
......@@ -97,10 +90,10 @@ class grade_summary_helper {
$result['competency_percent'] = self::calculate_competency_percent($summary);
$result['has_competencies'] = ($result['competency_percent'] > 0);
// Calculate combined final score: 80% test score + 20% competency score.
// Calculate combined final score: 50% test score + 50% competency score if available.
// If no competencies available, use test score only (weight 1.0).
$test_weight = $result['has_competencies'] ? 0.8 : 1.0;
$competency_weight = $result['has_competencies'] ? 0.2 : 0.0;
$test_weight = $result['has_competencies'] ? 0.5 : 1.0;
$competency_weight = $result['has_competencies'] ? 0.5 : 0.0;
$final_percent = ($test_weight * $result['test_score']) + ($competency_weight * $result['competency_percent']);
......
......@@ -33,6 +33,12 @@ namespace assignsubmission_dta\models;
*/
class dta_recommendation {
/** @var int Assignment ID (for database storage). */
public $assignment_id;
/** @var int Submission ID (for database storage). */
public $submission_id;
/**
* @var string $topic Topic of the recommendation.
*/
......
......@@ -38,16 +38,28 @@ class dta_result {
*/
public const ASSIGNSUBMISSION_DTA_COMPONENT_NAME = 'assignsubmission_dta';
/** @var int Assignment ID (for database storage). */
public $assignment_id;
/** @var int Submission ID (for database storage). */
public $submission_id;
/**
* @var string $packagename Package name of the test.
*/
public $packagename;
/** @var string Package name (snake_case for database storage). */
public $package_name;
/**
* @var string $classname Unit name of the test.
*/
public $classname;
/** @var string Class name (snake_case for database storage). */
public $class_name;
/**
* @var string $name Name of the test.
*/
......@@ -67,11 +79,17 @@ class dta_result {
*/
public $failuretype;
/** @var string Failure type (snake_case for database storage). */
public $failure_type;
/**
* @var string $failurereason Reason of test failure if applicable, empty string otherwise.
*/
public $failurereason;
/** @var string Failure reason (snake_case for database storage). */
public $failure_reason;
/**
* @var string $stacktrace Stack trace of test failure if applicable, empty string otherwise.
*/
......@@ -82,40 +100,22 @@ class dta_result {
*/
public $columnnumber;
/** @var int|string Column number (snake_case for database storage). */
public $column_number;
/**
* @var int|string $linenumber Line number of compile failure if applicable, empty string otherwise.
*/
public $linenumber;
/** @var int|string Line number (snake_case for database storage). */
public $line_number;
/**
* @var int|string $position Position of compile failure if applicable, empty string otherwise.
*/
public $position;
/** @var int Assignment ID (used when storing to database). */
public $assignment_id;
/** @var int Submission ID (used when storing to database). */
public $submission_id;
/** @var string Package name (alternative property name for database). */
public $package_name;
/** @var string Class name (alternative property name for database). */
public $class_name;
/** @var string Failure type (alternative property name for database). */
public $failure_type;
/** @var string Failure reason (alternative property name for database). */
public $failure_reason;
/** @var int|string Column number (alternative property name for database). */
public $column_number;
/** @var int|string Line number (alternative property name for database). */
public $line_number;
/**
* Returns the name of a state with the given number for display.
*
......
......@@ -38,36 +38,36 @@ namespace assignsubmission_dta\models;
*/
class dta_result_summary {
/** @var int Assignment ID (for database storage). */
public $assignment_id;
/** @var int Submission ID (for database storage). */
public $submission_id;
/** @var int Unix timestamp for the summary. */
public $timestamp;
/** @var string A global stacktrace if the entire run had a fatal error (optional). */
public $globalstacktrace;
/** @var string Global stacktrace (snake_case for database storage). */
public $global_stacktrace;
/** @var string Semi-colon-separated numbers for competencies actually passed. */
public $successfultestcompetencies;
/** @var string Successful competencies (snake_case for database storage). */
public $successful_competencies;
/** @var string Semi-colon-separated numbers for total tested competencies. */
public $overalltestcompetencies;
/** @var string Tested competencies (snake_case for database storage). */
public $tested_competencies;
/** @var dta_result[] Array of individual test results. */
public $results;
/** @var int Assignment ID (used when storing to database). */
public $assignment_id;
/** @var int Submission ID (used when storing to database). */
public $submission_id;
/** @var string Global stacktrace (alternative property name for database). */
public $global_stacktrace;
/** @var string Successful competencies (alternative property name for database). */
public $successful_competencies;
/** @var string Tested competencies (alternative property name for database). */
public $tested_competencies;
/**
* Decodes a JSON string into a dta_result_summary object.
*
......
......@@ -135,7 +135,8 @@ class suggestion_grade_summary implements renderable, templatable {
$final_score = 0.0;
if (!empty($summary['has_competencies'])) {
$final_score = ($testscore * 0.8) + ($summary['competency_percent'] * 0.2);
// Give competencies at least 50% weight when present.
$final_score = ($testscore * 0.5) + ($summary['competency_percent'] * 0.5);
} else {
$final_score = $testscore;
}
......
......@@ -110,8 +110,38 @@ echo $OUTPUT->header();
$maxgrade = $assign->get_instance()->grade ?? 100.0;
$gradesummary = grade_summary_helper::calculate_summary($summary, $maxgrade);
// --- Error/empty-state handling aligned with documentation ---
$alertmessages = [];
$rendercards = true;
if (empty($gradesummary['hasdata'])) {
$alertmessages[] = $OUTPUT->notification(
get_string('nodataavailable', 'assignsubmission_dta', null, true) ?: 'No evaluable results available.',
'warning'
);
$rendercards = false;
} else if (($gradesummary['totaltests'] ?? 0) === 0) {
$alertmessages[] = $OUTPUT->notification(
get_string('notestsavailable', 'assignsubmission_dta', null, true) ?: 'No test results available.',
'info'
);
$rendercards = false;
}
if (!empty($gradesummary['unknowncount'])) {
$alertmessages[] = $OUTPUT->notification(get_string('unknownstate_message', 'assignsubmission_dta'), 'info');
}
if (!empty($gradesummary['compilationerrors'])) {
$alertmessages[] = $OUTPUT->notification(get_string('compilationerror_message', 'assignsubmission_dta'), 'error');
}
foreach ($alertmessages as $msg) {
echo $msg;
}
// --- Render Overview Cards and Suggestion Grade Summary in one row ---
if ($summary !== null) {
if ($rendercards && $summary !== null) {
echo '<div class="row">';
echo '<div class="col-md-6">';
echo $OUTPUT->render(new test_summary_cards($gradesummary));
......
<?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/>.
defined('MOODLE_INTERNAL') || die();
$functions = [
'assignsubmission_dta_save_submission' => [
'classname' => 'assignsubmission_dta_external',
'methodname' => 'save_submission',
'classpath' => 'mod/assign/submission/dta/externallib.php',
'description' => 'Save a DTA submission for the given user using a previously uploaded draft itemid and trigger backend processing.',
'type' => 'write',
'ajax' => false,
'services' => [],
],
];
<?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.
defined('MOODLE_INTERNAL') || die();
/**
* Defines the web service parameters for the assignsubmission_dta plugin.
* This allows the standard mod_assign_save_submission function to accept
* the 'tasks_filemanager' parameter for this plugin.
*
* @package assignsubmission_dta
* @copyright 2023 onwards
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$functions = [
// This is our new, dedicated function to save a DTA submission..
// It bypasses the problematic core 'mod_assign_save_submission' function.
'assignsubmission_dta_save_submission' => [
'classname' => 'assign_submission_dta_external',
'methodname' => 'save_submission',
'description' => 'Saves a DTA submission and sends it to the backend.',
'type' => 'write',
'ajax' => true,
]
];
# Moodle Dockerized Test Agent (MoDTA) Plugin
This is the source code repository for the MoDTA plugin. It is an extended and enhanced version of the approved Moodle JUnit Exercise Corrector (MoJEC) plugin, and the Moodle Dockerized Code Testing (MoDoCoT) and Moodle Dockerized Test Tool (Moodle DTT) plugins - for which no approval was requested, which all still run up to Moodle 4.3. MoDTA can thus be considered MoJEC version 4, thought it can test code in any programming language for which a teacher provides a test runner docker image.
The zip archive in the root directory contains the files from the dta directory for easy installation as long as it is unavailable via Moodle Plugins Directory.
## Goals
MoDTA empowers teachers to provide programming Moodle assignments for their students, which are automatically corrected upon hand-in using teacher-provided tests and the results provided as extended submission feedback.
Corrections optionally include a pedagogic agent giving feedback on student competencies and in the next version recommending next exercises based on student competency levels and resilience.
Furthermore, MoDTA optionally provides the errors as tickets in supported ticketing systems to resemble current state-of-the-art software development workflows.
### Motivation
Due to contact time constraints, assignments for a new topic typically include about three tasks (one easy introductory, one standard usage, and one advanced combination with previous topics). Students e.g. stuck at the standard level assignment may face frustration and only little opportunity for qualified feedback. Especially in beginners’ programming education, many students struggle with the way of thinking and at the same time feel reluctant to ask teachers for help.
MoDTA allows for teachers to provide additional assignments at intermediate levels from their typically existing assignment collection. Teachers have to create automated tests for the assignments and place them in a git repository. Afterwards students can practice their skills 24/7 with a less steep learning curve and without having to overcome their potential reluctance to ask a teacher for help. They receive feedback consistent with other assignment results integrated into the Moodle environment.
MoDTA supports beginners not educated in state-of-the-art repository-based workflows by offering hand-ins in a zip archive containing the code to lower the learning curve. It also supports hand-in via repository URL and optionally repository credentials for advanced students.
Optionally, if a teacher provides competency profiles and difficulties for tasks and tests, students also receive feedback about their achieved competencies by a pedagogic agent, which in the next version optionally recommends a learning path to the students based on their resilience.
Furthermore and independent of the other optional features, MoDTA optionally supports a state-of-the-art workflow by placing tickets for compile errors in a student-provided ticketing system link (currently supported: GitLab and Atlassian Jira).
## Overview
The MoDTA system comprises two key components:
• The MoDTA Moodle plugin, designed as an assignment submission tool.
• The DTA backend web service, which interfaces with the Moodle plugin through REST and employs the JSON file format for communication.
The plugin establishes communication with the external DTA backend REST web service offering the endpoints:
• POST /v1/unittest:** This endpoint requires the assignment ID and a text file containing the repository link (see usage below for an example). Optionally, it may include credentials, if the repository is private. Credentials should be formatted as "username:password" or "username:auth-token". Also optionally, the file may contain a link to a ticketing system in a new line of the same format. The results are returned in JSON format.
• POST /v1/tasks:** This API expects the assignment ID and a text file containing a repository link. Similar to the previous endpoint, it can also include an optional line for credentials when dealing with private repositories, using the same "username:password" or "username:auth-token" format. The results are provided in JSON format.
• DELETE /v1/unittest?assignmentId={id}:** Initiates the deletion of test files when provided with the assignment ID as a query parameter.
## Installation & Configuration
After approval, install the plugin directly from the Moodle Plugins Directory via Site Administration/Plugins/Install Plugins.
Before that or alternatively: zip the plugin code from https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/moodledta (here). The readily-zipped current version also sits in the repository’s main directory. Then install the plugin from zip via Site Administration/Plugins/Install Plugins, or by extracting the plugin archive to {Moodle_Root}/mod/assign/submission/dta and visiting the admins notifications page.
Visit Site Administration/Plugins/Plugin Overview and select Settings next to the Moodle Dockerized Test Agent (MoDTA) entry to enter the URI of your backend as shown in Fig. 1. ![Fig. 1: Plugin List](.assets/install_conf_1.png) Finally, configure via Site Administration/Security/HTTP Security settings permitting communication with the backend URI and port as seen in Fig. 2. ![Fig. 2: DTA Configuration Dialog](.assets/install_conf_2.png) The plugin requires the external DTA REST webservice backend.
Notes:
The universal DTA REST webservice backend is available under the GPLv3 as well at https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/dtabackend and the docker image at https://hub.docker.com/r/hftstuttgart/dta-backend . See the documentation in the repository for the necessary setup.
An example JDK 17 JUnit 5 test runner is available under GPLv3 as well at https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/dtatestrunner and the pre-built docker image at https://hub.docker.com/r/hftstuttgart/dta-jdk17-junit5-testrunner . The repository contains an example docker-compose.yaml for tests with a bitnami Moodle and MariaDB setup and the backend.
## Usage
With the MoDTA plugin installed and configured backend URI (including Moodle Security/HTTP Security settings permitting communication with that URI):
### Teacher
When creating an assignment, a teacher can select the MoDTA exercise as a new assignment type via an additional checkbox on the assignment creation page as shown at the bottom of Fig. 3. ![Fig. 3: Moodle DTA Activation Checkbox](.assets/usage_teacher_1.png) A new standard file upload field appears as indicated in Fig. 4. ![Fig. 4: Moodle DTA Upload File Area](.assets/usage_teacher_2.png). There, the teacher must upload a text file with the git repository URI containing the tests as shown in Fig. 5. ![Fig. 5: Moodle DTA Teacher Text File Upload](.assets/usage_teacher_3.png) The text file has to adhere to the following format also given in the example repository:
The text file has to contain the following, each separated by ::
- dtt as the URI-type
- \<git https repository URI>
- \<git user name or the fixed string “none” for publicly accessible repositories>
- \<git password for the given user, git read access token for the repository, or the fixed string “none” for publicly accessible repositories>
- \<docker hub image for the test runner>
- optionally, an additional line of the same structure containing a ticketing system URI, user name and password or write access token
An example text file content looks like this:
dtt::https://transfer.hft-stuttgart.de/gitlab/dtt/example_openjdk11-junit5-calculator-test.git::none::none::hftstuttgart/dta-jdk17-junit5-testrunner:latest
Students use the same format, just without the runner part at the end.
### Student
Students use an additional MoDTA standard file upload field in the standard submission processs in Moodle like in Fig. 6. [Fig. 6: Moodle DTA Student File Upload](.assets/usage_student_1.png) There, they place either a zip archive or a text file adhering to the same format as the teacher’s file with their code repository URI and optionally credentials and/or a ticketing system URI as shown in Fig. 7. ![Fig. 7: Moodle DTA Student Text File Upload](.assets/usage_student_2.png)
Upon completion, students see a summarized overview of their test results in an additional column of the submission feedback table like in Fig. 8. ![Fig. 8: Moodle DTA Submission Result Summay](.assets/usage_student_3.png) Clicking on a new expansion icon in that column, they reach a detailed feedback dialog including stack traces of compile errors and test failures as in Fig. 9. ![Fig. 9: Moodle DTA Student Detail Result View](.assets/usage_student_4.png) Optionally, the MoDTA backend creates tickets for compile failures in the ticketing system under the URI provided by the student upon hand-in.
Note: Teachers have access to the Moodle submission result view to assess student results. However, teacher control and grading are not the focus of MoDTA.
### Technical Workflow
Assignment creation: The backend creates a temporary directory and checks out the test code from the given repository to that directory's subdirectory test. If the repository contains a file test-competencies.mft in its root directory with a structure described in the backend documentation, this enables the optional competency feedback.
Assignment submission: The MoDTA plugin passes the submission id and submitted text or zip file – no personal teacher student data – to the external DTA backend REST web service. The DTA backend REST web service fetches or extracts the code to the temporary directory's subdirectory src. It launches via docker a dedicated test runner based on the docker image provided in the teacher’s text file. This test runner compiles and executes the code, running the teacher-defined tests to evaluate the students' submission.
The runner returns the result in a file named result.json in the temporary directory's subdirectory result. The backend optionally enriches the result with competency feedback. It then returns the json result structure to the MoDTA moodle plugin. The MoDTA moodle plugin adds a new column to the submission result table and shows a result summary as well as an + button. Clicking on the + button, the student sees the detailed test results and, optionally, competency feedback.
## Plugin Detail Documentation – MoDTA Assignment Submission Plugin
The assignment submission plugin type was the most suitable choice with assignment feedback as another related option. It empowers you to present customized form fields to students during the assignment submission process and to teachers when configuring assignment settings. Moreover, it grants complete control over how submitted assignments are displayed to both graders and students.
The primary features of this plugin type include the ability to:
• Integrate additional settings into the module settings page for assignments.
• Provide a summary of the submission to students and teachers.
• Incorporate form fields into the student submission page for added flexibility and customization.
### File Structure
To ensure proper organization, all files related to the MoDTA assignment submission plugin reside in the directory path "mod/assign/submission/dta" within {Moodle_Root}.
### Language
The language files for our plugin are found under "lang/<country_code>/assignsubmission_dta.php." These files are organized into different subfolders depending on the language to be supported. For instance:
- English: "lang/en/assignsubmission_dta.php"
The filename corresponds to the component name of the plugin, structured as <plugintype>_<pluginname>, which, in our case, is "assignsubmission_dta." The repository delivers only English as requested by the Moodle team.
Each language file contains various key-value entries formatted as $string["key"] = "Value," with the key provided in English as the most widespread language remaining consistent across different language files, while the value varies according to the chosen language. Moodle incorporates a dedicated String API used In the plugin as required In the approval guidelines, allowing for easy value retrieval based on a given key and the selected language (e.g., get_string("key", "default value")).
### version.php
This file provides version information about the plugin to manage installation and upgrades.
### settings.php
The settings file defines two settings for the MoDTA plugin:
1. Default: This setting offers a checkbox to determine whether the plugin should be enabled by default when creating a new assignment.
2. Web Service Base URL: It features a text field where you can specify the base URL for the web service, facilitating file communication and actual testing.
### db/upgrade.php
This file is currently empty, as the data structure for the plugin has not changed so far.
### db/install.xml
This file defines the necessary database tables and rows for storing data associated with the MoDTA plugin. Moodle offers a specialized XML schema designed for modeling this information, featuring elements like TABLENAME, FIELDS, and KEY. The plugin utilizes two additional tables for cleanliness not to alter moodle standard tables:
assignsubmission_dta_summary which is related 1:1 to the submission and uses the assignment_id and submission_id as foreign keys, and assignsubmission_dta_result which stores the results of a submission as a 1:n relation to the assignsubmission_dta_summary. Whenever a new MoDTA assignment is submitted, the backend web service is engaged, returning one or more test results or compilation errors in the form of a JSON string. The front end parses this JSON string for the result summary and results and stores them in the appropriate tables.
### locallib.php
This is where all the functionality for this plugin is defined. All submission plugins must define a class with the component name of the plugin that extends assign_submission_plugin .
That yields the following class hierarchy:
The "assign_submission_plugin" class serves as an abstract foundation that all assignment submission plugins must build upon. It incorporates a limited set of supplementary functions tailored exclusively to submission plugins. On the other hand, the "assign_plugin" class is also an abstract class, but it functions as the fundamental class for all assignment plugins, encompassing both feedback and submission plugins. This class facilitates access to the assignment instance, represented as "$this->assignment." Collectively, these two classes offer a series of public functions, often referred to as "hooks," which are designed to be overridden to implement the required functionality.
The following provides brief descriptions of a selection of functions to illustrate the types of hooks available:
• assignsubmission_dta_get_settings(): This function comes into play during the creation of the assignment settings page. For the MoDTA plugin, this involves adding a file manager that permits teachers to upload their test repo and docker Image URI as a textfile. This function is overridden from the assign_plugin class.
• assignsubmission_dta_save_settings(): The assignsubmission_dta_save_settings function is invoked when the assignment settings page is submitted, whether for a new assignment or the modification of an existing one. In the MoDTA plugin, this function is responsible for preserving the text file chosen by the teacher and transmitting the file to the backend web service. Like the previous function, this one is overridden from the assign_plugin class.
• get_form_elements_for_user(): During the construction of the submission form, this function plays a similar role to the assignsubmission_dta_get_settings() function for settings. In the context of the MoDTA plugin, it adds a file manager to enable students to upload their text or zip file. Once again, this function is overridden from the assign_plugin class.
• save():This function is invoked to save a user's submission. Within the MoDTA plugin, this function sends the student's submission to the backend and receives the result as the response. For details see the technical details section above.
• view_summary(): This function is called to display a summary of the submission to both teachers and students. For the students, this summary will be shown within the submission status table and for the teachers within a column of the grading table. In the MoDTA plugin this method returns a more compact view (only essential data) for the grading table and a detailed view for the students submission status table.
### lib.php
This file serves as the gateway to various standard Moodle APIs designed for plugins. In the content of the MoDTA plugin, this function is denoted as "assignsubmission_dta_pluginfile."
### util folder
The folder contains various utility files, e.g. displaying the new test summary pages is delegated from the locallib.php for brevity of that source.
<?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/>.
/**
* This file contains the backend webservice contact functionality for the DTA plugin
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
/**
* backend webservice contact utility class
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
class DtaBackendUtils {
/**
* Returns the base url of the backend webservice as configured in the administration settings.
* @return string backend host base url
*/
private static function getbackendbaseurl(): string {
$backendaddress = get_config(assign_submission_dta::COMPONENT_NAME, "backendHost");
if (empty($backendaddress)) {
\core\notification::error(get_string("backendHost_not_set", assign_submission_dta::COMPONENT_NAME));
}
return $backendaddress;
}
/**
* Sends the configuration textfile uploaded by prof to the backend.
*
* @param stdClass $assignment assignment this test-config belongs to
* @param stdClass $file uploaded test-config
* @return bool true if no error occurred
*/
public static function sendtestconfigtobackend($assignment, $file): bool {
$backendaddress = self::getbackendbaseurl();
if (empty($backendaddress)) {
return true;
}
// Set endpoint for test upload.
$url = $backendaddress . "/v1/unittest";
// Prepare params.
$params = [
"unitTestFile" => $file,
"assignmentId" => $assignment->get_instance()->id,
];
// If request returned null, return false to indicate failure.
if (is_null(self::post($url, $params))) {
return false;
} else {
return true;
}
}
/**
* Sends submission config or archive to backend to be tested.
*
* @param stdClass $assignment assignment for the submission
* @param int $submissionid submissionid of the current file
* @param stdClass $file submission config file or archive with submission
* @return string json string with testresults or null on error
*/
public static function sendsubmissiontobackend($assignment, $submissionid, $file): ?string {
$backendaddress = self::getbackendbaseurl();
if (empty($backendaddress)) {
return true;
}
// Set endpoint for test upload.
$url = $backendaddress . "/v1/task/" . $submissionid;
// Prepare params.
$params = [
"taskFile" => $file,
"assignmentId" => $assignment->get_instance()->id,
];
return self::post($url, $params);
}
/**
* Posts the given params to the given url and returns the response as a string.
* @param string $url full url to request to
* @param array $params parameters for http-request
*
* @return string received body on success or null on error
*/
private static function post($url, $params): ?string {
if (!isset($url) || !isset($params)) {
return false;
}
$options = ["CURLOPT_RETURNTRANSFER" => true];
$curl = new curl();
$response = $curl->post($url, $params, $options);
// Check state of request, if response code is a 2xx return the answer.
$info = $curl->get_info();
if ($info["http_code"] >= 200 && $info["http_code"] < 300) {
return $response;
}
// Something went wrong, return null and give an error message.
debugging(assign_submission_dta::COMPONENT_NAME . ": Post file to server was not successful: http_code=" .
$info["http_code"]);
if ($info['http_code'] >= 400 && $info['http_code'] < 500) {
\core\notification::error(get_string("http_client_error_msg", assign_submission_dta::COMPONENT_NAME));
return null;
} else if ($info['http_code'] >= 500 && $info['http_code'] < 600) {
\core\notification::error(get_string("http_server_error_msg", assign_submission_dta::COMPONENT_NAME));
return null;
} else {
\core\notification::error(get_string("http_unknown_error_msg", assign_submission_dta::COMPONENT_NAME) .
$info["http_code"] . $response);
return null;
}
}
}
<?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/>.
/**
* persistence layer utility class
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
class DbUtils {
/**
* Summary database table name.
*/
private const TABLE_SUMMARY = "assignsubmission_dta_summary";
/**
* Result database table name.
*/
private const TABLE_RESULT = "assignsubmission_dta_result";
/**
* gets summary with all corresponding result entries
*
* @param int $assignmentid assignment id to search for
* @param int $submissionid submission id to search for
* @return DttResultSummary representing given submission
*/
public static function getresultsummaryfromdatabase(
int $assignmentid,
int $submissionid
): DtaResultSummary {
global $DB;
// Fetch data from database.
$summaryrecord = $DB->get_record(self::TABLE_SUMMARY, [
"assignment_id" => $assignmentid,
"submission_id" => $submissionid,
]);
$resultsarray = $DB->get_records(self::TABLE_RESULT, [
"assignment_id" => $assignmentid,
"submission_id" => $submissionid,
]);
// Create a summary instance.
$summary = new DtaResultSummary();
$summary->timestamp = $summaryrecord->timestamp;
$summary->globalstacktrace = $summaryrecord->global_stacktrace;
$summary->successfultestcompetencies = $summaryrecord->successful_competencies;
$summary->overalltestcompetencies = $summaryrecord->tested_competencies;
$summary->results = [];
// Create result instances and add to array of summary instance.
foreach ($resultsarray as $rr) {
$result = new DtaResult();
$result->packagename = $rr->package_name;
$result->classname = $rr->class_name;
$result->name = $rr->name;
$result->state = $rr->state;
$result->failuretype = $rr->failure_type;
$result->failurereason = $rr->failure_reason;
$result->stacktrace = $rr->stacktrace;
$result->columnnumber = $rr->column_number;
$result->linenumber = $rr->line_number;
$result->position = $rr->position;
$summary->results[] = $result;
}
return $summary;
}
/**
* save given result summary and single results to database
* under given assignment and submission id
*
* @param int $assignmentid assigment this is submission is linked to
* @param int $submissionid submission of this result
* @param DtaResultSummary $summary instance to persist
*/
public static function storeresultsummarytodatabase(
int $assignmentid,
int $submissionid,
DtaResultSummary $summary
): void {
global $DB;
// Prepare new database entries.
$summaryrecord = new stdClass();
$summaryrecord->assignment_id = $assignmentid;
$summaryrecord->submission_id = $submissionid;
$summaryrecord->timestamp = $summary->timestamp;
$summaryrecord->global_stacktrace = $summary->globalstacktrace;
$summaryrecord->successful_competencies = $summary->successfultestcompetencies;
$summaryrecord->tested_competencies = $summary->overalltestcompetencies;
// Prepare results to persist to array.
$resultrecords = [];
foreach ($summary->results as $r) {
$record = new stdClass();
$record->assignment_id = $assignmentid;
$record->submission_id = $submissionid;
$record->package_name = $r->packagename;
$record->class_name = $r->classname;
$record->name = $r->name;
$record->state = $r->state;
$record->failure_type = $r->failuretype;
$record->failure_reason = $r->failurereason;
$record->stacktrace = $r->stacktrace;
$record->column_number = $r->columnnumber;
$record->line_number = $r->linenumber;
$record->position = $r->position;
$resultrecords[] = $record;
}
// If results already exist, delete old values beforehand.
$submission = $DB->get_record(self::TABLE_SUMMARY, [
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]);
if ($submission) {
$DB->delete_records(self::TABLE_RESULT, [
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]);
$DB->delete_records(self::TABLE_SUMMARY, [
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]);
}
// Create summary and single result entries.
$DB->insert_record(self::TABLE_SUMMARY, $summaryrecord);
foreach ($resultrecords as $rr) {
$DB->insert_record(self::TABLE_RESULT, $rr);
}
}
/**
* cleans up database if plugin is uninstalled
*/
public static function uninstallplugincleaup(): void {
global $DB;
$DB->delete_records(self::TABLE_RESULT, null);
$DB->delete_records(self::TABLE_SUMMARY, null);
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment