Skip to content

Commit c50b0fd

Browse files
committed
error handling for unit testing
1 parent fc24759 commit c50b0fd

File tree

2 files changed

+49
-20
lines changed

2 files changed

+49
-20
lines changed

src/helpers/api.js

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,9 @@ async function makeRequest(data, options, customLogFunction) {
6464
});
6565
res.on('end', async function () {
6666
process.stdout.write('\n');
67-
if (res.statusCode >= 400) throw new Error(`Response status code: ${res.statusCode}. Error message: ${gptResponse}`);
68-
if (gptResponse.error) throw new Error(`Error: ${gptResponse.error.message}. Code: ${gptResponse.error.code}`);
69-
if (gptResponse.message) throw new Error(`Error: ${gptResponse.message}. Code: ${gptResponse.code}`);
67+
if (res.statusCode >= 400) reject(new Error(`Response status code: ${res.statusCode}. Error message: ${gptResponse}`));
68+
if (gptResponse.error) reject(new Error(`Error: ${gptResponse.error.message}. Code: ${gptResponse.error.code}`));
69+
if (gptResponse.message) reject(new Error(`Error: ${gptResponse.message}. Code: ${gptResponse.code}`));
7070
gptResponse = cleanupGPTResponse(gptResponse);
7171
resolve(gptResponse);
7272
});
@@ -85,8 +85,14 @@ async function makeRequest(data, options, customLogFunction) {
8585

8686
async function getUnitTests(data, customLogFunction) {
8787
let options = setOptions({path: '/api/generate-unit-tests'});
88-
let resp = await makeRequest(JSON.stringify(data), options, customLogFunction);
89-
return resp;
88+
let tests, error;
89+
try {
90+
tests = await makeRequest(JSON.stringify(data), options, customLogFunction);
91+
} catch (e) {
92+
error = e;
93+
} finally {
94+
return {tests, error};
95+
}
9096
}
9197

9298
async function getJestAuthFunction(loginMongoQueriesArray, loginRequestBody, loginEndpointPath) {

src/helpers/unitTests.js

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const fs = require('fs').promises;
1+
const fs = require('fs');
22
const path = require('path');
33
const _ = require('lodash');
44
const { getUnitTests, checkForAPIKey} = require('./api');
@@ -28,7 +28,8 @@ let functionList = {},
2828
folderStructureTree = [],
2929
testsGenerated = [],
3030
errors = [],
31-
ignoreFolders = ['node_modules', 'pythagora_tests']
31+
ignoreFolders = ['node_modules', 'pythagora_tests'],
32+
processExtensions = ['.js']
3233
;
3334

3435
async function processFile(filePath) {
@@ -142,16 +143,34 @@ async function createTests(filePath, prefix, funcToTest) {
142143
);
143144
spinner.start(folderStructureTree, indexToPush);
144145

146+
let testFilePath = path.join(getTestFilePath(filePath, rootPath), `/${funcData.functionName}.test.js`);
147+
if (fs.existsSync(testFilePath)) {
148+
await spinner.stop();
149+
folderStructureTree[indexToPush].line = `${green}${folderStructureTree[indexToPush].line}${reset}`;
150+
continue;
151+
}
152+
145153
let formattedData = await reformatDataForPythagoraAPI(funcData, filePath, getTestFilePath(filePath, rootPath));
146-
let tests = await getUnitTests(formattedData, (content) => {
154+
let { tests, error } = await getUnitTests(formattedData, (content) => {
147155
scrollableContent.setContent(content);
148156
scrollableContent.setScrollPerc(100);
149157
screen.render();
150158
});
151-
let testPath = await saveTests(filePath, funcData.functionName, tests);
152-
testsGenerated.push(testPath);
153-
await spinner.stop();
154-
folderStructureTree[indexToPush].line = `${green}${folderStructureTree[indexToPush].line}${reset}`;
159+
160+
if (tests) {
161+
let testPath = await saveTests(filePath, funcData.functionName, tests);
162+
testsGenerated.push(testPath);
163+
await spinner.stop();
164+
folderStructureTree[indexToPush].line = `${green}${folderStructureTree[indexToPush].line}${reset}`;
165+
} else {
166+
errors.push({
167+
file:filePath,
168+
function: funcData.functionName,
169+
error
170+
});
171+
await spinner.stop();
172+
folderStructureTree[indexToPush].line = `${red}${folderStructureTree[indexToPush].line}${reset}`;
173+
}
155174
}
156175

157176
if (foundFunctions.length > 0) {
@@ -168,24 +187,24 @@ async function saveTests(filePath, name, testData) {
168187
let dir = getTestFilePath(filePath, rootPath);
169188

170189
if (!await checkDirectoryExists(dir)) {
171-
await fs.mkdir(dir, { recursive: true });
190+
fs.mkdirSync(dir, { recursive: true });
172191
}
173192

174193
let testPath = path.join(dir, `/${name}.test.js`);
175-
await fs.writeFile(testPath, testData);
194+
fs.writeFileSync(testPath, testData);
176195
return testPath;
177196
}
178197

179198
async function traverseDirectory(directory, onlyCollectFunctionData, prefix = '', funcName) {
180199
if (await checkPathType(directory) === 'file' && !onlyCollectFunctionData) {
181-
if (path.extname(directory) !== '.js') throw new Error('File is not a javascript file');
200+
if (!processExtensions.includes(path.extname(directory))) throw new Error('File extension is not supported');
182201
const newPrefix = `| ${prefix}| `;
183202
return await createTests(directory, newPrefix, funcName);
184203
}
185-
const files = await fs.readdir(directory);
204+
const files = fs.readdirSync(directory);
186205
for (const file of files) {
187206
const absolutePath = path.join(directory, file);
188-
const stat = await fs.stat(absolutePath);
207+
const stat = fs.statSync(absolutePath);
189208
const isLast = files.indexOf(file) === files.length - 1;
190209
if (stat.isDirectory()) {
191210
if (ignoreFolders.includes(path.basename(absolutePath)) || path.basename(absolutePath).charAt(0) === '.') continue;
@@ -197,7 +216,7 @@ async function traverseDirectory(directory, onlyCollectFunctionData, prefix = ''
197216
const newPrefix = isLast ? `${prefix} ` : `${prefix}| `;
198217
await traverseDirectory(absolutePath, onlyCollectFunctionData, newPrefix, funcName);
199218
} else {
200-
if (path.extname(absolutePath) !== '.js') continue;
219+
if (!processExtensions.includes(path.extname(absolutePath))) continue;
201220
if (onlyCollectFunctionData) {
202221
if (isPathInside(path.dirname(queriedPath), absolutePath)) {
203222
updateFolderTree(prefix, isLast, absolutePath);
@@ -225,7 +244,6 @@ async function getFunctionsForExport(dirPath) {
225244
}
226245

227246
async function generateTestsForDirectory(pathToProcess, funcName) {
228-
229247
checkForAPIKey();
230248
queriedPath = path.resolve(pathToProcess);
231249
rootPath = process.cwd();
@@ -237,7 +255,12 @@ async function generateTestsForDirectory(pathToProcess, funcName) {
237255

238256
screen.destroy();
239257
process.stdout.write('\x1B[2J\x1B[0f');
240-
if (errors.length) console.log('Errors encountered while trying to generate unit tests:\n', errors);
258+
if (errors.length) {
259+
let errLogPath = `${path.resolve(PYTHAGORA_UNIT_DIR, 'errorLogs.log')}`
260+
fs.writeFileSync(errLogPath, JSON.stringify(errors));
261+
console.error('There were errors encountered while trying to generate unit tests.\n');
262+
console.error(`You can find logs here: ${errLogPath}`);
263+
}
241264
if (testsGenerated.length === 0) {
242265
console.log(`${bold+red}No tests generated!${reset}`);
243266
} else {

0 commit comments

Comments
 (0)