Skip to content

Commit

Permalink
fix: wait for file to be existed
Browse files Browse the repository at this point in the history
  • Loading branch information
kobenguyent committed Dec 19, 2023
1 parent 82627d6 commit cab480e
Showing 1 changed file with 53 additions and 14 deletions.
67 changes: 53 additions & 14 deletions lib/testrail.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,20 +175,27 @@ class TestRail {
}

async addAttachmentToResult(resultId, imageFile) {
let form = new FormData();
form.append('attachment', fs.createReadStream(path.join(global.output_dir, imageFile.toString())));

await this.axios({
method: 'post',
data: form,
url: 'add_attachment_to_result/' + resultId,
headers: form.getHeaders()
}).catch(error => {
const parsedError = error && error.response && error.response.data ? error.response.data.error : error;
output.error(`addAttachmentToResult: ERROR - cannot add attachment due to ${parsedError}`);
output.error(`addAttachmentToResult: ERROR - request data was ${JSON.stringify(form)}`);
throw Error(parsedError);
});

const isFileExisting = await holdBeforeFileExists(imageFile);

if (isFileExisting) {
let form = new FormData();
form.append('attachment', fs.createReadStream(path.join(global.output_dir, imageFile.toString())));

await this.axios({
method: 'post',
data: form,
url: 'add_attachment_to_result/' + resultId,
headers: form.getHeaders()
}).catch(error => {
const parsedError = error && error.response && error.response.data ? error.response.data.error : error;
output.error(`addAttachmentToResult: ERROR - cannot add attachment due to ${parsedError}`);
output.error(`addAttachmentToResult: ERROR - request data was ${JSON.stringify(form)}`);
throw Error(parsedError);
});
} else {
throw Error(`File at ${imageFile} doesn't exist!`);
}
}

async closeTestRun(runId) {
Expand All @@ -204,3 +211,35 @@ class TestRail {
}

module.exports = TestRail;


/**
*
* @param {String} filePath
* @param {Number} timeout in millisecond
* @returns {Promise<Boolean>}
*/
const holdBeforeFileExists = async (filePath, timeout = 3000) => {
timeout = timeout < 1000 ? 1000 : timeout;
try {
let nom = 0;
return new Promise(resolve => {
let inter = setInterval(() => {
nom = nom + 100;
if (nom >= timeout) {
clearInterval(inter);
//maybe exists, but my time is up!
resolve(false);
}

if (fs.existsSync(filePath) && fs.lstatSync(filePath).isFile()) {
clearInterval(inter);
//clear timer, even though there's still plenty of time left
resolve(true);
}
}, 100);
});
} catch (error) {
return false;
}
};

0 comments on commit cab480e

Please sign in to comment.