Files
BIPAuto/tests/test_extractor_component.py
Misaka_Company 440b74d09a 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.
2026-03-27 16:28:00 +08:00

164 lines
5.9 KiB
Python

"""
Test discrete_material_plan.extractor module functions
Tests pure functions for data extraction and post-processing.
Does not require actual browser or ERP connection.
"""
import sys
import logging
from pathlib import Path
# Add project root to Python path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(PROJECT_ROOT))
# Load environment variables
from dotenv import load_dotenv
load_dotenv(PROJECT_ROOT / ".env")
# Configure browser path (not used in this test, but consistent with other tests)
import os
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = os.getenv("PLAYWRIGHT_BROWSERS_PATH", "")
# Setup logging
logger = logging.getLogger('bipauto.tests.extractor_component')
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
logger.info("=" * 60)
logger.info("Testing discrete_material_plan.extractor Functions")
logger.info("=" * 60)
try:
# Test 1: Import all functions
logger.info("Importing extractor functions...")
from utils.discrete_material_plan.extractor import (
chunk_order_ids,
get_login_url,
extract_batch,
extract_batches,
extract_and_post_process,
read_order_ids_from_file,
extract_from_file,
)
logger.info("All functions imported successfully")
# Test 2: Test chunk_order_ids
logger.info("Testing chunk_order_ids...")
# Test normal chunking
result = chunk_order_ids(["A", "B", "C", "D", "E"], 2)
expected = [["A", "B"], ["C", "D"], ["E"]]
assert result == expected, f"Expected {expected}, got {result}"
logger.info(f" chunk_order_ids(['A','B','C','D','E'], 2) = {result}")
# Test exact division
result = chunk_order_ids(["A", "B", "C", "D"], 2)
expected = [["A", "B"], ["C", "D"]]
assert result == expected, f"Expected {expected}, got {result}"
logger.info(f" chunk_order_ids(['A','B','C','D'], 2) = {result}")
# Test batch size larger than list
result = chunk_order_ids(["A", "B"], 10)
expected = [["A", "B"]]
assert result == expected, f"Expected {expected}, got {result}"
logger.info(f" chunk_order_ids(['A','B'], 10) = {result}")
# Test empty list
result = chunk_order_ids([], 5)
expected = []
assert result == expected, f"Expected {expected}, got {result}"
logger.info(f" chunk_order_ids([], 5) = {result}")
logger.info("chunk_order_ids works correctly")
# Test 3: Test get_login_url
logger.info("Testing get_login_url...")
# Test with trailing slash
result = get_login_url("https://erp.example.com/")
expected = "https://erp.example.com/yonbip/resources/uap/rbac/login/main/index.html"
assert result == expected, f"Expected {expected}, got {result}"
logger.info(f" get_login_url('https://erp.example.com/') = {result}")
# Test without trailing slash
result = get_login_url("https://erp.example.com")
assert result == expected, f"Expected {expected}, got {result}"
logger.info(f" get_login_url('https://erp.example.com') = {result}")
# Test with path
result = get_login_url("https://erp.example.com/some/path/")
expected = "https://erp.example.com/some/path/yonbip/resources/uap/rbac/login/main/index.html"
assert result == expected, f"Expected {expected}, got {result}"
logger.info(f" get_login_url('https://erp.example.com/some/path/') = {result}")
logger.info("get_login_url works correctly")
# Test 4: Test read_order_ids_from_file
logger.info("Testing read_order_ids_from_file...")
# Create a temporary test file
import tempfile
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, encoding='utf-8') as f:
f.write("ID001\n")
f.write("ID002\n")
f.write("\n") # Empty line
f.write("ID003\n")
f.write(" \n") # Whitespace only
f.write("ID004\n")
temp_file = f.name
try:
result = read_order_ids_from_file(temp_file)
expected = ["ID001", "ID002", "ID003", "ID004"]
assert result == expected, f"Expected {expected}, got {result}"
logger.info(f" read_order_ids_from_file(temp_file) = {result}")
logger.info("read_order_ids_from_file works correctly")
finally:
# Cleanup temp file
Path(temp_file).unlink()
# Test FileNotFoundError
try:
read_order_ids_from_file("nonexistent_file.txt")
logger.error("Should have raised FileNotFoundError")
raise AssertionError("Should have raised FileNotFoundError")
except FileNotFoundError:
logger.info(" read_order_ids_from_file('nonexistent') raises FileNotFoundError")
# Test 5: Test module exports
logger.info("Testing module exports...")
from utils.discrete_material_plan import (
chunk_order_ids as exported_chunk,
get_login_url as exported_get_url,
extract_batch as exported_extract_batch,
extract_batches as exported_extract_batches,
extract_and_post_process as exported_extract_and_post,
read_order_ids_from_file as exported_read_ids,
extract_from_file as exported_extract_file,
)
logger.info("All functions exported correctly from module")
logger.info("=" * 60)
logger.info("ALL EXTRACTOR FUNCTION TESTS PASSED")
logger.info("=" * 60)
logger.info("Note: extract_batch, extract_batches, extract_and_post_process,")
logger.info(" and extract_from_file require actual browser session and")
logger.info(" are not tested here. Integration tests cover those cases.")
except Exception as e:
logger.error(f"Function test failed!")
logger.error(f"Error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
logger.info("=" * 60)
logger.info("Test completed successfully")
logger.info("=" * 60)