1 /******************************************************************************* 2 3 Copyright: 4 Copyright (c) 2017 dunnhumby Germany GmbH. 5 All rights reserved. 6 7 License: 8 Boost Software License Version 1.0. See LICENSE_BOOST.txt for details. 9 Alternatively, this file may be distributed under the terms of the Tango 10 3-Clause BSD License (see LICENSE_BSD.txt for details). 11 12 *******************************************************************************/ 13 14 module ocean.task.util.Timer_test; 15 16 import ocean.task.util.Timer; 17 import ocean.task.Scheduler; 18 import ocean.task.Task; 19 import ocean.core.Test; 20 import core.thread; 21 22 unittest 23 { 24 initScheduler(SchedulerConfiguration.init); 25 26 class SimpleTask : Task 27 { 28 override public void run ( ) 29 { 30 for (int i = 0; i < 10; ++i) 31 .wait(10); 32 } 33 } 34 35 auto task = new SimpleTask; 36 theScheduler.schedule(task); 37 theScheduler.eventLoop(); 38 } 39 40 unittest 41 { 42 // same as previous, but tests allocated event count inside `.timer` object 43 44 initScheduler(SchedulerConfiguration.init); 45 46 // re-create timer event pool to get rid of slots already allocated by other 47 // test cases 48 .timer = new typeof(.timer); 49 50 class SimpleTask : Task 51 { 52 override public void run ( ) 53 { 54 for (int i = 0; i < 10; ++i) 55 .wait(10); 56 } 57 } 58 59 auto task = new SimpleTask; 60 theScheduler.schedule(task); 61 theScheduler.eventLoop(); 62 63 test!("==")(.timer.scheduled_events(), 1); 64 } 65 66 unittest 67 { 68 initScheduler(SchedulerConfiguration.init); 69 70 static class InfiniteTask : Task 71 { 72 override public void run ( ) 73 { 74 for (;;) .wait(100); 75 } 76 } 77 78 static class RootTask : Task 79 { 80 Task to_wait_for; 81 82 override public void run ( ) 83 { 84 bool timeout = .awaitOrTimeout(this.to_wait_for, 5000); 85 test(timeout); 86 87 // `awaitOrTimeout` itself won't terminate awaited task on timeout, 88 // it will only "detach" it from the current context. If former is 89 // desired, it can be trivially done at the call site: 90 if (timeout) 91 this.to_wait_for.kill(); 92 } 93 } 94 95 auto root = new RootTask; 96 root.to_wait_for = new InfiniteTask; 97 98 theScheduler.schedule(root); 99 theScheduler.eventLoop(); 100 101 test(root.finished()); 102 test(root.to_wait_for.finished()); 103 } 104 105 unittest 106 { 107 initScheduler(SchedulerConfiguration.init); 108 109 static class FiniteTask : Task 110 { 111 override public void run ( ) 112 { 113 .wait(100); 114 } 115 } 116 117 static class RootTask : Task 118 { 119 Task to_wait_for; 120 121 override public void run ( ) 122 { 123 bool timeout = .awaitOrTimeout(this.to_wait_for, 1_000_000); 124 test(!timeout); 125 test(this.to_wait_for.finished()); 126 } 127 } 128 129 auto root = new RootTask; 130 root.to_wait_for = new FiniteTask; 131 132 theScheduler.schedule(root); 133 theScheduler.eventLoop(); 134 135 test(root.finished()); 136 test(root.to_wait_for.finished()); 137 138 } 139