DEV Community

Ben Brahim Moanes
Ben Brahim Moanes

Posted on

My PyInstaller build passed every test and still shipped without Selenium's Chrome modules

Last week I shipped two releases of a Windows desktop app that couldn't open Chrome. The unit tests passed, the build succeeded, and the installer worked. The app started and looked fine. Then, at the first moment it needed a browser, it failed with:

ModuleNotFoundError: No module named 'selenium.webdriver.chrome.options'
Enter fullscreen mode Exit fullscreen mode

Here's why, and the 40-line check that now runs on every build so it can't happen again.

The setup

The app is SlowUnfollow, a PySide6 desktop app that drives Chrome through Selenium. Releases are built by GitHub Actions: pip install -r requirements.txt pyinstaller, run the tests, then PyInstaller (one-folder, windowed) and Inno Setup for the installer.

The browser code was the textbook version:

from selenium import webdriver

opts = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=opts)
Enter fullscreen mode Exit fullscreen mode

On my machine, built locally, this worked. In the installer built on CI, it didn't.

What changed: lazy imports

requirements.txt said selenium>=4.20. My machine had 4.33. CI installed the newest release, 4.54, and in recent versions selenium/webdriver/__init__.py no longer imports the browsers up front. It maps names to modules and loads them on first use:

_LAZY_IMPORTS = {
    "Chrome": ("selenium.webdriver.chrome.webdriver", "WebDriver"),
    "ChromeOptions": ("selenium.webdriver.chrome.options", "Options"),
    ...
}

def __getattr__(name):
    module_path, attr = _LAZY_IMPORTS[name]
    return getattr(importlib.import_module(module_path), attr)
Enter fullscreen mode Exit fullscreen mode

That's a reasonable change: importing Selenium gets faster when you only use one browser. But PyInstaller decides what to bundle by reading the import statements in your code and its dependencies. A module name inside a dict, passed to importlib.import_module() at run time, is invisible to it. So the frozen app contained selenium.webdriver but not selenium.webdriver.chrome.options.

The tests didn't catch it because they run from source, where every module is installed. Only the frozen build was missing anything.

Fix 1: import what you use, by its full path

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.webdriver import WebDriver as Chrome

opts = Options()
driver = Chrome(options=opts)
Enter fullscreen mode Exit fullscreen mode

PyInstaller can see these, and it follows their own imports from there.

Fix 2: tell PyInstaller to collect the packages anyway

--collect-submodules selenium.webdriver.chrome
--collect-submodules selenium.webdriver.chromium
--collect-submodules selenium.webdriver.common
--collect-submodules selenium.webdriver.remote
Enter fullscreen mode Exit fullscreen mode

A belt with the braces: if Selenium moves something else behind a lazy import later, it's still in the build.

Fix 3: make the built app check itself before it becomes an installer

Neither fix tells you about the next missing module. So the app now has a hidden selfcheck command that imports everything it only loads later, and can start a real browser.

Here is the complete implementation used by the check:

# slowunfollow/selfcheck.py

import argparse
import importlib
import shutil
import sys
import tempfile
from pathlib import Path


MODULES = [
    "selenium.webdriver.chrome.options",
    "selenium.webdriver.chrome.webdriver",
    "selenium.webdriver.chrome.service",
    "selenium.webdriver.common.selenium_manager",
    "selenium.webdriver.common.driver_finder",
    "selenium.webdriver.remote.webdriver",
    "PySide6.QtMultimedia",
    # Add modules imported dynamically or inside functions here.
]


def check_modules():
    """Return a list of modules that cannot be imported."""
    failures = []

    for name in MODULES:
        try:
            importlib.import_module(name)
        except Exception as exc:
            failures.append(
                f"MISSING {name}: {type(exc).__name__}: {exc}"
            )

    return failures


def check_chrome():
    """Launch headless Chrome using a temporary browser profile."""
    profile = tempfile.mkdtemp(prefix="slowunfollow-selfcheck-")
    driver = None

    try:
        from selenium.webdriver.chrome.options import Options
        from selenium.webdriver.chrome.webdriver import WebDriver

        options = Options()
        options.add_argument("--headless=new")
        options.add_argument("--disable-gpu")
        options.add_argument("--no-sandbox")
        options.add_argument(f"--user-data-dir={profile}")

        driver = WebDriver(options=options)
        driver.get("about:blank")

        if driver.current_url != "about:blank":
            return "Chrome opened, but did not reach about:blank"

        return None

    except Exception as exc:
        return f"Chrome did not start: {type(exc).__name__}: {exc}"

    finally:
        if driver is not None:
            try:
                driver.quit()
            except Exception:
                pass

        shutil.rmtree(profile, ignore_errors=True)


def run_selfcheck(argv=None):
    parser = argparse.ArgumentParser(
        description="Validate the packaged SlowUnfollow application."
    )
    parser.add_argument("--chrome", action="store_true")
    parser.add_argument("--out", type=Path, required=True)
    args = parser.parse_args(argv)

    failures = check_modules()

    if args.chrome:
        chrome_failure = check_chrome()
        if chrome_failure:
            failures.append(chrome_failure)

    if failures:
        result = "\n".join(failures)
        exit_code = 1
    else:
        result = "SELF-CHECK PASSED"
        exit_code = 0

    # A windowed PyInstaller executable may not have stdout or stderr.
    # Always write diagnostics to the requested output file.
    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text(result + "\n", encoding="utf-8")

    return exit_code


if __name__ == "__main__":
    sys.exit(run_selfcheck())
Enter fullscreen mode Exit fullscreen mode

The module list is specific to the application. Whenever I add a dependency that is imported dynamically or only inside a function, I add it here too.

The selfcheck command also needs to be registered in the application's startup argument handling so that the frozen executable can dispatch to run_selfcheck() before starting the normal GUI.

The detail that makes this work: the module names are strings passed to importlib, so PyInstaller doesn't bundle them because of the check. The check only sees what the build really contains.

The build script runs the frozen exe and refuses to make an installer if it fails:

code = subprocess.run(
    [exe, "selfcheck", "--chrome", "--out", out],
    timeout=300
).returncode

if code != 0:
    sys.exit("The built app is incomplete; no installer made.")
Enter fullscreen mode Exit fullscreen mode

Two Windows details:

  • A --windowed PyInstaller app has no console, and sys.stdout is None. Write the result to a file and use the exit code.
  • GitHub's Windows runners have Chrome installed, so --chrome also proves that Selenium Manager can find Chrome and fetch a matching ChromeDriver.

Did it work?

I rebuilt the broken version on purpose: old import style, no collect flags, Selenium 4.54. The self-check failed with exactly the missing modules:

MISSING selenium.webdriver.chrome.webdriver: ModuleNotFoundError
MISSING selenium.webdriver.chrome.service: ModuleNotFoundError
MISSING selenium.webdriver.common.selenium_manager: ModuleNotFoundError
The built app is incomplete (exit code 1); no installer made.
Enter fullscreen mode Exit fullscreen mode

The fixed build passes, including a real headless Chrome start. Since then the check has also caught something new: when I added in-app video, I put PySide6.QtMultimedia and the video files in the list too.

Takeaways

  • Tests from source don't test the frozen app. Anything imported inside a function, by string, or behind a lazy __getattr__ can silently go missing.
  • Unpinned dependencies change your build without changing your code. Either pin them, or check the result. I chose to check.
  • Make the user-facing error human. The app used to say "repeated errors (ModuleNotFoundError)". It now says what happened and what to do: "SlowUnfollow is missing one of its own parts, a fault in this version, not in your account. Update it."

The code is MIT-licensed if you want to borrow the self-check: github.com/Moanesbbr/slow-unfollow, see slowunfollow/selfcheck.py and packaging/build.py.

Top comments (1)

Collapse
 
hoopvisionlab profile image
HoopVision Lab •

Passing every test and still shipping without the Chrome modules is a good reminder that tests run from source never exercise the frozen build. A smoke test against the built executable is a cheap fix.