db = <sqlalchemy.ext.asyncio.session.AsyncSession object at 0x7fe3e4c9fd90>, base_repo = <app.base.repo.base_repo.BaseRepo object at 0x7fe3e5a38150>
@pytest.mark.asyncio
async def test_update_or_create_prevents_duplicates(db, base_repo):
test_data = {
"name": "Duplicate Item",
"status": CallCampaignStatus.EXPECTING_FILES.value,
"start_datetime": datetime.now(ZoneInfo("UTC")),
"end_datetime": datetime.now(ZoneInfo("UTC")) + timedelta(days=1),
}
# Create first item
item, created = await base_repo.update_or_create(db, defaults=test_data)
assert created is True
# Try to create another item with the same unique name
async def update_or_create(
self,
db: AsyncSession,
defaults: dict[str, Any] | None = None,
**kwargs,
) -> Tuple[T, bool]:
# Use only the unique criteria for filtering in get_by_filters
unique_criteria = {
k: v
for k, v in kwargs.items()
if k in self.model.__table__.primary_key.columns
or self.model.__table__.columns[k].unique
}
instance = await self.get_by_filters(db, **unique_criteria)
if instance:
await self._update_instance(db, instance, defaults, kwargs)
return instance, False
create_data = {**defaults, **kwargs} if defaults else kwargs
new_instance = await self.create(db, create_data)
return new_instance, True
async def get_by_filters(self, db: AsyncSession, **kwargs) -> T | None:
stmt = select(self.model).where(self.model.enabled.is_(True))
for key, value in kwargs.items():
stmt = stmt.filter(
getattr(self.model, key)
== (value.value if isinstance(value, Enum) else value),
)
instance = await self._execute_query(db, stmt)
logger.debug(
f"{'Found' if instance else 'No'} instance found matching filters: {kwargs}",
)
return instance
async def _update_instance(
self,
db: AsyncSession,
instance: T,
defaults: dict[str, Any] | None,
kwargs: dict,
):
update_data = {**defaults, **kwargs} if defaults else kwargs
for key, value in update_data.items():
if hasattr(instance, key):
setattr(instance, key, value)
await self._commit_and_refresh(db, instance)
async def _commit_and_refresh(self, db: AsyncSession, instance: T):
try:
await db.commit()
await db.refresh(instance)
except Exception as e:
await db.rollback()
logger.error(f"Transaction rolled back. Error: {e}", exc_info=True)
raise
The log entries you've provided indicate there are two main issues occurring in the BaseRepo tests related to database integrity violations:
Unique Constraint Violation:
The first error is a UniqueViolationError, which implies that you're trying to insert a duplicate value for a column that must be unique. This suggests that the logic in the update_or_create method might not be correctly filtering existing records, potentially resulting in attempts to insert duplicates.
Not Null Constraint Violation:
The second issue is a NotNullViolationError, indicating the code is attempting to insert a null value into a column that requires a non-null value. This suggests that your default and provided data might not ensure all necessary fields are populated when creating a new instance.
Recommendations for Fixing the Code and Tests
Code Adjustments
Fix update_or_create method:
Ensure you check all necessary unique fields when trying to find an existing instance. If name is supposed to be unique and other unique constraints based on your model definition, ensure they are all part of unique_criteria.
unique_criteria = {k: v for k, v in {**defaults, **kwargs}.items() if k in unique_columns_set}
Check for Unique Columns:
You should be dynamically determining which fields are unique. If you have constraints defined beyond primary keys, such as uniqueness constraints, you should incorporate those in your lookup.
def get_unique_columns(self):
return [
col.name
for col in self.model.__table__.columns
if col.unique or col.primary_key
]
async def update_or_create(
...
) -> Tuple[T, bool]:
unique_columns = self.get_unique_columns()
unique_criteria = {k: kwargs[k] for k in unique_columns if k in kwargs}
...
Add Validation for Required Fields:
When creating a new instance, ensure that all fields that are non-nullable have been given a value in either defaults or kwargs.
required_columns = ["name", "status"] # Add other required columns
create_data = {**defaults, **kwargs} if defaults else kwargs
for column in required_columns:
if column not in create_data or create_data[column] is None:
raise ValueError(f"Missing required field: {column}")
Test Adjustments
Ensure Test Setup Meets All Constraints:
First, make sure that none of your test fixtures are leading to unique or not-null constraints being violated. For example, do not reuse names that should be unique unless you handle them by update logic.
Test Duplicate Handling Explicitly:
Write separate tests to confirm how update_or_create behaves when trying to create an instance with an existing unique value and when creating with a missing required value.
async def test_update_or_create_prevents_duplicates(db, base_repo):
test_data = {
"name": "Duplicate Item",
"status": CallCampaignStatus.EXPECTING_FILES.value,
"start_datetime": datetime.now(ZoneInfo("UTC")),
"end_datetime": datetime.now(ZoneInfo("UTC")) + timedelta(days=1),
}
# Create first item
item, created = await base_repo.update_or_create(db, defaults=test_data)
assert created is True
# Try to create another item with the same unique 'name'
with pytest.raises(Exception): # Ensure it raises an integrity error when duplicates occur
await base_repo.update_or_create(db, defaults=test_data)
Test Null Values Correctly:
Explicitly test cases where inputs might lead to null values in non-nullable fields and handle these correctly.
By implementing these modifications, your tests and the update_or_create method should be better equipped to handle the constraints enforced by the database schema. This will also provide clearer insights into where adjustments need to be made, based on the specific SQLAlchemy and database schema you're working with.
with pytest.raises(
IntegrityError,
): # Ensure it raises an integrity error when duplicates occur
E Failed: DID NOT RAISE <class 'sqlalchemy.exc.IntegrityError'>
tests/repo/test_base_repo.py:693: Failed
async def update_or_create(
self,
db: AsyncSession,
defaults: dict[str, Any] | None = None,
**kwargs,
) -> Tuple[T, bool]:
# Use only the unique criteria for filtering in get_by_filters
unique_criteria = {
k: v
for k, v in kwargs.items()
if k in self.model.__table__.primary_key.columns
or self.model.__table__.columns[k].unique
}
instance = await self.get_by_filters(db, **unique_criteria)
if instance:
await self._update_instance(db, instance, defaults, kwargs)
return instance, False
create_data = {**defaults, **kwargs} if defaults else kwargs
try:
new_instance = await self.create(db, create_data)
return new_instance, True
except IntegrityError as e:
logger.error(f"IntegrityError during update_or_create: {e}")
raise
The error message indicates that the test test_update_or_create_prevents_duplicates expects an IntegrityError to be raised when attempting to create a duplicate entry in the database. However, the IntegrityError is not being raised, indicating that the update_or_create logic is not behaving as expected.
Explanation
In the provided update_or_create method, an IntegrityError is expected to be caught if the same unique constraint field is found, yet the exception is not being triggered as the existence check (get_by_filters) is supposed to prevent duplicates in the first place.
Steps to Fix
Ensure Unique Constraints Checking
Ensure that the unique_criteria in update_or_create correctly includes all fields that need to be considered for uniqueness.
Confirm Creation Logic
Ensure the logic in update_or_create accurately distinguishes between updates and creates, and that fields in unique_criteria are sufficient to uniquely identify records.
Review Exception Handling in Tests
Make sure the test case is properly set up to handle failed logic in checking for duplicates.
Here’s how you might fix these issues:
Update the update_or_create method
Ensure you're correctly setting up the unique_criteria to identify whether a record should be updated or created:
async def update_or_create(
self,
db: AsyncSession,
defaults: dict[str, Any] = None,
**kwargs
) -> Tuple[T, bool]:
if defaults is None:
defaults = {}
# Merge defaults and kwargs to search for existing instance
search_data = {**defaults, **kwargs}
unique_columns = [col.name for col in self.model.__table__.columns if col.unique]
unique_criteria = {k: search_data[k] for k in unique_columns if k in search_data}
instance = await self.get_by_filters(db, **unique_criteria)
if instance:
# Update the existing instance
await self._update_instance(db, instance, defaults, kwargs)
return instance, False
else:
# Attempt to create a new instance
create_data = {**defaults, **kwargs}
try:
new_instance = await self.create(db, create_data)
return new_instance, True
except IntegrityError as e:
await db.rollback()
logger.error(f"IntegrityError during update_or_create: {e}")
raise
Review and Update Test
Ensure that the test accurately reflects a new insert when create method is called:
@pytest.mark.asyncio
async def test_update_or_create_prevents_duplicates(db, base_repo):
test_data = {
"name": "Duplicate Item",
"status": CallCampaignStatus.EXPECTING_FILES.value,
"start_datetime": datetime.now(ZoneInfo("UTC")),
"end_datetime": datetime.now(ZoneInfo("UTC")) + timedelta(days=1),
}
# Create first item
item, created = await base_repo.update_or_create(db, defaults=test_data)
assert created is True
# Try to create another item with the same unique name
duplicate_data = {
"name": "Duplicate Item", # Same unique field
"status": CallCampaignStatus.EXPECTING_FILES.value,
"start_datetime": datetime.now(ZoneInfo("UTC")),
"end_datetime": datetime.now(ZoneInfo("UTC")) + timedelta(days=1),
}
with pytest.raises(IntegrityError):
await base_repo.update_or_create(db, defaults=duplicate_data)
Considerations
Test Database State: Ensure the database is in a known state before running this test to avoid side effects from other tests. Use fixtures or transactional rollbacks to maintain isolation between tests.
Logging Adjustment: Enhance log statements in your methods to better capture the flow of data and operations for debugging purposes.
Through these steps, the test should properly trigger and catch the expected IntegrityError, and your BaseRepo method should handle updates/creates correctly with respect to unique constraints.
item, created = await base_repo.update_or_create(db, defaults=test_data)
async def update_or_create(
self,
db: AsyncSession,
defaults: dict[str, Any] | None = None,
**kwargs,
) -> Tuple[T, bool]:
# Use only the unique criteria for filtering in get_by_filters
if defaults is None:
defaults = {}
# Merge defaults and kwargs to search for existing instance
search_data = {**defaults, **kwargs}
unique_columns = [
col.name for col in self.model.table.columns if col.unique
]
E AttributeError: type object 'TestModel' has no attribute 'table'
app/base/repo/base_repo.py:259: AttributeError
The error message indicates that there is an AttributeError in the update_or_create method. Specifically, it is trying to access self.model.table.columns, which should be self.model.__table__.columns.
Here's a revised version of the update_or_create method with the necessary correction:
Corrected Code
async def update_or_create(
self,
db: AsyncSession,
defaults: dict[str, Any] | None = None,
**kwargs,
) -> Tuple[T, bool]:
if defaults is None:
defaults = {}
# Merge defaults and kwargs to search for existing instance
search_data = {**defaults, **kwargs}
# Correctly access the table's columns to determine unique fields
unique_columns = [
col.name for col in self.model.__table__.columns if col.unique
]
unique_criteria = {
k: search_data[k] for k in unique_columns if k in search_data
}
instance = await self.get_by_filters(db, **unique_criteria)
if instance:
# Update the existing instance
await self._update_instance(db, instance, defaults, kwargs)
return instance, False
else:
# Attempt to create a new instance
create_data = {**defaults, **kwargs}
try:
new_instance = await self.create(db, create_data)
return new_instance, True
except IntegrityError as e:
await db.rollback()
logger.error(f"IntegrityError during update_or_create: {e}")
raise
Explanation
Correction of __table__.columns: The error was due to attempting to access table.columns, which should be __table__.columns, as the __table__ attribute is how SQLAlchemy provides access to the table metadata for ORM models.
Test Code
Adjust your test case as follows if it wasn't correctly using the update_or_create:
@pytest.mark.asyncio
async def test_update_or_create_prevents_duplicates(db, base_repo):
test_data = {
"name": "Duplicate Item",
"status": CallCampaignStatus.EXPECTING_FILES.value,
"start_datetime": datetime.now(ZoneInfo("UTC")),
"end_datetime": datetime.now(ZoneInfo("UTC")) + timedelta(days=1),
}
# Create first item
item, created = await base_repo.update_or_create(db, defaults=test_data)
assert created is True
# Try to create another item with the same unique name
duplicate_data = {
"name": "Duplicate Item", # Same unique field
"status": CallCampaignStatus.EXPECTING_FILES.value,
"start_datetime": datetime.now(ZoneInfo("UTC")),
"end_datetime": datetime.now(ZoneInfo("UTC")) + timedelta(days=1),
}
with pytest.raises(IntegrityError):
await base_repo.update_or_create(db, defaults=duplicate_data)
Additional Considerations
Ensure Database State: Make sure your test database is in a consistent state before running each test. A good practice is to use fixtures to set up and tear down database state around each test.
Log and Debug: Use logging liberally and monitor exceptions to help with debugging. Checking the SQLAlchemy logs can provide insights into what's being queried or modified in the database.