Skip to content

Commit 1c66a5d

Browse files
committed
updated logic
updated logic for better execution of code and a more clear message if the test is failed
1 parent ee0c7eb commit 1c66a5d

File tree

3 files changed

+62
-40
lines changed

3 files changed

+62
-40
lines changed

src/executeCode.ts

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ export async function executeCode(fileName: string, language: string, testCaseIn
6363
let command: string;
6464
if (language === 'python') {
6565
const env = { ...process.env, LEETCODE_INPUT_FILE: resolvedInputPath };
66-
command = `python3 "${resolvedFilePath}"`; //use python3 for proper functioning
66+
command = `python3 "${resolvedFilePath}"`;
6767
options.env = env;
6868
} else if (language === 'cpp') {
6969
const outputFileName = path.basename(resolvedFilePath, '.cpp');
@@ -111,16 +111,24 @@ export async function executeCode(fileName: string, language: string, testCaseIn
111111
}
112112

113113
// Helper function to compare outputs
114-
function compareOutputs(expectedOutputPath: string, actualOutput: string, testCaseIndex: number, resolve: Function, reject: Function) {
114+
function compareOutputs(
115+
expectedOutputPath: string,
116+
actualOutput: string,
117+
testCaseIndex: number,
118+
resolve: Function,
119+
reject: Function
120+
) {
115121
const expectedOutput = fs.readFileSync(expectedOutputPath, 'utf-8').trim();
116122
const normalizedExpected = normalizeOutput(expectedOutput);
117123
const normalizedActual = normalizeOutput(actualOutput.trim());
118124

119125
if (normalizedExpected === normalizedActual) {
120-
console.log(`Test case ${testCaseIndex} passed!`);
126+
console.log(`Test case ${testCaseIndex} passed!`);
121127
resolve(actualOutput.trim());
122128
} else {
123-
console.error(`Test case ${testCaseIndex} failed. Expected: ${expectedOutput}, Got: ${actualOutput.trim()}`);
129+
console.error(`❌ Test case ${testCaseIndex} failed.`);
130+
console.error(`Expected Output: "${expectedOutput}"`);
131+
console.error(`Actual Output: "${actualOutput.trim()}"`);
124132
reject(`Test case ${testCaseIndex} failed.`);
125133
}
126134
}
@@ -144,31 +152,31 @@ async function main() {
144152
console.log(`\nRunning Test Case ${testCaseIndex}...`);
145153
try {
146154
const result = await executeCode(fileName, language, testCaseIndex);
155+
console.log(`Raw result for Test Case ${testCaseIndex}:`, result);
147156

148157
// Read the expected output
149158
const expectedOutputPath = path.join(testCasesDir, `output_${testCaseIndex}.txt`);
150159
if (fs.existsSync(expectedOutputPath)) {
151160
let expectedOutput = fs.readFileSync(expectedOutputPath, 'utf-8').trim();
152161

153-
// Remove quotes from the expected output if it is a string
154162
if (expectedOutput.startsWith('"') && expectedOutput.endsWith('"')) {
155163
expectedOutput = expectedOutput.slice(1, -1);
156164
}
157165

158166
// Normalize the outputs for comparison
159167
const normalize = (str: string) => str.replace(/\s+/g, '').toLowerCase();
160-
const normalizedResult = normalize(result);
168+
const normalizedResult = result ? normalize(result) : 'N/A';
161169
const normalizedExpectedOutput = normalize(expectedOutput);
162170

163171
const resultMessage = normalizedResult === normalizedExpectedOutput
164-
? `✅ Test Case ${testCaseIndex}: Passed!\n`
165-
: `❌ Test Case ${testCaseIndex}: Failed!\n`;
172+
? `✅ Test Case ${testCaseIndex}: Passed!\nExpected Output: ${expectedOutput}\nActual Output: ${result ? result.trim() : 'N/A'}`
173+
: `❌ Test Case ${testCaseIndex}: Failed!\nExpected Output: ${expectedOutput}\nActual Output: ${result ? result.trim() : 'N/A'}`;
166174

167-
console.log(`${resultMessage}Expected Output: ${expectedOutput}\nActual Output: ${result.trim()}`);
168-
vscode.window.showInformationMessage(`${resultMessage}Expected Output: ${expectedOutput}\nActual Output: ${result.trim()}`, { modal: true });
175+
console.log(resultMessage);
176+
vscode.window.showInformationMessage(resultMessage, { modal: true });
169177
} else {
170-
console.log(`Output for Test Case ${testCaseIndex}:\n${result.trim()}`);
171-
vscode.window.showInformationMessage(`Output for Test Case ${testCaseIndex}:\n${result.trim()}`, { modal: true });
178+
console.log(`Output for Test Case ${testCaseIndex}:\nExpected Output: ${expectedOutputPath}\nActual Output: ${result ? result.trim() : 'N/A'}`);
179+
vscode.window.showInformationMessage(`Output for Test Case ${testCaseIndex}:\nExpected Output: ${expectedOutputPath}\nActual Output: ${result ? result.trim() : 'N/A'}`, { modal: true });
172180
}
173181
} catch (error) {
174182
console.error(error);

src/extension.ts

Lines changed: 41 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import * as vscode from 'vscode';
22
import * as fs from 'fs';
33
import * as path from 'path';
4-
import { fetchTestCases } from './fetchTestCases';
54
import { executeCode } from './executeCode';
65
import { CommandTreeDataProvider } from './commandTreeDataProvider';
6+
import { fetchTestCases } from './fetchTestCases';
77

88
export function activate(context: vscode.ExtensionContext) {
99
console.log('LeetCode Helper Extension Activated!');
@@ -50,7 +50,7 @@ export function activate(context: vscode.ExtensionContext) {
5050
}
5151
);
5252

53-
// Command: Get IO File Directory
53+
// Command: Get I/O File Directory
5454
const getIOFileDirectoryCommand = vscode.commands.registerCommand(
5555
'leetcode-cph-helper-by-ashish.getIOFileDirectory',
5656
async () => {
@@ -64,9 +64,6 @@ export function activate(context: vscode.ExtensionContext) {
6464
}
6565
);
6666

67-
// Command: Get Solution File Directory
68-
69-
7067
// Command: Write Solution File
7168
const writeSolutionFileCommand = vscode.commands.registerCommand(
7269
'leetcode-cph-helper-by-ashish.writeSolutionFile',
@@ -105,23 +102,38 @@ export function activate(context: vscode.ExtensionContext) {
105102
}
106103

107104
const boilerplate = language === 'python'
108-
? `import os; run_test_case=lambda n,f: print((lambda p: (lambda a: f(*a))(eval(l.strip()) for l in open(p).read().strip().splitlines()) if os.path.isfile(p) else f"Error: File not found at {p}. Check the file path and try again.")((lambda d: os.path.join(d, 'test_cases', f"input_{n}.txt"))(os.path.dirname(os.path.dirname(file)))))
109-
#WRITE YOUR CODE LOGIC HERE
110-
111-
#---------------------------------------------------------------------------------------
112-
# Example usage
113-
# Provide the test case number and function name
114-
#run_test_case(TEST_CASE_NUMBER, FUNCTION_NAME);
115-
run_test_case()`
105+
? `import os
106+
107+
# Function to run test cases
108+
run_test_case = lambda n, f: (
109+
print(
110+
(
111+
lambda p: (
112+
lambda a: f(*a)
113+
)(eval(l.strip()) for l in open(p).read().strip().splitlines())
114+
if os.path.isfile(p) else f"Error: File not found at {p}. Check the file path and try again."
115+
)(
116+
(lambda d: os.path.join(d, 'test_cases', f"input_{n}.txt"))(
117+
os.path.dirname(os.path.dirname(__file__))
118+
)
119+
)
120+
)
121+
122+
)
116123
117124
125+
# Example usage
126+
# Uncomment the below line for testing
127+
# run_test_cases(TEST_CASE_NUMBER,FUNCTION WHERE YOUR CODE LOGIC IS PRESENT)
128+
run_test_case()
129+
`
118130
: `#include <bits/stdc++.h>
119131
using namespace std;
120132
121133
//write the code logic here
122134
123135
124-
// Function to run the tes\ case
136+
// Function to run the test case
125137
void runTestCase(int n) {
126138
string filePath = "../test_cases/input_" + to_string(n) + ".txt";
127139
ifstream file(filePath);
@@ -131,25 +143,29 @@ void runTestCase(int n) {
131143
return;
132144
}
133145
134-
// if your input files has vector/array uncomment the below code
135-
// Read the array from the file
146+
// Read the array from the file (Uncomment if needed)
136147
137-
// Call the function and print the result(pass all the varbles that you have read from the file)
138-
//<data type> result = <function_name>(<variables>);
148+
// Call the function and print the result (pass all the variables)
149+
// <data type> result = <function_name>(<variables>);
150+
/* for example
151+
string ans;
152+
getline(file, ans);
153+
string result = reverseWords(ans);
154+
// Print the result
155+
cout << result << endl;
156+
file.close();
157+
*/
139158
140159
cout << result << endl;
141160
}
142161
143162
int main() {
144-
// Example usage
145-
runTestCase(); // Adjust the number as needed for your actual test case
163+
// example -> runTestCases(ENTER_THE_TESTCASE_YOU_WANT_TO_TEST);
164+
runTestCase();
146165
return 0;
147166
}
148-
149167
`;
150168

151-
152-
153169
fs.writeFileSync(filePath, boilerplate, 'utf-8');
154170

155171
const document = await vscode.workspace.openTextDocument(filePath);
@@ -264,8 +280,6 @@ int main() {
264280
}
265281
}
266282
);
267-
268-
// Command: Show LeetCode Problem Links
269283
const showLeetCodeProblemLinksCommand = vscode.commands.registerCommand(
270284
'leetcode-cph-helper-by-ashish.showLeetCodeProblemLinks',
271285
async () => {
@@ -277,7 +291,7 @@ int main() {
277291
);
278292

279293
// Register commands in context so that commandTreeDataProvider can access them
280-
context.subscriptions.push(fetchCommand,showLeetCodeProblemLinksCommand, getIOFileDirectoryCommand, writeSolutionFileCommand, runCommand);
294+
context.subscriptions.push(fetchCommand, showLeetCodeProblemLinksCommand,runCommand, writeSolutionFileCommand, getIOFileDirectoryCommand);
281295
const commandTreeDataProvider = new CommandTreeDataProvider();
282296
vscode.window.registerTreeDataProvider('leetcodeHelperCommands', commandTreeDataProvider);
283297

@@ -287,4 +301,4 @@ int main() {
287301

288302
export function deactivate() {
289303
console.log('LeetCode Helper Extension Deactivated!');
290-
}
304+
}

src/fetchTestCases.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ async function addAdditionalTestCases(count: number, existingCount: number): Pro
245245
}
246246
}
247247
}
248-
248+
// (just for better clearity)
249249
// Example usage of saveTestCasesToFiles function
250250
const exampleTestCases = [
251251
{

0 commit comments

Comments
 (0)