Skip to content

test: add coverage for all cli commands#1848

Merged
yzh119 merged 24 commits into
flashinfer-ai:mainfrom
sricketts:test-cli-general
Jan 27, 2026
Merged

test: add coverage for all cli commands#1848
yzh119 merged 24 commits into
flashinfer-ai:mainfrom
sricketts:test-cli-general

Conversation

@sricketts
Copy link
Copy Markdown
Member

@sricketts sricketts commented Oct 2, 2025

📌 Description

For #1833 - adds coverage for all CLI commands in flashinfer/__main__.py.

🔍 Related Issues

🚀 Pull Request Checklist

Thank you for contributing to FlashInfer! Before we review your pull request, please make sure the following items are complete.

✅ Pre-commit Checks

  • I have installed pre-commit by running pip install pre-commit (or used your preferred method).
  • I have installed the hooks with pre-commit install.
  • I have run the hooks manually with pre-commit run --all-files and fixed any reported issues.

If you are unsure about how to set up pre-commit, see the pre-commit documentation.

🧪 Tests

  • Tests have been added or updated as needed.
  • All tests are passing (unittest, etc.).

Reviewer Notes

Do we want all tests in a single file or split by command?

Summary by CodeRabbit

  • Tests
    • Expanded CLI test coverage with new real and mocked scenarios for config display, download/listing, export behavior, and cache/cubin management.
    • Added a GPU-focused CLI test suite for module-status and module listing, gated for GPU environments.
    • Introduced shared CLI test helpers and removed a redundant show-config test.
  • Chores
    • Test orchestration updated to run the new CLI test suites.

✏️ Tip: You can customize this high-level summary in your review settings.

@sricketts
Copy link
Copy Markdown
Member Author

Main remaining items:

  • Fix module-status test (currently hitting error during module registration)
  • Maybe: add additional module tests as listed by TODO items in the code (or we can leave these for follow up PRs)
  • Get these tests added to internal and public CI

@sricketts sricketts self-assigned this Oct 3, 2025
@sricketts
Copy link
Copy Markdown
Member Author

@claude can you finish this PR to complete #1833?

@sricketts
Copy link
Copy Markdown
Member Author

@claude can you finish this PR to complete #1833?

@claude
Copy link
Copy Markdown

claude Bot commented Jan 14, 2026

Claude encountered an error —— View job

Command failed: git fetch origin --depth=20 test-cli-general

I'll analyze this and get back to you.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 22, 2026

Warning

Rate limit exceeded

@sricketts has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 13 minutes and 20 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📝 Walkthrough

Walkthrough

Adds CLI test helpers and two new test modules (general and GPU), integrates them into the test-run script, and removes a redundant standalone show-config test. Tests use monkeypatching and temporary directories and are guarded for GPU availability where applicable.

Changes

Cohort / File(s) Summary
Test Execution Pipeline
scripts/task_jit_run_tests_part5.sh
Added two pytest invocations to run tests/cli/test_cli_cmds.py and tests/cli/test_cli_cmds_gpu.py (preserves -s, runs sequentially).
Test Helpers
tests/cli/cli_cmd_helpers.py
Added _test_cmd_helper(cmd: list[str]), _assert_output_contains_all, and _assert_output_contains_any to invoke CLI via Click's CliRunner and assert output contents.
CLI Command Tests (General)
tests/cli/test_cli_cmds.py
New comprehensive tests covering show-config, CLI help, download-cubin, list-cubins, clear-cache, clear-cubin, and export-compile-commands with both mocked and real filesystem scenarios using monkeypatch and temp dirs.
CLI Command Tests (GPU)
tests/cli/test_cli_cmds_gpu.py
New GPU-guarded tests for module-status and list-modules, introducing MockModuleStatus and monkeypatching registration/stats and CUDA arch env to simulate GPU cases.
Test Consolidation
tests/cli/test_cli_show_config.py
Removed standalone test_show_config_cmd_smoke() (moved into test_cli_cmds.py).
Package Marker
tests/cli/__init__.py
Added comment # CLI test package.

Sequence Diagram(s)

(omitted — changes are test additions and helpers without new multi-component runtime control flow)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • yzh119
  • nvmbreughe
  • kahyunnam
  • yongwww
  • aleozlx

Poem

🐇 I hopped through tests with whiskers bright,

Helpers, GPU mocks, and scripts took flight,
Temp folders tucked where carrots hide,
Assertions checked with jittery pride,
Now CI hums — hop, run, delight! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 70.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'test: add coverage for all cli commands' clearly and concisely describes the main change—adding comprehensive test coverage for all CLI commands. It directly relates to the primary objective of the PR.
Description check ✅ Passed The PR description follows the template with a clear description section addressing issue #1833, checked pre-commit items, and reviewer notes. However, it lacks details about the actual changes and testing scope.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

sricketts and others added 4 commits January 22, 2026 13:49
Add test_clear_cache_cmd_real that actually invokes the cache clearing
logic using a temporary directory to avoid side effects. The test:
- Creates a temp cache directory with dummy files
- Uses monkeypatch to redirect FLASHINFER_JIT_DIR
- Verifies cache is cleared successfully
- Ensures no impact on the real environment

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Add test_clear_cubin_cmd_real that actually invokes the cubin clearing
logic using a temporary directory to avoid side effects. The test:
- Creates a temp cubin directory with dummy files
- Uses monkeypatch to redirect FLASHINFER_CUBIN_DIR in both import locations
- Verifies cubins are cleared successfully
- Ensures no impact on the real environment

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Add comprehensive tests for module-status and list-modules CLI commands:

- test_module_status_cmd_with_filters: Tests --filter option with
  compiled, not-compiled, and all filters
- test_module_status_cmd_detailed: Tests --detailed flag for verbose output
- test_list_modules_cmd_with_module_name: Tests inspecting a specific module
  by name, including both existing and non-existent modules

All tests use proper mocking to avoid GPU architecture issues and ensure
deterministic behavior. Mock module statuses are created with realistic
data to test all output formats.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Add CLI unit tests to the CI test suite by including them in
task_jit_run_tests_part5.sh:
- tests/cli/test_cli_cmds.py: Non-GPU CLI command tests
- tests/cli/test_cli_cmds_gpu.py: GPU-dependent CLI command tests

Part 5 was chosen as it's the lightest shard with only one existing test.
Both test files are now included in the CI pipeline and will run on PRs
and pushes to main.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
@sricketts sricketts marked this pull request as ready for review January 22, 2026 23:35
@sricketts sricketts requested a review from yongwww January 22, 2026 23:37
@sricketts
Copy link
Copy Markdown
Member Author

@yongwww this PR adds a new category of unit tests. Did I add them correctly to the CI scripts? I added them to scripts/task_jit_run_tests_part5.sh; not sure if that's right.

Note that only the tests in test_cli_cmds_gpu.py require a GPU. The other tests can run without a GPU. But I couldn't figure out how to distinguish that in our CI scripts.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@tests/cli/test_cli_cmds_gpu.py`:
- Around line 7-12: Add a runtime skip guard to the GPU tests by importing
pytest and the flashinfer.utils helpers (e.g., get_compute_capability,
is_sm90a_supported, is_sm100a_supported) at the top of the file and, before
using _MOCKED_CUDA_ARCH_LIST or any GPU tests, call get_compute_capability() (or
the is_sm90a_supported/is_sm100a_supported predicates) and call pytest.skip(...)
with a clear reason when the current device arch is not in the expected list;
ensure the guard sits alongside the existing _MOCKED_CUDA_ARCH_LIST declaration
so tests are skipped early on unsupported architectures.

In `@tests/cli/test_cli_cmds.py`:
- Around line 83-85: The test function test_list_cubins_cmd_real currently
declares an unused fixture parameter monkeypatch; remove monkeypatch from the
function signature so the test reads def test_list_cubins_cmd_real(): and ensure
no other references to monkeypatch remain in that test (the test body should
still call _test_cmd_helper(["list-cubins"]) and assert the same strings).
🧹 Nitpick comments (1)
tests/cli/cli_cmd_helpers.py (1)

6-12: Use proper typing for cmd instead of a list literal.

Line 6 uses cmd: [str], which is a list literal rather than a type. This is non-idiomatic and can confuse type checkers and IDEs. Prefer Sequence[str] or list[str].

♻️ Suggested refactor
+from typing import Sequence
 from click.testing import CliRunner

 from flashinfer.__main__ import cli


-def _test_cmd_helper(cmd: [str]):
+def _test_cmd_helper(cmd: Sequence[str]) -> str:
     """
     Helper for command tests
     """
     runner = CliRunner()
     result = runner.invoke(cli, cmd)
     assert result.exit_code == 0, result.output
     return result.output

Comment thread tests/cli/test_cli_cmds_gpu.py Outdated
Comment thread tests/cli/test_cli_cmds.py Outdated
@sricketts sricketts changed the title [wip] test: add coverage for all cli commands test: add coverage for all cli commands Jan 22, 2026
sricketts and others added 2 commits January 22, 2026 15:47
Fix failing test that was trying to mock a non-existent function.
The test now correctly:
- Mocks get_subdir_file_list (not get_cubin_file_list)
- Returns proper (filename, checksum) tuples
- Mocks download_file to avoid network calls
- Mocks verify_cubin to skip checksum verification

All 11 tests in test_cli_cmds.py now pass.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@tests/cli/test_cli_cmds.py`:
- Around line 68-80: The test test_download_cubin_cmd_mocked currently only
stubs flashinfer.artifacts.get_cubin_file_list but still triggers real
network/storage I/O during the download phase called by _test_cmd_helper;
replace or monkeypatch the actual downloader used by the CLI (the function that
performs cubin fetches inside the download-cubin flow) to a no-op or a fake that
records calls and returns success, so the test asserts behavior without network
access. Specifically, in the test replace the downloader function invoked by
_test_cmd_helper (the module/function responsible for fetching cubins in the
download-cubin command) with a stub, then assert that get_cubin_file_list was
used and that the CLI output contains "All cubin download tasks completed
successfully" without performing real downloads.

Comment thread tests/cli/test_cli_cmds.py
sricketts and others added 3 commits January 22, 2026 15:58
Fix module-level GPU check that was calling get_compute_capability()
without the required device argument. Replace with simpler
torch.cuda.is_available() check to skip tests when no GPU is present.

All 5 tests in test_cli_cmds_gpu.py now pass.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Change invalid type hint `[str]` to proper `list[str]` syntax.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1. Add __init__.py to make tests/cli a proper package
   - Consistent with other test subdirectories (attention, gemm, etc.)
   - Allows running tests from repository root

2. Update imports to use relative imports
   - Change `from cli_cmd_helpers` to `from .cli_cmd_helpers`

3. Refactor test_cli_cmds_gpu.py to reduce code duplication
   - Extract common mocks into mock_module_registry fixture
   - Add docstrings to MockModuleStatus and _create_mock_statuses
   - Fix import ordering (stdlib first, then third-party)
   - Simplify test functions by using the shared fixture

All 16 CLI tests pass when run from the repository root.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@sricketts
Copy link
Copy Markdown
Member Author

/bot run

@flashinfer-bot
Copy link
Copy Markdown
Collaborator

GitLab MR !259 has been created, and the CI pipeline #42353599 is currently running. I'll report back once the pipeline job completes.

@yongwww
Copy link
Copy Markdown
Member

yongwww commented Jan 23, 2026

@yongwww this PR adds a new category of unit tests. Did I add them correctly to the CI scripts? I added them to scripts/task_jit_run_tests_part5.sh; not sure if that's right.

I think it makes sense to put this in scripts/task_jit_run_tests_part5.sh.

Copy link
Copy Markdown
Member

@yongwww yongwww left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the pr looks good to me.

@flashinfer-bot
Copy link
Copy Markdown
Collaborator

[FAILED] Pipeline #42353599: 11/20 passed

Add three new tests covering the export-compile-commands CLI command:
- test_export_compile_commands_mocked: verifies JSON output with mock specs
- test_export_compile_commands_output_option: verifies --output overrides PATH
- test_export_compile_commands_no_modules: verifies empty module registry handling

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Copy link
Copy Markdown
Contributor

@jimmyzho jimmyzho left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

small nit, but everything looks good to me!

Comment thread tests/cli/test_cli_cmds.py Outdated

def test_list_cubins_cmd_real():
out = _test_cmd_helper(["list-cubins"])
assert "Cubin" in out and "Status" in out
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For assertions like this we could make a simple helper function

def assert_output_contains_all(output, *expected_strings):
"""Assert that output contains all expected strings."""
missing = [s for s in expected_strings if s not in output]
assert not missing, f"Missing strings in output: {missing}\n\nActual output:\n{output}"

so it is easier to read the expected strings in output

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks, updated

Comment thread tests/cli/test_cli_cmds_gpu.py Outdated
Comment on lines +97 to +100
assert "=== Summary ===" in out
assert "Total modules:" in out
assert "Compiled:" in out
assert "Not compiled:" in out
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above

sricketts and others added 3 commits January 26, 2026 12:10
Add comment to test_cli_cmds.py docstring explaining that the replay
CLI command is tested in tests/utils/test_logging_replay.py since it's
tightly coupled with the logging/replay feature tests.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@tests/cli/test_cli_cmds_gpu.py`:
- Around line 94-176: Several tests declare the mock_module_registry fixture as
a function parameter but never use its return value, causing ARG001 warnings;
replace the unused parameter with a decorator. For each test function named
test_module_status_cmd_mocked, test_module_status_cmd_with_filters,
test_module_status_cmd_detailed, test_list_modules_cmd_mocked, and
test_list_modules_cmd_with_module_name, remove mock_module_registry from the
function signature and add `@pytest.mark.usefixtures`("mock_module_registry")
above the function; ensure pytest is imported at the top of the file and keep
other parameters (e.g., monkeypatch) intact where used.

In `@tests/cli/test_cli_cmds.py`:
- Around line 90-96: Update the two monkeypatch lambda stubs so their unused
parameters are prefixed with an underscore to silence Ruff ARG005: in the
monkeypatch.setattr call for "flashinfer.artifacts.download_file" change the
lambda signature from lambda *args, **kwargs to lambda *_args, **_kwargs and in
the monkeypatch.setattr call for "flashinfer.artifacts.verify_cubin" change
lambda *args to lambda *_args; keep both lambdas returning True and leave the
monkeypatch.setattr targets unchanged.

Comment thread tests/cli/test_cli_cmds_gpu.py Outdated
Comment thread tests/cli/test_cli_cmds.py Outdated
@sricketts sricketts requested a review from jimmyzho January 26, 2026 20:22
Copy link
Copy Markdown
Contributor

@jimmyzho jimmyzho left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@yzh119 yzh119 merged commit 86101f6 into flashinfer-ai:main Jan 27, 2026
52 of 57 checks passed
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

Successfully merging this pull request may close these issues.

5 participants