Skip to content

Commit 3e3c1b9

Browse files
Fix ImportError in analyzer tests
This commit fixes an `ImportError: attempted relative import beyond top-level package` that occurred when running tests in `examples/google-ads-account-analyzer-demo/tests/test_analyzer.py` using standard test discovery. The import mechanism for the `analyzer` module within `test_analyzer.py` has been made more robust by dynamically adding the parent directory (`examples/google-ads-account-analyzer-demo`) to `sys.path` before attempting the import. This ensures that the `analyzer` module can be correctly located regardless of how the tests are invoked (e.g., direct execution, `unittest discover`). The changes ensure that tests can be reliably run from the repository root using commands like `python -m unittest discover -s examples/google-ads-account-analyzer-demo/tests -p test_analyzer.py`.
1 parent b6aa2c9 commit 3e3c1b9

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

examples/google-ads-account-analyzer-demo/tests/test_analyzer.py

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,40 @@
1+
import os
2+
import sys
13
import unittest
2-
from unittest.mock import MagicMock, patch, call
4+
from unittest.mock import MagicMock, patch, call # Ensure 'call' is imported if not already
5+
6+
# Dynamically add the parent directory to sys.path to resolve analyzer module
7+
# This makes the test runnable whether discovered or run directly
8+
current_dir = os.path.dirname(os.path.abspath(__file__))
9+
parent_dir = os.path.join(current_dir, '..')
10+
11+
# Check if the parent directory is already in sys.path to avoid duplicates
12+
# and to ensure the original sys.path is respected if possible.
13+
original_sys_path = list(sys.path) # Take a copy
14+
if parent_dir not in sys.path:
15+
sys.path.insert(0, parent_dir)
16+
path_inserted = True
17+
else:
18+
path_inserted = False
19+
20+
try:
21+
import analyzer
22+
except ImportError as e:
23+
# If it still fails, raise an error that's informative.
24+
raise ImportError(
25+
f"Failed to import 'analyzer' module. "
26+
f"Attempted to add '{parent_dir}' to sys.path. "
27+
f"Original error: {e}"
28+
)
29+
finally:
30+
# Clean up sys.path if we modified it.
31+
# This prevents side effects if tests are run in a persistent session.
32+
if path_inserted:
33+
if sys.path[0] == parent_dir:
34+
sys.path.pop(0)
35+
elif parent_dir in sys.path: # Fallback removal if it wasn't at index 0
36+
sys.path.remove(parent_dir)
337

4-
# Assuming analyzer.py is in the parent directory
5-
from .. import analyzer
638

739
class TestAnalyzer(unittest.TestCase):
840

0 commit comments

Comments
 (0)