108 lines
4.4 KiB
Python
108 lines
4.4 KiB
Python
import os
|
|
import json
|
|
import subprocess
|
|
import ezdxf
|
|
|
|
# Define paths to the core scripts
|
|
EXTRACT_SCRIPT = os.path.join("03_Python_OpenSource_DXF", "extract_entities_to_json.py")
|
|
DRAW_SCRIPT = os.path.join("03_Python_OpenSource_DXF", "draw_table_from_template.py")
|
|
PYTHON_EXECUTABLE = os.path.join("03_Python_OpenSource_DXF", "venv", "Scripts", "python.exe")
|
|
|
|
# Define paths for test files
|
|
TEST_OUTPUT_DIR = os.path.join("03_Python_OpenSource_DXF", "test_results")
|
|
TEST_DXF_OUTPUT = os.path.join(TEST_OUTPUT_DIR, "test_table_output.dxf")
|
|
TEST_JSON_SNAPSHOT = os.path.join(TEST_OUTPUT_DIR, "test_table_snapshot.json")
|
|
EMPTY_DXF_TEMPLATE = os.path.join("03_Python_OpenSource_DXF", "empty_template.dxf")
|
|
TEST_DATA_FILE = os.path.join("03_Python_OpenSource_DXF", "test_bom_data.json") # New data file
|
|
|
|
# Expected values for verification
|
|
EXPECTED_DATA_ROWS = 5
|
|
EXPECTED_HEADER_TEXTS = 18 # As counted from the snapshot
|
|
EXPECTED_COLUMNS = 8 # As defined in the columns template
|
|
|
|
def setup_test_environment():
|
|
"""Create an empty DXF for drawing and ensure the test output directory exists."""
|
|
os.makedirs(TEST_OUTPUT_DIR, exist_ok=True)
|
|
|
|
# Create a new, blank DXF document for the test
|
|
doc = ezdxf.new()
|
|
msp = doc.modelspace()
|
|
# Add a dummy entity to ensure the modelspace is not empty, which can sometimes cause issues
|
|
msp.add_line((0, 0), (0.1, 0.1), dxfattribs={'layer': 'DEFPOINTS'})
|
|
doc.saveas(EMPTY_DXF_TEMPLATE)
|
|
print(f"Created empty DXF template at: {EMPTY_DXF_TEMPLATE}")
|
|
|
|
def run_script(script_path, args=[]):
|
|
"""Helper function to run a python script and handle errors."""
|
|
command = [PYTHON_EXECUTABLE, script_path] + args
|
|
print(f"Executing: {' '.join(command)}")
|
|
result = subprocess.run(command, capture_output=True, text=True, encoding='utf-8')
|
|
if result.returncode != 0:
|
|
print(f"--- ERROR running {script_path} ---")
|
|
print("STDOUT:", result.stdout)
|
|
print("STDERR:", result.stderr)
|
|
return False
|
|
print(result.stdout)
|
|
return True
|
|
|
|
def run_tests():
|
|
"""Main test execution function."""
|
|
print("\n--- Phase 1: Setup Test Environment ---")
|
|
setup_test_environment()
|
|
|
|
print(f"\n--- Phase 2: Drawing Table into a Clean DXF using Test Data ---")
|
|
# Add coordinates to the drawing command for the test
|
|
draw_args = [
|
|
EMPTY_DXF_TEMPLATE,
|
|
TEST_DXF_OUTPUT,
|
|
TEST_DATA_FILE,
|
|
"--x", "100",
|
|
"--y", "150"
|
|
]
|
|
success = run_script(DRAW_SCRIPT, draw_args)
|
|
if not success:
|
|
print("Test Failed: Drawing script failed to execute.")
|
|
return
|
|
|
|
print(f"\n--- Phase 3: Extracting Entities from Generated DXF ---")
|
|
success = run_script(EXTRACT_SCRIPT, [TEST_DXF_OUTPUT, TEST_JSON_SNAPSHOT])
|
|
if not success:
|
|
print("Test Failed: Extraction script failed to execute.")
|
|
return
|
|
|
|
print("\n--- Phase 4: Verifying the Extracted Data ---")
|
|
try:
|
|
with open(TEST_JSON_SNAPSHOT, 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
except (IOError, json.JSONDecodeError) as e:
|
|
print(f"Test Failed: Could not read or parse the snapshot JSON file. Error: {e}")
|
|
return
|
|
|
|
num_texts = len(data.get("texts", []))
|
|
|
|
# --- Verification Logic ---
|
|
# The '名称' column has two text entities per row.
|
|
# Total columns with text definitions: 件号, 图号, 名称(2), 数量, 材料, 总. (7 text fields per row)
|
|
# The template defines 8 columns, but '单' and '备注' have no text_definitions. Let's adjust.
|
|
# A manual check of columns_template shows 7 text fields are defined per data row.
|
|
# Let's adjust EXPECTED_COLUMNS logic
|
|
expected_texts_per_row = 7 # Manually counted from columns_template.json
|
|
expected_total_texts = EXPECTED_HEADER_TEXTS + (EXPECTED_DATA_ROWS * expected_texts_per_row)
|
|
|
|
print(f"Found {num_texts} text entities in the output.")
|
|
print(f"Expected {expected_total_texts} text entities ({EXPECTED_HEADER_TEXTS} header + {EXPECTED_DATA_ROWS} rows * {expected_texts_per_row} fields/row).")
|
|
|
|
assert num_texts == expected_total_texts, \
|
|
f"Assertion Failed: Expected {expected_total_texts} texts, but found {num_texts}."
|
|
|
|
print("✅ Assertion Passed: The number of text entities is correct.")
|
|
|
|
# We can add more assertions here, e.g., for lines
|
|
# For now, verifying text count is a strong indicator of success.
|
|
|
|
print("\n--- Test Workflow Complete ---")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run_tests()
|