tgext.scheduler 2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: tgext.scheduler
3
+ Version: 2.0
4
+ Summary: Background task scheduler for TurboGears2
5
+ Author-email: TurboGears Team <turbogears@groups.google.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/TurboGears/tgext.scheduler
8
+ Project-URL: Repository, https://github.com/TurboGears/tgext.scheduler
9
+ Project-URL: Issues, https://github.com/TurboGears/tgext.scheduler/issues
10
+ Keywords: turbogears,tg2,scheduler,background tasks,cron
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: 3.15
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Framework :: TurboGears
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/plain
25
+ Requires-Dist: TurboGears2
26
+
27
+ This scheduler is based on TG1's scheduler which was based on Kronos by Irmen de Jong. It makes it easy to have one time or recurring background tasks run as needed
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 69", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tgext.scheduler"
7
+ version = "2.0"
8
+ description = "Background task scheduler for TurboGears2"
9
+ readme = { text = "This scheduler is based on TG1's scheduler which was based on Kronos by Irmen de Jong. It makes it easy to have one time or recurring background tasks run as needed", content-type = "text/plain" }
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "TurboGears Team", email = "turbogears@groups.google.com" }]
12
+ requires-python = ">=3.10"
13
+ dependencies = ["TurboGears2"]
14
+ keywords = ["turbogears", "tg2", "scheduler", "background tasks", "cron"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Programming Language :: Python :: 3.14",
25
+ "Programming Language :: Python :: 3.15",
26
+ "Topic :: Software Development :: Libraries :: Python Modules",
27
+ "Framework :: TurboGears",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/TurboGears/tgext.scheduler"
32
+ Repository = "https://github.com/TurboGears/tgext.scheduler"
33
+ Issues = "https://github.com/TurboGears/tgext.scheduler/issues"
34
+
35
+ [tool.setuptools.packages.find]
36
+ include = ["tgext.*"]
37
+ namespaces = true
38
+
39
+ [tool.ruff]
40
+ target-version = "py310"
41
+ src = [".", "tests"]
42
+
43
+ [tool.ruff.lint]
44
+ select = ["E", "F", "W", "I", "UP", "B", "SIM"]
45
+
46
+ [tool.ruff.lint.isort]
47
+ known-first-party = ["tgext.scheduler"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,144 @@
1
+ """Tests for the module-level API of tgext.scheduler.scheduler (the _get_scheduler
2
+ singleton, the add_*_task/cancel wrappers, _start/_stop_scheduler) and for
3
+ tgext.scheduler/__init__.py's start_scheduler/stop_scheduler."""
4
+
5
+ import threading
6
+ import time
7
+ from contextlib import suppress
8
+
9
+ import pytest
10
+
11
+ import tgext.scheduler
12
+ from tgext.scheduler import scheduler
13
+ from tgext.scheduler.scheduler import (
14
+ IntervalTask,
15
+ MonthdayTask,
16
+ SingleTask,
17
+ WeekdayTask,
18
+ method,
19
+ )
20
+
21
+
22
+ @pytest.fixture
23
+ def fresh_scheduler(monkeypatch):
24
+ """Reset the module-level singleton around each test."""
25
+ monkeypatch.setattr(scheduler, "_scheduler_instance", None)
26
+ yield scheduler
27
+ # do not leak a running scheduler thread into other tests
28
+ instance = scheduler._scheduler_instance
29
+ if instance is not None and getattr(instance, "running", False):
30
+ with suppress(Exception):
31
+ instance.stop()
32
+ monkeypatch.setattr(scheduler, "_scheduler_instance", None)
33
+
34
+
35
+ class TestSingleton:
36
+ def test_get_scheduler_returns_threaded_scheduler_singleton(self, fresh_scheduler):
37
+ first = fresh_scheduler._get_scheduler()
38
+ assert isinstance(first, fresh_scheduler.ThreadedScheduler)
39
+ second = fresh_scheduler._get_scheduler()
40
+ assert first is second
41
+ assert fresh_scheduler._scheduler_instance is first
42
+
43
+
44
+ class TestModuleLevelTaskFunctions:
45
+ def test_add_single_task(self, fresh_scheduler):
46
+ task = fresh_scheduler.add_single_task(
47
+ lambda: None, initialdelay=0, processmethod=method.sequential
48
+ )
49
+ assert isinstance(task, SingleTask)
50
+ assert type(task) is SingleTask
51
+ assert len(fresh_scheduler._scheduler_instance.sched.queue) == 1
52
+
53
+ def test_add_interval_task(self, fresh_scheduler):
54
+ task = fresh_scheduler.add_interval_task(
55
+ lambda: None, interval=30, initialdelay=0, processmethod=method.sequential
56
+ )
57
+ assert isinstance(task, IntervalTask)
58
+ assert task.interval == 30
59
+
60
+ def test_add_weekday_task(self, fresh_scheduler):
61
+ task = fresh_scheduler.add_weekday_task(
62
+ lambda: None,
63
+ weekdays=[1, 5],
64
+ timeonday=(9, 0),
65
+ processmethod=method.sequential,
66
+ )
67
+ assert type(task) is WeekdayTask
68
+ assert task.days == [1, 5]
69
+
70
+ def test_add_monthday_task(self, fresh_scheduler):
71
+ task = fresh_scheduler.add_monthday_task(
72
+ lambda: None,
73
+ monthdays=[1, 15],
74
+ timeonday=(9, 0),
75
+ processmethod=method.sequential,
76
+ )
77
+ assert type(task) is MonthdayTask
78
+ assert task.days == [1, 15]
79
+
80
+ def test_module_functions_share_one_scheduler(self, fresh_scheduler):
81
+ fresh_scheduler.add_single_task(lambda: None, initialdelay=0)
82
+ fresh_scheduler.add_interval_task(lambda: None, interval=30)
83
+ instance = fresh_scheduler._scheduler_instance
84
+ assert instance is not None
85
+ assert len(instance.sched.queue) == 2
86
+
87
+ def test_cancel(self, fresh_scheduler):
88
+ task = fresh_scheduler.add_single_task(
89
+ lambda: None, initialdelay=100, processmethod=method.sequential
90
+ )
91
+ assert len(fresh_scheduler._scheduler_instance.sched.queue) == 1
92
+ fresh_scheduler.cancel(task)
93
+ assert len(fresh_scheduler._scheduler_instance.sched.queue) == 0
94
+
95
+ def test_default_processmethod_is_threaded(self, fresh_scheduler):
96
+ task = fresh_scheduler.add_single_task(lambda: None, initialdelay=0)
97
+ assert type(task) is fresh_scheduler.ThreadedSingleTask
98
+
99
+
100
+ class TestStartStopScheduler:
101
+ def test_stop_without_instance_is_noop(self, fresh_scheduler):
102
+ fresh_scheduler._stop_scheduler() # must not raise
103
+
104
+ def test_start_and_stop_threaded_scheduler(self, fresh_scheduler, monkeypatch):
105
+ # keep the scheduler loop fast: cap every sleep at 10ms
106
+ real_sleep = time.sleep
107
+ monkeypatch.setattr(time, "sleep", lambda s: real_sleep(min(s, 0.01)))
108
+
109
+ done = threading.Event()
110
+ fresh_scheduler.add_single_task(
111
+ done.set, initialdelay=0, processmethod=method.sequential
112
+ )
113
+ fresh_scheduler._start_scheduler()
114
+
115
+ instance = fresh_scheduler._scheduler_instance
116
+ assert isinstance(instance, fresh_scheduler.ThreadedScheduler)
117
+ assert instance.thread.is_alive()
118
+ # the scheduled single task runs in the scheduler thread
119
+ assert done.wait(timeout=5)
120
+
121
+ fresh_scheduler._stop_scheduler()
122
+ assert instance.running is False
123
+ instance.thread.join(timeout=5)
124
+ assert not instance.thread.is_alive()
125
+
126
+
127
+ class TestPackageInit:
128
+ def test_start_scheduler_starts_and_registers_atexit(self, monkeypatch):
129
+ calls = []
130
+ monkeypatch.setattr(
131
+ scheduler, "_start_scheduler", lambda: calls.append("start")
132
+ )
133
+ monkeypatch.setattr(scheduler, "_stop_scheduler", lambda: calls.append("stop"))
134
+ registered = []
135
+ monkeypatch.setattr(
136
+ tgext.scheduler.atexit, "register", lambda fn: registered.append(fn)
137
+ )
138
+
139
+ tgext.scheduler.start_scheduler()
140
+ assert calls == ["start"]
141
+ assert registered == [tgext.scheduler.stop_scheduler]
142
+
143
+ tgext.scheduler.stop_scheduler()
144
+ assert calls == ["start", "stop"]
@@ -0,0 +1,439 @@
1
+ """Tests for tgext.scheduler.scheduler: the method enum, the Scheduler class,
2
+ the Task classes, and low-level schedule/cancel behavior."""
3
+
4
+ import os
5
+ import time
6
+ from unittest import mock
7
+
8
+ import pytest
9
+
10
+ from tgext.scheduler import scheduler
11
+ from tgext.scheduler.scheduler import (
12
+ DayTaskRescheduler,
13
+ IntervalTask,
14
+ MonthdayTask,
15
+ Scheduler,
16
+ SingleTask,
17
+ WeekdayTask,
18
+ method,
19
+ )
20
+
21
+ HAS_FORK = hasattr(os, "fork")
22
+
23
+
24
+ def _forked(cls_name):
25
+ """Reference a Forked* class, skipping the test if os.fork is missing."""
26
+ return pytest.param(
27
+ method.forked,
28
+ getattr(scheduler, cls_name),
29
+ marks=pytest.mark.skipif(not HAS_FORK, reason="os.fork not available"),
30
+ )
31
+
32
+
33
+ def test_method_enum():
34
+ assert method.sequential.value == 0
35
+ assert method.forked.value == 1
36
+ assert method.threaded.value == 2
37
+ assert len(method) == 3
38
+ assert list(method) == [method.sequential, method.forked, method.threaded]
39
+ assert method["sequential"] is method.sequential
40
+ assert method["threaded"] is method.threaded
41
+ assert method.threaded == method.threaded
42
+ assert method.threaded != method.sequential
43
+
44
+
45
+ @pytest.fixture
46
+ def sched():
47
+ return Scheduler()
48
+
49
+
50
+ class TestSchedulerValidation:
51
+ def test_add_interval_task_negative_initialdelay(self, sched):
52
+ with pytest.raises(ValueError):
53
+ sched.add_interval_task(
54
+ action=lambda: None,
55
+ taskname="t",
56
+ initialdelay=-1,
57
+ interval=10,
58
+ processmethod=method.sequential,
59
+ args=None,
60
+ kw=None,
61
+ )
62
+
63
+ def test_add_interval_task_interval_below_one(self, sched):
64
+ with pytest.raises(ValueError):
65
+ sched.add_interval_task(
66
+ action=lambda: None,
67
+ taskname="t",
68
+ initialdelay=0,
69
+ interval=0,
70
+ processmethod=method.sequential,
71
+ args=None,
72
+ kw=None,
73
+ )
74
+
75
+ def test_add_single_task_negative_initialdelay(self, sched):
76
+ with pytest.raises(ValueError):
77
+ sched.add_single_task(
78
+ action=lambda: None,
79
+ taskname="t",
80
+ initialdelay=-5,
81
+ processmethod=method.sequential,
82
+ args=None,
83
+ kw=None,
84
+ )
85
+
86
+ def test_add_daytime_task_weekdays_and_monthdays(self, sched):
87
+ with pytest.raises(ValueError):
88
+ sched.add_daytime_task(
89
+ action=lambda: None,
90
+ taskname="t",
91
+ weekdays=[1],
92
+ monthdays=[1],
93
+ timeonday=(10, 0),
94
+ processmethod=method.sequential,
95
+ args=None,
96
+ kw=None,
97
+ )
98
+
99
+ def test_add_interval_task_invalid_processmethod(self, sched):
100
+ with pytest.raises(ValueError):
101
+ sched.add_interval_task(
102
+ action=lambda: None,
103
+ taskname="t",
104
+ initialdelay=0,
105
+ interval=5,
106
+ processmethod="bogus",
107
+ args=None,
108
+ kw=None,
109
+ )
110
+
111
+ def test_add_single_task_invalid_processmethod(self, sched):
112
+ with pytest.raises(ValueError):
113
+ sched.add_single_task(
114
+ action=lambda: None,
115
+ taskname="t",
116
+ initialdelay=0,
117
+ processmethod="bogus",
118
+ args=None,
119
+ kw=None,
120
+ )
121
+
122
+ def test_add_weekday_task_invalid_processmethod(self, sched):
123
+ with pytest.raises(ValueError):
124
+ sched.add_daytime_task(
125
+ action=lambda: None,
126
+ taskname="t",
127
+ weekdays=[1],
128
+ monthdays=None,
129
+ timeonday=(10, 0),
130
+ processmethod="bogus",
131
+ args=None,
132
+ kw=None,
133
+ )
134
+
135
+ def test_add_monthday_task_invalid_processmethod(self, sched):
136
+ with pytest.raises(ValueError):
137
+ sched.add_daytime_task(
138
+ action=lambda: None,
139
+ taskname="t",
140
+ weekdays=None,
141
+ monthdays=[1],
142
+ timeonday=(10, 0),
143
+ processmethod="bogus",
144
+ args=None,
145
+ kw=None,
146
+ )
147
+
148
+
149
+ class TestAddTasks:
150
+ @pytest.mark.parametrize(
151
+ "pm,cls",
152
+ [
153
+ (method.sequential, IntervalTask),
154
+ (method.threaded, scheduler.ThreadedIntervalTask),
155
+ _forked("ForkedIntervalTask"),
156
+ ],
157
+ )
158
+ def test_add_interval_task_returns_task_class(self, sched, pm, cls):
159
+ task = sched.add_interval_task(
160
+ action=lambda: None,
161
+ taskname="t",
162
+ initialdelay=0,
163
+ interval=5,
164
+ processmethod=pm,
165
+ args=None,
166
+ kw=None,
167
+ )
168
+ assert type(task) is cls
169
+ assert task.interval == 5
170
+ assert task.name == "t"
171
+
172
+ @pytest.mark.parametrize(
173
+ "pm,cls",
174
+ [
175
+ (method.sequential, SingleTask),
176
+ (method.threaded, scheduler.ThreadedSingleTask),
177
+ _forked("ForkedSingleTask"),
178
+ ],
179
+ )
180
+ def test_add_single_task_returns_task_class(self, sched, pm, cls):
181
+ task = sched.add_single_task(
182
+ action=lambda: None,
183
+ taskname="t",
184
+ initialdelay=0,
185
+ processmethod=pm,
186
+ args=None,
187
+ kw=None,
188
+ )
189
+ assert type(task) is cls
190
+
191
+ @pytest.mark.parametrize(
192
+ "pm,cls",
193
+ [
194
+ (method.sequential, WeekdayTask),
195
+ (method.threaded, scheduler.ThreadedWeekdayTask),
196
+ _forked("ForkedWeekdayTask"),
197
+ ],
198
+ )
199
+ def test_add_weekday_task_returns_task_class(self, sched, pm, cls):
200
+ task = sched.add_daytime_task(
201
+ action=lambda: None,
202
+ taskname="t",
203
+ weekdays=[1, 3],
204
+ monthdays=None,
205
+ timeonday=(10, 0),
206
+ processmethod=pm,
207
+ args=None,
208
+ kw=None,
209
+ )
210
+ assert type(task) is cls
211
+ assert task.days == [1, 3]
212
+
213
+ @pytest.mark.parametrize(
214
+ "pm,cls",
215
+ [
216
+ (method.sequential, MonthdayTask),
217
+ (method.threaded, scheduler.ThreadedMonthdayTask),
218
+ _forked("ForkedMonthdayTask"),
219
+ ],
220
+ )
221
+ def test_add_monthday_task_returns_task_class(self, sched, pm, cls):
222
+ task = sched.add_daytime_task(
223
+ action=lambda: None,
224
+ taskname="t",
225
+ weekdays=None,
226
+ monthdays=[15],
227
+ timeonday=(10, 0),
228
+ processmethod=pm,
229
+ args=None,
230
+ kw=None,
231
+ )
232
+ assert type(task) is cls
233
+ assert task.days == [15]
234
+
235
+ def test_args_kw_default_to_empty(self, sched):
236
+ task = sched.add_single_task(
237
+ action=lambda: None,
238
+ taskname="t",
239
+ initialdelay=0,
240
+ processmethod=method.sequential,
241
+ args=None,
242
+ kw=None,
243
+ )
244
+ assert task.args == []
245
+ assert task.kw == {}
246
+
247
+ def test_args_kw_passed_through(self, sched):
248
+ task = sched.add_interval_task(
249
+ action=lambda *a, **k: None,
250
+ taskname="t",
251
+ initialdelay=0,
252
+ interval=5,
253
+ processmethod=method.sequential,
254
+ args=[1, 2],
255
+ kw={"x": 3},
256
+ )
257
+ assert task.args == [1, 2]
258
+ assert task.kw == {"x": 3}
259
+
260
+
261
+ class TestTaskExecution:
262
+ def test_execute_calls_action_with_args_and_kw(self):
263
+ calls = []
264
+ task = SingleTask("t", lambda *a, **k: calls.append((a, k)), [1, 2], {"x": 3})
265
+ task.execute()
266
+ assert calls == [((1, 2), {"x": 3})]
267
+
268
+ def test_call_routes_exception_to_handle_exception(self):
269
+ handled = []
270
+ task = SingleTask("t", mock.Mock(side_effect=RuntimeError("boom")), [], {})
271
+ task.handle_exception = handled.append
272
+ sched = mock.Mock()
273
+ task(lambda: sched) # must not propagate the exception
274
+ assert len(handled) == 1
275
+ assert isinstance(handled[0], RuntimeError)
276
+ assert str(handled[0]) == "boom"
277
+
278
+ def test_single_task_reschedule_does_nothing(self):
279
+ task = SingleTask("t", lambda: None, [], {})
280
+ sched = mock.Mock()
281
+ task.reschedule(sched)
282
+ assert sched.mock_calls == []
283
+
284
+ def test_interval_task_reschedule_uses_interval(self):
285
+ task = IntervalTask("t", 42, lambda: None, [], {})
286
+ sched = mock.Mock()
287
+ task.reschedule(sched)
288
+ sched.schedule_task.assert_called_once_with(task, 42)
289
+
290
+ def test_base_task_reschedule_not_implemented(self):
291
+ from tgext.scheduler.scheduler import Task
292
+
293
+ task = Task("t", lambda: None, [], {})
294
+ with pytest.raises(NotImplementedError):
295
+ task.reschedule(mock.Mock())
296
+
297
+
298
+ def _fixed_localtime(monkeypatch, year, month, day, hour, minute):
299
+ """Freeze time.localtime to the given wall-clock time and return the
300
+ struct_time that is now returned (with correct tm_wday/tm_yday)."""
301
+ probe = time.struct_time((year, month, day, hour, minute, 0, 0, 0, -1))
302
+ real = time.localtime(time.mktime(probe))
303
+ fixed = time.struct_time(
304
+ (year, month, day, hour, minute, 0, real.tm_wday, real.tm_yday, -1)
305
+ )
306
+ monkeypatch.setattr(time, "localtime", lambda *a: fixed)
307
+ return fixed
308
+
309
+
310
+ class TestDayTaskRescheduler:
311
+ def test_get_schedule_time_today_before_timeonday(self, monkeypatch):
312
+ # 2024-01-15 08:00, task at 10:30 -> today at 10:30
313
+ _fixed_localtime(monkeypatch, 2024, 1, 15, 8, 0)
314
+ r = DayTaskRescheduler((10, 30))
315
+ expected = time.mktime((2024, 1, 15, 10, 30, 0, 0, 15, -1))
316
+ assert r.get_schedule_time(True) == expected
317
+
318
+ def test_get_schedule_time_today_after_timeonday_rolls_over(self, monkeypatch):
319
+ # 2024-01-15 11:00, task at 10:30 -> already past, so tomorrow
320
+ _fixed_localtime(monkeypatch, 2024, 1, 15, 11, 0)
321
+ r = DayTaskRescheduler((10, 30))
322
+ expected = time.mktime((2024, 1, 16, 10, 30, 0, 1, 16, -1))
323
+ assert r.get_schedule_time(True) == expected
324
+
325
+ def test_get_schedule_time_tomorrow(self, monkeypatch):
326
+ _fixed_localtime(monkeypatch, 2024, 1, 15, 8, 0)
327
+ r = DayTaskRescheduler((10, 30))
328
+ expected = time.mktime((2024, 1, 16, 10, 30, 0, 1, 16, -1))
329
+ assert r.get_schedule_time(False) == expected
330
+
331
+ def test_get_schedule_time_rolls_over_month(self, monkeypatch):
332
+ # 2024-01-31 08:00 -> tomorrow is 2024-02-01
333
+ _fixed_localtime(monkeypatch, 2024, 1, 31, 8, 0)
334
+ r = DayTaskRescheduler((9, 15))
335
+ expected = time.mktime((2024, 2, 1, 9, 15, 0, 3, 32, -1))
336
+ assert r.get_schedule_time(False) == expected
337
+
338
+
339
+ class TestWeekdayTask:
340
+ def test_timeonday_must_be_2_tuple(self):
341
+ with pytest.raises(TypeError):
342
+ WeekdayTask("t", [1], 10, lambda: None)
343
+ with pytest.raises(TypeError):
344
+ WeekdayTask("t", [1], (10, 0, 0), lambda: None)
345
+
346
+ def test_weekdays_must_be_sequence(self):
347
+ with pytest.raises(TypeError):
348
+ WeekdayTask("t", 1, (10, 0), lambda: None)
349
+
350
+ def test_execute_runs_on_matching_weekday(self, monkeypatch):
351
+ # 2024-01-15 is a Monday -> tm_wday 0 -> weekday 1
352
+ _fixed_localtime(monkeypatch, 2024, 1, 15, 10, 0)
353
+ calls = []
354
+ task = WeekdayTask(
355
+ "t", [1], (10, 0), lambda *a, **k: calls.append((a, k)), [7], {"k": 8}
356
+ )
357
+ task.execute()
358
+ assert calls == [((7,), {"k": 8})]
359
+
360
+ def test_execute_skips_non_matching_weekday(self, monkeypatch):
361
+ # 2024-01-17 is a Wednesday -> tm_wday 2 -> weekday 3
362
+ _fixed_localtime(monkeypatch, 2024, 1, 17, 10, 0)
363
+ calls = []
364
+ task = WeekdayTask("t", [1], (10, 0), lambda: calls.append("run"), [], {})
365
+ task.execute()
366
+ assert calls == []
367
+
368
+
369
+ class TestMonthdayTask:
370
+ def test_timeonday_must_be_2_tuple(self):
371
+ with pytest.raises(TypeError):
372
+ MonthdayTask("t", [15], 10, lambda: None)
373
+
374
+ def test_monthdays_must_be_sequence(self):
375
+ with pytest.raises(TypeError):
376
+ MonthdayTask("t", 15, (10, 0), lambda: None)
377
+
378
+ def test_execute_runs_on_matching_monthday(self, monkeypatch):
379
+ # 2024-01-15 -> tm_mday 15
380
+ _fixed_localtime(monkeypatch, 2024, 1, 15, 10, 0)
381
+ calls = []
382
+ task = MonthdayTask("t", [15], (10, 0), lambda: calls.append("run"), [], {})
383
+ task.execute()
384
+ assert calls == ["run"]
385
+
386
+ def test_execute_skips_non_matching_monthday(self, monkeypatch):
387
+ _fixed_localtime(monkeypatch, 2024, 1, 15, 10, 0)
388
+ calls = []
389
+ task = MonthdayTask("t", [16], (10, 0), lambda: calls.append("run"), [], {})
390
+ task.execute()
391
+ assert calls == []
392
+
393
+
394
+ class TestScheduleAndCancel:
395
+ def test_schedule_task_adds_event_to_queue(self, sched):
396
+ task = SingleTask("t", lambda: None, [], {})
397
+ before = time.time()
398
+ sched.schedule_task(task, 100)
399
+ assert len(sched.sched.queue) == 1
400
+ event = sched.sched.queue[0]
401
+ assert event is task.event
402
+ assert event.action is task
403
+ assert before + 100 <= event.time <= time.time() + 100
404
+
405
+ def test_schedule_task_abs_uses_absolute_time(self, sched):
406
+ task = SingleTask("t", lambda: None, [], {})
407
+ abstime = time.time() + 500
408
+ sched.schedule_task_abs(task, abstime)
409
+ assert len(sched.sched.queue) == 1
410
+ assert sched.sched.queue[0] is task.event
411
+ assert task.event.time == abstime
412
+
413
+ def test_cancel_removes_task_from_queue(self, sched):
414
+ task = SingleTask("t", lambda: None, [], {})
415
+ sched.schedule_task(task, 100)
416
+ assert len(sched.sched.queue) == 1
417
+ sched.cancel(task)
418
+ assert len(sched.sched.queue) == 0
419
+
420
+ def test_cancel_twice_raises(self, sched):
421
+ task = SingleTask("t", lambda: None, [], {})
422
+ sched.schedule_task(task, 100)
423
+ sched.cancel(task)
424
+ with pytest.raises(ValueError):
425
+ sched.cancel(task)
426
+
427
+ def test_stop_sets_running_false_and_empties_queue(self, sched):
428
+ task = SingleTask("t", lambda: None, [], {})
429
+ other = SingleTask("u", lambda: None, [], {})
430
+ sched.schedule_task(task, 100)
431
+ sched.schedule_task(other, 200)
432
+ assert len(sched.sched.queue) == 2
433
+ assert sched.running is True
434
+ sched.stop()
435
+ assert sched.running is False
436
+ # the pending events must actually be cancelled, on every
437
+ # supported Python version (3.12+ queue is a property returning
438
+ # a copy, so in-place mutation would be a no-op)
439
+ assert len(sched.sched.queue) == 0