2023-04-20 17:06:16 +08:00
|
|
|
import time
|
|
|
|
from eventloop import EventLoop
|
|
|
|
|
|
|
|
run_time = 0
|
|
|
|
|
2023-04-20 19:26:04 +08:00
|
|
|
eventloop.set_debug(True)
|
|
|
|
|
|
|
|
|
2023-04-20 17:06:16 +08:00
|
|
|
def test_func(arg1, arg2):
|
|
|
|
global run_time
|
|
|
|
run_time += 1
|
|
|
|
print("Running test function with arguments:", arg1, arg2)
|
|
|
|
return arg1 + arg2
|
|
|
|
|
2023-04-20 19:26:04 +08:00
|
|
|
|
2023-04-20 17:06:16 +08:00
|
|
|
def test_func2(arg1, arg2):
|
|
|
|
print("test function 2 with arguments:", arg1, arg2)
|
|
|
|
return arg1 + arg2
|
|
|
|
|
2023-04-20 19:26:04 +08:00
|
|
|
|
2023-04-20 17:06:16 +08:00
|
|
|
def test_callback(res):
|
|
|
|
print("Running test callback function", res)
|
|
|
|
assert res == "Hello World"
|
|
|
|
|
2023-04-20 19:26:04 +08:00
|
|
|
|
2023-04-20 17:06:16 +08:00
|
|
|
# Test case 2: Add and run a periodic task
|
2023-06-06 03:28:21 +08:00
|
|
|
event_loop = EventLoop(period_ms=10)
|
2023-04-20 17:06:16 +08:00
|
|
|
|
2023-04-20 19:26:04 +08:00
|
|
|
event_loop.start_new_task_periodic(
|
|
|
|
test_func, ("Hello", " World"),
|
2023-06-06 03:28:21 +08:00
|
|
|
period_ms=100,
|
2023-04-20 19:26:04 +08:00
|
|
|
callback=test_callback
|
|
|
|
)
|
|
|
|
|
|
|
|
event_loop.start_new_task(
|
|
|
|
test_func2, ("Hello", " World"),
|
|
|
|
is_periodic=True,
|
2023-06-06 03:28:21 +08:00
|
|
|
period_ms=20,
|
2023-04-20 19:26:04 +08:00
|
|
|
callback=test_callback
|
|
|
|
)
|
|
|
|
|
2023-04-20 17:06:16 +08:00
|
|
|
event_loop.start()
|
|
|
|
|
|
|
|
# Sleep for enough time to allow the periodic task to run multiple times
|
|
|
|
while run_time < 3:
|
|
|
|
time.sleep(0.1)
|
|
|
|
|
|
|
|
event_loop.stop()
|
|
|
|
|
|
|
|
# Test case 3: Test removing a task
|
2023-04-20 19:26:04 +08:00
|
|
|
event_loop.start_new_task_periodic(
|
|
|
|
test_func, ("Hello", " World"), callback=test_callback, task_name="test_task_remove")
|
2023-04-20 17:06:16 +08:00
|
|
|
event_loop.remove_task("test_task_remove")
|
|
|
|
|
|
|
|
print(event_loop._tasks)
|
|
|
|
assert "test_task_remove" not in event_loop._tasks, "Failed to remove the task"
|