mirror of
https://github.com/fastapi/sqlmodel.git
synced 2025-08-17 20:01:41 +08:00
![google-labs-jules[bot]](/assets/img/avatar_default.png)
This commit represents the completed code modifications for consolidating multiple version-specific test files (for Python 3.8, 3.9, 3.10) into single test files for nearly all documentation examples. **Summary of Actions:** 1. **Comprehensive File Identification:** I identified all test files in `tests/test_advanced` and `tests/test_tutorial` that followed the pattern of version-specific suffixes (e.g., `_py39.py`, `_py310.py`) for consolidation. 2. **Consolidation Implementation:** * My primary strategy involved modifying the base test file (e.g., `test_example.py`). * I introduced a `pytest` fixture, typically named `module`. This fixture is parametrized to load the base version of the example code and its Python version-specific variants from the `docs_src` directory using `importlib.import_module`. * I applied `needs_py39` and `needs_py310` marks from `tests.conftest` to the relevant parameters to control test execution based on the Python version. * I updated test functions to use this `module` fixture. For FastAPI examples, this included careful adaptation of `session` and `client` fixtures to use the parametrized module's `app` and `engine`, ensuring proper database setup (in-memory SQLite, table creation) and module reloading with `clear_sqlmodel` for isolation. * I used the `print_mock` fixture for tests verifying console output. Other tests used `sqlalchemy.inspect` or API response assertions. * I incorporated your feedback regarding the use of `from types import ModuleType` for type hints and removal of unnecessary comments into later consolidations. * I deleted redundant version-specific test files after their logic was merged. 3. **Skipped File:** I did not consolidate `tests/test_tutorial/test_insert/test_tutorial002.py` due to persistent `ImportError`/`AttributeError` issues when trying to access a dependent `Team` model from another tutorial's source file within the pytest fixture. Multiple approaches to resolve this failed, suggesting a complex interaction with module loading or metadata in the test environment for this specific case. 4. **Testing Limitations (CRITICAL):** * While I often ran tests for individual files or smaller directories successfully after consolidation, a persistent "The command affected too many files in the repo" error plagued testing of larger directories and the entire project. * This environment constraint ultimately **prevented me from executing the full test suite** after all code modifications were complete. Dependency installation (`pip install -r requirements.txt`) also failed due to this limit in the final stages. * **Therefore, the submitted code, while structurally complete according to my plan, is NOT FULLY TESTED.** There is a risk that consolidations in the later-processed, larger directories might contain unfound issues. **Conclusion:** The code refactoring to consolidate tests is (almost entirely) complete. However, due to critical environment limitations preventing full test suite verification, this submission should be reviewed with caution. Further testing in an unrestricted environment is highly recommended.
80 lines
3.0 KiB
Python
80 lines
3.0 KiB
Python
import importlib
|
|
import sys
|
|
import types
|
|
from typing import Any
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
from sqlalchemy.exc import MultipleResultsFound # Keep this import
|
|
from sqlmodel import create_engine, SQLModel, Session, delete # Ensure Session and delete are imported
|
|
|
|
from ...conftest import get_testing_print_function, needs_py310, PrintMock
|
|
|
|
|
|
expected_calls_tutorial004 = [
|
|
[
|
|
"Hero:",
|
|
{
|
|
"id": 1, # Assuming ID will be 1 after clearing and adding one hero
|
|
"name": "Test Hero",
|
|
"secret_name": "Secret Test Hero",
|
|
"age": 24,
|
|
},
|
|
]
|
|
]
|
|
|
|
|
|
@pytest.fixture(
|
|
name="module",
|
|
params=[
|
|
"tutorial004",
|
|
pytest.param("tutorial004_py310", marks=needs_py310),
|
|
],
|
|
)
|
|
def module_fixture(request: pytest.FixtureRequest, clear_sqlmodel: Any):
|
|
module_name = request.param
|
|
full_module_name = f"docs_src.tutorial.one.{module_name}"
|
|
|
|
if full_module_name in sys.modules:
|
|
mod = importlib.reload(sys.modules[full_module_name])
|
|
else:
|
|
mod = importlib.import_module(full_module_name)
|
|
|
|
mod.sqlite_url = "sqlite://"
|
|
mod.engine = create_engine(mod.sqlite_url)
|
|
|
|
# Table creation is crucial here because the test interacts with the DB
|
|
# before calling main() in some cases (to clean up, then assert specific state).
|
|
# The main() function in tutorial004.py is expected to cause MultipleResultsFound,
|
|
# which implies tables and data should exist *before* main() is called for that specific check.
|
|
# The original test calls main() first, then manipulates DB.
|
|
# The fixture should ensure tables are ready.
|
|
if hasattr(mod, "SQLModel") and hasattr(mod.SQLModel, "metadata"):
|
|
mod.SQLModel.metadata.create_all(mod.engine)
|
|
|
|
return mod
|
|
|
|
|
|
def test_tutorial(module: types.ModuleType, print_mock: PrintMock, clear_sqlmodel: Any):
|
|
# The module.main() in tutorial004.py is designed to initially create heroes,
|
|
# then try to select one which results in MultipleResultsFound.
|
|
# It also defines select_heroes() which is called later.
|
|
|
|
# First, let main() run to create initial data and trigger the expected exception.
|
|
# The create_db_and_tables is called within main() in docs_src/tutorial/one/tutorial004.py
|
|
with pytest.raises(MultipleResultsFound):
|
|
module.main() # This function in the tutorial is expected to raise this
|
|
|
|
# After the expected exception, the original test clears the Hero table and adds a specific hero.
|
|
with Session(module.engine) as session:
|
|
# The delete statement needs the actual Hero class from the module
|
|
session.exec(delete(module.Hero))
|
|
session.add(module.Hero(name="Test Hero", secret_name="Secret Test Hero", age=24))
|
|
session.commit()
|
|
|
|
# Now, test the select_heroes function part
|
|
with patch("builtins.print", new=get_testing_print_function(print_mock.calls)):
|
|
module.select_heroes() # This function is defined in the tutorial module
|
|
|
|
assert print_mock.calls == expected_calls_tutorial004
|