test(logging): unify test file logging to standard logging module
- Replace print() statements with logging module in all test files - Use consistent logger naming: bipauto.tests.<test_name> - Apply unified log format: [%(levelname)s] %(name)s: %(message)s - Migrates test_extractor_real.py, test_login.py, test_auth_config.py, test_extractor_component.py This change ensures consistent log output format between test files and utils modules, matching the existing bipauto.* logger hierarchy.
This commit is contained in:
@@ -12,6 +12,7 @@ This test:
|
||||
"""
|
||||
|
||||
import sys
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
@@ -27,6 +28,15 @@ load_dotenv(PROJECT_ROOT / ".env")
|
||||
import os
|
||||
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = os.getenv("PLAYWRIGHT_BROWSERS_PATH", "")
|
||||
|
||||
# Setup logging
|
||||
logger = logging.getLogger('bipauto.tests.extractor_real')
|
||||
logger.setLevel(logging.INFO)
|
||||
if not logger.handlers:
|
||||
handler = logging.StreamHandler()
|
||||
handler.setFormatter(logging.Formatter("[%(levelname)s] %(name)s: %(message)s"))
|
||||
logger.addHandler(handler)
|
||||
logger.propagate = False
|
||||
|
||||
# Generate timestamp for unique output files
|
||||
TIMESTAMP = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
|
||||
@@ -39,32 +49,32 @@ OUTPUT_FILE = OUTPUT_DIR / f"merged_result_{TIMESTAMP}.xlsx"
|
||||
DOWNLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
print("=" * 60)
|
||||
print("Discrete Material Plan Extractor - Integration Test")
|
||||
print("=" * 60)
|
||||
print(f"\nConfiguration:")
|
||||
print(f" ID File: {PROJECT_ROOT / 'tests' / 'id-demo.txt'}")
|
||||
print(f" Download Dir: {DOWNLOAD_DIR}")
|
||||
print(f" Output File: {OUTPUT_FILE}")
|
||||
print(f" ERP URL: {os.getenv('ERP_URL', 'Not set')}")
|
||||
print(f" Headless: {os.getenv('ERP_HEADLESS', 'true')}")
|
||||
print("=" * 60)
|
||||
logger.info("=" * 60)
|
||||
logger.info("Discrete Material Plan Extractor - Integration Test")
|
||||
logger.info("=" * 60)
|
||||
logger.info(f"Configuration:")
|
||||
logger.info(f" ID File: {PROJECT_ROOT / 'tests' / 'id-demo.txt'}")
|
||||
logger.info(f" Download Dir: {DOWNLOAD_DIR}")
|
||||
logger.info(f" Output File: {OUTPUT_FILE}")
|
||||
logger.info(f" ERP URL: {os.getenv('ERP_URL', 'Not set')}")
|
||||
logger.info(f" Headless: {os.getenv('ERP_HEADLESS', 'true')}")
|
||||
logger.info("=" * 60)
|
||||
|
||||
# Verify environment variables
|
||||
required_vars = ["ERP_USERNAME", "ERP_PASSWORD", "ERP_URL"]
|
||||
missing_vars = [var for var in required_vars if not os.getenv(var)]
|
||||
|
||||
if missing_vars:
|
||||
print(f"\n[ERROR] Missing required environment variables: {missing_vars}")
|
||||
print("Please ensure .env file contains:")
|
||||
print(" ERP_USERNAME=your_username")
|
||||
print(" ERP_PASSWORD=your_password")
|
||||
print(" ERP_URL=https://your-erp-url.com")
|
||||
logger.error(f"Missing required environment variables: {missing_vars}")
|
||||
logger.error("Please ensure .env file contains:")
|
||||
logger.error(" ERP_USERNAME=your_username")
|
||||
logger.error(" ERP_PASSWORD=your_password")
|
||||
logger.error(" ERP_URL=https://your-erp-url.com")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
# Import required modules
|
||||
print("\n[1/6] Importing modules...")
|
||||
logger.info("[1/6] Importing modules...")
|
||||
from playwright.sync_api import sync_playwright
|
||||
from utils.auth import login
|
||||
from utils.discrete_material_plan import (
|
||||
@@ -73,18 +83,18 @@ try:
|
||||
read_order_ids_from_file,
|
||||
get_login_url,
|
||||
)
|
||||
print("[OK] Modules imported successfully")
|
||||
logger.info("Modules imported successfully")
|
||||
|
||||
# Read order IDs from demo file
|
||||
print("\n[2/6] Reading order IDs from data/demo/id-demo.txt...")
|
||||
logger.info("[2/6] Reading order IDs from data/demo/id-demo.txt...")
|
||||
id_file = PROJECT_ROOT / "data" / "demo" / "id-demo.txt"
|
||||
order_ids = read_order_ids_from_file(str(id_file))
|
||||
print(f"[OK] Loaded {len(order_ids)} order IDs")
|
||||
logger.info(f"Loaded {len(order_ids)} order IDs")
|
||||
|
||||
test_order_ids = order_ids
|
||||
|
||||
# Setup browser and extract data
|
||||
print("\n[3/6] Launching browser and logging in...")
|
||||
logger.info("[3/6] Launching browser and logging in...")
|
||||
with sync_playwright() as playwright:
|
||||
# Get required environment variables (with validation)
|
||||
username = os.getenv("ERP_USERNAME")
|
||||
@@ -107,17 +117,17 @@ try:
|
||||
|
||||
try:
|
||||
# Navigate to discrete material page
|
||||
print("\n[4/6] Navigating to discrete material plan page...")
|
||||
logger.info("[4/6] Navigating to discrete material plan page...")
|
||||
work_frame, page1 = navigate_to_discrete_material_page(main_frame, page)
|
||||
print("[OK] Navigation successful")
|
||||
logger.info("Navigation successful")
|
||||
|
||||
# Extract and post-process
|
||||
print("\n[5/6] Extracting data and post-processing...")
|
||||
print(f" Orders: {len(test_order_ids)}")
|
||||
print(f" Batch size: 100")
|
||||
print(f" Download dir: {DOWNLOAD_DIR}")
|
||||
print(f" Output file: {OUTPUT_FILE}")
|
||||
print(f" Cleanup temp files: True (default)")
|
||||
logger.info("[5/6] Extracting data and post-processing...")
|
||||
logger.info(f" Orders: {len(test_order_ids)}")
|
||||
logger.info(f" Batch size: 100")
|
||||
logger.info(f" Download dir: {DOWNLOAD_DIR}")
|
||||
logger.info(f" Output file: {OUTPUT_FILE}")
|
||||
logger.info(f" Cleanup temp files: True (default)")
|
||||
|
||||
output_path, df = extract_and_post_process(
|
||||
work_frame=work_frame,
|
||||
@@ -130,45 +140,45 @@ try:
|
||||
cleanup_temp_files=True, # Default: True, set to False to keep temp files
|
||||
)
|
||||
|
||||
print("\n[6/6] Verifying results...")
|
||||
print(f"[OK] Extraction completed successfully")
|
||||
print(f" Output file: {output_path}")
|
||||
print(f" Total records: {len(df)}")
|
||||
print(f" Columns: {list(df.columns)}")
|
||||
logger.info("[6/6] Verifying results...")
|
||||
logger.info("Extraction completed successfully")
|
||||
logger.info(f" Output file: {output_path}")
|
||||
logger.info(f" Total records: {len(df)}")
|
||||
logger.info(f" Columns: {list(df.columns)}")
|
||||
|
||||
# Verify output file exists
|
||||
if not Path(output_path).exists():
|
||||
raise FileNotFoundError(f"Output file not found: {output_path}")
|
||||
print(f"[OK] Output file verified: {output_path}")
|
||||
logger.info(f"Output file verified: {output_path}")
|
||||
|
||||
# Show sample data
|
||||
print("\n" + "=" * 60)
|
||||
print("Sample Data (first 3 rows, first 5 columns):")
|
||||
print("=" * 60)
|
||||
logger.info("=" * 60)
|
||||
logger.info("Sample Data (first 3 rows, first 5 columns):")
|
||||
logger.info("=" * 60)
|
||||
# Use unicode encoding for display
|
||||
sample = df.head(3).iloc[:, :5]
|
||||
print(sample.to_string())
|
||||
print("\n[OK] Data extraction verified - Chinese characters displayed correctly in console encoding")
|
||||
logger.info("\n" + sample.to_string())
|
||||
logger.info("Data extraction verified - Chinese characters displayed correctly in console encoding")
|
||||
|
||||
finally:
|
||||
# Cleanup browser
|
||||
print("\n\n[Cleanup] Closing browser...")
|
||||
logger.info("Closing browser...")
|
||||
context.close()
|
||||
browser.close()
|
||||
print("[OK] Browser closed")
|
||||
logger.info("Browser closed")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("[SUCCESS] Integration test completed successfully!")
|
||||
print("=" * 60)
|
||||
print(f"\nOutputs:")
|
||||
print(f" Raw Excel files: {DOWNLOAD_DIR}/*.xlsx")
|
||||
print(f" Merged result: {OUTPUT_FILE}")
|
||||
print(f" Total records: {len(df)}")
|
||||
print("=" * 60)
|
||||
logger.info("=" * 60)
|
||||
logger.info("INTEGRATION TEST COMPLETED SUCCESSFULLY")
|
||||
logger.info("=" * 60)
|
||||
logger.info(f"Outputs:")
|
||||
logger.info(f" Raw Excel files: {DOWNLOAD_DIR}/*.xlsx")
|
||||
logger.info(f" Merged result: {OUTPUT_FILE}")
|
||||
logger.info(f" Total records: {len(df)}")
|
||||
logger.info("=" * 60)
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n[ERROR] Integration test failed!")
|
||||
print(f"Error: {e}")
|
||||
logger.error(f"Integration test failed!")
|
||||
logger.error(f"Error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
|
||||
Reference in New Issue
Block a user