Branchwell

Jobley / app · jobley.ai / Tests / JobleyKitTests / APIClientTests.swift

1import XCTest
2@testable import JobleyKit
3
4/// The API client against the real API code, run by scripts/test-api.sh (jobley-site's dev server
5/// on a fresh database seeded with five sample jobs). Skipped when JOBLEY_TEST_BASE is not set.
6final class APIClientTests: XCTestCase {
7 var base: URL!
8 var token: String!
9
10 override func setUpWithError() throws {
11 let env = ProcessInfo.processInfo.environment
12 guard let value = env["JOBLEY_TEST_BASE"], let url = URL(string: value) else {
13 throw XCTSkip("Run scripts/test-api.sh to test against the dev server.")
14 }
15 base = url
16 token = env["JOBLEY_TEST_TOKEN"] ?? "dev-admin-token-not-for-production-0000"
17 }
18
19 var publicAPI: APIClient { APIClient(base: base, client: .iphone) }
20 var mac: APIClient { APIClient(base: base, client: .mac, token: token) }
21 var agent: APIClient { APIClient(base: base, client: .mcp, token: token) }
22
23 func draft(_ title: String) -> JobDraft {
24 var draft = JobDraft()
25 draft.title = title; draft.company = "Testwood Studio"; draft.location = "Remote, Canada"
26 draft.workplace = "remote"; draft.employmentType = "full_time"; draft.category = "engineering"
27 draft.payMin = "90000"; draft.payMax = "120,000"; draft.payPeriod = "year"; draft.payCurrency = "cad"
28 draft.description = String(repeating: "Build and look after the tools our small team uses every day. ", count: 3)
29 draft.contactName = "Test Poster"; draft.contactEmail = "poster@example.org"
30 return draft
31 }
32
33 func expectError(_ code: String, _ work: () async throws -> Void, file: StaticString = #filePath, line: UInt = #line) async {
34 do { try await work(); XCTFail("Expected \(code)", file: file, line: line) }
35 catch let error as APIError { XCTAssertEqual(error.code, code, error.message, file: file, line: line) }
36 catch { XCTFail("Unexpected \(error)", file: file, line: line) }
37 }
38
39 func testMetaAndBoard() async throws {
40 let meta = try await publicAPI.meta()
41 XCTAssertEqual(meta.name, "Jobley")
42 XCTAssertEqual(meta.categories["support"], "Customer support")
43 XCTAssertEqual(meta.employmentTypes["full_time"], "Full time", "value → label maps keep their snake_case keys")
44
45 let page = try await publicAPI.jobs()
46 XCTAssertGreaterThanOrEqual(page.jobs.count, 5)
47 let dates = page.jobs.compactMap { APIDate.date($0.publishedAt) }
48 XCTAssertEqual(dates, dates.sorted(by: >), "newest first")
49 XCTAssertNil(page.jobs.first?.contact, "the public board never carries contact details")
50
51 let remote = try await publicAPI.jobs(workplace: "remote")
52 XCTAssertFalse(remote.jobs.isEmpty)
53 XCTAssertTrue(remote.jobs.allSatisfy { $0.workplace == "remote" })
54
55 let search = try await publicAPI.jobs(query: "Firmware")
56 XCTAssertEqual(search.jobs.first?.company, "Tidepool Robotics")
57
58 let paged = try await publicAPI.jobs(limit: 2)
59 XCTAssertEqual(paged.jobs.count, 2)
60 let next = try await publicAPI.jobs(limit: 2, cursor: try XCTUnwrap(paged.nextCursor))
61 XCTAssertTrue(Set(next.jobs.map(\.id)).isDisjoint(with: paged.jobs.map(\.id)))
62
63 let one = try await publicAPI.job(page.jobs[0].id)
64 XCTAssertEqual(one.id, page.jobs[0].id)
65 XCTAssertFalse(one.pay.text.isEmpty)
66 }
67
68 func testPostReviewPublishAndClose() async throws {
69 let posted = try await publicAPI.post(draft("Tools Engineer"), turnstileToken: nil)
70 XCTAssertEqual(posted.status, "pending")
71 XCTAssertFalse(posted.manageToken.isEmpty)
72 await expectError("not_found") { _ = try await self.publicAPI.job(posted.id) }
73
74 let queue = try await mac.adminJobs(status: "pending")
75 let queued = try XCTUnwrap(queue.first { $0.id == posted.id })
76 XCTAssertEqual(queued.contact?.email, "poster@example.org")
77 XCTAssertEqual(queued.pay.currency, "CAD")
78 XCTAssertEqual(queued.pay.max, 120000)
79
80 // Agents never decide.
81 await expectError("people_only") { _ = try await self.agent.approve(job: posted.id, publish: true) }
82 await expectError("people_only") { _ = try await self.agent.reject(job: posted.id, reason: "Not a real job") }
83
84 // Agents may tidy wording and leave notes.
85 let tidied = try await agent.edit(job: posted.id, changes: ["title": "Tools Engineer (Remote)"])
86 XCTAssertEqual(tidied.title, "Tools Engineer (Remote)")
87 try await agent.addNote(job: posted.id, note: "The pay range is shown and the company has a website.")
88
89 var edit = JobEdit(tidied)
90 edit.location = "Remote, anywhere in Canada"
91 XCTAssertEqual(Array(edit.changes(from: tidied).keys), ["location"])
92 let edited = try await mac.edit(job: posted.id, changes: edit.changes(from: tidied))
93 XCTAssertEqual(edited.location, "Remote, anywhere in Canada")
94
95 let published = try await mac.approve(job: posted.id, publish: true)
96 XCTAssertEqual(published.status, "published")
97 XCTAssertNotNil(published.expiresAt)
98 let live = try await publicAPI.job(posted.id)
99 XCTAssertEqual(live.title, "Tools Engineer (Remote)")
100
101 let item = try await mac.reviewItem(posted.id)
102 let actions = item.activity.map(\.action)
103 XCTAssertTrue(actions.contains("note"), "\(actions)")
104 XCTAssertTrue(item.activity.contains { $0.client == "mcp" }, "agent changes are logged as mcp")
105 XCTAssertEqual(item.candidateCount, 0)
106
107 let unpublished = try await mac.unpublish(job: posted.id, reason: "Checking the pay range")
108 XCTAssertEqual(unpublished.status, "unpublished")
109 await expectError("not_found") { _ = try await self.publicAPI.job(posted.id) }
110 _ = try await mac.publish(job: posted.id)
111 await expectError("wrong_state") { _ = try await self.mac.publish(job: posted.id) }
112
113 try await publicAPI.close(job: posted.id, manageToken: posted.manageToken)
114 let closed = try await mac.reviewItem(posted.id)
115 XCTAssertEqual(closed.job.status, "closed")
116 }
117
118 func testSendBackNeedsAReason() async throws {
119 let posted = try await publicAPI.post(draft("Commission Closer"), turnstileToken: nil)
120 await expectError("invalid") { _ = try await self.mac.reject(job: posted.id, reason: "") }
121 let sentBack = try await mac.reject(job: posted.id, reason: "Commission-only roles are not published.")
122 XCTAssertEqual(sentBack.status, "rejected")
123 XCTAssertEqual(sentBack.review?.reason, "Commission-only roles are not published.")
124 let sent = try await mac.adminJobs(status: "rejected")
125 XCTAssertTrue(sent.contains { $0.id == posted.id })
126 }
127
128 func testFormValidationComesBackPerField() async throws {
129 var bad = draft("x")
130 bad.payMin = "100"; bad.payMax = "50"; bad.description = "Too short."
131 do { _ = try await publicAPI.post(bad, turnstileToken: nil); XCTFail("expected invalid") }
132 catch let error as APIError {
133 XCTAssertEqual(error.code, "invalid")
134 XCTAssertNotNil(error.fields["title"])
135 XCTAssertNotNil(error.fields["description"])
136 }
137 }
138
139 func testCandidatesAndIntroductions() async throws {
140 let job = try await publicAPI.jobs().jobs[0]
141 var draft = CandidateDraft(jobID: job.id)
142 draft.name = "Robin Test"; draft.email = "robin@example.org"; draft.headline = "Support engineer, six years"
143 draft.links = "https://robin.example/work https://github.com/robin-example"; draft.consent = true
144 let received = try await publicAPI.putForward(draft, turnstileToken: nil)
145 XCTAssertEqual(received.status, "received")
146 let again = try await publicAPI.putForward(draft, turnstileToken: nil)
147 XCTAssertEqual(again.already, true)
148
149 await expectError("people_only") { _ = try await self.agent.candidates(jobID: job.id) }
150
151 let forJob = try await mac.candidates(jobID: job.id)
152 let robin = try XCTUnwrap(forJob.first { $0.email == "robin@example.org" })
153 XCTAssertEqual(robin.links.count, 2)
154 XCTAssertEqual(robin.status, "new")
155
156 var general = CandidateDraft()
157 general.name = "Sam Test"; general.email = "sam@example.org"; general.headline = "Bookkeeper"
158 general.lookingFor = "Part-time bookkeeping near Halifax"; general.consent = true
159 _ = try await publicAPI.putForward(general, turnstileToken: nil)
160 let anyJob = try await mac.candidates(jobID: "none")
161 XCTAssertTrue(anyJob.contains { $0.email == "sam@example.org" })
162 XCTAssertTrue(anyJob.allSatisfy { $0.jobID == nil })
163 let everyone = try await mac.candidates()
164 let times = everyone.compactMap { APIDate.date($0.createdAt) }
165 XCTAssertEqual(times, times.sorted(), "people are listed oldest first, never ranked")
166
167 let intro = try await mac.introduce(candidate: robin.id, jobID: nil, note: "Introduced by email to the hiring contact.")
168 XCTAssertEqual(intro.jobID, job.id)
169 XCTAssertEqual(intro.status, "introduced")
170 let introAgain = try await mac.introduce(candidate: robin.id, jobID: nil, note: nil)
171 XCTAssertEqual(introAgain.already, true)
172 let detail = try await mac.candidate(robin.id)
173 XCTAssertEqual(detail.introductions.count, 1)
174 XCTAssertEqual(detail.candidate.status, "introduced")
175
176 let reviewed = try await mac.setStatus(candidate: try XCTUnwrap(anyJob.first).id, status: "reviewed")
177 XCTAssertEqual(reviewed.status, "reviewed")
178 }
179
180 func testModeratorsAndRoles() async throws {
181 let me = try await mac.me()
182 XCTAssertTrue(me.isCurator)
183 let stats = try await mac.stats()
184 XCTAssertGreaterThanOrEqual(stats.jobs(.published), 5)
185
186 let application = try await applyToModerate()
187 let applications = try await mac.moderatorApplications()
188 XCTAssertTrue(applications.contains { $0.id == application })
189
190 // Approving gives a one-time passkey setup link, never a token. (The passkey itself is
191 // tested in jobley-site's test/passkeys.test.mjs with a software authenticator.)
192 let made = try await mac.approve(application: application, canSeeCandidates: false)
193 XCTAssertNotNil(PasskeyResponse.setupCode(from: made.setup.url))
194 let options = try await publicAPI.passkeyOptions(setupCode: PasskeyResponse.setupCode(from: made.setup.url)!)
195 XCTAssertEqual(options.options.user?.name, "Alex Test")
196 XCTAssertNotNil(options.challenge)
197 let again = try await mac.setupLink(moderator: made.moderator.id)
198 XCTAssertNotEqual(again.url, made.setup.url)
199
200 try await mac.setAccess(moderator: made.moderator.id, canSeeCandidates: true)
201 let list = try await mac.moderators()
202 XCTAssertEqual(list.first { $0.id == made.moderator.id }?.canSeeCandidates, true)
203
204 try await mac.revoke(moderator: made.moderator.id)
205 await expectError("link_expired") { _ = try await self.publicAPI.passkeyOptions(setupCode: PasskeyResponse.setupCode(from: again.url)!) }
206 }
207
208 func testPasskeySignInOptions() async throws {
209 let options = try await publicAPI.passkeySignInOptions()
210 XCTAssertFalse(options.challengeID.isEmpty)
211 XCTAssertNotNil(options.challenge)
212 await expectError("challenge_expired") {
213 _ = try await self.publicAPI.signIn(challengeID: "ch_unknown", assertion: [:])
214 }
215 let keys = try await mac.passkeys()
216 XCTAssertTrue(keys.isEmpty)
217 }
218
219 func testTokensAreRequired() async throws {
220 await expectError("unauthorized") { _ = try await self.publicAPI.me() }
221 await expectError("unauthorized") { _ = try await APIClient(base: self.base, client: .mac, token: "wrong-token-wrong-token-wrong").me() }
222 let purged = try await mac.purge()
223 XCTAssertFalse(purged.olderThan.isEmpty)
224 }
225
226 /// The client has no moderator form (only the website shows it), so post it directly.
227 func applyToModerate() async throws -> String {
228 var request = URLRequest(url: base.appending(path: "api/moderators"))
229 request.httpMethod = "POST"
230 request.setValue("application/json", forHTTPHeaderField: "Content-Type")
231 request.httpBody = try JSONSerialization.data(withJSONObject: [
232 "name": "Alex Test", "email": "alex+\(UUID().uuidString.prefix(6))@example.org", "hours_per_week": 3,
233 "why": "I have hired for small teams and I want job boards to be honest about pay.", "agree": true])
234 let (data, _) = try await URLSession.shared.data(for: request)
235 let reply = try JSONDecoder().decode(Received.self, from: data)
236 return reply.id
237 }
238}