JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix: 解决pytest找不到self fixture问题
huanggawa9398c8c20542
diff --git a/jiuwenclaw/utils.py b/jiuwenclaw/utils.pyindex fbc78c1766..934c0be56e 100644--- a/jiuwenclaw/utils.py+++ b/jiuwenclaw/utils.py@@ -350,7 +350,9 @@ def setup_logger(log_level: str = "INFO") -> logging.Logger:logger = logging.getLogger("jiuwenclaw.app")logger.setLevel(getattr(logging, log_level.upper(), logging.INFO))logger.propagate = False- logger.handlers.clear()+ for handler in logger.handlers[:]:+ handler.close()+ logger.removeHandler(handler)formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d %(levelname)s %(name)s: %(message)s",diff --git a/tests/unit/evolution/test_message.py b/tests/unit/evolution/test_message.pyindex 902d521cfa..12706f7c14 100644--- a/tests/unit/evolution/test_message.py+++ b/tests/unit/evolution/test_message.py@@ -12,7 +12,7 @@ class TestReqMethod:"""Test ReqMethod enum."""@staticmethod- def test_chat_methods(self):+ def test_chat_methods():"""Test chat-related request methods."""assert ReqMethod.CHAT_SEND.value == "chat.send"assert ReqMethod.CHAT_RESUME.value == "chat.resume"@@ -20,20 +20,20 @@ class TestReqMethod:assert ReqMethod.CHAT_ANSWER.value == "chat.user_answer"@staticmethod- def test_config_methods(self):+ def test_config_methods():"""Test config-related request methods."""assert ReqMethod.CONFIG_GET.value == "config.get"assert ReqMethod.CONFIG_SET.value == "config.set"@staticmethod- def test_session_methods(self):+ def test_session_methods():"""Test session-related request methods."""assert ReqMethod.SESSION_LIST.value == "session.list"assert ReqMethod.SESSION_CREATE.value == "session.create"assert ReqMethod.SESSION_DELETE.value == "session.delete"@staticmethod- def test_skills_methods(self):+ def test_skills_methods():"""Test skills-related request methods."""assert ReqMethod.SKILLS_LIST.value == "skills.list"assert ReqMethod.SKILLS_INSTALL.value == "skills.install"@@ -44,13 +44,13 @@ class TestEventType:"""Test EventType enum."""@staticmethod- def test_connection_events(self):+ def test_connection_events():"""Test connection-related event types."""assert EventType.CONNECTION_ACK.value == "connection.ack"assert EventType.HELLO.value == "hello"@staticmethod- def test_chat_events(self):+ def test_chat_events():"""Test chat-related event types."""assert EventType.CHAT_DELTA.value == "chat.delta"assert EventType.CHAT_FINAL.value == "chat.final"@@ -62,7 +62,7 @@ class TestMode:"""Test Mode enum."""@staticmethod- def test_mode_values(self):+ def test_mode_values():"""Test mode enum values."""assert Mode.AGENT.value == "agent"assert Mode.PLAN.value == "plan"@@ -72,7 +72,7 @@ class TestAgentRequest:"""Test AgentRequest dataclass."""@staticmethod- def test_create_agent_request_minimal(self):+ def test_create_agent_request_minimal():"""Test creating AgentRequest with minimal fields."""request = AgentRequest(request_id="test-123")assert request.request_id == "test-123"@@ -83,7 +83,7 @@ class TestAgentRequest:assert request.is_stream is False@staticmethod- def test_create_agent_request_full(self):+ def test_create_agent_request_full():"""Test creating AgentRequest with all fields."""request = AgentRequest(request_id="test-456",@@ -109,7 +109,7 @@ class TestAgentResponse:"""Test AgentResponse dataclass."""@staticmethod- def test_create_agent_response_success(self):+ def test_create_agent_response_success():"""Test creating successful AgentResponse."""response = AgentResponse(request_id="req-1",@@ -124,7 +124,7 @@ class TestAgentResponse:assert response.metadata is None@staticmethod- def test_create_agent_response_error(self):+ def test_create_agent_response_error():"""Test creating error AgentResponse."""response = AgentResponse(request_id="req-2",@@ -142,7 +142,7 @@ class TestAgentResponseChunk:"""Test AgentResponseChunk dataclass."""@staticmethod- def test_create_response_chunk(self):+ def test_create_response_chunk():"""Test creating AgentResponseChunk."""chunk = AgentResponseChunk(request_id="req-3",@@ -156,7 +156,7 @@ class TestAgentResponseChunk:assert chunk.is_complete is False@staticmethod- def test_create_final_chunk(self):+ def test_create_final_chunk():"""Test creating final response chunk."""chunk = AgentResponseChunk(request_id="req-4",@@ -171,7 +171,7 @@ class TestMessage:"""Test Message dataclass."""@staticmethod- def test_create_request_message(self):+ def test_create_request_message():"""Test creating a request message."""message = Message(id="msg-1",@@ -194,7 +194,7 @@ class TestMessage:assert message.event_type is None@staticmethod- def test_create_response_message(self):+ def test_create_response_message():"""Test creating a response message."""message = Message(id="msg-2",@@ -210,7 +210,7 @@ class TestMessage:assert message.payload == {"response": "Hello"}@staticmethod- def test_create_event_message(self):+ def test_create_event_message():"""Test creating an event message."""message = Message(id="msg-3",@@ -226,7 +226,7 @@ class TestMessage:assert message.event_type == EventType.CHAT_DELTA@staticmethod- def test_create_streaming_message(self):+ def test_create_streaming_message():"""Test creating a streaming message."""message = Message(id="msg-4",@@ -245,7 +245,7 @@ class TestMessage:assert message.stream_id == "stream-123"@staticmethod- def test_message_mode(self):+ def test_message_mode():"""Test message mode field."""plan_message = Message(id="msg-5",diff --git a/tests/unit/evolution/test_schema.py b/tests/unit/evolution/test_schema.pyindex 0cf93e7a17..61e54a1b57 100644--- a/tests/unit/evolution/test_schema.py+++ b/tests/unit/evolution/test_schema.py@@ -18,13 +18,13 @@ class TestEvolutionType:"""Test EvolutionType enum."""@staticmethod- def test_evolution_type_values(self):+ def test_evolution_type_values():"""Test that EvolutionType has expected values."""assert EvolutionType.SKILL_EXPERIENCE.value == "skill_experience"assert EvolutionType.NEW_SKILL.value == "new_skill"@staticmethod- def test_evolution_type_comparison(self):+ def test_evolution_type_comparison():"""Test EvolutionType comparison."""assert EvolutionType.SKILL_EXPERIENCE == EvolutionType.SKILL_EXPERIENCEassert EvolutionType.SKILL_EXPERIENCE != EvolutionType.NEW_SKILL@@ -34,7 +34,7 @@ class TestEvolutionChange:"""Test EvolutionChange dataclass."""@staticmethod- def test_create_evolution_change(self):+ def test_create_evolution_change():"""Test creating an EvolutionChange."""change = EvolutionChange(section="Instructions",@@ -48,7 +48,7 @@ class TestEvolutionChange:assert change.merge_target is None@staticmethod- def test_evolution_change_to_dict(self):+ def test_evolution_change_to_dict():"""Test converting EvolutionChange to dict."""change = EvolutionChange(section="Troubleshooting",@@ -67,7 +67,7 @@ class TestEvolutionChange:}@staticmethod- def test_evolution_change_from_dict(self):+ def test_evolution_change_from_dict():"""Test creating EvolutionChange from dict."""data = {"section": "Examples",@@ -84,7 +84,7 @@ class TestEvolutionChange:assert change.merge_target == "entry_456"@staticmethod- def test_evolution_change_from_dict_with_defaults(self):+ def test_evolution_change_from_dict_with_defaults():"""Test creating EvolutionChange from dict with default values."""data = {"content": "Test content"}change = EvolutionChange.from_dict(data)@@ -95,7 +95,7 @@ class TestEvolutionChange:assert change.merge_target is None@staticmethod- def test_valid_sections_constant(self):+ def test_valid_sections_constant():"""Test that VALID_SECTIONS contains expected sections."""assert "Instructions" in VALID_SECTIONSassert "Examples" in VALID_SECTIONS@@ -106,7 +106,7 @@ class TestEvolutionEntry:"""Test EvolutionEntry dataclass."""@staticmethod- def test_create_evolution_entry(self):+ def test_create_evolution_entry():"""Test creating an EvolutionEntry."""change = EvolutionChange(section="Instructions",@@ -126,7 +126,7 @@ class TestEvolutionEntry:assert entry.applied is False@staticmethod- def test_evolution_entry_make(self):+ def test_evolution_entry_make():"""Test EvolutionEntry.make factory method."""change = EvolutionChange(section="Examples",@@ -145,7 +145,7 @@ class TestEvolutionEntry:assert entry.applied is False@staticmethod- def test_evolution_entry_to_dict(self):+ def test_evolution_entry_to_dict():"""Test converting EvolutionEntry to dict."""change = EvolutionChange(section="Troubleshooting",@@ -169,7 +169,7 @@ class TestEvolutionEntry:assert "change" in result@staticmethod- def test_evolution_entry_from_dict(self):+ def test_evolution_entry_from_dict():"""Test creating EvolutionEntry from dict."""data = {"id": "ev_xyz789",@@ -192,7 +192,7 @@ class TestEvolutionEntry:assert entry.change.section == "Instructions"@staticmethod- def test_evolution_entry_is_pending(self):+ def test_evolution_entry_is_pending():"""Test is_pending property."""change = EvolutionChange(section="Examples",@@ -223,7 +223,7 @@ class TestEvolutionFile:"""Test EvolutionFile dataclass."""@staticmethod- def test_create_evolution_file(self):+ def test_create_evolution_file():"""Test creating an EvolutionFile."""efile = EvolutionFile(skill_id="test-skill")assert efile.skill_id == "test-skill"@@ -231,7 +231,7 @@ class TestEvolutionFile:assert len(efile.entries) == 0@staticmethod- def test_evolution_file_pending_entries(self):+ def test_evolution_file_pending_entries():"""Test pending_entries property."""change1 = EvolutionChange(section="Instructions",@@ -268,7 +268,7 @@ class TestEvolutionFile:assert pending[0].id == "ev_001"@staticmethod- def test_evolution_file_to_dict(self):+ def test_evolution_file_to_dict():"""Test converting EvolutionFile to dict."""change = EvolutionChange(section="Troubleshooting",@@ -294,7 +294,7 @@ class TestEvolutionFile:assert result["entries"][0]["id"] == "ev_123"@staticmethod- def test_evolution_file_from_dict(self):+ def test_evolution_file_from_dict():"""Test creating EvolutionFile from dict."""data = {"skill_id": "another-skill",@@ -323,7 +323,7 @@ class TestEvolutionFile:assert efile.entries[0].id == "ev_456"@staticmethod- def test_evolution_file_empty(self):+ def test_evolution_file_empty():"""Test creating empty EvolutionFile."""efile = EvolutionFile.empty("empty-skill")assert efile.skill_id == "empty-skill"@@ -334,7 +334,7 @@ class TestEvolutionSignal:"""Test EvolutionSignal dataclass."""@staticmethod- def test_create_evolution_signal(self):+ def test_create_evolution_signal():"""Test creating an EvolutionSignal."""signal = EvolutionSignal(type="execution_failure",@@ -352,7 +352,7 @@ class TestEvolutionSignal:assert signal.skill_name == "test-skill"@staticmethod- def test_evolution_signal_to_dict(self):+ def test_evolution_signal_to_dict():"""Test converting EvolutionSignal to dict."""signal = EvolutionSignal(type="user_correction",@@ -370,7 +370,7 @@ class TestEvolutionSignal:assert result["tool_name"] is None@staticmethod- def test_evolution_signal_with_optional_fields(self):+ def test_evolution_signal_with_optional_fields():"""Test EvolutionSignal with None optional fields."""signal = EvolutionSignal(type="execution_failure",diff --git a/tests/unit/evolution/test_signal_detector.py b/tests/unit/evolution/test_signal_detector.pyindex 736e8a9adb..fb3bcde237 100644--- a/tests/unit/evolution/test_signal_detector.py+++ b/tests/unit/evolution/test_signal_detector.py@@ -12,7 +12,7 @@ class TestSignalDetector:"""Test SignalDetector class."""@staticmethod- def test_detect_no_signals(self):+ def test_detect_no_signals():"""Test detecting signals from messages without any signals."""detector = SignalDetector()messages = [@@ -23,7 +23,7 @@ class TestSignalDetector:assert len(signals) == 0@staticmethod- def test_detect_execution_failure(self):+ def test_detect_execution_failure():"""Test detecting execution failure signals."""detector = SignalDetector()messages = [@@ -42,7 +42,7 @@ class TestSignalDetector:assert "Command failed" in signals[0].excerpt@staticmethod- def test_detect_user_correction_chinese(self):+ def test_detect_user_correction_chinese():"""Test detecting user correction signals in Chinese."""detector = SignalDetector()messages = [@@ -55,7 +55,7 @@ class TestSignalDetector:assert signals[0].section == "Examples"@staticmethod- def test_detect_user_correction_english(self):+ def test_detect_user_correction_english():"""Test detecting user correction signals in English."""detector = SignalDetector()messages = [@@ -67,7 +67,7 @@ class TestSignalDetector:assert signals[0].type == "user_correction"@staticmethod- def test_detect_multiple_signals(self):+ def test_detect_multiple_signals():"""Test detecting multiple signals from messages."""detector = SignalDetector()messages = [@@ -88,7 +88,7 @@ class TestSignalDetector:assert len(signals) >= 2@staticmethod- def test_deduplicate_signals(self):+ def test_deduplicate_signals():"""Test signal deduplication."""detector = SignalDetector()messages = [@@ -100,7 +100,7 @@ class TestSignalDetector:assert len(signals) == 1@staticmethod- def test_detect_with_skill_from_tool_calls(self):+ def test_detect_with_skill_from_tool_calls():"""Test detecting skill name from tool calls."""detector = SignalDetector(skill_dir_map={"test-skill": "/path/to/test-skill"})messages = [@@ -125,7 +125,7 @@ class TestSignalDetector:assert signals[0].skill_name == "test-skill"@staticmethod- def test_ignore_tool_schema_in_content(self):+ def test_ignore_tool_schema_in_content():"""Test that tool schema content is ignored even with error keywords."""detector = SignalDetector()messages = [@@ -139,7 +139,7 @@ class TestSignalDetector:assert len(signals) == 0@staticmethod- def test_extract_around_match(self):+ def test_extract_around_match():"""Test excerpt extraction around matched text."""detector = SignalDetector()long_content = "Starting process... " * 10 + "ERROR: File not found" + " End of process... " * 10@@ -152,7 +152,7 @@ class TestSignalDetector:assert "ERROR" in signals[0].excerpt or "error" in signals[0].excerpt.lower()@staticmethod- def test_various_error_keywords(self):+ def test_various_error_keywords():"""Test detection of various error keywords."""error_keywords = ["exception",@@ -197,7 +197,7 @@ class TestSignalDetector:assert len(signals) == 1@staticmethod- def test_signal_to_dict_structure(self):+ def test_signal_to_dict_structure():"""Test that detected signals can be converted to dict properly."""detector = SignalDetector()messages = [diff --git a/tests/unit/test_config.py b/tests/unit/test_config.pyindex 820bd4973c..716db78722 100644--- a/tests/unit/test_config.py+++ b/tests/unit/test_config.py@@ -16,39 +16,39 @@ class TestResolveEnvVars:"""Test environment variable resolution in config."""@staticmethod- def test_resolve_string_with_env_var(self, monkeypatch: pytest.MonkeyPatch):+ def test_resolve_string_with_env_var(monkeypatch: pytest.MonkeyPatch):"""Test resolving string with environment variable."""monkeypatch.setenv("TEST_VAR", "test_value")result = resolve_env_vars("${TEST_VAR}")assert result == "test_value"@staticmethod- def test_resolve_string_with_default(self):+ def test_resolve_string_with_default():"""Test resolving string with default value."""result = resolve_env_vars("${TEST_VAR:-default_value}")assert result == "default_value"@staticmethod- def test_resolve_string_with_env_and_default(self, monkeypatch: pytest.MonkeyPatch):+ def test_resolve_string_with_env_and_default(monkeypatch: pytest.MonkeyPatch):"""Test resolving string when env var exists with default."""monkeypatch.setenv("TEST_VAR", "actual_value")result = resolve_env_vars("${TEST_VAR:-default_value}")assert result == "actual_value"@staticmethod- def test_resolve_empty_string(self):+ def test_resolve_empty_string():"""Test resolving empty string."""result = resolve_env_vars("")assert result == ""@staticmethod- def test_resolve_string_without_env_var(self):+ def test_resolve_string_without_env_var():"""Test resolving string without environment variable syntax."""result = resolve_env_vars("plain_string")assert result == "plain_string"@staticmethod- def test_resolve_dict_with_env_vars(self, monkeypatch: pytest.MonkeyPatch):+ def test_resolve_dict_with_env_vars(monkeypatch: pytest.MonkeyPatch):"""Test resolving dictionary with environment variables."""monkeypatch.setenv("API_KEY", "secret_key")monkeypatch.setenv("PORT", "8080")@@ -65,7 +65,7 @@ class TestResolveEnvVars:}@staticmethod- def test_resolve_list_with_env_vars(self, monkeypatch: pytest.MonkeyPatch):+ def test_resolve_list_with_env_vars(monkeypatch: pytest.MonkeyPatch):"""Test resolving list with environment variables."""monkeypatch.setenv("VAR1", "value1")monkeypatch.setenv("VAR2", "value2")@@ -78,7 +78,7 @@ class TestResolveEnvVars:assert result == ["value1", "value2", "static_value"]@staticmethod- def test_resolve_nested_structure(self, monkeypatch: pytest.MonkeyPatch):+ def test_resolve_nested_structure(monkeypatch: pytest.MonkeyPatch):"""Test resolving nested structure with environment variables."""monkeypatch.setenv("HOST", "example.com")input_dict = {@@ -98,7 +98,7 @@ class TestResolveEnvVars:}@staticmethod- def test_resolve_multiple_vars_in_string(self, monkeypatch: pytest.MonkeyPatch):+ def test_resolve_multiple_vars_in_string(monkeypatch: pytest.MonkeyPatch):"""Test resolving multiple environment variables in one string."""monkeypatch.setenv("USER", "john")monkeypatch.setenv("DOMAIN", "example.com")@@ -106,7 +106,7 @@ class TestResolveEnvVars:assert result == "[email protected]"@staticmethod- def test_resolve_non_string_types(self):+ def test_resolve_non_string_types():"""Test that non-string types are returned as-is."""assert resolve_env_vars(123) == 123assert resolve_env_vars(True) is True@@ -118,14 +118,14 @@ class TestConfigFunctions:"""Test config module functions."""@staticmethod- def test_get_config_raw(self, temp_config_file: Path):+ def test_get_config_raw(temp_config_file: Path):"""Test reading raw config without env resolution."""config = get_config_raw()assert config is not Noneassert "model" in config or "channels" in config@staticmethod- def test_config_file_structure(self, temp_config_file: Path):+ def test_config_file_structure(temp_config_file: Path):"""Test that config file has expected structure."""config = get_config_raw()# Check for common top-level keysdiff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.pyindex 7e423be253..69bb5ed06f 100644--- a/tests/unit/test_utils.py+++ b/tests/unit/test_utils.py@@ -16,40 +16,40 @@ class TestPathResolution:"""Test path resolution functions."""@staticmethod- def test_get_root_dir(self):+ def test_get_root_dir():"""Test get_root_dir returns a Path."""root = utils.get_root_dir()assert isinstance(root, Path)assert root.exists()@staticmethod- def test_get_config_dir(self):+ def test_get_config_dir():"""Test get_config_dir returns a Path."""config_dir = utils.get_config_dir()assert isinstance(config_dir, Path)@staticmethod- def test_get_workspace_dir(self):+ def test_get_workspace_dir():"""Test get_workspace_dir returns a Path."""workspace = utils.get_workspace_dir()assert isinstance(workspace, Path)@staticmethod- def test_get_config_file(self):+ def test_get_config_file():"""Test get_config_file returns config.yaml path."""config_file = utils.get_config_file()assert isinstance(config_file, Path)assert config_file.name == "config.yaml"@staticmethod- def test_get_agent_workspace_dir(self):+ def test_get_agent_workspace_dir():"""Test get_agent_workspace_dir returns agent workspace."""agent_workspace = utils.get_agent_workspace_dir()assert isinstance(agent_workspace, Path)assert "agent" in str(agent_workspace)@staticmethod- def test_path_caching(self):+ def test_path_caching():"""Test that path results are cached."""# First callroot1 = utils.get_root_dir()@@ -62,7 +62,7 @@ class TestPackageDetection:"""Test package installation detection."""@staticmethod- def test_is_package_installation(self):+ def test_is_package_installation():"""Test package installation detection."""# In normal testing, this should return False (development mode)result = utils.is_package_installation()@@ -73,26 +73,26 @@ class TestLoggerSetup:"""Test logger setup."""@staticmethod- def test_setup_logger_default(self):+ def test_setup_logger_default():"""Test logger setup with default level."""logger = utils.setup_logger()assert logger.name == "jiuwenclaw.app"assert logger.level == 20 # INFO level@staticmethod- def test_setup_logger_debug(self):+ def test_setup_logger_debug():"""Test logger setup with DEBUG level."""logger = utils.setup_logger("DEBUG")assert logger.level == 10 # DEBUG level@staticmethod- def test_setup_logger_error(self):+ def test_setup_logger_error():"""Test logger setup with ERROR level."""logger = utils.setup_logger("ERROR")assert logger.level == 40 # ERROR level@staticmethod- def test_logger_handlers(self):+ def test_logger_handlers():"""Test that logger has both console and file handlers."""logger = utils.setup_logger()handler_types = [type(h).__name__ for h in logger.handlers]@@ -120,13 +120,13 @@ class TestConstants:"""Test module constants."""@staticmethod- def test_user_home_defined(self):+ def test_user_home_defined():"""Test USER_HOME is defined and is a Path."""assert hasattr(utils, "USER_HOME")assert isinstance(utils.USER_HOME, Path)@staticmethod- def test_user_workspace_dir_defined(self):+ def test_user_workspace_dir_defined():"""Test USER_WORKSPACE_DIR is defined."""assert hasattr(utils, "USER_WORKSPACE_DIR")assert isinstance(utils.USER_WORKSPACE_DIR, Path)