# retoor <retoor@molodetz.nl>


def test_nl_requires_auth(client):
    assert (
        client.post("/dbapi/nl", json={"question": "x", "table": "users"}).status_code
        == 403
    )


def test_nl_missing_fields_is_400(client, auth):
    assert client.post("/dbapi/nl", json={"question": "x"}, headers=auth).status_code == 400


def test_nl_denied_table_is_404(client, auth):
    response = client.post(
        "/dbapi/nl", json={"question": "x", "table": "sessions"}, headers=auth
    )
    assert response.status_code == 404


def test_nl_is_graceful_when_gateway_fails(client, auth, monkeypatch):
    async def _boom(*args, **kwargs):
        raise RuntimeError("gateway down")

    monkeypatch.setattr(
        "devplacepy.services.dbapi.nl2sql._complete", _boom
    )
    response = client.post(
        "/dbapi/nl",
        json={"question": "all administrators", "table": "users"},
        headers=auth,
    )
    assert response.status_code == 200
    body = response.json()
    assert body["valid"] is False
    assert body["error"]
