summaryrefslogtreecommitdiff
path: root/tests/test_executors.py
blob: f126f3dc0138052189df019b0b69c2ba3dd03589 (plain)
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
import time

import pytest

from apscheduler.executors.base import MaxInstancesReachedError


try:
    from unittest.mock import Mock, MagicMock
except ImportError:
    from mock import Mock, MagicMock


@pytest.fixture
def mock_scheduler():
    scheduler_ = Mock([])
    scheduler_._create_lock = MagicMock()
    return scheduler_


@pytest.fixture
def threadpoolexecutor(request):
    from apscheduler.executors.pool import ThreadPoolExecutor
    executor = ThreadPoolExecutor()
    request.addfinalizer(executor.shutdown)
    return executor


@pytest.fixture
def processpoolexecutor(request):
    from apscheduler.executors.pool import ProcessPoolExecutor
    executor = ProcessPoolExecutor()
    request.addfinalizer(executor.shutdown)
    return executor


@pytest.fixture(params=[threadpoolexecutor, processpoolexecutor], ids=['threadpool', 'processpool'])
def executor(request, mock_scheduler):
    executor_ = request.param(request)
    executor_.start(mock_scheduler, 'dummy')
    request.addfinalizer(executor_.shutdown)
    return executor_


def wait_event():
    time.sleep(0.2)
    return 'test'


def test_max_instances(mock_scheduler, executor, create_job, freeze_time):
    """Tests that the maximum instance limit on a job is respected."""

    events = []
    mock_scheduler._dispatch_event = lambda event: events.append(event)
    job = create_job(func=wait_event, max_instances=2)
    executor.submit_job(job, [freeze_time.current])
    executor.submit_job(job, [freeze_time.current])

    pytest.raises(MaxInstancesReachedError, executor.submit_job, job, [freeze_time.current])
    executor.shutdown()
    assert len(events) == 2
    assert events[0].retval == 'test'
    assert events[1].retval == 'test'