示例#1
0
async def test_run_checks_pass_cached():
    def check1():
        yield True, ''
        yield False, ''

    def check2():
        yield True, ''
        yield False, ''

    def check3():
        yield True, ''
        yield False, ''

    checker = HealthCheck(checks=[check1, check2, check3], )

    resp = await checker.run(None)

    assert resp.status == 200
    assert resp.headers == {}
    assert resp.body.decode() == MSG_OK

    assert len(checker.cache) == 3

    resp = await checker.run(None)

    assert resp.status == 200
    assert resp.headers == {}
    assert resp.body.decode() == MSG_OK

    assert len(checker.cache) == 3
def test_init_with_app_custom_uri():
    app = Sanic()
    assert len(app.router.routes_names) == 0

    HealthCheck(app=app, uri='/v2/health')
    assert len(app.router.routes_names) == 1
    assert 'run' in app.router.routes_names
    assert '/v2/health' in app.router.routes_names['run'][0]
def test_init_with_app():
    app = Sanic()
    assert len(app.router.routes_names) == 0

    HealthCheck(app=app)
    assert len(app.router.routes_names) == 1
    assert 'run' in app.router.routes_names
    assert HealthCheck.default_uri in app.router.routes_names['run'][0]
示例#4
0
async def test_run_no_checks():
    checker = HealthCheck()

    resp = await checker.run(None)

    assert resp.status == 200
    assert resp.headers == {}
    assert resp.body.decode() == MSG_OK

    assert len(checker.cache) == 0
async def test_exec_check_fails_coro():
    checker = HealthCheck()

    async def test_check():
        return False, 'test message'

    now = time.time()
    resp = await checker.exec_check(test_check)

    assert isinstance(resp, dict)
    assert len(resp) == 4
    assert resp['check'] == 'test_check'
    assert resp['message'] == 'test message'
    assert resp['passed'] is False
    assert math.isclose(resp['timestamp'], now, rel_tol=1)
async def test_exec_check_exception_coro():
    checker = HealthCheck()

    async def test_check():
        raise ValueError('test error')

    now = time.time()
    resp = await checker.exec_check(test_check)

    assert isinstance(resp, dict)
    assert len(resp) == 4
    assert resp['check'] == 'test_check'
    assert resp['message'] == 'Exception raised: ValueError: test error'
    assert resp['passed'] is False
    assert math.isclose(resp['timestamp'], now, rel_tol=1)
示例#7
0
async def test_run_checks_fail():
    def check1():
        return True, ''

    def check2():
        return False, ''

    checker = HealthCheck(checks=[check1, check2], )

    resp = await checker.run(None)

    assert resp.status == 500
    assert resp.headers == {}
    assert resp.body.decode() == MSG_FAIL

    assert len(checker.cache) == 2
def test_add_check():
    checker = HealthCheck()
    assert len(checker.checks) == 0

    def check():
        return True, ''

    checker.add_check(check)
    assert len(checker.checks) == 1
    checker.add_check(check)
    assert len(checker.checks) == 2
示例#9
0
async def test_run_custom_success_data():
    def handler(results):
        return 'handler called'

    checker = HealthCheck(
        success_headers={'foo': 'bar'},
        success_status=201,
        success_handler=handler,
    )

    resp = await checker.run(None)

    assert resp.status == 201
    assert resp.headers == {'foo': 'bar'}
    assert resp.body.decode() == 'handler called'

    assert len(checker.cache) == 0
示例#10
0
async def test_run_custom_failure_data():
    def check1():
        return False, ''

    def handler(results):
        return 'handler called'

    checker = HealthCheck(
        failure_headers={'foo': 'bar'},
        failure_status=501,
        failure_handler=handler,
        checks=[check1],
    )

    resp = await checker.run(None)

    assert resp.status == 501
    assert resp.headers == {'foo': 'bar'}
    assert resp.body.decode() == 'handler called'

    assert len(checker.cache) == 1
示例#11
0
async def test_run_checks_pass_no_cache():
    def check1():
        return True, ''

    def check2():
        return True, ''

    def check3():
        return True, ''

    checker = HealthCheck(
        no_cache=True,
        checks=[check1, check2, check3],
    )

    resp = await checker.run(None)

    assert resp.status == 200
    assert resp.headers == {}
    assert resp.body.decode() == MSG_OK

    assert len(checker.cache) == 0
示例#12
0
"""Example Sanic application showcasing sanic-healthcheck."""

import time
import random
from sanic import Sanic, response
from sanic_healthcheck import HealthCheck, ReadyCheck

app = Sanic()
health_check = HealthCheck(app, no_cache=True)
ready_check = ReadyCheck(app)

start = time.time()


@app.route('/')
async def test(request):
    return response.json({'hello', 'world'})


# Define checks for the health check.
def check_health_random():
    if random.random() > 0.9:
        return False, 'the random number is > 0.9'
    return True, 'the random number is <= 0.9'


# Define checks for the ready check.
def check_ready():
    if time.time() > start + 7:
        return True, 'ready: seven seconds elapsed'
    return False, 'not ready: seven seconds have not elapsed yet'
示例#13
0
    os.write(2, 'Received SIGINT. Stop!\n'.encode())
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)


app = Sanic(__name__)
CORS(app)

logging.basicConfig(level='INFO', filename="/mnt/log/worker.log", filemode='a',
                    format='%(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logging.addLevelName(logging.WARNING, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
logging.addLevelName(logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR))
logger = logging.getLogger(__name__)

health = HealthCheck(app, "/healthcheck")

def worker_status():
    return True, 'worker ok'

health.add_check(worker_status)


@app.route('/load', methods=['POST'])
async def load(request):

    timer = Timer()

    global_response = update_status = update_models()
    update_model_detection()