Test is failing even though expectations are met - dart

I have a test that looks like this:
test('should throw error if threshold is null', (){
final findEngine = new FindEngine<Foo>();
expect(findEngine.streamResults('foo', null), throwsA(new
isInstanceOf<ThresholdNullOrOutOfBoundsError>()));
});
The test is failing with the following message:
ERROR: should throw error if threshold is null
Test failed: Caught Instance of 'ThresholdNullOrOutOfBoundsError'
Am I doing something wrong here?

Figured it out. Needed to close over the call that I expected to fail:
expect(() => findEngine.streamResults('foo', null), throwsA(new
isInstanceOf<ThresholdNullOrOutOfBoundsError>()));

Related

Dart timeout() does not seem to be triggering after specified duration

I'm trying to wrap a function call in a retry and timeout. The retry below seems to be working fine, but the timeout() doesn't seem to be triggering as expected at all.
I've tried setting the ontimeout to print a message, throw an exception, throw a TimeoutException, and in all cases the expected timeout triggered. I've also tried adding a sleep() in the function being called to ensure that it takes longer then the timeout() duration.
await retry(
() => _sendUpdateTaskRequest(resultsJson).timeout(Duration(seconds: 5),
onTimeout: () => throw new Exception("ERRRR!")),
retryIf: (Exception e) =>
e is SocketException ||
e is TimeoutException ||
e is ClientException,
maxAttempts: requestRetryLimit,
);
lrn's comment was accurate. Changing the sleep to await Future.delayed(const Duration(seconds: 5)) was the correct course of action.

tabs.executeScript - how can I tell if content script was being injected?

I inject content scripts into websites programmatically using browser.tabs.executeScript. This will return a Promise, but in case of its rejection there seems to be no way of differentiating between the following 2 cases:
The content script couldn't be injected (i.e. for missing host
permission)
An error occured on script updateparsingend:update(but the script was being injected)
I'm only interested in whether the script was being injected or not.
The argument passed to the catch is an Error object.
catch(e => console.log(e.toString()) will output the error message, which can either be a reason for an injection failure (i.e. Missing host permission) or an error that occurred updatereading the scriptend:update.
browser.tabs.executeScript(tabId, {
file: '../path/to/content-script.js',
frameId: 0,
runAt: 'document_idle'
})
.catch(e => console.log(e.toString()));
So, for example if the content script is as follows:
window.document.body.addEventListener('click', e => console.log('clicked body'), false);
bla.bla();
then the Promise is being rejected, since bla.bla is undefined - but the script was being injected successfully.
In case the content script couldn't be injected I'd like to notify the user with the corresponding error message.
But when an error occurred updatethat is unrelated to whether the script could be injectedend:update, while the script was being injected, I don't want to notify the user, but handle it silently.
Is there a way to differentiate between those 2 cases?
EDIT: I came up with an indirect solution: In case the returned Promise was rejected I try to send a message to the content script. If this fails then the background script "knows" that no content script was being injected -> notify user.
This is how the Promise works....
browser.tabs.executeScript(tabId, {
file: '../path/to/content-script.js',
frameId: 0,
runAt: 'document_idle'
})
.catch(e => console.log(e.toString()));
catch in above will catch errors if the tabs.executeScript failed to inject. It may also show some errors when parsing the file in order to inject, if the JS file has parsing errors (invalid JS). It has nothing to do with what '../path/to/content-script.js' will be doing afterwards.
So once it was injected, then above Promise is fulfilled.
If the injected script has a sync return, then it can be received by the tabs.executeScript via then() e.g.
browser.tabs.executeScript(tabId, {
file: '../path/to/content-script.js',
frameId: 0,
runAt: 'document_idle'
})
.then(result => {})
.catch(e => console.log(e.toString()));
In case of async functions such as .addEventListener which will happen later, then is nothing returned to tabs.executeScript
To catch errors in the content scripts, you can generate the error message within the content script or send a message to background script i.e. sendMessage & onMessage.addListener
tabs.executeScript()
A Promise that will be fulfilled with an array of objects,
representing the result of the script in every injected frame.
The result of the script is the last evaluated statement, which is
similar to what would be output (the results, not any console.log()
output) if you executed the script in the Web Console. For example,
consider a script like this:
var foo='my result';foo;
browser.tabs.executeScript(tabId, {
file: '../path/to/content-script.js',
frameId: 0,
runAt: 'document_idle'
})
.then(result => {
// result is returned by the Promise
if (result === []) {
// it was fine but there was nothing to return
}
else if (result[0]) {
// result[0] is return from the promise
}
})
.catch(e => console.log(e.toString()));
Now if you want a return (it must be sync or else you have to tie it to another Promise), return something from '../path/to/content-script.js'

Is it possible to change the output of Lua error messages?

I managed to change the output of error messages by modifying the dbg_printf method. However, that method doesn't handle the following error messages:
lua: ?:0: attempt to call global 'log' (a nil value)
Which method(s) handle these types of errors?
The error message is from the file ldebug.c in the function luaG_typeerror. But i guess you are using an older Lua Version because my message is a bit different:
attempt to call a nil value (global 'log')
You sould try to prevent the error if you can:
if type(log) == "function" then
log()
end
or as #lhf said use pcall:
if pcall(log) then
-- no errors while running 'log'
...
else
-- 'log' raised an error: take appropriate actions
...
end
It should be simpler than digging into the C api.
like #lhf says:
if pcal(risky) then
print("this works")
else
print("phooey!")
end
alternatively you can stop the program and get your error message like this:
if pcal(risky) then
print("this works")
else
error("your error message here")
end

How do I fail a script running in Bitbucket Pipelines?

When a pipeline runs a node series of commands, how can I trigger a fail within the pipeline?
I have tried the following:
const failBuild = function(message) {
console.error('Deploy failed: ', message)
throw new Error('Deploy failed')
}
I see the "Deploy failed" message, but the pipeline still says "Success".
Bb Pipelines fail when a command exits with a non-zero exit code. So, if you want the pipeline to fail, you have to make sure the code is not 0.
In your case (note for people reading this later: see comments), you get 0 as exit status, because the throw is executed in a promise, but then catched in the promise’s catch() function – which does neither stop execution nor have any influence on the exit code.
Solution: explicitly throw an error in the catch() function.
For anyone else who might be struggling with this...
You need to return a non zero as already mentioned, I find the easiest way to do this is by passing a negative integer to PHP's exit() function.
https://php.net/manual/en/function.exit.php
if($condition == true)
{
// Whatever we were doing, it worked YAY!!
exit();
}
else
{
// Something went wrong so fail the step in the pipeline
exit(-1);
}
The accepted answer states:
Solution: explicitly throw an error in the catch() function.
So if I understand that correctly, it suggests you should write the script as:
async function main() { throw "err"; }
main().catch(e => { throw e; });
However, this does not work: the exit code is still 0, and the console displays a nasty warning:
> node "main.js"
(node:32996) UnhandledPromiseRejectionWarning: err
(node:32996) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:32996) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
> $?
0
The correct way to bubble up the error to the node process is:
process.on('unhandledRejection', up => { throw up });
async function main() { throw "err"; }
main();
This way, you get teh following result:
> node "main.js"
test2.js:1
process.on('unhandledRejection', up => { throw up });
^
err
> $?
1
Which is a little bit better (except the stacktrace is not very clear).

Squeak - SUnit Testing for Errors

I have been suggested to use should:rise in my test case to test for errors that a method might raise. For some reason it does not work as expected, so I want to verify that I'm doing it right. Here is the code in the test case:
self should: [aMyClass compareTo: 'This is a string'] raise: 'invalid input'.
My compareTo/1 method looks like this:
(aMyClass isKindOf: MyClass) ifFalse: [self error: 'invalid input'.].
The test runner output is that there is "1 errors".
Thank you.
#should:raise: expects an Exception class as its second argument, similar to the first argument of #on:do: in exception handling:
self should: [ aMyClass compareTo: 'This is a string' ] raise: Error

Resources