@@ -219,6 +219,40 @@ def test_env_loading_for_agent(self):
219219assert agent .config == "production"
220220assert os .environ .get ("AGENT_SECRET" )== "test_secret_123"
221221
222+ def test_loading_order_preference (self ):
223+ """Test that module/package is preferred over agent.py in a sub-package."""
224+ with tempfile .TemporaryDirectory ()as temp_dir :
225+ temp_path = Path (temp_dir )
226+ agent_name = "order_test_agent"
227+
228+ # Create structure 1: agents_dir/agent_name.py (expected to be loaded)
229+ agent_module_file = temp_path / f"{ agent_name } .py"
230+ agent_module_file .write_text (dedent (f"""
231+ from google.adk.agents.base_agent import BaseAgent
232+ class ModuleAgent(BaseAgent):
233+ def __init__(self):
234+ super().__init__(name="{ agent_name } _module_version")
235+ root_agent = ModuleAgent()
236+ """ ))
237+
238+ # Create structure 2: agents_dir/agent_name/agent.py (should be ignored)
239+ agent_package_dir = temp_path / agent_name
240+ agent_package_dir .mkdir ()
241+ agent_submodule_file = agent_package_dir / "agent.py"
242+ agent_submodule_file .write_text (dedent (f"""
243+ from google.adk.agents.base_agent import BaseAgent
244+ class SubmoduleAgent(BaseAgent):
245+ def __init__(self):
246+ super().__init__(name="{ agent_name } _submodule_version")
247+ root_agent = SubmoduleAgent()
248+ """ ))
249+
250+ loader = AgentLoader (str (temp_path ))
251+ agent = loader .load_agent (agent_name )
252+
253+ # Assert that the module version was loaded due to the new loading order
254+ assert agent .name == f"{ agent_name } _module_version"
255+
222256def test_load_multiple_different_agents (self ):
223257"""Test loading multiple different agents."""
224258with tempfile .TemporaryDirectory ()as temp_dir :
@@ -249,12 +283,24 @@ def test_agent_not_found_error(self):
249283"""Test that appropriate error is raised when agent is not found."""
250284with tempfile .TemporaryDirectory ()as temp_dir :
251285loader = AgentLoader (temp_dir )
286+ agents_dir = temp_dir # For use in the expected message string
252287
253288# Try to load non-existent agent
254289with pytest .raises (ValueError )as exc_info :
255290loader .load_agent ("nonexistent_agent" )
256291
257- assert "Module nonexistent_agent not found" in str (exc_info .value )
292+ expected_msg_part_1 = "No root_agent found for 'nonexistent_agent'."
293+ expected_msg_part_2 = (
294+ "Searched in 'nonexistent_agent.agent.root_agent',"
295+ " 'nonexistent_agent.root_agent'."
296+ )
297+ expected_msg_part_3 = (
298+ f"Ensure '{ agents_dir } /nonexistent_agent' is structured correctly"
299+ )
300+
301+ assert expected_msg_part_1 in str (exc_info .value )
302+ assert expected_msg_part_2 in str (exc_info .value )
303+ assert expected_msg_part_3 in str (exc_info .value )
258304
259305def test_agent_without_root_agent_error (self ):
260306"""Test that appropriate error is raised when agent has no root_agent."""
@@ -279,6 +325,65 @@ def __init__(self):
279325
280326assert "No root_agent found for 'broken_agent'" in str (exc_info .value )
281327
328+ def test_agent_internal_module_not_found_error (self ):
329+ """Test error when an agent tries to import a non-existent module."""
330+ with tempfile .TemporaryDirectory ()as temp_dir :
331+ temp_path = Path (temp_dir )
332+ agent_name = "importer_agent"
333+
334+ # Create agent that imports a non-existent module
335+ agent_file = temp_path / f"{ agent_name } .py"
336+ agent_file .write_text (dedent (f"""
337+ from google.adk.agents.base_agent import BaseAgent
338+ import non_existent_module # This will fail
339+
340+ class{ agent_name .title ()} Agent(BaseAgent):
341+ def __init__(self):
342+ super().__init__(name="{ agent_name } ")
343+
344+ root_agent ={ agent_name .title ()} Agent()
345+ """ ))
346+
347+ loader = AgentLoader (str (temp_path ))
348+ with pytest .raises (ModuleNotFoundError )as exc_info :
349+ loader .load_agent (agent_name )
350+
351+ assert f"Fail to load '{ agent_name } ' module." in str (exc_info .value )
352+ assert "No module named 'non_existent_module'" in str (exc_info .value )
353+
354+ def test_agent_internal_import_error (self ):
355+ """Test other import errors within an agent's code (e.g., SyntaxError)."""
356+ with tempfile .TemporaryDirectory ()as temp_dir :
357+ temp_path = Path (temp_dir )
358+ agent_name = "syntax_error_agent"
359+
360+ # Create agent with a syntax error (which leads to ImportError)
361+ agent_file = temp_path / f"{ agent_name } .py"
362+ agent_file .write_text (dedent (f"""
363+ from google.adk.agents.base_agent import BaseAgent
364+
365+ # Invalid syntax
366+ this is not valid python code
367+
368+ class{ agent_name .title ()} Agent(BaseAgent):
369+ def __init__(self):
370+ super().__init__(name="{ agent_name } ")
371+
372+ root_agent ={ agent_name .title ()} Agent()
373+ """ ))
374+
375+ loader = AgentLoader (str (temp_path ))
376+ # SyntaxError is a subclass of Exception, and importlib might wrap it
377+ # The loader is expected to prepend its message and re-raise.
378+ with pytest .raises (
379+ SyntaxError
380+ )as exc_info :# Or potentially ImportError depending on Python version specifics with importlib
381+ loader .load_agent (agent_name )
382+
383+ assert f"Fail to load '{ agent_name } ' module." in str (exc_info .value )
384+ # Check for part of the original SyntaxError message
385+ assert "invalid syntax" in str (exc_info .value ).lower ()
386+
282387def test_sys_path_modification (self ):
283388"""Test that agents_dir is added to sys.path correctly."""
284389with tempfile .TemporaryDirectory ()as temp_dir :