import os
import signal
import time

from threading import Event, Thread

import pytest

from terry.api import Job


@pytest.mark.timeout(10)
def test_worker_job_success(controller, worker):
    job_started = Event()

    def work_func(channel):
        job_started.set()

    worker._worker_func = work_func

    job_id = controller.create_job_id()
    controller.create_job(job_id, 'test-tag')

    job_started.wait()  # wait until worker start the job
    worker.stop()

    job = controller.get_job(job_id)

    assert job.status == Job.COMPLETED
    assert job.worker_exception is None
    assert job.worker_id == worker.id


@pytest.mark.timeout(10)
def test_worker_job_exception(controller, worker):
    job_started = Event()

    def work_func(channel):
        job_started.set()
        raise Exception('exception from job')

    worker._worker_func = work_func

    job_id = controller.create_job_id()
    controller.create_job(job_id, 'test-tag')

    job_started.wait()  # wait until worker start the job
    worker.stop()

    job = controller.get_job(job_id)

    assert job.status == Job.COMPLETED
    assert job.worker_exception['reason'] == 'exception from job'
    assert job.worker_id == worker.id


@pytest.mark.timeout(10)
def test_worker_signal_handling(controller, worker):

    def handler(signum, frame):
        worker.request_stop()

    def signal_thread():
        time.sleep(1)  # wait until worker.join() is called
        os.kill(os.getpid(), signal.SIGUSR1)

    signal.signal(signal.SIGUSR1, handler)

    thread = Thread(target=signal_thread)
    thread.start()

    worker.join()

    assert not worker.is_running

@@ -1643,8 +1643,476 @@
 running%0A
+%0A%0A@pytest.mark.timeout(10)%0Adef test_worker_is_busy(controller, worker):%0A    job_started = Event()%0A    job_may_complete = Event()%0A%0A    def work_func(channel):%0A        job_started.set()%0A        job_may_complete.wait()%0A%0A    worker._worker_func = work_func%0A%0A    job_id = controller.create_job_id()%0A    controller.create_job(job_id, 'test-tag')%0A%0A    job_started.wait()%0A%0A    assert worker.is_busy%0A%0A    job_may_complete.set()%0A    worker.stop()%0A%0A    assert not worker.is_busy%0A

Add test for is_busy