forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPIClientMemoryMutationRequestTests.swift
More file actions
180 lines (149 loc) · 5.67 KB
/
Copy pathAPIClientMemoryMutationRequestTests.swift
File metadata and controls
180 lines (149 loc) · 5.67 KB
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
import XCTest
@testable import Omi_Computer
private final class MemoryMutationURLCapture: URLProtocol, @unchecked Sendable {
private static let lock = NSLock()
private nonisolated(unsafe) static var _request: URLRequest?
private nonisolated(unsafe) static var _body: Data?
private nonisolated(unsafe) static var _requests: [(method: String, path: String)] = []
static var request: URLRequest? {
lock.lock()
defer { lock.unlock() }
return _request
}
static var body: Data? {
lock.lock()
defer { lock.unlock() }
return _body
}
static var requests: [(method: String, path: String)] {
lock.lock()
defer { lock.unlock() }
return _requests
}
static func reset() {
lock.lock()
_request = nil
_body = nil
_requests = []
lock.unlock()
}
override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
override func startLoading() {
let body = Self.bodyData(from: request)
Self.lock.lock()
Self._request = request
Self._body = body
Self._requests.append((request.httpMethod ?? "GET", request.url?.path ?? ""))
Self.lock.unlock()
let response = HTTPURLResponse(
url: request.url!,
statusCode: 200,
httpVersion: nil,
headerFields: ["Content-Type": "application/json"]
)!
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
let payload: Data
if request.httpMethod == "GET", request.url?.path == "/v1/users/transcription-preferences" {
payload = Data(
"{\"single_language_mode\":false,\"vocabulary\":[\"Omi\",\"Codex\"],\"language\":\"en\"}".utf8)
} else {
payload = Data("{\"status\":\"ok\"}".utf8)
}
client?.urlProtocol(self, didLoad: payload)
client?.urlProtocolDidFinishLoading(self)
}
override func stopLoading() {}
private static func bodyData(from request: URLRequest) -> Data? {
if let body = request.httpBody {
return body
}
guard let stream = request.httpBodyStream else {
return nil
}
stream.open()
defer { stream.close() }
var body = Data()
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 4_096)
defer { buffer.deallocate() }
while stream.hasBytesAvailable {
let readCount = stream.read(buffer, maxLength: 4_096)
if readCount > 0 {
body.append(buffer, count: readCount)
} else {
break
}
}
return body
}
}
final class APIClientMemoryMutationRequestTests: XCTestCase {
override func setUp() {
super.setUp()
MemoryMutationURLCapture.reset()
setenv("OMI_PYTHON_API_URL", "http://memory-contract-test:9001", 1)
}
override func tearDown() {
unsetenv("OMI_PYTHON_API_URL")
MemoryMutationURLCapture.reset()
super.tearDown()
}
private func makeClient() async -> APIClient {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [MemoryMutationURLCapture.self]
let client = APIClient(session: URLSession(configuration: configuration))
await client.setTestAuthHeader("Bearer test-token")
return client
}
func testReviewMemorySendsVerdictAsQueryParameter() async throws {
let client = await makeClient()
try await client.reviewMemory(id: "memory-1", keep: false)
let request = try XCTUnwrap(MemoryMutationURLCapture.request)
XCTAssertEqual(request.httpMethod, "POST")
XCTAssertEqual(request.url?.path, "/v3/memories/memory-1/review")
// The route declares `value` as a bare scalar, so FastAPI binds it from the
// query string. Sending it in the body would 422.
XCTAssertEqual(request.url?.query, "value=false")
}
func testReviewMemoryKeepSendsTrue() async throws {
let client = await makeClient()
try await client.reviewMemory(id: "memory-2", keep: true)
let request = try XCTUnwrap(MemoryMutationURLCapture.request)
XCTAssertEqual(request.url?.path, "/v3/memories/memory-2/review")
XCTAssertEqual(request.url?.query, "value=true")
}
func testEditMemorySendsValueInJSONBody() async throws {
let client = await makeClient()
try await client.editMemory(id: "memory-1", content: "Updated content")
let request = try XCTUnwrap(MemoryMutationURLCapture.request)
XCTAssertEqual(request.httpMethod, "PATCH")
XCTAssertEqual(request.url?.path, "/v3/memories/memory-1")
XCTAssertNil(request.url?.query)
XCTAssertEqual(try requestJSON()["value"] as? String, "Updated content")
}
func testUpdateMemoryVisibilitySendsValueInJSONBody() async throws {
let client = await makeClient()
try await client.updateMemoryVisibility(id: "memory-1", visibility: "private")
let request = try XCTUnwrap(MemoryMutationURLCapture.request)
XCTAssertEqual(request.httpMethod, "PATCH")
XCTAssertEqual(request.url?.path, "/v3/memories/memory-1/visibility")
XCTAssertNil(request.url?.query)
XCTAssertEqual(try requestJSON()["value"] as? String, "private")
}
func testUpdateTranscriptionPreferencesReadsCanonicalStateAfterStatusResponse() async throws {
let client = await makeClient()
let saved = try await client.updateTranscriptionPreferences(vocabulary: ["Omi", "Codex"])
XCTAssertEqual(saved.vocabulary, ["Omi", "Codex"])
XCTAssertEqual(
MemoryMutationURLCapture.requests.map { "\($0.method) \($0.path)" },
[
"PATCH /v1/users/transcription-preferences",
"GET /v1/users/transcription-preferences",
]
)
}
private func requestJSON() throws -> [String: Any] {
let body = try XCTUnwrap(MemoryMutationURLCapture.body)
return try XCTUnwrap(JSONSerialization.jsonObject(with: body) as? [String: Any])
}
}