forked from dbader/schedule
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_schedule.py
617 lines (524 loc) · 23.7 KB
/
test_schedule.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
"""Unit tests for schedule.py"""
import sys
import datetime
import logging
import functools
import mock
import unittest
# from test import support
# Silence "missing docstring", "method could be a function",
# "class already defined", and "too many public methods" messages:
# pylint: disable-msg=R0201,C0111,E0102,R0904,R0901
import schedule
from schedule import every, ScheduleError, ScheduleValueError, IntervalError
from schedule.parent_logger import setup_logging
try:
from datetime import timezone
utc = timezone.utc
except ImportError:
from schedule.timezone import UTC
utc = UTC()
def make_mock_job(name=None):
job = mock.Mock()
job.__name__ = name or 'job'
return job
class mock_datetime(object):
"""
Monkey-patch datetime for predictable results
"""
def __init__(self, year, month, day, hour, minute, second=0):
self.year = year
self.month = month
self.day = day
self.hour = hour
self.minute = minute
self.second = second
def __enter__(self):
class MockDate(datetime.datetime):
@classmethod
def today(cls):
return cls(self.year, self.month, self.day)
@classmethod
def now(cls, tz=None):
return cls(self.year, self.month, self.day,
self.hour, self.minute, self.second).replace(tzinfo=tz)
self.original_datetime = datetime.datetime
datetime.datetime = MockDate
def __exit__(self, *args, **kwargs):
datetime.datetime = self.original_datetime
class SchedulerTests(unittest.TestCase):
def setUp(self):
schedule.clear()
def test_time_units(self):
assert every().seconds.unit == 'seconds'
assert every().minutes.unit == 'minutes'
assert every().hours.unit == 'hours'
assert every().days.unit == 'days'
assert every().weeks.unit == 'weeks'
job_instance = schedule.Job(interval=2)
# without a context manager, it incorrectly raises an error because
# it is not callable
with self.assertRaises(IntervalError):
job_instance.minute
with self.assertRaises(IntervalError):
job_instance.hour
with self.assertRaises(IntervalError):
job_instance.day
with self.assertRaises(IntervalError):
job_instance.week
with self.assertRaises(IntervalError):
job_instance.monday
with self.assertRaises(IntervalError):
job_instance.tuesday
with self.assertRaises(IntervalError):
job_instance.wednesday
with self.assertRaises(IntervalError):
job_instance.thursday
with self.assertRaises(IntervalError):
job_instance.friday
with self.assertRaises(IntervalError):
job_instance.saturday
with self.assertRaises(IntervalError):
job_instance.sunday
# test an invalid unit
job_instance.unit = "foo"
self.assertRaises(ScheduleValueError, job_instance.at, "1:0:0")
self.assertRaises(ScheduleValueError, job_instance._schedule_next_run)
# test start day exists but unit is not 'weeks'
job_instance.unit = "days"
job_instance.start_day = 1
self.assertRaises(ScheduleValueError, job_instance._schedule_next_run)
# test weeks with an invalid start day
job_instance.unit = "weeks"
job_instance.start_day = "bar"
self.assertRaises(ScheduleValueError, job_instance._schedule_next_run)
# test a valid unit with invalid hours/minutes/seconds
job_instance.unit = "days"
self.assertRaises(ScheduleValueError, job_instance.at, "25:00:00")
self.assertRaises(ScheduleValueError, job_instance.at, "00:61:00")
self.assertRaises(ScheduleValueError, job_instance.at, "00:00:61")
# test invalid time format
self.assertRaises(ScheduleValueError, job_instance.at, "25:0:0")
self.assertRaises(ScheduleValueError, job_instance.at, "0:61:0")
self.assertRaises(ScheduleValueError, job_instance.at, "0:0:61")
# test (very specific) seconds with unspecified start_day
job_instance.unit = "seconds"
job_instance.at_time = datetime.datetime.now()
job_instance.start_day = None
self.assertRaises(ScheduleValueError, job_instance._schedule_next_run)
# test self.latest >= self.interval
job_instance.latest = 1
self.assertRaises(ScheduleError, job_instance._schedule_next_run)
job_instance.latest = 3
self.assertRaises(ScheduleError, job_instance._schedule_next_run)
def test_singular_time_units_match_plural_units(self):
assert every().second.unit == every().seconds.unit
assert every().minute.unit == every().minutes.unit
assert every().hour.unit == every().hours.unit
assert every().day.unit == every().days.unit
assert every().week.unit == every().weeks.unit
def test_time_range(self):
with mock_datetime(2014, 6, 28, 12, 0):
mock_job = make_mock_job()
# Choose a sample size large enough that it's unlikely the
# same value will be chosen each time.
minutes = set([
every(5).to(30).minutes.do(mock_job).next_run.minute
for i in range(100)
])
assert len(minutes) > 1
assert min(minutes) >= 5
assert max(minutes) <= 30
def test_time_range_repr(self):
mock_job = make_mock_job()
with mock_datetime(2014, 6, 28, 12, 0):
job_repr = repr(every(5).to(30).minutes.do(mock_job))
assert job_repr.startswith('Every 5 to 30 minutes do job()')
def test_at_time(self):
mock_job = make_mock_job()
assert every().day.at('10:30').do(mock_job).next_run.hour == 10
assert every().day.at('10:30').do(mock_job).next_run.minute == 30
assert every().day.at('10:30:50').do(mock_job).next_run.second == 50
self.assertRaises(ScheduleValueError, every().day.at, '2:30:000001')
self.assertRaises(ScheduleValueError, every().day.at, '::2')
self.assertRaises(ScheduleValueError, every().day.at, '.2')
self.assertRaises(ScheduleValueError, every().day.at, '2')
self.assertRaises(ScheduleValueError, every().day.at, ':2')
self.assertRaises(ScheduleValueError, every().day.at, ' 2:30:00')
self.assertRaises(ScheduleValueError, every().do, lambda: 0)
self.assertRaises(TypeError, every().day.at, 2)
# without a context manager, it incorrectly raises an error because
# it is not callable
with self.assertRaises(IntervalError):
every(interval=2).second
with self.assertRaises(IntervalError):
every(interval=2).minute
with self.assertRaises(IntervalError):
every(interval=2).hour
with self.assertRaises(IntervalError):
every(interval=2).day
with self.assertRaises(IntervalError):
every(interval=2).week
with self.assertRaises(IntervalError):
every(interval=2).monday
with self.assertRaises(IntervalError):
every(interval=2).tuesday
with self.assertRaises(IntervalError):
every(interval=2).wednesday
with self.assertRaises(IntervalError):
every(interval=2).thursday
with self.assertRaises(IntervalError):
every(interval=2).friday
with self.assertRaises(IntervalError):
every(interval=2).saturday
with self.assertRaises(IntervalError):
every(interval=2).sunday
def test_at_time_hour(self):
with mock_datetime(2010, 1, 6, 12, 20):
mock_job = make_mock_job()
assert every().hour.at(':30').do(mock_job).next_run.hour == 12
assert every().hour.at(':30').do(mock_job).next_run.minute == 30
assert every().hour.at(':30').do(mock_job).next_run.second == 0
assert every().hour.at(':10').do(mock_job).next_run.hour == 13
assert every().hour.at(':10').do(mock_job).next_run.minute == 10
assert every().hour.at(':10').do(mock_job).next_run.second == 0
assert every().hour.at(':00').do(mock_job).next_run.hour == 13
assert every().hour.at(':00').do(mock_job).next_run.minute == 0
assert every().hour.at(':00').do(mock_job).next_run.second == 0
self.assertRaises(ScheduleValueError, every().hour.at, '2:30:00')
self.assertRaises(ScheduleValueError, every().hour.at, '::2')
self.assertRaises(ScheduleValueError, every().hour.at, '.2')
self.assertRaises(ScheduleValueError, every().hour.at, '2')
self.assertRaises(ScheduleValueError, every().hour.at, ' 2:30')
self.assertRaises(ScheduleValueError, every().hour.at, "61:00")
self.assertRaises(ScheduleValueError, every().hour.at, "00:61")
self.assertRaises(ScheduleValueError, every().hour.at, "01:61")
self.assertRaises(TypeError, every().hour.at, 2)
def test_at_time_minute(self):
with mock_datetime(2010, 1, 6, 12, 20, 30):
mock_job = make_mock_job()
assert every().minute.at(':40').do(mock_job).next_run.hour == 12
assert every().minute.at(':40').do(mock_job).next_run.minute == 20
assert every().minute.at(':40').do(mock_job).next_run.second == 40
assert every().minute.at(':10').do(mock_job).next_run.hour == 12
assert every().minute.at(':10').do(mock_job).next_run.minute == 21
assert every().minute.at(':10').do(mock_job).next_run.second == 10
self.assertRaises(ScheduleValueError, every().minute.at, '::2')
self.assertRaises(ScheduleValueError, every().minute.at, '.2')
self.assertRaises(ScheduleValueError, every().minute.at, '2')
self.assertRaises(ScheduleValueError, every().minute.at, '2:30:00')
self.assertRaises(ScheduleValueError, every().minute.at, '2:30')
self.assertRaises(ScheduleValueError, every().minute.at, ' :30')
self.assertRaises(TypeError, every().minute.at, 2)
def test_next_run_time(self):
with mock_datetime(2010, 1, 6, 12, 15):
mock_job = make_mock_job()
assert schedule.next_run() is None
assert every().minute.do(mock_job).next_run.minute == 16
assert every(5).minutes.do(mock_job).next_run.minute == 20
assert every().hour.do(mock_job).next_run.hour == 13
assert every().day.do(mock_job).next_run.day == 7
assert every().day.at('09:00').do(mock_job).next_run.day == 7
assert every().day.at('12:30').do(mock_job).next_run.day == 6
assert every().week.do(mock_job).next_run.day == 13
assert every().monday.do(mock_job).next_run.day == 11
assert every().tuesday.do(mock_job).next_run.day == 12
assert every().wednesday.do(mock_job).next_run.day == 13
assert every().thursday.do(mock_job).next_run.day == 7
assert every().friday.do(mock_job).next_run.day == 8
assert every().saturday.do(mock_job).next_run.day == 9
assert every().sunday.do(mock_job).next_run.day == 10
def test_run_all(self):
mock_job = make_mock_job()
every().minute.do(mock_job)
every().hour.do(mock_job)
every().day.at('11:00').do(mock_job)
schedule.run_all()
assert mock_job.call_count == 3
def test_run_tag(self):
with mock_datetime(2010, 1, 6, 12, 15):
mock_job = make_mock_job()
assert schedule.last_run() is None
job1 = every().hour.do(mock_job(name='job1')).tag('tag1')
job2 = every().hour.do(mock_job(name='job2')).tag('tag1', 'tag2')
job3 = every().hour.do(mock_job(name='job3')).tag('tag3', 'tag3',
'tag3', 'tag2')
assert len(schedule.jobs) == 3
schedule.run_all(0, 'tag1')
assert 'tag1' in str(job1.tags)
assert 'tag1' not in str(job3.tags)
assert 'tag1' in str(job2.tags)
assert job1.last_run.minute == 15
assert job2.last_run.hour == 12
assert job3.last_run is None
def test_job_func_args_are_passed_on(self):
mock_job = make_mock_job()
every().second.do(mock_job, 1, 2, 'three', foo=23, bar={})
schedule.run_all()
mock_job.assert_called_once_with(1, 2, 'three', foo=23, bar={})
def test_to_string(self):
def job_fun():
pass
s = str(every().minute.do(job_fun, 'foo', bar=23))
assert s == ("Job(interval=1, unit=minutes, do=job_fun, "
"args=('foo',), kwargs={'bar': 23})")
assert 'job_fun' in s
assert 'foo' in s
assert '{\'bar\': 23}' in s
def test_to_repr(self):
def job_fun():
pass
s = repr(every().minute.do(job_fun, 'foo', bar=23))
assert s.startswith("Every 1 minute do job_fun('foo', bar=23) "
"(last run: [never], next run: ")
assert 'job_fun' in s
assert 'foo' in s
assert 'bar=23' in s
# test repr when at_time is not None
s2 = repr(every().day.at("00:00").do(job_fun, 'foo', bar=23))
assert s2.startswith(("Every 1 day at 00:00:00 do job_fun('foo', "
"bar=23) (last run: [never], next run: "))
def test_to_string_lambda_job_func(self):
assert len(str(every().minute.do(lambda: 1))) > 1
assert len(str(every().day.at('10:30').do(lambda: 1))) > 1
def test_to_string_functools_partial_job_func(self):
def job_fun(arg):
pass
job_fun = functools.partial(job_fun, 'foo')
job_repr = repr(every().minute.do(job_fun, bar=True, somekey=23))
assert 'functools.partial' in job_repr
assert 'bar=True' in job_repr
assert 'somekey=23' in job_repr
def test_run_pending(self):
"""Check that run_pending() runs pending jobs.
We do this by overriding datetime.datetime with mock objects
that represent increasing system times.
Please note that it is *intended behavior that run_pending() does not
run missed jobs*. For example, if you've registered a job that
should run every minute and you only call run_pending() in one hour
increments then your job won't be run 60 times in between but
only once.
"""
mock_job = make_mock_job()
with mock_datetime(2010, 1, 6, 12, 15):
every().minute.do(mock_job)
every().hour.do(mock_job)
every().day.do(mock_job)
every().sunday.do(mock_job)
schedule.run_pending()
assert mock_job.call_count == 0
with mock_datetime(2010, 1, 6, 12, 16):
schedule.run_pending()
assert mock_job.call_count == 1
with mock_datetime(2010, 1, 6, 13, 16):
mock_job.reset_mock()
schedule.run_pending()
assert mock_job.call_count == 2
with mock_datetime(2010, 1, 7, 13, 16):
mock_job.reset_mock()
schedule.run_pending()
assert mock_job.call_count == 3
with mock_datetime(2010, 1, 10, 13, 16):
mock_job.reset_mock()
schedule.run_pending()
assert mock_job.call_count == 4
def test_run_every_weekday_at_specific_time_today(self):
mock_job = make_mock_job()
with mock_datetime(2010, 1, 6, 13, 16):
every().wednesday.at('14:12').do(mock_job)
schedule.run_pending()
assert mock_job.call_count == 0
with mock_datetime(2010, 1, 6, 14, 16):
schedule.run_pending()
assert mock_job.call_count == 1
def test_run_every_weekday_at_specific_time_past_today(self):
mock_job = make_mock_job()
with mock_datetime(2010, 1, 6, 13, 16):
every().wednesday.at('13:15').do(mock_job)
schedule.run_pending()
assert mock_job.call_count == 0
with mock_datetime(2010, 1, 13, 13, 14):
schedule.run_pending()
assert mock_job.call_count == 0
with mock_datetime(2010, 1, 13, 13, 16):
schedule.run_pending()
assert mock_job.call_count == 1
def test_run_every_n_days_at_specific_time(self):
mock_job = make_mock_job()
with mock_datetime(2010, 1, 6, 11, 29):
every(2).days.at('11:30').do(mock_job)
schedule.run_pending()
assert mock_job.call_count == 0
with mock_datetime(2010, 1, 6, 11, 31):
schedule.run_pending()
assert mock_job.call_count == 0
with mock_datetime(2010, 1, 7, 11, 31):
schedule.run_pending()
assert mock_job.call_count == 0
with mock_datetime(2010, 1, 8, 11, 29):
schedule.run_pending()
assert mock_job.call_count == 0
with mock_datetime(2010, 1, 8, 11, 31):
schedule.run_pending()
assert mock_job.call_count == 1
with mock_datetime(2010, 1, 10, 11, 31):
schedule.run_pending()
assert mock_job.call_count == 2
def test_next_run_property(self):
original_datetime = datetime.datetime
with mock_datetime(2010, 1, 6, 13, 16):
hourly_job = make_mock_job('hourly')
daily_job = make_mock_job('daily')
every().day.do(daily_job)
every().hour.do(hourly_job)
assert len(schedule.jobs) == 2
# Make sure the hourly job is first
assert schedule.next_run() == original_datetime(2010, 1, 6, 14, 16,
tzinfo=utc)
assert schedule.idle_seconds() == 60 * 60
def test_last_run_property(self):
original_datetime = datetime.datetime
with mock_datetime(2010, 1, 6, 13, 16):
hourly_job = make_mock_job('hourly')
daily_job = make_mock_job('daily')
every().day.do(daily_job)
every().hour.do(hourly_job)
assert schedule.idle_seconds_since() is None
schedule.run_all()
assert schedule.last_run() == original_datetime(2010, 1, 6, 13, 16,
tzinfo=utc)
assert schedule.idle_seconds_since() == 0
schedule.clear()
assert schedule.last_run() is None
def test_job_info(self):
with mock_datetime(2010, 1, 6, 14, 16):
mock_job = make_mock_job(name='info_job')
info_job = every().minute.do(mock_job, 1, 7, 'three')
schedule.run_all()
assert len(schedule.jobs) == 1
assert schedule.jobs[0] == info_job
assert repr(info_job)
assert info_job.job_name is not None
s = info_job.info
assert 'info_job' in s
assert 'three' in s
assert '2010' in s
assert '14:16' in s
def test_cancel_job(self):
def stop_job():
return schedule.CancelJob
mock_job = make_mock_job()
every().second.do(stop_job)
mj = every().second.do(mock_job)
assert len(schedule.jobs) == 2
schedule.run_all()
assert len(schedule.jobs) == 1
assert schedule.jobs[0] == mj
schedule.cancel_job('Not a job')
assert len(schedule.jobs) == 1
schedule.default_scheduler.cancel_job('Not a job')
assert len(schedule.jobs) == 1
schedule.cancel_job(mj)
assert len(schedule.jobs) == 0
def test_cancel_jobs(self):
def stop_job():
return schedule.CancelJob
every().second.do(stop_job)
every().second.do(stop_job)
every().second.do(stop_job)
assert len(schedule.jobs) == 3
schedule.run_all()
assert len(schedule.jobs) == 0
def test_tag_type_enforcement(self):
job1 = every().second.do(make_mock_job(name='job1'))
self.assertRaises(TypeError, job1.tag, {})
self.assertRaises(TypeError, job1.tag, 1, 'a', [])
job1.tag(0, 'a', True)
assert len(job1.tags) == 3
def test_clear_by_tag(self):
every().second.do(make_mock_job(name='job1')).tag('tag1')
every().second.do(make_mock_job(name='job2')).tag('tag1', 'tag2')
every().second.do(make_mock_job(name='job3')).tag('tag3', 'tag3',
'tag3', 'tag2')
assert len(schedule.jobs) == 3
schedule.run_all()
assert len(schedule.jobs) == 3
schedule.clear('tag3')
assert len(schedule.jobs) == 2
schedule.clear('tag1')
assert len(schedule.jobs) == 0
every().second.do(make_mock_job(name='job1'))
every().second.do(make_mock_job(name='job2'))
every().second.do(make_mock_job(name='job3'))
schedule.clear()
assert len(schedule.jobs) == 0
def test_misconfigured_job_wont_break_scheduler(self):
"""
Ensure an interrupted job definition chain won't break
the scheduler instance permanently.
"""
scheduler = schedule.Scheduler()
scheduler.every()
scheduler.every(10).seconds
scheduler.run_pending()
class TimezoneTests(unittest.TestCase):
if sys.version_info < (3, 0, 0):
from schedule.timezone import UTC
utc = UTC()
def test_tzname(self):
fo = utc
self.assertIsInstance(fo, datetime.tzinfo)
dt = datetime.datetime.now()
self.assertIn("UTC", fo.tzname(dt))
def test_utcoffset(self):
fo = utc
self.assertIsInstance(fo, datetime.tzinfo)
dt = datetime.datetime.now()
self.assertEqual(fo.utcoffset(dt), datetime.timedelta(0))
def test_dst_is_datetime(self):
fo = utc
dt = datetime.datetime.now()
if sys.version_info > (3, 0, 0):
dst_arg = None
else:
dst_arg = datetime.timedelta(0)
self.assertEqual(fo.dst(dt), dst_arg)
class BasicConfigTest(unittest.TestCase):
"""Tests for logging.basicConfig."""
def setUp(self):
super(BasicConfigTest, self).setUp()
self.handlers = logging.root.handlers
self.saved_handlers = logging._handlers.copy()
self.saved_handler_list = logging._handlerList[:]
self.original_logging_level = logging.root.level
self.addCleanup(self.cleanup)
logging.root.handlers = []
def tearDown(self):
for h in logging.root.handlers[:]:
logging.root.removeHandler(h)
h.close()
super(BasicConfigTest, self).tearDown()
def cleanup(self):
setattr(logging.root, 'handlers', self.handlers)
logging._handlers.clear()
logging._handlers.update(self.saved_handlers)
logging._handlerList[:] = self.saved_handler_list
logging.root.level = self.original_logging_level
def test_debug_level(self):
old_level = logging.root.level
self.addCleanup(logging.root.setLevel, old_level)
debug = True
setup_logging(debug, '/dev/null')
self.assertEqual(logging.root.level, logging.DEBUG)
# Test that second call has no effect
logging.basicConfig(level=58)
self.assertEqual(logging.root.level, logging.DEBUG)
def test_info_level(self):
old_level = logging.root.level
self.addCleanup(logging.root.setLevel, old_level)
debug = False
setup_logging(debug, '/dev/null')
self.assertEqual(logging.root.level, logging.INFO)
# Test that second call has no effect
logging.basicConfig(level=58)
self.assertEqual(logging.root.level, logging.INFO)