#!/usr/bin/env python3
# Use the run.py library from ../cqlpy:
import sys
sys.path.insert(1, sys.path[0] + '/../cqlpy')
import run

import redis

print('Scylla is: ' + run.find_scylla() + '.')

REDIS_PORT = 6379

# run_redis_cmd runs the same as run_scylla_cmd with *additional*
# parameters, so in particular both CQL and Reds APIs will be enabled.
def run_redis_cmd(pid, dir):
    (cmd, env) = run.run_scylla_cmd(pid, dir)
    ip = run.pid_to_ip(pid)
    cmd += [
        '--redis-port', str(REDIS_PORT),
    ]
    return (cmd, env)

pid = run.run_with_temporary_dir(run_redis_cmd)
ip = run.pid_to_ip(pid)

# Wait for both CQL and Redis APIs to become responsive. We obviously
# need the Redis API to test Redis, and currently we don't really need
# the CQL API, but maybe in the future we'll want it, so let's be prepared.
def check_redis(ip, port):
    try:
        r = redis.Redis(ip, port, decode_responses=True)
        assert r.ping() == True
    except redis.exceptions.ConnectionError:
        raise run.NotYetUp
    # Any other exception may indicate a problem, and is passed to the caller.

run.wait_for_services(pid, [
    lambda: run.check_cql(ip),
    lambda: check_redis(ip, REDIS_PORT),
])

# Finally run pytest:
success = run.run_pytest(sys.path[0], ['--redis-host', ip, '--redis-port', str(REDIS_PORT)] + sys.argv[1:])

run.summary = 'Redis tests pass' if success else 'Redis tests failure'

exit(0 if success else 1)

# Note that the run.cleanup_all() function runs now, just like on any exit
# for any reason in this script. It will delete the temporary files and
# announce the failure or success of the test (printing run.summary).
