wrdler / tests /test_generator_wrdler.py
Surn's picture
fix word distribution
5f8a848
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Quick test script for Wrdler puzzle generator.
Tests the new horizontal-only, 6x8 grid generator.
"""
import sys
import os
# Force UTF-8 encoding on Windows
if sys.platform == "win32":
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
sys.stderr = codecs.getwriter("utf-8")(sys.stderr.detach())
from wrdler.generator import generate_puzzle, validate_puzzle
from wrdler.word_loader import load_word_list
def test_basic_generation():
"""Test basic puzzle generation with default parameters."""
print("Test 1: Basic puzzle generation (6 rows Γ— 8 columns)")
print("=" * 60)
try:
puzzle = generate_puzzle()
print(f"βœ“ Puzzle generated successfully!")
print(f" Grid: {puzzle.grid_rows} rows Γ— {puzzle.grid_cols} columns")
print(f" Words: {len(puzzle.words)}")
print()
# Print words
print("Words in puzzle:")
for i, word in enumerate(sorted(puzzle.words, key=lambda w: w.start.x), 1):
print(f" {i}. '{word.text}' ({len(word.text)} letters) - Row {word.start.x}, Cols {word.start.y}-{word.start.y + len(word.text) - 1}, Direction: {word.direction}")
print()
# Validate
validate_puzzle(puzzle, grid_rows=puzzle.grid_rows, grid_cols=puzzle.grid_cols)
print("βœ“ Puzzle validation passed!")
print()
return True
except Exception as e:
print(f"βœ— Test failed: {e}")
import traceback
traceback.print_exc()
return False
def test_with_seed():
"""Test deterministic generation with seed."""
print("Test 2: Deterministic generation with seed")
print("=" * 60)
try:
puzzle1 = generate_puzzle(seed=12345)
puzzle2 = generate_puzzle(seed=12345)
# Should generate same words
words1 = [w.text for w in puzzle1.words]
words2 = [w.text for w in puzzle2.words]
if words1 == words2:
print(f"βœ“ Deterministic generation works!")
print(f" Both puzzles have words: {words1}")
print()
return True
else:
print(f"βœ— Deterministic generation failed!")
print(f" Puzzle 1: {words1}")
print(f" Puzzle 2: {words2}")
print()
return False
except Exception as e:
print(f"βœ— Test failed: {e}")
import traceback
traceback.print_exc()
return False
def test_target_words():
"""Test generation with specific target words."""
print("Test 3: Generation with target words")
print("=" * 60)
target_words = ["CAT", "DOGS", "BIRDS", "FISH", "MONKEY", "ELEPHANT"]
try:
puzzle = generate_puzzle(target_words=target_words)
generated_words = sorted([w.text for w in puzzle.words])
expected_words = sorted([w.upper() for w in target_words])
if generated_words == expected_words:
print(f"βœ“ Target words generation works!")
print(f" Generated: {generated_words}")
print()
return True
else:
print(f"βœ— Target words generation failed!")
print(f" Expected: {expected_words}")
print(f" Got: {generated_words}")
print()
return False
except Exception as e:
print(f"βœ— Test failed: {e}")
import traceback
traceback.print_exc()
return False
def test_grid_visualization():
"""Visualize a generated puzzle on the grid."""
print("Test 4: Grid visualization")
print("=" * 60)
try:
puzzle = generate_puzzle(seed=42)
# Create 6x8 grid
grid = [[' ' for _ in range(puzzle.grid_cols)] for _ in range(puzzle.grid_rows)]
# Fill in words
for word in puzzle.words:
for i, cell in enumerate(word.cells):
grid[cell.x][cell.y] = word.text[i]
# Print grid
print("Grid visualization:")
print(" " + "+-" * puzzle.grid_cols + "+")
for row_idx, row in enumerate(grid):
print(f"{row_idx} |" + "|".join(row) + "|")
print(" " + "+-" * puzzle.grid_cols + "+")
print(" " + "".join(str(i) for i in range(puzzle.grid_cols)))
print()
print("βœ“ Grid visualization complete!")
print()
return True
except Exception as e:
print(f"βœ— Test failed: {e}")
import traceback
traceback.print_exc()
return False
def test_validation_checks():
"""Test that validation catches errors."""
print("Test 5: Validation error detection")
print("=" * 60)
# This should work
try:
puzzle = generate_puzzle()
validate_puzzle(puzzle, grid_rows=6, grid_cols=8)
print("βœ“ Valid puzzle passes validation")
except AssertionError as e:
print(f"βœ— Valid puzzle failed validation: {e}")
return False
# Test row count enforcement
try:
from wrdler.models import Word, Coord, Puzzle
# Try to create puzzle with wrong number of rows
words = [
Word("CAT", Coord(0, 0), "H"),
Word("DOG", Coord(1, 0), "H"),
Word("RAT", Coord(2, 0), "H"),
]
bad_puzzle = Puzzle(words=words, grid_rows=6, grid_cols=8)
try:
validate_puzzle(bad_puzzle, grid_rows=6, grid_cols=8)
print("βœ— Validation should have failed for 3 words (expected 6)")
return False
except AssertionError:
print("βœ“ Validation correctly rejects wrong word count")
except Exception as e:
print(f"βœ— Test error: {e}")
return False
print()
return True
def main():
"""Run all tests."""
print("\n" + "=" * 60)
print("WRDLER PUZZLE GENERATOR TESTS")
print("=" * 60)
print()
tests = [
test_basic_generation,
test_with_seed,
test_target_words,
test_grid_visualization,
test_validation_checks,
]
results = []
for test_func in tests:
result = test_func()
results.append((test_func.__name__, result))
# Summary
print("=" * 60)
print("TEST SUMMARY")
print("=" * 60)
for name, passed in results:
status = "βœ“ PASS" if passed else "βœ— FAIL"
print(f"{status}: {name}")
total = len(results)
passed = sum(1 for _, p in results if p)
print()
print(f"Results: {passed}/{total} tests passed")
print("=" * 60)
return all(p for _, p in results)
if __name__ == "__main__":
import sys
success = main()
sys.exit(0 if success else 1)