Merging unit tests, language switching and mps export #48

Closed
SinusFox wants to merge 56 commits from adding-unit-tests-and-language-switching into export-mps
4 changed files with 124 additions and 110 deletions
Showing only changes of commit 3e86c784e7 - Show all commits
+22
View File
@@ -0,0 +1,22 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import Home from "../src/app/page";
import { customLog, customLogClear } from '../src/app/scripts';
jest.mock('../src/app/scripts', () => ({
customLog: jest.fn(),
customLogClear: jest.fn(),
}));
jest.mock('../src/solver/glpk.min.js', () => ({
LPF_ECOND: 2,
}));
test('render home page', () => {
// render website
render(<Home />);
// check if text is in document
const headingElement = screen.getByText(/OR-Tool/i); // text search in document
expect(headingElement).toBeInTheDocument();
});
+96 -13
View File
@@ -1,21 +1,104 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import { render, fireEvent, screen } from '@testing-library/react';
import '@testing-library/jest-dom'; import {
import Home from "../src/app/page"; customLog,
customLogClear,
jest.mock('../src/app/scripts', () => ({ getTranslation,
customLog: jest.fn(), isInputValidRegex,
customLogClear: jest.fn(), isInputFilled,
})); downloadLPFormatting,
downloadLP,
calculate_click
} from '../src/app/scripts';
import Home from '../src/app/page'
import text from '../src/app/lang';
// Mocking GLPKAPI and console log
jest.mock('../src/solver/glpk.min.js', () => ({ jest.mock('../src/solver/glpk.min.js', () => ({
LPF_ECOND: 2, LPF_ECOND: 2,
})); }));
test('render home page', () => { // Mocking console.log
// render website const consoleLogMock = jest.spyOn(console, 'log').mockImplementation(() => {});
beforeEach(() => {
document.body.innerHTML = `
<div>
<select id="language_current">
<option value="eng">English</option>
</select>
<textarea id="objective"></textarea>
<textarea id="subject"></textarea>
<textarea id="bounds"></textarea>
<textarea id="vars"></textarea>
<select id="maxminswitch">
<option value="maximize">Maximize</option>
<option value="minimize">Minimize</option>
</select>
<div id="out"></div>
</div>
`;
jest.clearAllMocks(); // Clear any previous mocks
});
test('customLog should append message to output box', () => {
const message = 'Test message';
customLog(message);
const outputElement = document.getElementById('out');
expect(outputElement.innerHTML).toContain(message);
});
test('customLogClear should clear the output box', () => {
const message = 'Test message';
customLog(message);
customLogClear();
const outputElement = document.getElementById('out');
expect(outputElement.innerHTML).toBe('');
});
test('getTranslation should return translation based on selected language', () => {
const result = getTranslation('header_title');
expect(result).toBe(text('eng', 'header_title')); // Assuming text function provides correct translation
});
test('isInputValidRegex should validate input regex correctly', () => {
expect(isInputValidRegex("x + y", "+1 x + 2 y <= 15\n+3 x + 1 y <= 20", "x >= 0\ny >= 0", "x\ny")).toBe(true);
expect(isInputValidRegex("x + y", "+1 x + 2 y <= 15\n+3 x + 1 y <= 20", "x >= 0\ny >= 0", "")).toBe(false); // Invalid objective
});
test('isInputFilled should check for filled inputs', () => {
expect(isInputFilled('3x + 5y', 'x + y <= 10', 'x <= 5', 'x\ny')).toBe(true);
expect(isInputFilled('', 'x + y <= 10', 'x <= 5', 'x\ny')).toBe(false); // Objective empty
});
test('downloadLPFormatting should format LP correctly', () => {
const formattedLP = downloadLPFormatting('3x + 5y', 'x + y <= 10', 'x <= 5');
expect(formattedLP).toContain('obj: 3x + 5y');
expect(formattedLP).toContain('Subject To');
expect(formattedLP).toContain('Bounds');
});
test('calculate_click should display "Calculating" in the output box', () => {
render(<Home />); render(<Home />);
// check if text is in document // Spy on customLog and customLogClear to prevent actual logging and check the calls
const headingElement = screen.getByText(/OR-Tool/i); // text search in document const mockClear = jest.spyOn({ customLogClear }, 'customLogClear').mockImplementation();
expect(headingElement).toBeInTheDocument(); const mockLog = jest.spyOn({ customLog }, 'customLog').mockImplementation();
// Set valid inputs
document.getElementById('objective').value = '3x + 5y';
document.getElementById('subject').value = 'x + y <= 10';
document.getElementById('bounds').value = 'x <= 5';
document.getElementById('vars').value = 'x\ny';
// Simuliere den Button-Klick, der die Berechnung startet
fireEvent.click(screen.getByText('Calculate'));
// Check the contents of out box
const outputElement = document.getElementById('out');
expect(outputElement.innerHTML).toContain('Calculating');
// Clear mock
mockClear.mockRestore();
mockLog.mockRestore();
}); });
+3 -3
View File
@@ -2,12 +2,12 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Box, Button, Output } from "./modules"; import { Box, Button, Output } from "./modules";
import { calculate_click, downloadLP, import_click } from "./scripts"; import { calculate_click, downloadLP } from "./scripts";
import text from "./lang"; import text from "./lang";
export default function Home() { export default function Home() {
const [language, setLanguage] = useState('eng'); const [language, setLanguage] = useState('eng');
const [maxminOption, setMaxminOption] = useState('maximize'); // Zustand für den MaxMin-Switch const [maxminOption, setMaxminOption] = useState('maximize');
const tr_hTitle = text(language, 'header_title'); const tr_hTitle = text(language, 'header_title');
const tr_hSubtitle = text(language, 'header_subtitle'); const tr_hSubtitle = text(language, 'header_subtitle');
@@ -30,7 +30,7 @@ export default function Home() {
}; };
const handleMaxMinChange = (event: React.ChangeEvent<HTMLSelectElement>) => { const handleMaxMinChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
setMaxminOption(event.target.value); // Update den Zustand basierend auf dem Wert des Selects setMaxminOption(event.target.value);
}; };
return ( return (
+3 -94
View File
@@ -62,7 +62,7 @@ function walltimeStart() {
return Date.now(); return Date.now();
} }
function isInputValidRegex(obj: string | undefined, subj: string | undefined, bounds: string | undefined, vars: string | undefined): boolean { export function isInputValidRegex(obj: string | undefined, subj: string | undefined, bounds: string | undefined, vars: string | undefined): boolean {
customLog("input_checks_start"); customLog("input_checks_start");
// standard case: input is undefined - invalid // standard case: input is undefined - invalid
@@ -108,7 +108,7 @@ function isInputValidRegex(obj: string | undefined, subj: string | undefined, bo
return true; return true;
} }
function isInputFilled(obj: string | undefined, subj: string | undefined, bounds: string | undefined, vars: string | undefined) { export function isInputFilled(obj: string | undefined, subj: string | undefined, bounds: string | undefined, vars: string | undefined): boolean {
if (obj == "" || obj == null || obj == undefined) { if (obj == "" || obj == null || obj == undefined) {
customLog("err_emptyBox"); customLog("err_emptyBox");
return false; return false;
@@ -158,56 +158,6 @@ export function calculate_click() {
variables = (varsElement as HTMLInputElement).value; variables = (varsElement as HTMLInputElement).value;
} }
// let funcs:string[] = functions.split(/;/);
// let vars:string[] = variables.split(/;/);
// let direction = null;
// let namesVars:string[] = [];
// let variablesMIP:VariableMIP[];
// let variablesLP:VariableLP[];
// // console.log(vars);
// for (const decider of vars) {
// // match comments
// let regexMatch:RegExpMatchArray|null = decider.match(/#.*/);
// if (regexMatch != null)
// continue;
// regexMatch = decider.match(/var/);
// if (regexMatch != null)
// namesVars.push(regexMatch[1]);
// console.log(regexMatch);
// }
// for (const decider of funcs) {
// let dir = decider.match(/(min|max) .*/);
// if (direction != null && dir != null) {
// document.getElementById('out').innerHTML = "ERROR: Multiple Functions!";
// return;
// }
// if (direction == null && dir != null) {
// direction = dir[1];
// let test = parseFunction(decider);
// console.log(test?.name);
// variablesLP.
// continue;
// }
// console.log(direction);
// document.getElementById('out').innerHTML = direction;
// console.log(parseFunction(decider));
// catch error: empty input field(s) // catch error: empty input field(s)
if (!isInputFilled(objective, subject, bounds, variables)) return; if (!isInputFilled(objective, subject, bounds, variables)) return;
@@ -225,8 +175,6 @@ export function calculate_click() {
+ "\nGenerals \n" + variables + "\nGenerals \n" + variables
+ "\nEnd"; + "\nEnd";
// customLog("<br><br>DEBUGGING<br><br>\nfunctions:<br>" + functions + "<br><br>variables:<br>" + variables + "<br><br>DEBUGGING END<br>");
customLog(getTranslation("run_optimization") + ": \"" + wholeText + "\""); customLog(getTranslation("run_optimization") + ": \"" + wholeText + "\"");
customLog(""); customLog("");
run(wholeText); run(wholeText);
@@ -276,7 +224,7 @@ function run(text: string) {
customLog(""); customLog("");
} }
function downloadLPFormatting(objective: any, subject: any, bounds: any) { export function downloadLPFormatting(objective: any, subject: any, bounds: any) {
customLog(getTranslation("downloadPrepFileString")); customLog(getTranslation("downloadPrepFileString"));
customLog(""); customLog("");
@@ -294,7 +242,6 @@ function downloadLPFormatting(objective: any, subject: any, bounds: any) {
const header = "\\ Your problem\n"; const header = "\\ Your problem\n";
// format objective // format objective
const objectiveFunction = operator + `\n obj: ${formattedObjective}\n`; const objectiveFunction = operator + `\n obj: ${formattedObjective}\n`;
// turn each subject into a single line // turn each subject into a single line
@@ -358,41 +305,3 @@ export function downloadLP() {
downloadProblemDownload(exportString); downloadProblemDownload(exportString);
} }
// Irgend ein Interface
// document.getElementById('out').innerHTML = funcs;
// output.innerHTML = functions.innerHTML;
// createProblemMIP();
// LPAPI.default();
export function import_click() {
console.log("importing");
}
// export function export_click() {
// console.log("Exporting...");
// }
// function parseFunction(toParse: string) {
// var regex = toParse.match(/([a-zA-Z][a-zA-Z0-9]*):/);
// if (regex == null)
// return;
// var name = regex[1];
// regex = toParse.match(/(?:([0-9]*) *\* *([a-zA-Z][a-zA-Z0-9]*))/g);
// let coefs:number[] = [];
// let vars:string[] = [];
// for (const rg of regex) {
// coefs.push(+rg.match(/([0-9]+)/g));
// vars.push(rg.match(/([a-zA-Z][a-zA-Z0-9]*)/g)[0]);
// }
// return {name, coefs, vars};
// }