~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
221 lines · 10.9 KB Raw History
import Observation
import XCTest

@testable import OldFella

extension AppModelTests {
    func testPagePreparationReusesDecisionsAndPreservesModeratedOrder() async {
        let service = ModerationTestService()
        service.mutedWords = [.init(value: "hidden")]
        let author = Post.Author(id: "a", name: "A", handle: "a")
        func post(_ id: String, _ text: String = "safe") -> Post {
            Post(
                id: id, author: author, text: text, likeCount: 0, repostCount: 0,
                isLiked: false, isReposted: false, imageURLs: [], replyIDs: [])
        }
        let first = (0..<10).map { post("first-\($0)") }
        service.feedPage = FeedPage(posts: first, cursor: "next")
        service.nextFeedPage = FeedPage(posts: [post("hidden", "hidden"), post("last")], cursor: nil)
        let model = makeAppModel(service: service)
        await model.signInWithDemo()
        let preparations = model.contentPreparationCount
        let constructions = model.moderationInputConstructionCount

        await model.loadNextPage()

        XCTAssertEqual(model.contentPreparationCount, preparations + 1)
        XCTAssertEqual(model.timelineRowIDs, first.map(\.id) + ["last"])
        XCTAssertEqual(model.postViewState(for: post("hidden", "hidden")).decision?.action, .hide)
        XCTAssertLessThanOrEqual(model.moderationInputConstructionCount - constructions, 14)

        let last = post("last")
        let preparedConstructions = model.moderationInputConstructionCount
        XCTAssertEqual(model.contentDecision(for: last)?.action, .allow)
        XCTAssertEqual(model.contentDecision(author: last.author)?.action, .allow)
        XCTAssertEqual(model.moderationInputConstructionCount, preparedConstructions)
        XCTAssertNotNil(model.preparedPostText.renderedText(id: last.id, text: last.text, facets: last.facets))
    }

    func testPagePreparationUpdatesExistingReplyAndQuoteModeration() async {
        let service = ModerationTestService()
        service.mutedWords = [.init(value: "hidden")]
        let author = Post.Author(id: "a", name: "A", handle: "a", isFollowing: true)
        func post(_ id: String, _ text: String = "safe") -> Post {
            Post(
                id: id, author: author, text: text, likeCount: 0, repostCount: 0,
                isLiked: false, isReposted: false, imageURLs: [], replyIDs: [])
        }
        var reply = post("reply")
        reply.replyRootURI = "parent"
        reply.replyParentURI = "parent"
        var quoting = post("quoting")
        quoting.quote = Post.Quote(postID: "quoted")
        service.feedPage = FeedPage(posts: [reply, quoting, post("quoted")], cursor: "next")
        service.nextFeedPage = FeedPage(
            posts: [post("parent", "hidden"), post("quoted", "hidden"), post("last")], cursor: nil)
        let model = makeAppModel(service: service)
        await model.signInWithDemo()
        XCTAssertEqual(model.timelineRowIDs, ["reply", "quoting", "quoted"])

        await model.loadNextPage()

        XCTAssertEqual(model.timelineRowIDs, ["last"])
        XCTAssertEqual(model.postViewState(for: quoting).decision?.action, .hide)
        XCTAssertEqual(model.replyContext(for: reply).map(\.id), ["parent"])
    }

    func testPreparationDistinguishesDifferentContentWithTheSamePostID() async {
        let service = ModerationTestService()
        service.mutedWords = [.init(value: "hidden")]
        let author = Post.Author(id: "a", name: "A", handle: "a")
        let safe = Post(
            id: "shared", author: author, text: "safe", likeCount: 0, repostCount: 0,
            isLiked: false, isReposted: false, imageURLs: [], replyIDs: [])
        var hidden = safe
        hidden.text = "hidden"
        var hiddenAuthor = author
        hiddenAuthor.moderationLabels = [.init(value: "!hide", sourceDID: author.id)]
        service.feedPage = FeedPage(posts: [safe], cursor: nil)
        service.notificationPage = NotificationPage(
            notifications: [
                FeedNotification(
                    id: "hidden-notification", author: author, reason: .reply,
                    indexedAt: Date(), isRead: false, postID: hidden.id, relatedPost: hidden),
                FeedNotification(
                    id: "hidden-author", author: hiddenAuthor, reason: .follow,
                    indexedAt: Date(), isRead: false, postID: nil)
            ], cursor: nil)
        let model = makeAppModel(service: service)
        await model.signInWithDemo()

        await model.loadNotifications()

        XCTAssertEqual(model.timelineRowIDs, [safe.id])
        XCTAssertTrue(model.visibleNotifications.isEmpty)
        XCTAssertEqual(model.postViewState(for: safe).decision?.action, .allow)
        XCTAssertEqual(model.contentDecision(for: hidden)?.action, .hide)
    }

    func testNextPageLoadsOnlyOnRequestAndAppends() async throws {
        let suite = "next-feed-\(UUID().uuidString)"
        let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
        defer { defaults.removePersistentDomain(forName: suite) }
        let service = ModerationTestService()
        let author = Post.Author(id: "a", name: "A", handle: "a")
        func post(_ id: String) -> Post {
            Post(
                id: id, author: author, text: "safe", likeCount: 0, repostCount: 0, isLiked: false, isReposted: false,
                imageURLs: [], quote: nil, replyIDs: [])
        }
        let first = (0..<15).map { post("first-\($0)") }
        service.feedPages = [
            "first": FeedPage(posts: first, cursor: "next"), "next": FeedPage(posts: [post("last")], cursor: nil)
        ]
        let model = makeAppModel(service: service, feedDefaults: defaults)
        await model.signIn(handle: "demo", appPassword: "password")
        XCTAssertEqual(model.posts.map(\.id), first.map(\.id))
        XCTAssertEqual(service.feedRequests, ["first"])
        XCTAssertTrue(model.hasMorePosts)
        await model.loadNextPage()
        XCTAssertEqual(model.posts.map(\.id), first.map(\.id) + ["last"])
        XCTAssertEqual(service.feedRequests, ["first", "next"])
        XCTAssertFalse(model.hasMorePosts)
    }

    func testReplyTimelineShowsRootContextAndKeepsFeedOrder() async {
        let model = makeAppModel(service: MockBlueskyService())
        await model.signIn(handle: "demo.bsky.social", appPassword: "test-only")

        XCTAssertEqual(model.timelinePosts.map(\.id), ["post-1", "post-3"])
        XCTAssertEqual(model.replyContext(for: model.post(id: "post-2")!).map(\.id), ["post-1"])
        XCTAssertTrue(model.hasEarlierPosts(for: model.post(id: "post-2")!))
        XCTAssertFalse(model.hasEarlierPosts(for: model.post(id: "post-1")!))

        let replyWithDifferentRootAndParent = Post(
            id: "timeline-reply",
            author: Post.Author(id: "sam", name: "Sam Lee", handle: "sam.example"),
            text: "A reply with a distinct root and parent.",
            likeCount: 0,
            repostCount: 0,
            isLiked: false,
            isReposted: false,
            imageURLs: [],
            replyRootURI: "post-1",
            replyParentURI: "post-2",
            replyIDs: []
        )
        XCTAssertEqual(model.replyContext(for: replyWithDifferentRootAndParent).map(\.id), ["post-1", "post-2"])
        let root = model.post(id: "post-1")!
        let parent = model.post(id: "post-2")!
        XCTAssertFalse(model.hasMissingReplyContext(between: root, and: parent))
        XCTAssertFalse(model.hasMissingReplyContext(between: parent, and: replyWithDifferentRootAndParent))
        XCTAssertTrue(model.hasMissingReplyContext(between: root, and: replyWithDifferentRootAndParent))
        var disconnectedParent = parent
        disconnectedParent.replyParentURI = "missing-post"
        XCTAssertTrue(model.hasMissingReplyContext(between: root, and: disconnectedParent))
        disconnectedParent.replyParentURI = nil
        XCTAssertFalse(model.hasMissingReplyContext(between: root, and: disconnectedParent))
    }

    func testFilteredPostClearsCacheButNetworkFailurePreservesIt() async {
        for fails in [false, true] {
            let model = makeAppModel(service: ProfilePostTestService(postLoadFails: fails))
            await model.signIn(handle: "demo.bsky.social", appPassword: "test-only")
            XCTAssertNotNil(model.post(id: "post-1"))
            await model.loadPost(id: "post-1")
            if fails {
                XCTAssertNotNil(model.post(id: "post-1"))
            } else {
                XCTAssertNil(model.post(id: "post-1"))
                XCTAssertFalse(model.timelinePosts.contains { $0.id == "post-1" })
            }
            XCTAssertTrue(model.failedPostIDs.contains("post-1"))
        }
    }

    func testThreadRefreshRemovesExplicitlyMutedReplyAndKeepsVisibleAncestor() async throws {
        let base = MockBlueskyService()
        var selected = try await base.loadPost(uri: "post-2").first { $0.id == "post-2" }!
        let grandparent = try await base.loadPost(uri: "post-1").first { $0.id == "post-1" }!
        selected.replyParentURI = "muted-parent"
        let result = ThreadResult(posts: [grandparent, selected], mutedPostIDs: ["post-3"])
        let model = makeAppModel(service: ProfilePostTestService(threadResult: result))
        await model.signIn(handle: "demo.bsky.social", appPassword: "test-only")
        XCTAssertNotNil(model.post(id: "post-3"))
        await model.loadPost(id: "post-2")
        XCTAssertNil(model.post(id: "post-3"))
        XCTAssertFalse(model.timelinePosts.contains { $0.id == "post-3" })
        XCTAssertEqual(model.threadAncestors(for: selected).map(\.id), ["post-1"])
    }

    func testPopulatedFeedRefreshDoesNotPublishAtGestureStartOrForUnchangedResults() async throws {
        let suite = "refresh-feed-\(UUID().uuidString)"
        let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
        defer { defaults.removePersistentDomain(forName: suite) }
        let gate = ThreadGate()
        let service = ProfilePostTestService(secondFeedGate: gate)
        let model = makeAppModel(service: service, feedDefaults: defaults)
        await model.signIn(handle: "demo.bsky.social", appPassword: "test-only")
        let previous = model.posts
        let posts = ObservationProbe { model.posts }
        let rows = ObservationProbe { model.timelineRowIDs }
        let loading = ObservationProbe { model.isLoading }
        let refresh = Task { await model.loadFeed() }
        await gate.waitUntilStarted()
        await Task.yield()
        XCTAssertTrue(posts.values.isEmpty)
        XCTAssertTrue(rows.values.isEmpty)
        XCTAssertTrue(loading.values.isEmpty)
        XCTAssertEqual(model.posts, previous)
        await model.loadNextPage()
        await model.loadFeed()
        XCTAssertEqual(service.firstPageCalls.count, 2)
        await gate.release()
        await refresh.value
        await Task.yield()
        XCTAssertTrue(posts.values.isEmpty)
        XCTAssertTrue(rows.values.isEmpty)
        XCTAssertTrue(loading.values.isEmpty)
        XCTAssertEqual(model.posts, previous)
    }
}