mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-27 15:25:22 +00:00
* Deflake two iOS-sim CI tests with unbounded timing assumptions Both failed on main-adjacent CI runs during this session's PRs. Neither was a product bug; both asserted things about real time that a loaded runner is under no obligation to honour. **NetworkReachabilityGateTests: a wall-clock upper bound.** test_monitor_duplicateUpdatesDoNotPostponeOfflineCommit slept 500ms for real, then asserted total elapsed time was under 1.4s to prove a duplicate mid-window had not restarted the 1.0s debounce. One CI run took 3.75s. No wall-clock bound can separate "deadline preserved" from "runner is slow", because Task.sleep and the asyncAfter flush are both real time and neither is bounded above. The deadline property was already covered deterministically one level down: test_debounce_duplicateObservationsPreservePendingDeadline drives ReachabilityDebounce with injected timestamps and checks pendingRemaining directly. So the monitor test now asserts only what needs a real monitor — that a duplicate still yields exactly one committed false through the debounce — with an injected clock for the arithmetic and a generous liveness budget. Renamed to say what it actually checks. No coverage lost, and it runs in 0.14s instead of ~3.8s because the real sleep is gone. **NoiseEncryptionServiceTests: injected timeouts that also arm during setup.** #1483 diagnosed and fixed exactly this in the quarantine-restore test, but two sibling tests kept the shape. Their injected ordinaryResponderHandshakeTimeout (0.04 and 0.06) also arms during the establishSessions setup handshake, where bob is the responder — so a preempted runner fires it mid-setup, tears down the half-open responder, and message 3 gets answered as a fresh initiation. The CI failure named setup's own `#expect(finalMessage == nil)` seeing a 96-byte message 2, which is precisely the signature #1483 recorded. Raised both to 1.0s, matching #1483's remedy: the scenarios still need the responder timeout to fire, and it still does, just with room for setup to complete first. Thin 1-second waitUntil budgets in the file now use the shared TestConstants.longTimeout; every one of them backs a positive assertion, so waitUntil still returns the moment the condition holds and nothing gets slower in the passing case. No assertion weakened in either file. Verified 3x sequentially and 3x with all 18 cores saturated. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Raise two more starvation-prone test deadlines Both surfaced on the CI runs for this PR and #1487, both in tests neither PR touches, both the same shape as the two already fixed here: a deadline sized for the work rather than for a runner executing many suites at once. VoiceNotePlaybackControllerTests waited 5s for a @MainActor Task that playback schedules for the session acquire and its failure path. When that Task is not scheduled in time the helper reports *two* failures — the wait, and the `!isPlaying` the un-run failure path has not reset yet — which reads like a playback bug rather than a starved scheduler. That is exactly what CI showed. GeoRelayDirectoryTests waited 10s for work the directory runs in Task.detached(priority: .utility); utility priority competes with every other suite. The retry-scheduling case timed out at exactly 10.06s with the retry never scheduled, reading like a missing retry rather than a starved background task. Raised to 30s each with the reasoning recorded at the helper. Both helpers return as soon as their condition holds, so nothing slows down when tests pass — only the genuine-failure case takes longer to report. Verified 3x with all cores saturated: both suites clean. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Make the flake class unrepeatable, not just fixed Raising four deadlines fixed the four tests that happened to fire. The class was still there: fourteen separate waitUntil helpers, most defaulting to 1.0s, plus wait call sites with literal budgets. The fifth instance would have landed the same way, on someone else's unrelated PR. The rule, now written down in TestConstants.settleTimeout: **a wait deadline is not a latency budget.** It exists so a genuine hang eventually fails the suite, so size it for the worst-case scheduler, never for how long the operation should take. Waits return as soon as their condition holds, so a generous deadline is free in the passing case and only extends genuine failures. - Every wait helper now defaults to TestConstants.settleTimeout (30s), and the literal wait call sites below the floor were converted too — sixteen sites across ten files. - TestTimingHygieneTests enforces it by scanning the test sources: wait defaults and wait call sites must be at least minimumSettleTimeout, and no test may assert an upper bound on elapsed wall-clock time (the assertion that started this, which cannot separate correct behaviour from a slow machine). - Both rules waive per line with "test-timing-ok: <reason>", accepted on the line or in the comment block above it so the reason has room to be a sentence. One legitimate use so far: a NEGATIVE wait in NoiseCoverageTests asserting a promotion has *not* completed within 50ms, where a long deadline would only make the suite slow while still passing. Injected production timeouts are deliberately not matched — the Noise handshake timeouts are the behaviour under test, and short values are correct there. Verified the guard actually fails: a canary file with both banned shapes was flagged with file and line, and the suite went green again once it was removed. Full suite passes with all 18 cores saturated. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Close the guard's blind spot: named short timeouts A fifth flake landed on CI while the first guard was in review — GossipSyncBoardTests timing out at 1.03s — and the guard did not catch it, because the deadline was `TestConstants.shortTimeout` rather than a literal. A literals-only scan cannot see a short value behind a symbol, which is the more common way it is written: 81 wait sites used shortTimeout (1s) or defaultTimeout (5s), every one of them below the floor. Rather than guess which of those were safe to raise, all 81 were converted and the suite timed. Runtime went 15s -> 72s, which located the genuine negative waits precisely: ten tests that assert something does *not* happen and therefore always run their deadline out. Measurement instead of a heuristic, since a mis-guess in either direction is invisible — too short reintroduces the flake, too long silently costs a minute a run. Those 28 sites now use `TestConstants.negativeWaitWindow`, a named constant whose doc explains the inverted reasoning: for a negative wait, starvation can only make the assertion *more* likely to hold, so short is correct, and the name states the polarity instead of leaving a bare literal that reads like the mistake. Suite is back to 15.3s. The guard now also rejects `timeout: TestConstants.shortTimeout` and `defaultTimeout`, while accepting `negativeWaitWindow` by name. Re-verified with a canary carrying every banned shape — literal default, both named constants, and an elapsed-time upper bound. All four were flagged with file and line; the suite went green again on removal. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Delete shortTimeout now that nothing may use it The hygiene guard bans `TestConstants.shortTimeout` at every wait site and the last users were converted, so Periphery correctly flagged the constant itself as dead and failed CI. Remove it from both TestConstants copies; the banned-name entry stays so the symbol cannot quietly return. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
477 lines
18 KiB
Swift
477 lines
18 KiB
Swift
import Combine
|
|
import CoreLocation
|
|
import XCTest
|
|
@testable import bitchat
|
|
|
|
/// Tap-to-reveal privacy contract: the nearby-notes counter must not open a
|
|
/// building-precision relay REQ until one explicit act calls `reveal()`, and
|
|
/// the pooled subscription must come up exactly once and go down exactly once.
|
|
@MainActor
|
|
final class NearbyNotesCounterTests: XCTestCase {
|
|
func test_counterOnlySubscribesAfterReveal_countsUnexpiredNotes_andUnsubscribesOnDeactivate() async throws {
|
|
let relays = SubscriptionRecorder()
|
|
let settings = LocationNotesSettingsStub()
|
|
let locationManager = try await makeAuthorizedLocationManager()
|
|
let buildingGeohash = try XCTUnwrap(
|
|
locationManager.availableChannels.first(where: { $0.level == .building })?.geohash
|
|
)
|
|
|
|
let counter = NearbyNotesCounter(
|
|
locationManager: locationManager,
|
|
managerFactory: { LocationNotesManager(geohash: $0, dependencies: relays.dependencies) },
|
|
releaseManager: { $0?.cancel() },
|
|
locationNotesEnabled: { settings.enabled },
|
|
locationNotesSettings: settings.changes
|
|
)
|
|
|
|
counter.activate()
|
|
// Let the availableChannels replay and any queued retargets land:
|
|
// being active is not consent, so still no REQ.
|
|
try await Task.sleep(nanoseconds: 50_000_000)
|
|
XCTAssertEqual(relays.subscribeCount, 0)
|
|
XCTAssertFalse(counter.revealed)
|
|
|
|
counter.reveal()
|
|
|
|
XCTAssertTrue(counter.revealed)
|
|
XCTAssertEqual(relays.subscribeCount, 1)
|
|
let gTags = try XCTUnwrap(geohashTagFilter(of: XCTUnwrap(relays.lastFilter)))
|
|
XCTAssertEqual(gTags.count, 9)
|
|
XCTAssertEqual(
|
|
Set(gTags),
|
|
Set([buildingGeohash] + Geohash.neighbors(of: buildingGeohash)),
|
|
"REQ must cover the building geohash plus its 8 neighbors"
|
|
)
|
|
|
|
// An expired NIP-40 note must never count.
|
|
let identity = try NostrIdentity.generate()
|
|
let now = Date()
|
|
let expired = NostrEvent(
|
|
pubkey: identity.publicKeyHex,
|
|
createdAt: now.addingTimeInterval(-3600),
|
|
kind: .textNote,
|
|
tags: [["g", buildingGeohash], ["expiration", String(Int(now.timeIntervalSince1970) - 60)]],
|
|
content: "gone"
|
|
)
|
|
relays.lastHandler?(try expired.sign(with: identity.schnorrSigningKey()))
|
|
try await Task.sleep(nanoseconds: 50_000_000)
|
|
XCTAssertEqual(counter.noteCount, 0)
|
|
|
|
// A live matching kind-1 note drives the count to 1.
|
|
let live = NostrEvent(
|
|
pubkey: identity.publicKeyHex,
|
|
createdAt: now,
|
|
kind: .textNote,
|
|
tags: [["g", buildingGeohash]],
|
|
content: "still here"
|
|
)
|
|
relays.lastHandler?(try live.sign(with: identity.schnorrSigningKey()))
|
|
let counted = await waitUntil { counter.noteCount == 1 }
|
|
XCTAssertTrue(counted)
|
|
// Still exactly one REQ after all the async retarget re-entries.
|
|
XCTAssertEqual(relays.subscribeCount, 1)
|
|
|
|
counter.deactivate()
|
|
|
|
XCTAssertEqual(relays.unsubscribeCount, 1)
|
|
XCTAssertEqual(counter.noteCount, 0)
|
|
}
|
|
|
|
func test_permissionRevocation_releasesBuildingSubscriptionDespiteCachedChannels() async throws {
|
|
let relays = SubscriptionRecorder()
|
|
let settings = LocationNotesSettingsStub()
|
|
let locationManager = try await makeAuthorizedLocationManager()
|
|
let counter = NearbyNotesCounter(
|
|
locationManager: locationManager,
|
|
managerFactory: { LocationNotesManager(geohash: $0, dependencies: relays.dependencies) },
|
|
releaseManager: { $0?.cancel() },
|
|
locationNotesEnabled: { settings.enabled },
|
|
locationNotesSettings: settings.changes
|
|
)
|
|
|
|
counter.activate()
|
|
counter.reveal()
|
|
XCTAssertEqual(relays.subscribeCount, 1)
|
|
|
|
locationManager.locationManager(CLLocationManager(), didChangeAuthorization: .denied)
|
|
|
|
let denied = await waitUntil { locationManager.permissionState == .denied }
|
|
XCTAssertTrue(denied)
|
|
let released = await waitUntil { relays.unsubscribeCount == 1 }
|
|
XCTAssertTrue(released)
|
|
XCTAssertTrue(
|
|
locationManager.availableChannels.contains { $0.level == .building },
|
|
"the privacy boundary must not depend on cached channels being cleared"
|
|
)
|
|
XCTAssertEqual(counter.noteCount, 0)
|
|
|
|
counter.deactivate()
|
|
XCTAssertEqual(relays.unsubscribeCount, 1, "revocation already released the manager")
|
|
}
|
|
|
|
func test_locationNotesKillSwitch_releasesAndCanReacquireBuildingSubscription() async throws {
|
|
let relays = SubscriptionRecorder()
|
|
let settings = LocationNotesSettingsStub()
|
|
let locationManager = try await makeAuthorizedLocationManager()
|
|
let counter = NearbyNotesCounter(
|
|
locationManager: locationManager,
|
|
managerFactory: { LocationNotesManager(geohash: $0, dependencies: relays.dependencies) },
|
|
releaseManager: { $0?.cancel() },
|
|
locationNotesEnabled: { settings.enabled },
|
|
locationNotesSettings: settings.changes
|
|
)
|
|
|
|
counter.activate()
|
|
counter.reveal()
|
|
XCTAssertEqual(relays.subscribeCount, 1)
|
|
|
|
settings.setEnabled(false)
|
|
|
|
let released = await waitUntil { relays.unsubscribeCount == 1 }
|
|
XCTAssertTrue(released)
|
|
XCTAssertEqual(counter.noteCount, 0)
|
|
|
|
settings.setEnabled(true)
|
|
|
|
let reacquired = await waitUntil { relays.subscribeCount == 2 }
|
|
XCTAssertTrue(reacquired)
|
|
counter.deactivate()
|
|
XCTAssertEqual(relays.unsubscribeCount, 2)
|
|
}
|
|
|
|
func test_checkNotesHint_requiresAuthorizedLocationPermission() {
|
|
let relays = SubscriptionRecorder()
|
|
let settings = LocationNotesSettingsStub()
|
|
let counter = NearbyNotesCounter(
|
|
locationManager: makeBareLocationManager(),
|
|
managerFactory: { LocationNotesManager(geohash: $0, dependencies: relays.dependencies) },
|
|
releaseManager: { $0?.cancel() },
|
|
locationNotesEnabled: { settings.enabled },
|
|
locationNotesSettings: settings.changes
|
|
)
|
|
|
|
// An unauthorized install must never see the hint: the tap can't
|
|
// subscribe (retarget requires authorization) and must not prompt,
|
|
// so offering it would be a silent dead-end for the session.
|
|
XCTAssertFalse(counter.offersRevealHint(permissionState: .notDetermined))
|
|
XCTAssertFalse(counter.offersRevealHint(permissionState: .denied))
|
|
XCTAssertFalse(counter.offersRevealHint(permissionState: .restricted))
|
|
XCTAssertTrue(counter.offersRevealHint(permissionState: .authorized))
|
|
|
|
// The app-info kill switch hides it too.
|
|
settings.setEnabled(false)
|
|
XCTAssertFalse(counter.offersRevealHint(permissionState: .authorized))
|
|
settings.setEnabled(true)
|
|
|
|
// Once revealed, the hint yields to the live strip and count.
|
|
counter.reveal()
|
|
XCTAssertFalse(counter.offersRevealHint(permissionState: .authorized))
|
|
XCTAssertEqual(relays.subscribeCount, 0, "reveal without authorization must not open a REQ")
|
|
}
|
|
|
|
func test_noticesSheet_revealsOnlyOnExplicitGeoTabSelectionWithScope() {
|
|
// The sheet reveals the local counter only when the person actively
|
|
// picks the geo tab and the sheet actually has a geo scope —
|
|
// auto-landing on geo (initial tab) never calls this path at all.
|
|
XCTAssertTrue(NoticesView.revealsNearbyNotes(onSwitchingTo: .geo, geoGeohash: "u4pruydq"))
|
|
XCTAssertFalse(NoticesView.revealsNearbyNotes(onSwitchingTo: .geo, geoGeohash: nil))
|
|
XCTAssertFalse(NoticesView.revealsNearbyNotes(onSwitchingTo: .mesh, geoGeohash: "u4pruydq"))
|
|
}
|
|
|
|
func test_noticesGeoPresentation_disabledOverridesSelectedScopeAndHidesOnlyGeoComposer() {
|
|
XCTAssertEqual(
|
|
NoticesView.geoPresentationState(notesEnabled: false, geohash: "9q8yyk8y"),
|
|
.disabled,
|
|
"a selected remote channel must not leave a blank manager-less notes view"
|
|
)
|
|
XCTAssertNil(
|
|
NoticesView.composerGeohash(
|
|
tab: .geo,
|
|
notesEnabled: false,
|
|
geoGeohash: "9q8yyk8y"
|
|
),
|
|
"the dead geo composer must be hidden while the notes kill switch is off"
|
|
)
|
|
XCTAssertEqual(
|
|
NoticesView.composerGeohash(tab: .mesh, notesEnabled: false, geoGeohash: nil),
|
|
"",
|
|
"the location-notes setting must not disable mesh notices"
|
|
)
|
|
}
|
|
|
|
func test_noticesGeoSession_revocationEndsLiveRefreshAndReleasesDeviceScope() {
|
|
let relays = SubscriptionRecorder()
|
|
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: relays.dependencies)
|
|
var beginCount = 0
|
|
var endCount = 0
|
|
var releaseCount = 0
|
|
|
|
let next = NoticesView.reconcileGeoSession(
|
|
tab: .geo,
|
|
needsDeviceLocation: true,
|
|
permissionState: .denied,
|
|
notesEnabled: true,
|
|
geohash: "u4pruydq",
|
|
manager: manager,
|
|
ownsLiveRefresh: true,
|
|
beginLiveRefresh: { beginCount += 1 },
|
|
endLiveRefresh: { endCount += 1 },
|
|
acquire: { _ in XCTFail("revocation must not acquire"); return manager },
|
|
release: {
|
|
releaseCount += 1
|
|
$0?.cancel()
|
|
}
|
|
)
|
|
|
|
XCTAssertNil(next.manager)
|
|
XCTAssertFalse(next.ownsLiveRefresh)
|
|
XCTAssertEqual(beginCount, 0)
|
|
XCTAssertEqual(endCount, 1)
|
|
XCTAssertEqual(releaseCount, 1)
|
|
XCTAssertEqual(relays.unsubscribeCount, 1)
|
|
}
|
|
|
|
func test_noticesGeoSession_killSwitchClosesLocalScope_butDeniedRemoteScopeRemainsUsable() {
|
|
let relays = SubscriptionRecorder()
|
|
let localManager = LocationNotesManager(geohash: "u4pruydq", dependencies: relays.dependencies)
|
|
var endCount = 0
|
|
var releaseCount = 0
|
|
|
|
let disabled = NoticesView.reconcileGeoSession(
|
|
tab: .geo,
|
|
needsDeviceLocation: true,
|
|
permissionState: .authorized,
|
|
notesEnabled: false,
|
|
geohash: "u4pruydq",
|
|
manager: localManager,
|
|
ownsLiveRefresh: true,
|
|
beginLiveRefresh: {},
|
|
endLiveRefresh: { endCount += 1 },
|
|
acquire: { _ in XCTFail("disabled notes must not acquire"); return localManager },
|
|
release: {
|
|
releaseCount += 1
|
|
$0?.cancel()
|
|
}
|
|
)
|
|
|
|
XCTAssertNil(disabled.manager)
|
|
XCTAssertFalse(disabled.ownsLiveRefresh)
|
|
XCTAssertEqual(endCount, 1)
|
|
XCTAssertEqual(releaseCount, 1)
|
|
|
|
let remoteManager = LocationNotesManager(geohash: "9q8yyk8y", dependencies: relays.dependencies)
|
|
let remote = NoticesView.reconcileGeoSession(
|
|
tab: .geo,
|
|
needsDeviceLocation: false,
|
|
permissionState: .denied,
|
|
notesEnabled: true,
|
|
geohash: "9q8yyk8y",
|
|
manager: remoteManager,
|
|
ownsLiveRefresh: false,
|
|
beginLiveRefresh: {},
|
|
endLiveRefresh: { endCount += 1 },
|
|
acquire: { _ in XCTFail("matching remote manager should be reused"); return remoteManager },
|
|
release: { _ in XCTFail("device permission must not release an explicit remote scope") }
|
|
)
|
|
|
|
XCTAssertTrue(remote.manager === remoteManager)
|
|
XCTAssertFalse(remote.ownsLiveRefresh)
|
|
XCTAssertEqual(endCount, 1)
|
|
}
|
|
|
|
func test_pool_sharesOneManagerPerGeohash_andCancelsOnLastRelease() {
|
|
let relays = SubscriptionRecorder()
|
|
let pool = LocationNotesPool(
|
|
makeManager: { LocationNotesManager(geohash: $0, dependencies: relays.dependencies) }
|
|
)
|
|
|
|
let first = pool.acquire("u4pruydq")
|
|
let second = pool.acquire("U4PRUYDQ")
|
|
|
|
XCTAssertTrue(first === second, "same geohash (case-insensitive) must share one manager")
|
|
XCTAssertEqual(relays.subscribeCount, 1)
|
|
|
|
pool.release(first)
|
|
|
|
XCTAssertEqual(relays.unsubscribeCount, 0, "first release keeps the shared REQ live")
|
|
XCTAssertNotEqual(first.state, .idle)
|
|
|
|
pool.release(second)
|
|
|
|
XCTAssertEqual(relays.unsubscribeCount, 1)
|
|
XCTAssertEqual(first.state, .idle)
|
|
|
|
// An instance the pool never owned (test-injected) degrades to cancel.
|
|
let stray = LocationNotesManager(geohash: "u4pruydp", dependencies: relays.dependencies)
|
|
pool.release(stray)
|
|
XCTAssertEqual(relays.unsubscribeCount, 2)
|
|
XCTAssertEqual(stray.state, .idle)
|
|
}
|
|
|
|
func test_pool_reacquireAfterFullRelease_bringsSubscriptionBackUp() {
|
|
let relays = SubscriptionRecorder()
|
|
let pool = LocationNotesPool(
|
|
makeManager: { LocationNotesManager(geohash: $0, dependencies: relays.dependencies) }
|
|
)
|
|
|
|
// The notices sheet's geo → mesh → geo cycle: switching to mesh
|
|
// releases (REQ goes down), switching back re-acquires (fresh REQ),
|
|
// with exactly one live REQ at any point.
|
|
let first = pool.acquire("u4pruydq")
|
|
XCTAssertEqual(relays.subscribeCount, 1)
|
|
|
|
pool.release(first)
|
|
XCTAssertEqual(relays.unsubscribeCount, 1)
|
|
XCTAssertEqual(first.state, .idle)
|
|
|
|
let second = pool.acquire("u4pruydq")
|
|
XCTAssertEqual(relays.subscribeCount, 2)
|
|
XCTAssertNotEqual(second.state, .idle)
|
|
|
|
// Dismissal after the round trip releases once more — no double
|
|
// unsubscribe from the earlier tab-switch release.
|
|
pool.release(second)
|
|
XCTAssertEqual(relays.unsubscribeCount, 2)
|
|
}
|
|
|
|
// MARK: - Helpers
|
|
|
|
/// A LocationStateManager that never touches CoreLocation; for tests
|
|
/// that don't need channels or authorization.
|
|
private func makeBareLocationManager() -> LocationStateManager {
|
|
let suiteName = "NearbyNotesCounterTests-\(UUID().uuidString)"
|
|
let storage = UserDefaults(suiteName: suiteName)!
|
|
storage.removePersistentDomain(forName: suiteName)
|
|
addTeardownBlock {
|
|
storage.removePersistentDomain(forName: suiteName)
|
|
}
|
|
return LocationStateManager(
|
|
storage: storage,
|
|
locationManager: MockLocationManager(authorizationStatus: .denied),
|
|
geocoder: MockLocationGeocoder(),
|
|
shouldInitializeCoreLocation: false
|
|
)
|
|
}
|
|
|
|
/// An authorized LocationStateManager whose availableChannels carry a
|
|
/// real building-level geohash (Honolulu), built over CoreLocation mocks.
|
|
private func makeAuthorizedLocationManager() async throws -> LocationStateManager {
|
|
let suiteName = "NearbyNotesCounterTests-\(UUID().uuidString)"
|
|
let storage = UserDefaults(suiteName: suiteName)!
|
|
storage.removePersistentDomain(forName: suiteName)
|
|
addTeardownBlock {
|
|
storage.removePersistentDomain(forName: suiteName)
|
|
}
|
|
|
|
let manager = LocationStateManager(
|
|
storage: storage,
|
|
locationManager: MockLocationManager(authorizationStatus: .authorizedAlways),
|
|
geocoder: MockLocationGeocoder(),
|
|
shouldInitializeCoreLocation: true
|
|
)
|
|
let authorized = await waitUntil { manager.permissionState == .authorized }
|
|
XCTAssertTrue(authorized)
|
|
|
|
manager.locationManager(
|
|
CLLocationManager(),
|
|
didUpdateLocations: [CLLocation(latitude: 21.2850, longitude: -157.8357)]
|
|
)
|
|
let channelsLoaded = await waitUntil {
|
|
manager.availableChannels.contains { $0.level == .building }
|
|
}
|
|
XCTAssertTrue(channelsLoaded)
|
|
return manager
|
|
}
|
|
|
|
/// The filter's `g` tag values, read through its NIP-01 wire encoding
|
|
/// (the stored tag filters aren't visible outside the Nostr layer).
|
|
private func geohashTagFilter(of filter: NostrFilter) throws -> [String]? {
|
|
let data = try JSONEncoder().encode(filter)
|
|
let json = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
|
return json["#g"] as? [String]
|
|
}
|
|
|
|
private func waitUntil(
|
|
timeout: TimeInterval = TestConstants.settleTimeout,
|
|
condition: @escaping @MainActor () -> Bool
|
|
) async -> Bool {
|
|
let deadline = Date().addingTimeInterval(timeout)
|
|
while Date() < deadline {
|
|
if condition() {
|
|
return true
|
|
}
|
|
try? await Task.sleep(nanoseconds: 10_000_000)
|
|
}
|
|
return condition()
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
private final class LocationNotesSettingsStub {
|
|
private let changesSubject = PassthroughSubject<Void, Never>()
|
|
private(set) var enabled = true
|
|
|
|
var changes: AnyPublisher<Void, Never> {
|
|
changesSubject.eraseToAnyPublisher()
|
|
}
|
|
|
|
func setEnabled(_ enabled: Bool) {
|
|
self.enabled = enabled
|
|
changesSubject.send(())
|
|
}
|
|
}
|
|
|
|
/// Stub relay layer: counts REQs, captures the last filter/handler, and never
|
|
/// touches the network.
|
|
@MainActor
|
|
private final class SubscriptionRecorder {
|
|
private(set) var subscribeCount = 0
|
|
private(set) var unsubscribeCount = 0
|
|
private(set) var lastFilter: NostrFilter?
|
|
private(set) var lastHandler: ((NostrEvent) -> Void)?
|
|
|
|
var dependencies: LocationNotesDependencies {
|
|
LocationNotesDependencies(
|
|
relayLookup: { _, _ in ["wss://relay.one"] },
|
|
subscribe: { [weak self] filter, _, _, handler, _ in
|
|
self?.subscribeCount += 1
|
|
self?.lastFilter = filter
|
|
self?.lastHandler = handler
|
|
},
|
|
unsubscribe: { [weak self] _ in
|
|
self?.unsubscribeCount += 1
|
|
},
|
|
sendEvent: { _, _ in },
|
|
deriveIdentity: { _ in try NostrIdentity.generate() },
|
|
now: { Date() }
|
|
)
|
|
}
|
|
}
|
|
|
|
private final class MockLocationManager: LocationStateManaging {
|
|
weak var delegate: CLLocationManagerDelegate?
|
|
var desiredAccuracy: CLLocationAccuracy = 0
|
|
var distanceFilter: CLLocationDistance = 0
|
|
var authorizationStatus: CLAuthorizationStatus
|
|
|
|
init(authorizationStatus: CLAuthorizationStatus) {
|
|
self.authorizationStatus = authorizationStatus
|
|
}
|
|
|
|
func requestWhenInUseAuthorization() {}
|
|
func requestLocation() {}
|
|
func startUpdatingLocation() {}
|
|
func stopUpdatingLocation() {}
|
|
}
|
|
|
|
private final class MockLocationGeocoder: LocationStateGeocoding {
|
|
func cancelGeocode() {}
|
|
|
|
func reverseGeocodeLocation(
|
|
_ location: CLLocation,
|
|
completionHandler: @escaping ([CLPlacemark]?, Error?) -> Void
|
|
) {
|
|
completionHandler(nil, nil)
|
|
}
|
|
}
|