Files
crewAI/lib/cli/tests/tools/test_main.py
T
João MouraandClaude Opus 5.5 87c2868123 feat(cli): rewrite the scaffolded AGENTS.md and fail PRs that teach coding agents less (#8298)
* feat(cli): rewrite the scaffolded AGENTS.md around the CrewAI + AMP workflow

The template opened with an API reference and mentioned traces, eval and
deployment as optional extras, so coding agents rarely used them. It now
opens with the steps an agent follows in a session (set up, reuse what the
organization has on AMP, run, trace and evaluate every change, deploy when the
work has to run elsewhere), then a short reference of the facts models get
wrong. About 3.3K tokens instead of 11.9K, with outdated claims corrected.

Tests assert the behaviours the old wording carried, check every documented
`crewai` command against the CLI, and keep numbered lists gapless with and
without the evaluation blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(cli): index the features AGENTS.md no longer details, and guard the file

The workflow rewrite dropped references to guardrails, knowledge, MCP,
conversational and declarative flows, checkpoints and more. An "Also
available" index under Reference names each one with its API and docs path.

Tests now guard the shipped file on every PR: a reference manifest, a
token budget, text that is wrong on main, imports that must resolve,
python blocks that must parse, and docs paths that must exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(cli): add a core API section to AGENTS.md for models that don't know CrewAI

Measured with OpenAI models, the workflow rewrite lost the basics they don't
know without the file: flow decorators and state, the @CrewBase class, task
fields, CrewOutput and custom tools. A short Core API section restores them
and folds in the two crew and router facts it would otherwise repeat.

The reference manifest now guards those core references too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: run the AGENTS.md guards on PRs that touch the template

The guards live in lib/cli/tests, which the main test workflow doesn't run.
A path-filtered job runs them when the template, its tests or the docs
pages it links change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: run the AGENTS.md workflow only on pull requests against main

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(cli): close the gaps where AGENTS.md taught less than the file it replaces

Question by question against today's file, V6 trailed on facts it had cut or
worded loosely: the context window and date options, task output folders and
human review, the guardrail's return shape, test targets before writes, the
eval's structural fixes, logged-in trace visibility, partial selector misses,
written IDs for silent failures, ZIP deploys with an origin, the flow memory
root, and LiteLLM for providers outside the native set. Each is back, verified
on main. Measured on Claude Code (Haiku, Sonnet) and Codex, no question now
scores below today's file. The token budget rises to 4,800 to hold them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(cli): teach the hooks and planning that telemetry counts, and three facts the old file had

The index named kickoff hooks and Crew(planning=True), but the features most
projects use are interception hooks (@on(InterceptionPoint...) in crewai.hooks)
and agent planning (Agent(planning_config=PlanningConfig(...))). Both lines now
lead with those. Three facts today's file taught come back: OpenAI's Responses
API, agents judge while code computes, and answering a paused deployed flow
through AMP's human_feedback_requests API.

Measured on 221 questions in Claude Code (Haiku, Sonnet) and Codex, no question
scores below today's file. The budget rises to 5,000 tokens, guards cover the
new lines, and the never-teach list allows naming reasoning=True as replaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(devtools): agents-md-eval fails a PR whose AGENTS.md teaches coding agents less

`devtools agents-md-eval` asks a 218-question bank in fresh, tool-less Claude
Code and Codex sessions, once with the base branch's AGENTS.md and once with
this branch's, grades each answer by its key, and exits non-zero when either
agent scores more than 10% below the base. The AGENTS.md workflow runs it on
PRs that change the template, the eval or its questions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(devtools): run the AGENTS.md eval per model and count sessions with no answer

The action asks Claude Code with the latest Haiku and Sonnet and Codex with
gpt-5.6-luna and gpt-5.6-sol, one job per model. A session that hangs, fails or
returns nothing is retried once and then counted; past 2% unanswered the
comparison is called unreliable instead of scored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: run the AGENTS.md eval only on pull requests against main

Drops the manual trigger and the conditions it needed; a test pins the trigger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(devtools): say why AGENTS.md eval sessions gave no answer

Each unanswered session records its exit code and last error line (keys
redacted) or a timeout, and the command prints the most common reasons, so a
run called unreliable can be diagnosed from the CI log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(devtools): grade 'is a different command' as a warning, accept 'call the agent directly'

Two answer-key misses found reading V6's answers: a correct answer that warns
off `crewai update` tripped its trap, and "No. Call the agent directly" didn't
count as needing no crew.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(devtools): B-065's trap fires only on advice to run crewai update

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(devtools): read a failed session's reason from stdout when stderr is empty

Claude Code prints some failures, such as 'Not logged in', on stdout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(devtools): accept 'never a fix' in C-018's key

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(devtools): read typographic apostrophes and 'replaces' as warnings in traps

Codex writes "don’t"; the negation check knew only "don't", so its warnings
counted as recommendations. "X replaces reasoning=True" now reads as a
warning too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(devtools): add hooks and agent planning questions; D-018 needs the tools, not the package name

Three questions for features telemetry counts and the bank missed: tool-call
hooks, LLM-call hooks and agent planning (221 questions).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(cli): AGENTS.md teaches that crewai eval runs the crew itself, logged in or out

Since #8270, `crewai eval` runs the crew, traced, when the project changed
since its last traced run. The file still said to `crewai run` first, and
that a run without a terminal is traced only when logged in, so logged-out
coding agents logged in or stopped instead of evaluating. It now says
`crewai eval` works logged in or out, with or without a terminal, with no
`crewai run` between rounds and no wait on a login.

The CLI test's command parser stops at a group that runs without a
subcommand (`crewai eval`, `crewai eval --models ...`), which `crewai eval`
became when it gained `export`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(devtools): ask whether crewai eval needs a login, and read "doesn't" as a warning

Two questions join the bank: can a logged-out coding agent with no terminal
get a verdict, and does it need `crewai run` first. Three keys follow main:
C-004 and B-051 accept `crewai eval` (it runs and traces the crew), C-032
accepts "flow code". Negations now include doesn't, didn't, aren't and
can't, so "evaluation doesn't require an account" no longer trips the trap
it warns against.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ci): run the AGENTS.md eval from the base commit, with the PR's files as data

The eval job checked out the pull request and ran its devtools with both
API keys in the environment, so a branch could print or send them. It now
checks out the base commit, fetches the pull request's commit only to read
its AGENTS.md and CLAUDE.md (`agents-md-eval --head <sha>`), and runs in the
`agents-md-eval` environment, where the keys can sit behind a required
reviewer. When the base branch has no eval yet, the job skips with a notice.

The eval also names a session's real error: Claude Code can end its output
with a JSON log line after the message ("Invalid API key"), which hid every
Haiku failure. Item text and reasons print as text, so `[tool.crewai]` isn't
dropped and `[/...]` can't raise MarkupError after the paid runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): AGENTS.md says deploys build from any git origin, not only GitHub

`crewai deploy create` sends whatever `origin` URL the project has, and AMP
builds from GitHub or another git host (`any_git`). The file said an origin
meant GitHub, which pointed GitLab and other users at the wrong fix. The
GitHub integration note now applies to GitHub only, and a guard keeps it so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ci): run the AGENTS.md eval on pull_request_target, so its keys reach only reviewed code

Under pull_request a branch's own copy of the workflow runs, so a pull
request could edit the eval's steps and still get the keys. The eval now
has its own workflow on pull_request_target: GitHub runs it from the base
branch, the job checks out the base commit, and the pull request's
AGENTS.md and CLAUDE.md are fetched and read as data, never run. It runs
for this repository's branches only, since pull_request_target would hand
the keys to forks too, and it fetches the pull request's commit only once
it knows it will run, so a skip can't fail on the fetch.

The guards stay on pull_request, with no secrets, and no longer persist
the checkout's token for the pull request's code to read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(devtools): accept "go-ahead" as asking first in C-052's key

"Publishing writes to your organization, so it needs your go-ahead first"
asks before publishing, but the key only matched ask, approve, confirm or
permission, so correct answers scored wrong.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:28:47 +05:30

504 lines
18 KiB
Python

import os
import tempfile
import unittest
import unittest.mock
from contextlib import contextmanager
from datetime import datetime, timedelta
from pathlib import Path
from unittest import mock
from unittest.mock import MagicMock, patch
import pytest
from crewai_cli.shared.token_manager import TokenManager
from crewai_cli.tools.main import ToolCommand
from pytest import raises
@contextmanager
def in_temp_dir():
original_dir = os.getcwd()
with tempfile.TemporaryDirectory() as temp_dir:
os.chdir(temp_dir)
try:
yield temp_dir
finally:
os.chdir(original_dir)
@pytest.fixture
def tool_command():
with tempfile.TemporaryDirectory() as temp_dir:
with patch.object(
TokenManager, "_get_secure_storage_path", return_value=Path(temp_dir)
):
TokenManager().save_tokens(
"test-token", (datetime.now() + timedelta(seconds=36000)).timestamp()
)
tool_command = ToolCommand()
with patch.object(tool_command, "login"):
yield tool_command
@patch("crewai_cli.tools.main.subprocess.run")
def test_create_success(mock_subprocess, capsys, tool_command):
with in_temp_dir():
tool_command.create("test-tool")
output = capsys.readouterr().out
assert "Creating custom tool test_tool..." in output
assert os.path.isdir("test_tool")
assert os.path.isfile(os.path.join("test_tool", "README.md"))
assert os.path.isfile(os.path.join("test_tool", "pyproject.toml"))
assert os.path.isfile(
os.path.join("test_tool", "src", "test_tool", "__init__.py")
)
assert os.path.isfile(os.path.join("test_tool", "src", "test_tool", "tool.py"))
with open(os.path.join("test_tool", "pyproject.toml"), "r") as f:
content = f.read()
assert '"crewai[tools]>=1.15.0,<2.0.0"' in content
with open(os.path.join("test_tool", "src", "test_tool", "tool.py"), "r") as f:
content = f.read()
assert "class TestTool" in content
mock_subprocess.assert_called_once_with(["git", "init"], check=True)
@patch("crewai_cli.tools.main.subprocess.run")
def test_create_scaffolds_assistant_instructions(mock_subprocess, tool_command):
with in_temp_dir():
tool_command.create("test-tool")
agents_md = Path("test_tool", "AGENTS.md").read_text(encoding="utf-8")
assert "## Working in this project" in agents_md
assert "Never turn off tracing or telemetry" in agents_md
claude_md = Path("test_tool", "CLAUDE.md").read_text(encoding="utf-8")
assert "@AGENTS.md" in claude_md.splitlines()
cursor_md = Path("test_tool", "CURSOR.md").read_text(encoding="utf-8")
assert "@AGENTS.md" in cursor_md.splitlines()
gemini_md = Path("test_tool", "GEMINI.md").read_text(encoding="utf-8")
assert "@./AGENTS.md" in gemini_md.splitlines()
@patch("crewai_cli.tools.main.subprocess.run")
def test_a_tool_project_gets_no_evaluation_guidance(mock_subprocess, tool_command):
# A tool project has no `crewai run` and no traced run for `crewai eval`.
with in_temp_dir():
tool_command.create("test-tool")
agents_md = Path("test_tool", "AGENTS.md").read_text(encoding="utf-8")
assert "Check every change: run, trace, evaluate" not in agents_md
assert "crewai eval" not in agents_md
assert "crewai-eval:" not in agents_md
assert "## Reference" in agents_md
@patch("crewai_cli.tools.main.subprocess.run")
@patch("crewai_cli.plus_api.PlusAPI.get_tool")
@patch("crewai_cli.tools.main.ToolCommand._print_current_organization")
def test_install_success(
mock_print_org, mock_get, mock_subprocess_run, capsys, tool_command
):
mock_get_response = MagicMock()
mock_get_response.status_code = 200
mock_get_response.json.return_value = {
"handle": "sample-tool",
"repository": {"handle": "sample-repo", "url": "https://example.com/repo"},
}
mock_get.return_value = mock_get_response
mock_subprocess_run.return_value = MagicMock(stderr=None)
tool_command.install("sample-tool")
output = capsys.readouterr().out
assert "Successfully installed sample-tool" in output
mock_get.assert_has_calls([mock.call("sample-tool"), mock.call().json()])
mock_subprocess_run.assert_any_call(
[
"uv",
"add",
"--index",
"sample-repo=https://example.com/repo",
"sample-tool",
],
capture_output=False,
text=True,
check=True,
env=unittest.mock.ANY,
)
mock_print_org.assert_called_once()
@patch("crewai_cli.tools.main.subprocess.run")
@patch("crewai_cli.plus_api.PlusAPI.get_tool")
def test_install_success_from_pypi(mock_get, mock_subprocess_run, capsys, tool_command):
mock_get_response = MagicMock()
mock_get_response.status_code = 200
mock_get_response.json.return_value = {
"handle": "sample-tool",
"repository": {"handle": "sample-repo", "url": "https://example.com/repo"},
"source": "pypi",
}
mock_get.return_value = mock_get_response
mock_subprocess_run.return_value = MagicMock(stderr=None)
tool_command.install("sample-tool")
output = capsys.readouterr().out
assert "Successfully installed sample-tool" in output
mock_get.assert_has_calls([mock.call("sample-tool"), mock.call().json()])
mock_subprocess_run.assert_any_call(
[
"uv",
"add",
"sample-tool",
],
capture_output=False,
text=True,
check=True,
env=unittest.mock.ANY,
)
@patch("crewai_cli.plus_api.PlusAPI.get_tool")
def test_install_tool_not_found(mock_get, capsys, tool_command):
mock_get_response = MagicMock()
mock_get_response.status_code = 404
mock_get.return_value = mock_get_response
with raises(SystemExit):
tool_command.install("non-existent-tool")
output = capsys.readouterr().out
assert "No tool found with this name" in output
mock_get.assert_called_once_with("non-existent-tool")
@patch("crewai_cli.plus_api.PlusAPI.get_tool")
def test_install_api_error(mock_get, capsys, tool_command):
mock_get_response = MagicMock()
mock_get_response.status_code = 500
mock_get.return_value = mock_get_response
with raises(SystemExit):
tool_command.install("error-tool")
output = capsys.readouterr().out
assert "Failed to get tool details" in output
mock_get.assert_called_once_with("error-tool")
@patch("crewai_cli.tools.main.git.Repository")
def test_publish_when_not_in_sync(mock_repository, capsys, tool_command):
mock_repository.return_value.is_synced.return_value = False
with raises(SystemExit):
tool_command.publish(is_public=True)
output = capsys.readouterr().out
assert "Local changes need to be resolved before publishing" in output
mock_repository.return_value.is_synced.assert_called_once_with()
@patch("crewai_cli.tools.main.get_project_name", return_value="sample-tool")
@patch("crewai_cli.tools.main.get_project_version", return_value="1.0.0")
@patch("crewai_cli.tools.main.get_project_description", return_value="A sample tool")
@patch("crewai_cli.tools.main.subprocess.run")
@patch("crewai_cli.tools.main.os.listdir", return_value=["sample-tool-1.0.0.tar.gz"])
@patch(
"crewai_cli.tools.main.open",
new_callable=unittest.mock.mock_open,
read_data=b"sample tarball content",
)
@patch("crewai_cli.tools.main.git.Repository.fetch")
@patch("crewai_cli.plus_api.PlusAPI.publish_tool")
@patch("crewai_cli.tools.main.git.Repository.is_synced", return_value=False)
@patch(
"crewai.utilities.project_utils.extract_available_exports",
return_value=[{"name": "SampleTool"}],
)
@patch(
"crewai.utilities.project_utils.extract_tools_metadata",
return_value=[{"name": "SampleTool", "humanized_name": "sample_tool", "description": "A sample tool", "run_params_schema": {}, "init_params_schema": {}, "env_vars": []}],
)
@patch("crewai_cli.tools.main.ToolCommand._print_current_organization")
def test_publish_when_not_in_sync_and_force(
mock_print_org,
mock_tools_metadata,
mock_available_exports,
mock_is_synced,
mock_publish,
mock_fetch,
mock_open,
mock_listdir,
mock_subprocess_run,
mock_get_project_description,
mock_get_project_version,
mock_get_project_name,
tool_command,
):
mock_publish_response = MagicMock()
mock_publish_response.status_code = 200
mock_publish_response.json.return_value = {"handle": "sample-tool"}
mock_publish.return_value = mock_publish_response
tool_command.publish(is_public=True, force=True)
mock_get_project_name.assert_called_with(require=True)
mock_get_project_version.assert_called_with(require=True)
mock_get_project_description.assert_called_with(require=False)
mock_subprocess_run.assert_called_with(
["uv", "build", "--sdist", "--out-dir", unittest.mock.ANY],
check=True,
capture_output=False,
env=unittest.mock.ANY,
)
mock_open.assert_called_with(unittest.mock.ANY, "rb")
mock_publish.assert_called_with(
handle="sample-tool",
is_public=True,
version="1.0.0",
description="A sample tool",
encoded_file=unittest.mock.ANY,
available_exports=[{"name": "SampleTool"}],
tools_metadata=[{"name": "SampleTool", "humanized_name": "sample_tool", "description": "A sample tool", "run_params_schema": {}, "init_params_schema": {}, "env_vars": []}],
)
mock_print_org.assert_called_once()
@patch("crewai_cli.tools.main.get_project_name", return_value="sample-tool")
@patch("crewai_cli.tools.main.get_project_version", return_value="1.0.0")
@patch("crewai_cli.tools.main.get_project_description", return_value="A sample tool")
@patch("crewai_cli.tools.main.subprocess.run")
@patch("crewai_cli.tools.main.os.listdir", return_value=["sample-tool-1.0.0.tar.gz"])
@patch(
"crewai_cli.tools.main.open",
new_callable=unittest.mock.mock_open,
read_data=b"sample tarball content",
)
@patch("crewai_cli.tools.main.git.Repository.fetch")
@patch("crewai_cli.plus_api.PlusAPI.publish_tool")
@patch("crewai_cli.tools.main.git.Repository.is_synced", return_value=True)
@patch(
"crewai.utilities.project_utils.extract_available_exports",
return_value=[{"name": "SampleTool"}],
)
@patch(
"crewai.utilities.project_utils.extract_tools_metadata",
return_value=[{"name": "SampleTool", "humanized_name": "sample_tool", "description": "A sample tool", "run_params_schema": {}, "init_params_schema": {}, "env_vars": []}],
)
def test_publish_success(
mock_tools_metadata,
mock_available_exports,
mock_is_synced,
mock_publish,
mock_fetch,
mock_open,
mock_listdir,
mock_subprocess_run,
mock_get_project_description,
mock_get_project_version,
mock_get_project_name,
tool_command,
):
mock_publish_response = MagicMock()
mock_publish_response.status_code = 200
mock_publish_response.json.return_value = {"handle": "sample-tool"}
mock_publish.return_value = mock_publish_response
tool_command.publish(is_public=True)
mock_get_project_name.assert_called_with(require=True)
mock_get_project_version.assert_called_with(require=True)
mock_get_project_description.assert_called_with(require=False)
mock_subprocess_run.assert_called_with(
["uv", "build", "--sdist", "--out-dir", unittest.mock.ANY],
check=True,
capture_output=False,
env=unittest.mock.ANY,
)
mock_open.assert_called_with(unittest.mock.ANY, "rb")
mock_publish.assert_called_with(
handle="sample-tool",
is_public=True,
version="1.0.0",
description="A sample tool",
encoded_file=unittest.mock.ANY,
available_exports=[{"name": "SampleTool"}],
tools_metadata=[{"name": "SampleTool", "humanized_name": "sample_tool", "description": "A sample tool", "run_params_schema": {}, "init_params_schema": {}, "env_vars": []}],
)
@patch("crewai_cli.tools.main.get_project_name", return_value="sample-tool")
@patch("crewai_cli.tools.main.get_project_version", return_value="1.0.0")
@patch("crewai_cli.tools.main.get_project_description", return_value="A sample tool")
@patch("crewai_cli.tools.main.subprocess.run")
@patch("crewai_cli.tools.main.os.listdir", return_value=["sample-tool-1.0.0.tar.gz"])
@patch(
"crewai_cli.tools.main.open",
new_callable=unittest.mock.mock_open,
read_data=b"sample tarball content",
)
@patch("crewai_cli.plus_api.PlusAPI.publish_tool")
@patch(
"crewai.utilities.project_utils.extract_available_exports",
return_value=[{"name": "SampleTool"}],
)
@patch(
"crewai.utilities.project_utils.extract_tools_metadata",
return_value=[{"name": "SampleTool", "humanized_name": "sample_tool", "description": "A sample tool", "run_params_schema": {}, "init_params_schema": {}, "env_vars": []}],
)
def test_publish_failure(
mock_tools_metadata,
mock_available_exports,
mock_publish,
mock_open,
mock_listdir,
mock_subprocess_run,
mock_get_project_description,
mock_get_project_version,
mock_get_project_name,
capsys,
tool_command,
):
mock_publish_response = MagicMock()
mock_publish_response.status_code = 422
mock_publish_response.json.return_value = {"name": ["is already taken"]}
mock_publish.return_value = mock_publish_response
with raises(SystemExit):
tool_command.publish(is_public=True)
output = capsys.readouterr().out
assert "Failed to complete operation" in output
assert "Name is already taken" in output
mock_publish.assert_called_once()
@patch("crewai_cli.tools.main.get_project_name", return_value="sample-tool")
@patch("crewai_cli.tools.main.get_project_version", return_value="1.0.0")
@patch("crewai_cli.tools.main.get_project_description", return_value="A sample tool")
@patch("crewai_cli.tools.main.subprocess.run")
@patch("crewai_cli.tools.main.os.listdir", return_value=["sample-tool-1.0.0.tar.gz"])
@patch(
"crewai_cli.tools.main.open",
new_callable=unittest.mock.mock_open,
read_data=b"sample tarball content",
)
@patch("crewai_cli.plus_api.PlusAPI.publish_tool")
@patch(
"crewai.utilities.project_utils.extract_available_exports",
return_value=[{"name": "SampleTool"}],
)
@patch(
"crewai.utilities.project_utils.extract_tools_metadata",
return_value=[{"name": "SampleTool", "humanized_name": "sample_tool", "description": "A sample tool", "run_params_schema": {}, "init_params_schema": {}, "env_vars": []}],
)
def test_publish_api_error(
mock_tools_metadata,
mock_available_exports,
mock_publish,
mock_open,
mock_listdir,
mock_subprocess_run,
mock_get_project_description,
mock_get_project_version,
mock_get_project_name,
capsys,
tool_command,
):
mock_response = MagicMock()
mock_response.status_code = 500
mock_response.json.return_value = {"error": "Internal Server Error"}
mock_response.is_success = False
mock_publish.return_value = mock_response
with raises(SystemExit):
tool_command.publish(is_public=True)
output = capsys.readouterr().out
assert "Request to Enterprise API failed" in output
mock_publish.assert_called_once()
@patch("crewai_cli.tools.main.get_project_name", return_value="sample-tool")
@patch("crewai_cli.tools.main.get_project_version", return_value="1.0.0")
@patch("crewai_cli.tools.main.get_project_description", return_value="A sample tool")
@patch("crewai_cli.tools.main.subprocess.run")
@patch("crewai_cli.tools.main.os.listdir", return_value=["sample-tool-1.0.0.tar.gz"])
@patch(
"crewai_cli.tools.main.open",
new_callable=unittest.mock.mock_open,
read_data=b"sample tarball content",
)
@patch("crewai_cli.plus_api.PlusAPI.publish_tool")
@patch("crewai_cli.tools.main.git.Repository.is_synced", return_value=True)
@patch(
"crewai.utilities.project_utils.extract_available_exports",
return_value=[{"name": "SampleTool"}],
)
@patch(
"crewai.utilities.project_utils.extract_tools_metadata",
side_effect=Exception("Failed to extract metadata"),
)
def test_publish_metadata_extraction_failure_continues_with_warning(
mock_tools_metadata,
mock_available_exports,
mock_is_synced,
mock_publish,
mock_open,
mock_listdir,
mock_subprocess_run,
mock_get_project_description,
mock_get_project_version,
mock_get_project_name,
capsys,
tool_command,
):
"""Test that metadata extraction failure shows warning but continues publishing."""
mock_publish_response = MagicMock()
mock_publish_response.status_code = 200
mock_publish_response.json.return_value = {"handle": "sample-tool"}
mock_publish.return_value = mock_publish_response
tool_command.publish(is_public=True)
output = capsys.readouterr().out
assert "Warning: Could not extract tool metadata" in output
assert "Publishing will continue without detailed metadata" in output
assert "No tool metadata extracted" in output
mock_publish.assert_called_once_with(
handle="sample-tool",
is_public=True,
version="1.0.0",
description="A sample tool",
encoded_file=unittest.mock.ANY,
available_exports=[{"name": "SampleTool"}],
tools_metadata=[],
)
@patch("crewai_cli.tools.main.Settings")
def test_print_current_organization_with_org(mock_settings, capsys, tool_command):
mock_settings_instance = MagicMock()
mock_settings_instance.org_uuid = "test-org-uuid"
mock_settings_instance.org_name = "Test Organization"
mock_settings.return_value = mock_settings_instance
tool_command._print_current_organization()
output = capsys.readouterr().out
assert "Current organization: Test Organization (test-org-uuid)" in output
@patch("crewai_cli.tools.main.Settings")
def test_print_current_organization_without_org(mock_settings, capsys, tool_command):
mock_settings_instance = MagicMock()
mock_settings_instance.org_uuid = None
mock_settings_instance.org_name = None
mock_settings.return_value = mock_settings_instance
tool_command._print_current_organization()
output = capsys.readouterr().out
assert "No organization currently set" in output
assert "org switch <org_id>" in output