#!/usr/bin/python3

import json
import os
import subprocess
import time


path = os.path.dirname(os.path.realpath(__file__))

msgs = [
    {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {"rootUri": "file://" + path},
    },
    {"jsonrpc": "2.0", "id": 1, "method": "$ccls/info"},
    {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "workspace/symbol",
        "params": {"query": "test"},
    },
]


def get_msg(msg):
    msg_str = json.dumps(msg)
    rpc_str = "Content-Length: %d\r\n\r\n%s" % (len(msg_str), msg_str)
    return rpc_str.encode()


with subprocess.Popen(
    ["ccls", "-v=-2"], stdin=subprocess.PIPE, stdout=subprocess.PIPE
) as proc:
    for msg in msgs:
        proc.stdin.write(get_msg(msg))
        proc.stdin.flush()
        time.sleep(0.5)
    proc.stdin.close()
    out = proc.stdout.read().decode()
    print(out)
    assert "test_var" in out
    assert '"error":' not in out
