gitbayTests/DiscoveryTests.swift

v1.10.0
gitbay-ios/gitbayTests/DiscoveryTests.swift history · blame · raw

160 lines · 6161 bytes

  1import Foundation
  2import Testing
  3@testable import gitbay
  4
  5private func makeClient() throws -> (GitbayClient, StubProtocol.Box) {
  6    let box = StubProtocol.box()
  7    let client = GitbayClient(
  8        instance: try GitbayInstance(url: "https://gitbay.org"),
  9        token: "test-token",
 10        session: box.session()
 11    )
 12    return (client, box)
 13}
 14
 15struct FeedEventTests {
 16
 17    private func decode(_ json: String) throws -> FeedEvent {
 18        let decoder = GitbayClient.decoder()
 19        return try decoder.decode(FeedEvent.self, from: Data(json.utf8))
 20    }
 21
 22    @Test func knownKindsGetPhrasesAndDestinations() throws {
 23        let merged = try decode("""
 24            {"id":777,"repo":"krz/gitbay-ios","actor":"cmc","kind":"mr.merged",\
 25            "data":{"number":6,"sha":"b55fbb"},"created_at":"2026-08-27T15:31:10Z"}
 26            """)
 27        #expect(merged.phrase == "merged !6")
 28        #expect(merged.destination == .mr(repo: "krz/gitbay-ios", number: 6))
 29
 30        let build = try decode("""
 31            {"id":1,"repo":"krz/gitbay","actor":"","kind":"build.success",\
 32            "data":{"number":56,"job":"ci"},"created_at":"2026-08-27T15:31:10Z"}
 33            """)
 34        #expect(build.phrase == "build success ci")
 35        #expect(build.displayActor == "gitbay")
 36        #expect(build.destination == .build(repo: "krz/gitbay", number: 56))
 37
 38        let release = try decode("""
 39            {"id":2,"repo":"krz/orgo","actor":"krz","kind":"release.created",\
 40            "data":{"tag":"v2.1.0"},"created_at":"2026-08-27T15:31:10Z"}
 41            """)
 42        #expect(release.phrase == "released v2.1.0")
 43        #expect(release.destination == .release(repo: "krz/orgo", tag: "v2.1.0"))
 44    }
 45
 46    @Test func unknownKindsRenderRawAndFallBackToTheRepo() throws {
 47        let event = try decode("""
 48            {"id":3,"repo":"krz/gitbay","kind":"wiki.edited",\
 49            "data":{"page":"Parity"},"created_at":"2026-08-27T15:31:10Z"}
 50            """)
 51        #expect(event.phrase == "wiki.edited")
 52        #expect(event.destination == .repo("krz/gitbay"))
 53    }
 54
 55    @Test func missingDataDoesNotSinkTheEvent() throws {
 56        let event = try decode("""
 57            {"id":4,"repo":"krz/gitbay","actor":"cmc","kind":"push",\
 58            "created_at":"2026-08-27T15:31:10Z"}
 59            """)
 60        #expect(event.phrase == "pushed")
 61        #expect(event.destination == .repo("krz/gitbay"))
 62    }
 63}
 64
 65@MainActor
 66struct GrepViewModelTests {
 67
 68    @Test func searchGroupsMatchesByFileInServerOrder() async throws {
 69        let (client, stub) = try makeClient()
 70        stub.enqueue(.init(status: 200, json: """
 71            {"protocol_version":1,"data":[\
 72            {"path":"internal/a.go","line":3,"text":"foo bar"},\
 73            {"path":"internal/a.go","line":9,"text":"more foo"},\
 74            {"path":"cmd/b.go","line":1,"text":"foo again"}\
 75            ],"exit_code":0}
 76            """))
 77        let model = GrepViewModel(client: client, repoPath: "krz/gitbay")
 78
 79        await model.search("  foo ")
 80
 81        #expect(model.byFile.map(\.file) == ["internal/a.go", "cmd/b.go"])
 82        #expect(model.byFile[0].matches.map(\.line) == [3, 9])
 83        let seen = try #require(stub.seen.first)
 84        #expect(seen.url.query() == "argv=repo&argv=grep&argv=krz/gitbay&argv=foo")
 85    }
 86
 87    @Test func noMatchesIsAnEmptyStateNamingTheQuery() async throws {
 88        let (client, stub) = try makeClient()
 89        stub.enqueue(.init(status: 200, json: #"{"protocol_version":1,"exit_code":0}"#))
 90        let model = GrepViewModel(client: client, repoPath: "krz/gitbay")
 91
 92        await model.search("nothing")
 93
 94        guard case .empty(let message)? = model.state else {
 95            Issue.record("expected .empty, got \(String(describing: model.state))")
 96            return
 97        }
 98        #expect(message.contains("nothing"))
 99    }
100
101    @Test func aBlankQueryDoesNotSearch() async throws {
102        let (client, stub) = try makeClient()
103        _ = client
104        let model = GrepViewModel(client: client, repoPath: "krz/gitbay")
105
106        await model.search("   ")
107
108        #expect(model.state == nil)
109        #expect(stub.seen.isEmpty)
110    }
111}
112
113@MainActor
114struct RepoSearchTests {
115
116    @Test func aTypedQuerySearchesServerSideAfterTheDebounce() async throws {
117        let (client, stub) = try makeClient()
118        stub.enqueue(.init(status: 200, json: """
119            {"protocol_version":1,"data":{"items":[\
120            {"path":"cmc/notes","visibility":"private"}]},"exit_code":0}
121            """, match: "argv=repo&argv=list"))
122        stub.enqueue(.init(status: 200, json: """
123            {"protocol_version":1,"data":[\
124            {"path":"krz/space-wiki","visibility":"public","description":"A fun wiki about space.",\
125            "topics":["wiki"]}],"exit_code":0}
126            """, match: "argv=search"))
127        let model = RepoListViewModel(client: client)
128        await model.load()
129
130        model.searchText = "space"
131        // Before the server answers, the client filter runs over loaded
132        // pages — no match here.
133        #expect(model.visibleRepos.isEmpty)
134        try await Task.sleep(for: .milliseconds(700))
135
136        // The server search found a public repo not in the account's list.
137        #expect(model.visibleRepos.map(\.path) == ["krz/space-wiki"])
138        #expect(stub.seen.contains {
139            $0.url.query() == "argv=repo&argv=search&argv=space"
140        })
141    }
142
143    @Test func clearingTheQueryRestoresThePagedList() async throws {
144        let (client, stub) = try makeClient()
145        stub.enqueue(.init(status: 200, json: """
146            {"protocol_version":1,"data":{"items":[\
147            {"path":"cmc/notes","visibility":"private"}]},"exit_code":0}
148            """, match: "argv=repo&argv=list"))
149        let model = RepoListViewModel(client: client)
150        await model.load()
151
152        model.searchText = "zzz"
153        model.searchText = ""
154        try await Task.sleep(for: .milliseconds(500))
155
156        #expect(model.visibleRepos.map(\.path) == ["cmc/notes"])
157        // The emptied query never reached the server.
158        #expect(!stub.seen.contains { ($0.url.query() ?? "").contains("argv=search") })
159    }
160}