Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Crash: ViewHosting.swift:162: Fatal error: Unexpectedly found nil while unwrapping an Optional value #312

Closed
esemusa opened this issue Jun 21, 2024 · 2 comments

Comments

@esemusa
Copy link

esemusa commented Jun 21, 2024

Description of the Issue

The crash occurs because ViewInspector's precondition is not safeguarded against external manipulation during testing. Once the static window is initialized and set as the keyWindow, it becomes accessible to other tests, leading to potential crashes.

static func makeWindow() -> UIWindow {
#if os(visionOS)
let frame = CGRect(x: 0, y: 0, width: 1280, height: 720)
#else
let frame = UIScreen.main.bounds
#endif
let window = UIWindow(frame: frame)
window.rootViewController = UIViewController()
window.rootViewController?.view.translatesAutoresizingMaskIntoConstraints = false
window.makeKeyAndVisible()

The crash itself will be triggered here:

static var rootViewController: UIViewController {
window.rootViewController!
}

Steps to Reproduce

The following example demonstrates how to reproduce the crash (tested in Xcode 15.4, Simulator iOS 17.5):

import SwiftUI
import ViewInspector
import XCTest

final class ViewInspectorCrash: XCTestCase {
    func testViewInspectorCrash() {
        let view = Text("Crash")

        // This triggers the one-time creation of ViewHosting.window
        ViewHosting.host(view: view)

        // The created window is now the keyWindow and can be accessed and manipulated by any other test
        UIApplication.shared.keyWindow?.rootViewController = nil

        // Manipulation from another test will lead to a crash:
        ViewHosting.host(view: view)
    }
}

Each test execution should be isolated and safe from external interference (ensuring the static window/window.rootViewController is reset or properly cleaned or implementing checks to verify the integrity of the keyWindow before it is used).

@nalexn nalexn added the pending release A fixed issue that'll be released in an upcoming update label Jun 21, 2024
@nalexn
Copy link
Owner

nalexn commented Jun 21, 2024

Thanks for the heads up

@nalexn
Copy link
Owner

nalexn commented Sep 17, 2024

Released with v0.10.0

@nalexn nalexn closed this as completed Sep 17, 2024
@nalexn nalexn removed the pending release A fixed issue that'll be released in an upcoming update label Sep 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants