import Foundation import Testing @testable import gitbay private func makeClient() throws -> (GitbayClient, StubProtocol.Box) { let box = StubProtocol.box() let client = GitbayClient( instance: try GitbayInstance(url: "https://gitbay.org"), token: "test-token", session: box.session() ) return (client, box) } private func show(_ fields: String) -> String { #"{"protocol_version":1,"data":{"mail":true,"watch":false,"# + fields + #"},"exit_code":0}"# } @MainActor struct ReplyByMailTests { @Test func theSwitchShowsWhereTheInstanceReadsReplies() async throws { let (client, stub) = try makeClient() stub.enqueue(.init(status: 200, json: show(#""reply":false,"reply_available":true"#), match: "argv=show")) let model = AccountViewModel(client: client) await model.loadNotificationPreferences() #expect(model.replyOn == false) #expect(model.offersReply) } @Test func noSwitchWhereTheInstanceDoesNot() async throws { let (client, stub) = try makeClient() stub.enqueue(.init(status: 200, json: show(#""reply":false,"reply_available":false"#), match: "argv=show")) let model = AccountViewModel(client: client) await model.loadNotificationPreferences() #expect(!model.offersReply) } /// A server without reply_available says nothing either way: the /// switch shows, and the refusal explains if it cannot be turned on. @Test func anOlderServerShowsTheSwitch() async throws { let (client, stub) = try makeClient() stub.enqueue(.init(status: 200, json: show(#""reply":false"#), match: "argv=show")) let model = AccountViewModel(client: client) await model.loadNotificationPreferences() #expect(model.offersReply) } @Test func turningItOnSendsReplyOn() async throws { let (client, stub) = try makeClient() stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"data":{},"exit_code":0}"#, match: "cmd")) stub.enqueue(.init(status: 200, json: show(#""reply":true,"reply_available":true"#), match: "argv=show")) let model = AccountViewModel(client: client) await model.setReply(true) let write = try #require(stub.seen.first { $0.method == "POST" }) let body = try #require(try JSONSerialization.jsonObject(with: write.body) as? [String: Any]) #expect(body["argv"] as? [String] == ["notifications", "settings", "reply", "on"]) #expect(model.replyOn == true) } }