import XCTest @testable import JobleyKit /// The API client against the real API code, run by scripts/test-api.sh (jobley-site's dev server /// on a fresh database seeded with five sample jobs). Skipped when JOBLEY_TEST_BASE is not set. final class APIClientTests: XCTestCase { var base: URL! var token: String! override func setUpWithError() throws { let env = ProcessInfo.processInfo.environment guard let value = env["JOBLEY_TEST_BASE"], let url = URL(string: value) else { throw XCTSkip("Run scripts/test-api.sh to test against the dev server.") } base = url token = env["JOBLEY_TEST_TOKEN"] ?? "dev-admin-token-not-for-production-0000" } var publicAPI: APIClient { APIClient(base: base, client: .iphone) } var mac: APIClient { APIClient(base: base, client: .mac, token: token) } var agent: APIClient { APIClient(base: base, client: .mcp, token: token) } func draft(_ title: String) -> JobDraft { var draft = JobDraft() draft.title = title; draft.company = "Testwood Studio"; draft.location = "Remote, Canada" draft.workplace = "remote"; draft.employmentType = "full_time"; draft.category = "engineering" draft.payMin = "90000"; draft.payMax = "120,000"; draft.payPeriod = "year"; draft.payCurrency = "cad" draft.description = String(repeating: "Build and look after the tools our small team uses every day. ", count: 3) draft.contactName = "Test Poster"; draft.contactEmail = "poster@example.org" return draft } func expectError(_ code: String, _ work: () async throws -> Void, file: StaticString = #filePath, line: UInt = #line) async { do { try await work(); XCTFail("Expected \(code)", file: file, line: line) } catch let error as APIError { XCTAssertEqual(error.code, code, error.message, file: file, line: line) } catch { XCTFail("Unexpected \(error)", file: file, line: line) } } func testMetaAndBoard() async throws { let meta = try await publicAPI.meta() XCTAssertEqual(meta.name, "Jobley") XCTAssertEqual(meta.categories["support"], "Customer support") XCTAssertEqual(meta.employmentTypes["full_time"], "Full time", "value → label maps keep their snake_case keys") let page = try await publicAPI.jobs() XCTAssertGreaterThanOrEqual(page.jobs.count, 5) let dates = page.jobs.compactMap { APIDate.date($0.publishedAt) } XCTAssertEqual(dates, dates.sorted(by: >), "newest first") XCTAssertNil(page.jobs.first?.contact, "the public board never carries contact details") let remote = try await publicAPI.jobs(workplace: "remote") XCTAssertFalse(remote.jobs.isEmpty) XCTAssertTrue(remote.jobs.allSatisfy { $0.workplace == "remote" }) let search = try await publicAPI.jobs(query: "Firmware") XCTAssertEqual(search.jobs.first?.company, "Tidepool Robotics") let paged = try await publicAPI.jobs(limit: 2) XCTAssertEqual(paged.jobs.count, 2) let next = try await publicAPI.jobs(limit: 2, cursor: try XCTUnwrap(paged.nextCursor)) XCTAssertTrue(Set(next.jobs.map(\.id)).isDisjoint(with: paged.jobs.map(\.id))) let one = try await publicAPI.job(page.jobs[0].id) XCTAssertEqual(one.id, page.jobs[0].id) XCTAssertFalse(one.pay.text.isEmpty) } func testPostReviewPublishAndClose() async throws { let posted = try await publicAPI.post(draft("Tools Engineer"), turnstileToken: nil) XCTAssertEqual(posted.status, "pending") XCTAssertFalse(posted.manageToken.isEmpty) await expectError("not_found") { _ = try await self.publicAPI.job(posted.id) } let queue = try await mac.adminJobs(status: "pending") let queued = try XCTUnwrap(queue.first { $0.id == posted.id }) XCTAssertEqual(queued.contact?.email, "poster@example.org") XCTAssertEqual(queued.pay.currency, "CAD") XCTAssertEqual(queued.pay.max, 120000) // Agents never decide. await expectError("people_only") { _ = try await self.agent.approve(job: posted.id, publish: true) } await expectError("people_only") { _ = try await self.agent.reject(job: posted.id, reason: "Not a real job") } // Agents may tidy wording and leave notes. let tidied = try await agent.edit(job: posted.id, changes: ["title": "Tools Engineer (Remote)"]) XCTAssertEqual(tidied.title, "Tools Engineer (Remote)") try await agent.addNote(job: posted.id, note: "The pay range is shown and the company has a website.") var edit = JobEdit(tidied) edit.location = "Remote, anywhere in Canada" XCTAssertEqual(Array(edit.changes(from: tidied).keys), ["location"]) let edited = try await mac.edit(job: posted.id, changes: edit.changes(from: tidied)) XCTAssertEqual(edited.location, "Remote, anywhere in Canada") let published = try await mac.approve(job: posted.id, publish: true) XCTAssertEqual(published.status, "published") XCTAssertNotNil(published.expiresAt) let live = try await publicAPI.job(posted.id) XCTAssertEqual(live.title, "Tools Engineer (Remote)") let item = try await mac.reviewItem(posted.id) let actions = item.activity.map(\.action) XCTAssertTrue(actions.contains("note"), "\(actions)") XCTAssertTrue(item.activity.contains { $0.client == "mcp" }, "agent changes are logged as mcp") XCTAssertEqual(item.candidateCount, 0) let unpublished = try await mac.unpublish(job: posted.id, reason: "Checking the pay range") XCTAssertEqual(unpublished.status, "unpublished") await expectError("not_found") { _ = try await self.publicAPI.job(posted.id) } _ = try await mac.publish(job: posted.id) await expectError("wrong_state") { _ = try await self.mac.publish(job: posted.id) } try await publicAPI.close(job: posted.id, manageToken: posted.manageToken) let closed = try await mac.reviewItem(posted.id) XCTAssertEqual(closed.job.status, "closed") } func testSendBackNeedsAReason() async throws { let posted = try await publicAPI.post(draft("Commission Closer"), turnstileToken: nil) await expectError("invalid") { _ = try await self.mac.reject(job: posted.id, reason: "") } let sentBack = try await mac.reject(job: posted.id, reason: "Commission-only roles are not published.") XCTAssertEqual(sentBack.status, "rejected") XCTAssertEqual(sentBack.review?.reason, "Commission-only roles are not published.") let sent = try await mac.adminJobs(status: "rejected") XCTAssertTrue(sent.contains { $0.id == posted.id }) } func testFormValidationComesBackPerField() async throws { var bad = draft("x") bad.payMin = "100"; bad.payMax = "50"; bad.description = "Too short." do { _ = try await publicAPI.post(bad, turnstileToken: nil); XCTFail("expected invalid") } catch let error as APIError { XCTAssertEqual(error.code, "invalid") XCTAssertNotNil(error.fields["title"]) XCTAssertNotNil(error.fields["description"]) } } func testCandidatesAndIntroductions() async throws { let job = try await publicAPI.jobs().jobs[0] var draft = CandidateDraft(jobID: job.id) draft.name = "Robin Test"; draft.email = "robin@example.org"; draft.headline = "Support engineer, six years" draft.links = "https://robin.example/work https://github.com/robin-example"; draft.consent = true let received = try await publicAPI.putForward(draft, turnstileToken: nil) XCTAssertEqual(received.status, "received") let again = try await publicAPI.putForward(draft, turnstileToken: nil) XCTAssertEqual(again.already, true) await expectError("people_only") { _ = try await self.agent.candidates(jobID: job.id) } let forJob = try await mac.candidates(jobID: job.id) let robin = try XCTUnwrap(forJob.first { $0.email == "robin@example.org" }) XCTAssertEqual(robin.links.count, 2) XCTAssertEqual(robin.status, "new") var general = CandidateDraft() general.name = "Sam Test"; general.email = "sam@example.org"; general.headline = "Bookkeeper" general.lookingFor = "Part-time bookkeeping near Halifax"; general.consent = true _ = try await publicAPI.putForward(general, turnstileToken: nil) let anyJob = try await mac.candidates(jobID: "none") XCTAssertTrue(anyJob.contains { $0.email == "sam@example.org" }) XCTAssertTrue(anyJob.allSatisfy { $0.jobID == nil }) let everyone = try await mac.candidates() let times = everyone.compactMap { APIDate.date($0.createdAt) } XCTAssertEqual(times, times.sorted(), "people are listed oldest first, never ranked") let intro = try await mac.introduce(candidate: robin.id, jobID: nil, note: "Introduced by email to the hiring contact.") XCTAssertEqual(intro.jobID, job.id) XCTAssertEqual(intro.status, "introduced") let introAgain = try await mac.introduce(candidate: robin.id, jobID: nil, note: nil) XCTAssertEqual(introAgain.already, true) let detail = try await mac.candidate(robin.id) XCTAssertEqual(detail.introductions.count, 1) XCTAssertEqual(detail.candidate.status, "introduced") let reviewed = try await mac.setStatus(candidate: try XCTUnwrap(anyJob.first).id, status: "reviewed") XCTAssertEqual(reviewed.status, "reviewed") } func testModeratorsAndRoles() async throws { let me = try await mac.me() XCTAssertTrue(me.isCurator) let stats = try await mac.stats() XCTAssertGreaterThanOrEqual(stats.jobs(.published), 5) let application = try await applyToModerate() let applications = try await mac.moderatorApplications() XCTAssertTrue(applications.contains { $0.id == application }) // Approving gives a one-time passkey setup link, never a token. (The passkey itself is // tested in jobley-site's test/passkeys.test.mjs with a software authenticator.) let made = try await mac.approve(application: application, canSeeCandidates: false) XCTAssertNotNil(PasskeyResponse.setupCode(from: made.setup.url)) let options = try await publicAPI.passkeyOptions(setupCode: PasskeyResponse.setupCode(from: made.setup.url)!) XCTAssertEqual(options.options.user?.name, "Alex Test") XCTAssertNotNil(options.challenge) let again = try await mac.setupLink(moderator: made.moderator.id) XCTAssertNotEqual(again.url, made.setup.url) try await mac.setAccess(moderator: made.moderator.id, canSeeCandidates: true) let list = try await mac.moderators() XCTAssertEqual(list.first { $0.id == made.moderator.id }?.canSeeCandidates, true) try await mac.revoke(moderator: made.moderator.id) await expectError("link_expired") { _ = try await self.publicAPI.passkeyOptions(setupCode: PasskeyResponse.setupCode(from: again.url)!) } } func testPasskeySignInOptions() async throws { let options = try await publicAPI.passkeySignInOptions() XCTAssertFalse(options.challengeID.isEmpty) XCTAssertNotNil(options.challenge) await expectError("challenge_expired") { _ = try await self.publicAPI.signIn(challengeID: "ch_unknown", assertion: [:]) } let keys = try await mac.passkeys() XCTAssertTrue(keys.isEmpty) } func testTokensAreRequired() async throws { await expectError("unauthorized") { _ = try await self.publicAPI.me() } await expectError("unauthorized") { _ = try await APIClient(base: self.base, client: .mac, token: "wrong-token-wrong-token-wrong").me() } let purged = try await mac.purge() XCTAssertFalse(purged.olderThan.isEmpty) } /// The client has no moderator form (only the website shows it), so post it directly. func applyToModerate() async throws -> String { var request = URLRequest(url: base.appending(path: "api/moderators")) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try JSONSerialization.data(withJSONObject: [ "name": "Alex Test", "email": "alex+\(UUID().uuidString.prefix(6))@example.org", "hours_per_week": 3, "why": "I have hired for small teams and I want job boards to be honest about pay.", "agree": true]) let (data, _) = try await URLSession.shared.data(for: request) let reply = try JSONDecoder().decode(Received.self, from: data) return reply.id } }