Slow functions
Future<bool> verySlowFunction([Duration duration = const Duration(milliseconds: 2000)]) async{
await Future.delayed(duration, () {
debugPrint('run very slow function...');
});
return true;
}
bool verySlowFunction2(){
for(var index = 0; index <1000000000000; index ++){}
return true;
}
Actual test code
group('my timeout tests', () {
test('timeout test', ()async {
final result = await verySlowFunction() ;
expect(result, equals(true));
}, timeout: const Timeout(Duration(milliseconds: 300)));
test('timeout test2', (){
final result = verySlowFunction2() ;
expect(result, equals(true));
}, timeout: const Timeout(Duration(milliseconds: 500)));
},);
I expected to tests are failed as the slow functions has more time than timeout duration I set. But the tests succeed... How this happens?
Related
In the async codelab:
Ref: https://dart.dev/codelabs/async-await
They have the following snippet:
Future<void> printOrderMessage() async {
print('Awaiting user order...');
var order = await fetchUserOrder();
print('Your order is: $order');
}
Future<String> fetchUserOrder() {
// Imagine that this function is more complex and slow.
return Future.delayed(const Duration(seconds: 4), () => 'Large Latte');
}
void main() async {
countSeconds(4);
await printOrderMessage();
}
Based on the logic of printOrderMessage() I've made a similar function:
void main() async {
int? value;
value = await test();
print(value);
}
Future<int?> test() async{
print('Function has started');
Future.delayed(Duration(milliseconds: 2000), () {
return 4;
});
}
In my case, it prints Function has started null. why doesn't it wait for the value to be populated
Future<int?> test() async {
print('Function has started');
await Future.delayed(Duration(milliseconds: 2000), () {});
return 4;
}
Future<int?> test() async {
print('Function has started');
return Future.delayed(Duration(milliseconds: 2000), () {
return 4;
});
}
void main() {
test('simple', () async {
await fakeAsync((async) async {
final stream = Stream.value(42);
print('hi before await');
await stream.toList();
print('hi after await');
});
});
}
stucks forever in the toList line...
I have also tried to call whatever methods, but still stuck forever in the "await" line
test('simple', () async {
await fakeAsync((async) async {
final stream = Stream.value(42);
final future = stream.toList();
print('hi before await');
async.flushMicrotasks();
async.flushTimers();
async.elapse(const Duration(seconds: 10));
async.elapseBlocking(const Duration(seconds: 10));
await future;
print('hi after await');
});
});
I have looked at the implementation of Stream.toList as follows, but it seems quite normal
Future<List<T>> toList() {
List<T> result = <T>[];
_Future<List<T>> future = new _Future<List<T>>();
this.listen(
(T data) {
result.add(data);
},
onError: future._completeError,
onDone: () {
future._complete(result);
},
cancelOnError: true);
return future;
}
I'm writing test code for VS Code Extension with mocha and puppeteer.
This code behaves oddly.
This test will change the result without editing the code.
Sometimes test is failed because timeout of const e = await global.page.waitForSelector("iframe", { timeout: 10000 });, and sometimes it succeeds.
Changing the value of the slowMo option of puppeteer.launch() after several timeouts may result in a successful test. (not every time)
How can I make this stable?
describe("test", () => {
before(async () => {
global.browser = await puppeteer.connect({
browserURL: 'http://127.0.0.1:9229',
defaultViewport: null,
slowMo: 10
});
global.page = (await global.browser.pages())[0];
});
after(async () => {
if (global.page) {
await global.page.close();
}
if (global.browser) {
global.browser.disconnect();
}
});
describe("open file", () => {
before(async () => {
// open file with my custom editor
const uri = Uri.file(path.join(__dirname, "test.pdf"));
await commands.executeCommand("vscode.open", uri);
// get editor's dom content
const e = await global.page.waitForSelector("iframe", { timeout: 10000 });
const ec = await editor.contentFrame();
const ee = await editorFrame.waitForSelector("iframe#active-frame", { timeout: 10000 });
const eec = await editorContent.contentFrame();
global.dom = eec;
});
after(async () => {
await commands.executeCommand("workbench.action.closeActiveEditor");
});
it("should have x", async () => {
const x = await global.doc.waitForSelector("#x", { timeout: 5000 });
assert.ok(x);
});
});
});
Hello I am trying to run following code, I want to run a specific asynchronous code and show alert dialog until it's running. But the code is not being executed after await showAlertDialog(); this line.
void appendAndRunPythonCode() async {
await showAlertDialog();
await runPythonScript(final_code);
_alertDialogUtils.dismissAlertDialog(context);
}
This is how my showAlertDialog() function is implemented:
Future<void> showAlertDialog() async {
if (!_alertDialogUtils.isShowing) {
await _alertDialogUtils.showAlertDialog(context);
}
}
runPythonCode():
Future<void> runPythonScript(String code) async {
if (inputImg == null) {
ToastUtils.showToastMessage(text: ConstUtils.input_image_empty_notice);
return;
}
if (code.isEmpty) {
ToastUtils.showToastMessage(text: ConstUtils.code_empty);
return;
}
List<String> lines = code.split('\n');
String lastLine = lines.elementAt(lines.length - 4);
if (lastLine.split(' ').elementAt(0).compareTo('outputImage') != 0) {
ToastUtils.showToastMessage(text: ConstUtils.cv_error_line2);
return;
}
data.putIfAbsent("code", () => code);
data.putIfAbsent("inputImg", () => inputImg);
_alertDialogUtils.showAlertDialog(context);
final result = await _channel.invokeMethod("runPythonCVScript", data);
// Add Artifical Delay of 3 seconds..
await Future.delayed(
Duration(seconds: 3),
);
_alertDialogUtils.dismissAlertDialog(context);
setState(
() {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
curve: Curves.easeOut,
duration: const Duration(milliseconds: 300),
);
output = result['textOutput'] ??= "";
error = result['error'] ??= "";
outputImg = (result['graphOutput']);
data.clear();
},
);
}
You shouldn't await the showAlertDialog because runPythonScript won't be executed until the dialog is dismissed.
Remove the await.
Like so:
void appendAndRunPythonCode() async {
showAlertDialog();
await runPythonScript(final_code);
_alertDialogUtils.dismissAlertDialog(context);
}
I was experimenting with asynchronous programming in dart when I stumbled upon a problem in which when I put a return statement inside a Future.delayed function it doesn't seem to return a value.
void main() {
perform();
}
void perform() async {
String result = await firstTask();
finalTask(result);
}
Future firstTask() async {
Duration duration = Duration(seconds: 4);
String result = 'task 2 data';
await Future.delayed(duration, () {
print('First Task Completed');
return result;
});
}
void finalTask(String result) {
print('final task completed and returned $result');
}
but if I put the return result; statement outside the Future.delayed function it returns its value to task 3. like,
void main() {
perform();
}
void perform() async {
String result = await firstTask();
finalTask(result);
}
Future firstTask() async {
Duration duration = Duration(seconds: 4);
String result = 'task 2 data';
await Future.delayed(duration, () {
print('First Task Completed');
});
return result;
}
void finalTask(String result) {
print('final task completed and returned $result');
}
Your first task doesn't have any return statement. IDE should be warning you about it. To fix it you have to do
Future firstTask() async {
Duration duration = Duration(seconds: 4);
String result = 'task 2 data';
return await Future.delayed(duration, () {
print('First Task Completed');
return result;
});
}
Or
Future firstTask() { // No async here
Duration duration = Duration(seconds: 4);
String result = 'task 2 data';
return Future.delayed(duration, () {
print('First Task Completed');
return result;
});
}