Skip to content

Commit c18e3c5

Browse files
committed
started integrating opt-testcases.ts into opt-frontend.ts, ergh!
1 parent a905b11 commit c18e3c5

3 files changed

Lines changed: 310 additions & 26 deletions

File tree

‎v5-unity/js/opt-frontend.ts‎

Lines changed: 308 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,8 @@ import {AbstractBaseFrontend, generateUUID, supports_html5_storage} from './opt-
5757
var pytutor = require('./pytutor.ts');
5858
var assert = pytutor.assert;
5959

60-
var optTests = require('./opt-testcases.ts');
61-
6260
require('../css/opt-frontend.css');
61+
require('../css/opt-testcases.css');
6362

6463

6564
const JAVA_BLANK_TEMPLATE = 'public class YourClassNameHere {\n\
@@ -76,6 +75,27 @@ const CPP_BLANK_TEMPLATE = 'int main() {\n\
7675
const CODE_SNAPSHOT_DEBOUNCE_MS = 1000;
7776
const SUBMIT_UPDATE_HISTORY_INTERVAL_MS = 1000 * 60;
7877

78+
const redSadFace = require('./images/red-sad-face.jpg');
79+
const yellowHappyFace = require('./images/yellow-happy-face.jpg');
80+
81+
const testcasesPaneHtml = '\
82+
<table id="testCasesTable">\
83+
<thead>\
84+
<tr>\
85+
<td style="width: 310px">Tests</td>\
86+
<td><button id="runAllTestsButton" type="button">Run All Tests</button></td>\
87+
<td>Results</td>\
88+
<td></td>\
89+
<td></td>\
90+
</tr>\
91+
</thead>\
92+
<tbody>\
93+
</tbody>\
94+
</table>\
95+
\
96+
<a href="#" id="addNewTestCase">Add new test</a>\
97+
'
98+
7999

80100
var optFrontend; // singleton OptFrontend object
81101

@@ -107,17 +127,11 @@ class OptFrontend extends AbstractBaseFrontend {
107127
originFrontendJsFile: string = 'opt-frontend.js';
108128
pyInputAceEditor; // Ace editor object that contains the user's code
109129

110-
appStateAugmenter: (appState: any) => void;
111-
loadTestCases: (testCasesLst: any[]) => void;
112-
113130
prevExecutionExceptionObjLst = []; // previous consecutive executions with "compile"-time exceptions
114131

115132
constructor(params) {
116133
super(params);
117134

118-
this.appStateAugmenter = optTests.appStateAugmenter;
119-
this.loadTestCases = optTests.loadTestcasesIntoPane;
120-
121135
this.initAceEditor(420);
122136
this.pyInputAceEditor.getSession().on("change", (e) => {
123137
// unfortunately, Ace doesn't detect whether a change was caused
@@ -710,6 +724,8 @@ class OptFrontend extends AbstractBaseFrontend {
710724
return false; // to prevent default "a href" click action
711725
}
712726

727+
appStateAugmenter(x) { }; // NOP for now
728+
713729
// get the ENTIRE current state of the app
714730
getAppState() {
715731
assert(this.originFrontendJsFile);
@@ -739,11 +755,8 @@ class OptFrontend extends AbstractBaseFrontend {
739755
if (ret.curInstr === undefined)
740756
delete ret.curInstr;
741757

742-
// different frontends can optionally AUGMENT the app state with
743-
// custom fields
744-
if (this.appStateAugmenter) {
745-
this.appStateAugmenter(ret);
746-
}
758+
// frontends can optionally AUGMENT the app state with custom fields
759+
this.appStateAugmenter(ret);
747760
return ret;
748761
}
749762

@@ -788,10 +801,6 @@ class OptFrontend extends AbstractBaseFrontend {
788801
codeopticonUsername = queryStrOptions.codeopticonUsername; // GLOBAL defined in codeopticon-learner.js
789802
}
790803

791-
if (queryStrOptions.testCasesLst && this.loadTestCases) {
792-
this.loadTestCases(queryStrOptions.testCasesLst);
793-
}
794-
795804
if ((queryStrOptions.appMode == 'display' ||
796805
queryStrOptions.appMode == 'visualize' /* deprecated */) &&
797806
queryStrOptions.preseededCode /* jump to 'display' mode only with preseeded code */) {
@@ -803,6 +812,288 @@ class OptFrontend extends AbstractBaseFrontend {
803812
} // END class OptFrontend
804813

805814

815+
// Like OptFrontend but augmented with an "add test cases" pane
816+
class OptFrontendWithTestcases extends OptFrontend {
817+
curTestcaseId: number = 1;
818+
819+
constructor(params) {
820+
super(params);
821+
this.initTestcasesPane();
822+
}
823+
824+
parseQueryString() {
825+
var queryStrOptions = this.getQueryStringOptions();
826+
if (queryStrOptions.testCasesLst) {
827+
this.loadTestCases(queryStrOptions.testCasesLst);
828+
}
829+
super.parseQueryString();
830+
}
831+
832+
initTestcasesPane(onChangeCallback=null /* optional */) {
833+
var _me = this;
834+
$("#testCasesParent")
835+
.empty() // just to be paranoid, empty this out (and its event handlers, too, supposedly)
836+
.append('<p style="margin-top: 25px;"><a href="#" id="createTestsLink">Create test cases</a></p><div id="testCasesPane"></div>');
837+
838+
$("#testCasesParent #createTestsLink").click(function() {
839+
_me.initTestcasesPane();
840+
$(this).hide();
841+
return false;
842+
});
843+
844+
$("#testCasesParent #testCasesPane")
845+
.empty() // just to be paranoid, empty this out (and its event handlers, too, supposedly)
846+
.html(testcasesPaneHtml);
847+
848+
$("#addNewTestCase").click(function() {
849+
_me.addTestcase(null, onChangeCallback);
850+
return false; // to prevent link from being followed
851+
});
852+
853+
$("#runAllTestsButton").click(function() {
854+
$(".runTestCase").click();
855+
});
856+
}
857+
858+
loadTestCases(lst: string[]) {
859+
var _me = this;
860+
$("#createTestsLink").hide();
861+
this.initTestcasesPane();
862+
lst.forEach(function(e) {
863+
_me.addTestcase(e);
864+
});
865+
}
866+
867+
addTestcase(initialCod /* optional code to pre-seed this test */,
868+
onChangeCallback=null /* to be called if this elt changes */) {
869+
var _me = this;
870+
871+
var id = this.curTestcaseId;
872+
this.curTestcaseId++;
873+
var newTr = $('<tr/>').attr('id', 'testCaseRow_' + id);
874+
$("#testCasesParent #testCasesTable tbody").append(newTr);
875+
var editorTd = $('<td/>');
876+
var runBtnTd = $('<td/>');
877+
var outputTd = $('<td/>');
878+
var visualizeTd = $('<td/>');
879+
var deleteTd = $('<td/>');
880+
881+
editorTd.append('<div id="testCaseEditor_' + id + '" class="testCaseEditor">');
882+
runBtnTd.append('<button id="runTestCase_' + id + '" class="runTestCase" type="button">Run</button>');
883+
outputTd.attr('id', 'outputTd_' + id);
884+
outputTd.attr('class', 'outputTd');
885+
visualizeTd.append('<button id="vizTestCase_' + id + '" class="vizTestCase" type="button">Visualize</button>');
886+
deleteTd.append('<a id="delTestCase_' + id + '" href="javascript:void(0);">Delete test</a></td>');
887+
888+
newTr.append(editorTd);
889+
newTr.append(runBtnTd);
890+
newTr.append(outputTd);
891+
newTr.append(visualizeTd);
892+
newTr.append(deleteTd);
893+
894+
// initialize testCaseEditor with Ace:
895+
var te = ace.edit('testCaseEditor_' + id);
896+
// set the size and value ASAP to get alignment working well ...
897+
te.setOptions({minLines: 2, maxLines: 4}); // keep this SMALL
898+
te.setHighlightActiveLine(false);
899+
te.setShowPrintMargin(false);
900+
te.setBehavioursEnabled(false);
901+
te.setFontSize('11px');
902+
te.$blockScrolling = Infinity; // kludgy to shut up weird warnings
903+
904+
var s = te.getSession();
905+
s.setTabSize(2);
906+
s.setUseSoftTabs(true);
907+
// disable extraneous indicators:
908+
s.setFoldStyle('manual'); // no code folding indicators
909+
// don't do real-time syntax checks:
910+
// https://github.com/ajaxorg/ace/wiki/Syntax-validation
911+
s.setOption("useWorker", false);
912+
913+
// TODO: change syntax highlighting mode if the user changes languages:
914+
var lang = $('#pythonVersionSelector').val();
915+
var mod = 'python';
916+
var defaultVal = '\n# assert <test condition>';
917+
if (lang === 'java') {
918+
mod = 'java';
919+
defaultVal = '// sorry, Java tests not yet supported';
920+
} else if (lang === 'c' || lang === 'cpp') {
921+
mod = 'c_cpp';
922+
defaultVal = '// sorry, C/C++ tests not yet supported';
923+
} else if (lang === 'js') {
924+
mod = 'javascript';
925+
defaultVal = '\n// console.assert(<test condition>);';
926+
} else if (lang === 'ts') {
927+
mod = 'typescript';
928+
defaultVal = '\n// console.assert(<test condition>);';
929+
} else if (lang === 'ruby') {
930+
mod = 'ruby';
931+
defaultVal = "\n# raise 'fail' unless <test condition>";
932+
}
933+
s.setMode("ace/mode/" + mod);
934+
935+
// detect when the buffer has changed
936+
s.on("change", function() {
937+
if (onChangeCallback) {
938+
onChangeCallback();
939+
}
940+
});
941+
942+
te.setValue(initialCod ? initialCod.rtrim() : defaultVal,
943+
-1 /* do NOT select after setting text */);
944+
te.focus();
945+
946+
function runOrVizTestCase(isViz /* true for visualize, false for run */) {
947+
if (isViz) {
948+
$('#vizTestCase_' + id).html("Visualizing ...");
949+
} else {
950+
$('#runTestCase_' + id).html("Running ...");
951+
}
952+
953+
$("#runAllTestsButton,.runTestCase,.vizTestCase").attr('disabled', true);
954+
var e = ace.edit('testCaseEditor_' + id);
955+
e.getSession().clearAnnotations();
956+
$('#outputTd_' + id).html('');
957+
958+
var dat = _me.getCombinedCode(id);
959+
960+
// adapted from executeCode in opt-frontend.js
961+
var backendOptionsObj = _me.getBaseBackendOptionsObj();
962+
var frontendOptionsObj = _me.getBaseFrontendOptionsObj();
963+
(frontendOptionsObj as any).jumpToEnd = true;
964+
965+
if (isViz) {
966+
(backendOptionsObj as any).viz_test_case = true; // just so we can see this in server logs
967+
//this.activateSyntaxErrorSurvey = false; // disable survey when running test cases since it gets confusing
968+
} else {
969+
(backendOptionsObj as any).run_test_case = true; // just so we can see this in server logs
970+
(frontendOptionsObj as any).runTestCaseCallback = function(trace) {
971+
// scan through the trace to find any exception events. report
972+
// the first one if found, otherwise assume test is 'passed'
973+
var exceptionMsg = null;
974+
trace.forEach(function(e) {
975+
if (exceptionMsg) {
976+
return;
977+
}
978+
979+
if (e.event === 'exception') {
980+
exceptionMsg = e.exception_msg;
981+
}
982+
});
983+
984+
if (exceptionMsg) {
985+
$('#outputTd_' + id).html('<img src="' + redSadFace + '"></img>');
986+
} else {
987+
$('#outputTd_' + id).html('<img src="' + yellowHappyFace + '"></img>');
988+
}
989+
};
990+
}
991+
992+
function runTestHandleUncaughtExceptionFunc(trace) {
993+
if (trace.length == 1 && trace[0].line) {
994+
var errorLineNo = trace[0].line;
995+
// highlight the faulting line in the test case pane itself
996+
if (errorLineNo !== undefined &&
997+
errorLineNo != NaN &&
998+
errorLineNo >= dat.firstTestLine) {
999+
var adjustedErrorLineNo = errorLineNo - dat.firstTestLine;
1000+
s.setAnnotations([{row: adjustedErrorLineNo,
1001+
column: null, /* for TS typechecking */
1002+
type: 'error',
1003+
text: trace[0].exception_msg}]);
1004+
te.gotoLine(adjustedErrorLineNo + 1 /* one-indexed */);
1005+
}
1006+
}
1007+
1008+
var msg = trace[0].exception_msg;
1009+
var trimmedMsg = msg.split(':')[0];
1010+
$('#outputTd_' + id).html(pytutor.htmlspecialchars(trimmedMsg));
1011+
1012+
optCommon.handleUncaughtExceptionFunc(trace);
1013+
doneRunningTest();
1014+
}
1015+
}
1016+
1017+
this.executeCodeAndCreateViz(dat.cod,
1018+
$('#pythonVersionSelector').val(),
1019+
backendOptionsObj,
1020+
frontendOptionsObj,
1021+
'pyOutputPane');
1022+
/*
1023+
isViz ? vizTestFinishSuccessfulExecution :
1024+
runTestFinishSuccessfulExecution,
1025+
runTestHandleUncaughtExceptionFunc);
1026+
*/
1027+
1028+
$('#runTestCase_' + id).click(runOrVizTestCase.bind(this, false));
1029+
$('#vizTestCase_' + id).click(runOrVizTestCase.bind(this, true));
1030+
1031+
$('#delTestCase_' + id).click(function() {
1032+
$('#testCaseRow_' + id).remove();
1033+
if (onChangeCallback) {
1034+
onChangeCallback();
1035+
}
1036+
return false; // to prevent link from being followed
1037+
});
1038+
1039+
if (onChangeCallback) {
1040+
onChangeCallback();
1041+
}
1042+
}
1043+
1044+
/*
1045+
doneRunningTest() {
1046+
$("#runAllTestsButton,.runTestCase,.vizTestCase").attr('disabled', false);
1047+
$(".runTestCase").html('Run');
1048+
$(".vizTestCase").html('Visualize');
1049+
}
1050+
1051+
finishSuccessfulExecution() {
1052+
if (this.isViz) {
1053+
super.optFinishSuccessfulExecution();
1054+
}
1055+
doneRunningTest();
1056+
}
1057+
*/
1058+
1059+
getCombinedCode(id) {
1060+
var userCod = this.pyInputGetValue();
1061+
var testCod = ace.edit('testCaseEditor_' + id).getValue();
1062+
// for reporting syntax errors separately for user and test code
1063+
var userCodNumLines = userCod.split('\n').length;
1064+
1065+
var lang = $('#pythonVersionSelector').val();
1066+
if (lang === 'ts' || lang === 'js' || lang === 'java' || lang === 'c' || lang === 'cpp') {
1067+
var bufferCod = '\n\n// Test code //\n';
1068+
} else {
1069+
var bufferCod = '\n\n## Test code ##\n';
1070+
}
1071+
1072+
var bufferCodNumLines = bufferCod.split('\n').length;
1073+
1074+
var combinedCod = userCod + bufferCod + testCod;
1075+
return {cod: combinedCod,
1076+
firstTestLine: userCodNumLines + bufferCodNumLines - 1};
1077+
}
1078+
1079+
appStateAugmenter(appState) {
1080+
// returns a list of strings, each of which is a test case
1081+
function getAllTestcases() {
1082+
return $.map($("#testCasesParent #testCasesTable .testCaseEditor"), function(e) {
1083+
var editor = ace.edit($(e).attr('id'));
1084+
return editor.getValue();
1085+
});
1086+
}
1087+
1088+
var tc = getAllTestcases();
1089+
if (tc.length > 0) {
1090+
appState['testCasesJSON'] = JSON.stringify(tc);
1091+
}
1092+
}
1093+
1094+
} // END class OptFrontendWithTestcases
1095+
1096+
8061097
var JS_EXAMPLES = {
8071098
jsFactExLink: 'fact.js',
8081099
jsDatatypesExLink: 'data-types.js',
@@ -1047,11 +1338,5 @@ $(document).ready(function() {
10471338
initCodeopticon(); // defined in codeopticon-learner.js
10481339
}
10491340

1050-
$("#createTestsLink").click(function() {
1051-
optTests.initTestcasesPane('#testCasesPane');
1052-
$(this).hide();
1053-
return false;
1054-
});
1055-
10561341
$("#liveModeBtn").click(optFrontend.openLiveModeUrl.bind(optFrontend));
10571342
});

0 commit comments

Comments
 (0)