aboutsummaryrefslogtreecommitdiffstats
path: root/tests/mock.rs
blob: 80d965b4c707540711625683eb2a700614f853b6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
use std::sync::atomic::AtomicBool;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

use serde_json::json;

use agent686::config::Config;
use agent686::provider::{self, Error, Outcome, Sink};

#[derive(Default)]
struct Collector {
    text: String,
    reasoning: String,
    finished: bool,
}

impl Sink for Collector {
    fn text(&mut self, s: &str) {
        self.text.push_str(s);
    }
    fn reasoning(&mut self, s: &str) {
        self.reasoning.push_str(s);
    }
    fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) {
        self.finished = true;
    }
}

/// Serves exactly one request on a random port, then closes. Returns the base
/// URL and a receiver for the request as the client sent it.
fn serve_once(response: &'static str) -> (String, mpsc::Receiver<String>) {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let (mut stream, _) = listener.accept().unwrap();
        let mut reader = BufReader::new(stream.try_clone().unwrap());

        let mut request = String::new();
        let mut content_length = 0usize;
        loop {
            let mut line = String::new();
            if reader.read_line(&mut line).unwrap_or(0) == 0 {
                break;
            }
            if line == "\r\n" || line == "\n" {
                break;
            }
            if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") {
                content_length = value.trim().parse().unwrap_or(0);
            }
            request.push_str(&line);
        }
        let mut body = vec![0u8; content_length];
        let _ = reader.read_exact(&mut body);
        request.push_str(&String::from_utf8_lossy(&body));
        let _ = tx.send(request);

        let _ = stream.write_all(response.as_bytes());
        let _ = stream.flush();
    });

    (format!("http://{addr}"), rx)
}

fn config(base_url: String) -> Config {
    Config {
        base_url,
        api_key: "test-key".into(),
        model: "test-model".into(),
        session: "testsession".into(),
    }
}

#[test]
fn streams_text_reasoning_and_usage() {
    const SSE: &str = concat!(
        "HTTP/1.1 200 OK\r\n",
        "Content-Type: text/event-stream\r\n",
        "Connection: close\r\n",
        "\r\n",
        "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}\n\n",
        "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n",
        "data: {\"choices\":[{\"delta\":{\"content\":\" from mock\"},\"finish_reason\":\"stop\"}]}\n\n",
        "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2}}\n\n",
        "data: [DONE]\n\n",
    );
    let (base, rx) = serve_once(SSE);
    let mut sink = Collector::default();
    let outcome = provider::chat(
        &config(base),
        &[json!({ "role": "user", "content": "hi" })],
        &AtomicBool::new(false),
        &mut sink,
    )
    .expect("chat should succeed");

    assert_eq!(outcome.content, "Hello from mock");
    assert_eq!(outcome.reasoning, "thinking");
    assert_eq!(sink.text, "Hello from mock");
    assert_eq!(sink.reasoning, "thinking");
    assert!(sink.finished);
    assert_eq!(outcome.usage.unwrap()["completion_tokens"], 2);

    let request = rx.recv().unwrap().to_ascii_lowercase();
    assert!(
        request.contains("x-opencode-session: testsession"),
        "session header missing from request:\n{request}"
    );
    assert!(request.contains("user-agent: agent686/"));
    assert!(request.contains("\"stream\":true"));
    assert!(request.contains("\"include_usage\":true"));
}

#[test]
fn assembles_tool_call_arguments_byte_for_byte() {
    const SSE: &str = concat!(
        "HTTP/1.1 200 OK\r\n",
        "Content-Type: text/event-stream\r\n",
        "Connection: close\r\n",
        "\r\n",
        "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\"}}]}}]}\n\n",
        "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\"a.txt\\\"}\"}}]}}]}\n\n",
        "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
        "data: [DONE]\n\n",
    );
    let (base, _rx) = serve_once(SSE);
    let mut sink = Collector::default();
    let outcome = provider::chat(
        &config(base),
        &[json!({ "role": "user", "content": "read a.txt" })],
        &AtomicBool::new(false),
        &mut sink,
    )
    .expect("chat should succeed");

    assert_eq!(outcome.tool_calls.len(), 1);
    let call = &outcome.tool_calls[0];
    assert_eq!(call.id, "call_1");
    assert_eq!(call.name, "read");
    assert_eq!(call.arguments, r#"{"path":"a.txt"}"#);
    assert_eq!(outcome.finish.as_deref(), Some("tool_calls"));
}

#[test]
fn surfaces_provider_error_text() {
    const RESPONSE: &str = concat!(
        "HTTP/1.1 401 Unauthorized\r\n",
        "Content-Type: application/json\r\n",
        "Connection: close\r\n",
        "\r\n",
        "{\"error\":{\"type\":\"authentication_error\",\"code\":\"api_key_expired\",",
        "\"message\":\"This API key has expired.\"}}",
    );
    let (base, _rx) = serve_once(RESPONSE);
    let mut sink = Collector::default();
    let error = provider::chat(
        &config(base),
        &[json!({ "role": "user", "content": "hi" })],
        &AtomicBool::new(false),
        &mut sink,
    )
    .expect_err("should fail");

    match error {
        Error::Status { code, message } => {
            assert_eq!(code, 401);
            assert!(message.contains("This API key has expired."), "{message}");
            assert!(message.contains("api_key_expired"), "{message}");
        }
        other => panic!("unexpected error: {other:?}"),
    }
}

#[test]
fn honours_a_cancelled_turn() {
    const SSE: &str = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\ndata: {\"choices\":[{\"delta\":{\"content\":\"x\"}}]}\n\n";
    let (base, _rx) = serve_once(SSE);
    let mut sink = Collector::default();
    let error = provider::chat(
        &config(base),
        &[json!({ "role": "user", "content": "hi" })],
        &AtomicBool::new(true),
        &mut sink,
    )
    .expect_err("cancelled turn should abort");
    assert!(matches!(error, Error::Aborted));
}