Abort the test in k6

Hi Team,
I am working on a script where I expect inputs from shell script as an argument. This shell script calls my K6 script and execute based on the inputs given by user (say API NAME). Now, I would like to add validation of user input. In case user doesn’t provide the right API Name, then the test should not start and throw an error message “Invalid API Name”.

import http from 'k6/http';
import { sleep } from 'k6';

let resultAPIStatus = validateAPIName(__ENV.APINAME);
if (resultAPIStatus !== true) {
 // I want to stop the test right here if 'resultAPIStatus' returns false
}

export default function () {
              frameAPIRequest(__ENV.APINAME) // frameAPIRequest is another function use to form the request based on the API.
}
const validateAPIName = (apiName) => {
    switch (apiName) {
        case ('GetConfiguration'):
            return true;
        default:
            console.log('Invalid API name');
            return false;
    }
}

Can someone please help?

Hi Satheesh,

this is currently not possible in k6, but will be soon in the upcoming v0.35.0 release or the one after that.

Take a look at issue #1001 and PR #2093. The PR is functionally complete for the k6 CLI tool, but we need to finish some changes for k6 Cloud which have delayed merging it. If you’re comfortable with the Go toolchain, you could build your own k6 binary from the feat/1001-abort-test branch and use it today.

The documentation is still pending for this and the API might change before release, but it’s part of the k6/execution module and you’ll be able to use it like so:

import exec from 'k6/execution';

if (!validateAPIName(__ENV.APINAME)) {
  exec.test.abort('API name validation failed');
}

Though since you’re already wrapping k6 in a shell script, I wonder if it would be simpler for now to just do the validation in the shell script itself instead of the k6 script.

If i understood your question correctly, you want to abort you current run if there is a invalid API Name passed from command line.

With this context, i would suggest to make use of fail() which will stops the execution with custom message. please refer below docs.
fail(‘Invalid API Name’);

@kaushik fail() will abort a single iteration, not the entire test. A new API was needed for this which is why we’re adding exec.test.abort().

1 Like

I think there was a bit of a miscommunication here.

You can easily do this even now, just throw an error in the init context and k6 will immediately abort, without starting the test run, like this:

if (resultAPIStatus !== true) {
  throw new Error("invalid API name");
}

Thanks @ned . Here is the outcome of your solution. I didn’t get any graceful exit without error message pointing some line of code.

Yeah, unfortunately there isn’t any way to hide that it’s an exception that aborted the test…