feat: 为现场日历增加单据类型并同步派车记录,减少重复录入。

按起止地关键词生成现场出入库计划,同步来源修改和删除,保留历史记录不补录。调整卡片及复制文本的单据类型格式,并记录测试库和生产库迁移结果。
This commit is contained in:
wuzilong committed 2026-10-30 14:04:24 +08:00
1 parent 1ae8603045
commit fcbf8a9b65
17 files changed
+732 -42

No files matched your search

+6 -1
View File
@@ -1,7 +1,7 @@
"""独立手工派车记录,与运输计划无写入联动。"""
from datetime import datetime
from sqlalchemy import Column, Date, DateTime, Index, Integer, SmallInteger, String
from sqlalchemy import Column, Date, DateTime, Index, Integer, SmallInteger, String, UniqueConstraint
from app.core.database import Base
@@ -11,6 +11,7 @@ class PlDispatchCalendar(Base):
__table_args__ = (
Index("idx_dispatch_calendar_month", "tenant_no", "del_flag", "dispatch_date"),
Index("idx_dispatch_calendar_vehicle", "tenant_no", "vehicle_id", "dispatch_date"),
UniqueConstraint("tenant_no", "source_record_id", name="uk_dispatch_calendar_source"),
)
id = Column(String(64), primary_key=True, comment="主键UUID")
@@ -26,6 +27,10 @@ class PlDispatchCalendar(Base):
String(16), nullable=False, default="acid", server_default="acid",
comment="日历类型:acid酸派车 alkali碱派车 other其他 site现场",
)
document_type = Column(String(50), nullable=True, comment="单据类型(现场日历,支持自定义)")
site_sync_enabled = Column(SmallInteger, nullable=False, default=0, server_default="0",
comment="是否启用现场同步:仅新建来源置1,历史为0")
source_record_id = Column(String(64), nullable=True, comment="自动现场记录的来源派车ID,手工记录为空")
tenant_no = Column(String(64), nullable=False, comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(500), nullable=True, comment="备注")
@@ -16,6 +16,7 @@ class CreateBody(BaseModel):
destination: str = Field(default="", max_length=255)
quantity: Optional[str] = Field(default=None, max_length=16, description="数量文本,单位吨,最多两位小数;不参与汇总")
calendar_kind: str = Field(default="acid", alias="calendarKind", min_length=1, max_length=16)
document_type: Optional[str] = Field(default=None, alias="documentType", max_length=50)
remark: Optional[str] = Field(default=None, max_length=500)
@field_validator("dispatch_date", mode="before")
@@ -1,9 +1,11 @@
"""手工派车 CRUD:租户、角色数据范围和关联主数据校验。"""
import re
from datetime import date
from functools import wraps
from typing import Optional
from fastapi import HTTPException
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session
from app.core.db_auth import DbUserContext
@@ -36,6 +38,8 @@ def _row_to_dict(row: PlDispatchCalendar) -> dict:
"destination": row.destination,
"quantity": row.quantity,
"calendarKind": row.calendar_kind or "acid",
"documentType": row.document_type,
"sourceRecordId": row.source_record_id,
"remark": row.remark,
"createTime": row.create_time,
"updateTime": row.update_time,
@@ -73,8 +77,13 @@ def list_records(db: Session, tenant_no: str, user: DbUserContext, *, month: str
return {"list": [_row_to_dict(row) for row in rows], "total": total}
def get_record(db: Session, tenant_no: str, user: DbUserContext, record_id: str) -> PlDispatchCalendar:
row = _query(db, tenant_no, user).filter(PlDispatchCalendar.id == record_id).first()
def get_record(db: Session, tenant_no: str, user: DbUserContext, record_id: str,
*, for_update: bool = False) -> PlDispatchCalendar:
query = _query(db, tenant_no, user).filter(PlDispatchCalendar.id == record_id)
if for_update:
# 来源行锁串行化同一来源的更新/删除;刷新会话内缓存,避免并发覆盖关联状态。
query = query.populate_existing().with_for_update()
row = query.first()
if row is None:
raise HTTPException(status_code=404, detail="派车记录不存在或无权访问")
return row
@@ -94,38 +103,127 @@ def _resolve_snapshots(db: Session, tenant_no: str, user: DbUserContext, body: C
return {"license_plate": vehicle.license_plate, "product_name": product.product_name}
def _site_document_type(origin: str, destination: str) -> Optional[str]:
outbound = any(word in (origin or "") for word in ("山峡", "云栋"))
inbound = any(word in (destination or "") for word in ("山峡", "云栋"))
if outbound and inbound:
return "出入库计划"
if outbound:
return "出库计划"
if inbound:
return "入库计划"
return None
def _sync_site_record(db: Session, tenant_no: str, user: DbUserContext,
source: PlDispatchCalendar) -> None:
"""在来源事务和行锁内维护唯一现场记录;不为历史来源补录。"""
if not source.site_sync_enabled or source.calendar_kind not in ("acid", "alkali", "other"):
return
# 包含已软删除关联行,以便重新命中时恢复原 ID 和创建信息。
query = db.query(PlDispatchCalendar).filter(
PlDispatchCalendar.tenant_no == tenant_no,
PlDispatchCalendar.source_record_id == source.id,
PlDispatchCalendar.calendar_kind == "site",
)
target = apply_pl_scope(query, PlDispatchCalendar, user, db, tenant_no).populate_existing().with_for_update().first()
document_type = None if source.del_flag == 1 else _site_document_type(source.origin, source.destination)
if document_type is None:
if target is not None and target.del_flag != 1:
target.del_flag = 1
target.update_by = user.id
return
if target is None:
target = PlDispatchCalendar(
id=generate_uuid(), tenant_no=tenant_no, source_record_id=source.id,
calendar_kind="site", site_sync_enabled=0, create_by=source.create_by,
create_dept_id=source.create_dept_id,
)
db.add(target)
for field in ("dispatch_date", "vehicle_id", "license_plate", "product_id", "product_name",
"origin", "destination", "quantity", "remark"):
setattr(target, field, getattr(source, field))
target.document_type = document_type
target.del_flag = 0
target.update_by = user.id
def _ensure_manual_record(row: PlDispatchCalendar) -> None:
if row.source_record_id:
raise HTTPException(status_code=409, detail="此现场记录由派车日历自动同步,请在来源派车日历修改或删除")
def _retry_deadlock(action):
"""MySQL 间隙锁竞争可能选择当前事务为死锁牺牲者,回滚后完整重试。"""
@wraps(action)
def run(db: Session, *args, **kwargs):
for attempt in range(3):
try:
return action(db, *args, **kwargs)
except OperationalError as exc:
db.rollback()
code = exc.orig.args[0] if getattr(exc.orig, "args", ()) else None
if code != 1213 or attempt == 2:
raise
return run
@_retry_deadlock
def create_record(db: Session, tenant_no: str, user: DbUserContext, body: CreateBody) -> PlDispatchCalendar:
snapshots = _resolve_snapshots(db, tenant_no, user, body)
row = PlDispatchCalendar(
id=generate_uuid(), tenant_no=tenant_no, create_by=user.id,
create_dept_id=user.dept_id or "", update_by=user.id,
site_sync_enabled=1 if body.calendar_kind in ("acid", "alkali", "other") else 0,
**body.model_dump(), **snapshots,
)
db.add(row)
db.commit()
db.refresh(row)
try:
db.add(row)
db.flush()
_sync_site_record(db, tenant_no, user, row)
db.commit()
except Exception:
db.rollback()
raise
# ORM 默认值已在 flush/commit 时赋值;提交后不再查询,避免重试已提交的写入。
return row
@_retry_deadlock
def update_record(db: Session, tenant_no: str, user: DbUserContext, record_id: str,
body: UpdateBody) -> PlDispatchCalendar:
row = get_record(db, tenant_no, user, record_id)
if body.calendar_kind != (row.calendar_kind or "acid"):
raise HTTPException(status_code=422, detail="不能把派车计划改到另一本日历")
values = {**body.model_dump(), **_resolve_snapshots(db, tenant_no, user, body)}
for key, value in values.items():
setattr(row, key, value)
row.update_by = user.id
db.commit()
db.refresh(row)
try:
row = get_record(db, tenant_no, user, record_id, for_update=True)
_ensure_manual_record(row)
if body.calendar_kind != (row.calendar_kind or "acid"):
raise HTTPException(status_code=422, detail="不能把派车计划改到另一本日历")
values = {**body.model_dump(), **_resolve_snapshots(db, tenant_no, user, body)}
# 兼容未提交新字段的旧客户端;显式空值仍可清空。
if "document_type" not in body.model_fields_set:
values.pop("document_type", None)
for key, value in values.items():
setattr(row, key, value)
row.update_by = user.id
_sync_site_record(db, tenant_no, user, row)
db.commit()
except Exception:
db.rollback()
raise
return row
@_retry_deadlock
def delete_record(db: Session, tenant_no: str, user: DbUserContext, record_id: str) -> int:
row = get_record(db, tenant_no, user, record_id)
row.del_flag = 1
row.update_by = user.id
db.commit()
try:
row = get_record(db, tenant_no, user, record_id, for_update=True)
_ensure_manual_record(row)
row.del_flag = 1
row.update_by = user.id
_sync_site_record(db, tenant_no, user, row)
db.commit()
except Exception:
db.rollback()
raise
return 1
+38 -1
View File
@@ -73,7 +73,7 @@ def test_crud_duplicate_trips_snapshots_and_soft_delete(db):
assert result['licensePlate'] == '鄂E67890' and result['productName'] == '盐酸'
assert result['origin'] == '武汉'
assert result['calendarKind'] == 'acid'
assert set(result) == {'id', 'dispatchDate', 'vehicleId', 'licensePlate', 'productId', 'productName', 'origin', 'destination', 'quantity', 'calendarKind', 'remark', 'createTime', 'updateTime'}
assert set(result) == {'id', 'dispatchDate', 'vehicleId', 'licensePlate', 'productId', 'productName', 'origin', 'destination', 'quantity', 'calendarKind', 'documentType', 'sourceRecordId', 'remark', 'createTime', 'updateTime'}
assert svc.delete_record(db, 't1', user(), first.id) == 1
assert db.get(model, first.id).del_flag == 1
assert svc.list_records(db, 't1', user(), month='2026-10')['total'] == 1
@@ -168,6 +168,7 @@ def test_invalid_cross_tenant_and_deleted_relations_rejected(db, field, value):
{'dispatchDate': '2026-02-30'}, {'dispatchDate': '1899-12-31'}, {'dispatchDate': '2101-01-01'},
{'dispatchDate': 1792972800}, {'dispatchDate': '2026-10-26T00:00:00'}, {'origin': 'x' * 256}, {'destination': 'x' * 256},
{'vehicleId': ''}, {'productId': ''}, {'remark': 'x' * 501}, {'calendarKind': 'salt'}, {'tenantNo': 't2'},
{'sourceRecordId': '伪造'}, {'siteSyncEnabled': 1}, {'source_record_id': '伪造'}, {'site_sync_enabled': 1},
{'licensePlate': '伪造'}, {'productName': '伪造'}, {'createBy': 'other'},
])
def test_schema_rejects_bad_fields_and_client_snapshots(bad):
@@ -239,6 +240,19 @@ def test_http_read_only_manage_permissions_both_clients_and_routes(db, monkeypat
assert other.status_code == 200 and other.json()['calendarKind'] == 'other'
assert client.get(path, params={'month': '2026-10', 'calendarKind': 'other'}).json()['total'] == 1
assert client.put(f"{path}/{other.json()['id']}", json=payload(calendarKind='alkali')).status_code == 422
for kind in ('acid', 'alkali', 'other'):
source = client.post(path, json=payload(calendarKind=kind, origin='山峡')).json()
sites = client.get(path, params={'month': '2026-10', 'calendarKind': 'site'}).json()['list']
assert len(sites) == 1 and sites[0]['sourceRecordId'] == source['id']
assert sites[0]['documentType'] == '出库计划'
site_path = f"{path}/{sites[0]['id']}"
assert client.put(site_path, json=payload(calendarKind='site')).status_code == 409
assert client.delete(site_path).status_code == 409
assert client.put(f"{path}/{source['id']}", json=payload(
calendarKind=kind, origin='山峡', destination='云栋')).status_code == 200
assert client.get(site_path).json()['documentType'] == '出入库计划'
assert client.delete(f"{path}/{source['id']}").status_code == 200
assert client.get(site_path).status_code == 404
engine.dispose()
@@ -388,3 +402,26 @@ def test_calendar_addresses_optional_on_create_and_update(db, kind, addresses):
omitted.pop('destination')
body = schema(**omitted)
assert body.origin == body.destination == ''
@pytest.mark.parametrize('document_type', ['入库计划', '出库计划', '客户现场调拨'])
def test_site_document_type_round_trip_and_omitted_update_preserves_value(db, document_type):
_, _, Update, svc = modules()
row = create(db, calendarKind='site', documentType=' ' + document_type + ' ')
original = (row.id, row.create_by, row.create_time)
assert svc._row_to_dict(row)['documentType'] == document_type
assert svc.list_records(db, 't1', user(), month='2026-10', calendar_kind='site')['list'][0]['documentType'] == document_type
row = svc.update_record(db, 't1', user(), row.id, Update(**payload(calendarKind='site', remark='只改备注')))
assert row.document_type == document_type
assert (row.id, row.create_by, row.create_time) == original
row = svc.update_record(db, 't1', user(), row.id, Update(**payload(calendarKind='site', documentType='自定义类型')))
assert row.document_type == '自定义类型'
row = svc.update_record(db, 't1', user(), row.id, Update(**payload(calendarKind='site', documentType='')))
assert not row.document_type
def test_site_document_type_optional_and_length_limit(db):
_, Create, _, svc = modules()
assert not svc._row_to_dict(create(db, calendarKind='site'))['documentType']
with pytest.raises(ValidationError):
Create(**payload(calendarKind='site', documentType='字' * 51))
@@ -0,0 +1,265 @@
"""来源派车与现场日历的匹配、关联生命周期和事务回归。"""
import pytest
from fastapi import HTTPException
from sqlalchemy import event
from sqlalchemy.exc import IntegrityError, OperationalError
from test_pl_dispatch_calendar import db, create, modules, payload, user
@pytest.fixture(autouse=True)
def production_session_options(db):
db.autoflush = False
db.expire_on_commit = False
def site_rows(db, tenant='t1', caller=None, month='2026-10'):
return modules()[3].list_records(db, tenant, caller or user(tenant=tenant),
month=month, calendar_kind='site')['list']
@pytest.mark.parametrize('kind', ['acid', 'alkali', 'other'])
@pytest.mark.parametrize('origin,destination,expected', [
('山峡化工仓库', '武汉', '出库计划'),
('云栋厂区', '武汉', '出库计划'),
('武汉', '山峡化工仓库', '入库计划'),
('武汉', '云栋厂区', '入库计划'),
('山峡仓库', '云栋厂区', '出入库计划'),
('云栋一库', '云栋二库', '出入库计划'),
('武汉', '安庆', None),
('', '', None),
])
def test_new_source_match_matrix(db, kind, origin, destination, expected):
source = create(db, calendarKind=kind, origin=origin, destination=destination,
quantity='32.50', remark='保持备注')
rows = site_rows(db)
assert len(rows) == (1 if expected else 0)
if expected:
target = rows[0]
assert target['id'] != source.id
assert target['sourceRecordId'] == source.id
assert target['documentType'] == expected
original = modules()[3]._row_to_dict(source)
for key in ('dispatchDate', 'vehicleId', 'licensePlate', 'productId', 'productName',
'origin', 'destination', 'quantity', 'remark'):
assert target[key] == original[key]
def test_source_update_preserves_identity_and_soft_delete_lifecycle(db):
model, _, Update, svc = modules()
source = create(db, origin='山峡')
assert len(site_rows(db)) == 1
target = db.get(model, site_rows(db)[0]['id'])
identity = (target.id, target.create_by, target.create_dept_id, target.create_time)
# 不变保存以及更换月份、主数据和类型,均为原地更新。
for _ in range(2):
svc.update_record(db, 't1', user(), source.id, Update(**payload(origin='山峡')))
assert len(site_rows(db)) == 1
svc.update_record(db, 't1', user('u2'), source.id, Update(**payload(
dispatchDate='2026-11-01', vehicleId='v2', productId='p2',
origin='武汉', destination='云栋', quantity='20.00', remark='改备注')))
assert site_rows(db) == []
changed = site_rows(db, month='2026-11')[0]
assert changed['id'] == target.id and changed['documentType'] == '入库计划'
assert changed['licensePlate'] == '鄂E67890' and changed['productName'] == '盐酸'
assert changed['quantity'] == '20.00' and changed['remark'] == '改备注'
assert (target.id, target.create_by, target.create_dept_id, target.create_time) == identity
assert target.update_by == 'u2'
svc.update_record(db, 't1', user(), source.id, Update(**payload()))
assert site_rows(db) == [] and target.del_flag == 1
svc.update_record(db, 't1', user(), source.id,
Update(**payload(origin='山峡', destination='云栋')))
assert site_rows(db)[0]['id'] == target.id
assert target.del_flag == 0 and target.document_type == '出入库计划'
assert (target.id, target.create_by, target.create_dept_id, target.create_time) == identity
svc.delete_record(db, 't1', user(), source.id)
assert source.del_flag == target.del_flag == 1
assert site_rows(db) == []
assert db.query(model).count() == 2
def test_new_nonmatching_source_can_match_later_but_history_never_backfills(db):
model, _, Update, svc = modules()
source = create(db)
assert site_rows(db) == []
svc.update_record(db, 't1', user(), source.id, Update(**payload(destination='云栋')))
assert len(site_rows(db)) == 1
# 模拟迁移前已有记录,数据库新字段使用默认值;不依赖派车日期判断历史。
historical = model(id='legacy', tenant_no='t1', calendar_kind='acid',
dispatch_date=source.dispatch_date, vehicle_id='v1', license_plate='鄂E12345',
product_id='p1', product_name='液碱', origin='山峡', destination='云栋',
create_by='u1', create_dept_id='d1')
db.add(historical)
db.commit()
svc.update_record(db, 't1', user(), historical.id, Update(**payload(origin='山峡', destination='云栋')))
assert len(site_rows(db)) == 1
assert all(row['sourceRecordId'] != historical.id for row in site_rows(db))
svc.delete_record(db, 't1', user(), historical.id)
assert len(site_rows(db)) == 1
def test_manual_site_is_independent_and_generated_site_is_read_only(db):
model, _, Update, svc = modules()
manual = create(db, calendarKind='site', origin='山峡', destination='云栋', documentType='自定义')
assert len(site_rows(db)) == 1
create(db, origin='山峡')
assert len(site_rows(db)) == 2
generated = next(row for row in site_rows(db) if row['id'] != manual.id)
for action in [lambda: svc.update_record(db, 't1', user(), generated['id'],
Update(**payload(calendarKind='site'))),
lambda: svc.delete_record(db, 't1', user(), generated['id'])]:
with pytest.raises(HTTPException) as exc:
action()
assert exc.value.status_code == 409 and '来源' in exc.value.detail
svc.update_record(db, 't1', user(), manual.id, Update(**payload(calendarKind='site', documentType='出库计划')))
svc.delete_record(db, 't1', user(), manual.id)
assert len(site_rows(db)) == 1 and db.get(model, generated['id']).del_flag == 0
def test_generated_record_inherits_scope_and_cannot_cross_tenant(db, monkeypatch):
_, Create, Update, svc = modules()
own = create(db, origin='山峡')
other = create(db, caller=user('u2'), origin='山峡')
foreign = svc.create_record(db, 't2', user(tenant='t2'), Create(**payload(
vehicleId='v3', productId='p3', origin='山峡')))
assert len(site_rows(db)) == 2
assert site_rows(db, tenant='t2')[0]['sourceRecordId'] == foreign.id
import app.core.data_scope as scope
monkeypatch.setattr(scope, '_resolve_user_role_scopes', lambda *a: [{'data_scope': '4', 'details': []}])
limited = user(role='admin')
assert [r['sourceRecordId'] for r in site_rows(db, caller=limited)] == [own.id]
for source in (other, foreign):
for action in [lambda: svc.update_record(db, 't1', limited, source.id, Update(**payload())),
lambda: svc.delete_record(db, 't1', limited, source.id)]:
with pytest.raises(HTTPException) as exc:
action()
assert exc.value.status_code == 404
svc.update_record(db, 't1', limited, own.id, Update(**payload(origin='山峡', destination='云栋')))
assert site_rows(db, caller=limited)[0]['documentType'] == '出入库计划'
svc.delete_record(db, 't1', limited, own.id)
assert len(site_rows(db)) == 1 and len(site_rows(db, tenant='t2')) == 1
@pytest.mark.parametrize('operation', ['create', 'update', 'delete'])
def test_source_and_site_rollback_together(db, operation):
model, _, Update, svc = modules()
source = None
if operation != 'create':
source = create(db, origin='山峡')
assert len(site_rows(db)) == 1
def reject_site(mapper, connection, target):
if target.calendar_kind == 'site':
raise RuntimeError('模拟现场写入失败')
hook = 'before_insert' if operation == 'create' else 'before_update'
event.listen(model, hook, reject_site)
try:
with pytest.raises(RuntimeError, match='模拟现场写入失败'):
if operation == 'create':
create(db, origin='山峡')
elif operation == 'update':
svc.update_record(db, 't1', user(), source.id, Update(**payload(origin='云栋')))
else:
svc.delete_record(db, 't1', user(), source.id)
finally:
event.remove(model, hook, reject_site)
# 服务已回滚,会话可直接继续查询。
if source is None:
assert db.query(model).count() == 0
else:
assert source.origin == '山峡' and source.del_flag == 0
assert len(site_rows(db)) == 1 and site_rows(db)[0]['origin'] == '山峡'
def test_database_unique_source_including_soft_deleted_rows(db):
model, _, Update, svc = modules()
source = create(db, origin='山峡')
assert len(site_rows(db)) == 1
target = db.get(model, site_rows(db)[0]['id'])
svc.update_record(db, 't1', user(), source.id, Update(**payload()))
assert target.del_flag == 1
db.add(model(id='duplicate', tenant_no='t1', source_record_id=source.id,
calendar_kind='site', dispatch_date=source.dispatch_date,
vehicle_id='v1', license_plate='鄂E12345', product_id='p1', product_name='液碱',
origin='山峡', destination='武汉', create_dept_id='d1'))
with pytest.raises(IntegrityError):
db.commit()
db.rollback()
def test_identical_source_trips_remain_independent_of_manual_site(db):
_, _, _, svc = modules()
manual = create(db, calendarKind='site', origin='山峡')
first = create(db, origin='山峡')
second = create(db, origin='山峡')
assert len(site_rows(db)) == 3
assert {row['sourceRecordId'] for row in site_rows(db)} == {None, first.id, second.id}
svc.delete_record(db, 't1', user(), first.id)
assert len(site_rows(db)) == 2
assert {row['sourceRecordId'] for row in site_rows(db)} == {None, second.id}
assert svc.get_record(db, 't1', user(), manual.id).del_flag == 0
@pytest.mark.parametrize('operation', ['create', 'update', 'delete'])
def test_mysql_deadlock_retries_entire_transaction(db, operation):
model, _, Update, svc = modules()
source = create(db, origin='山峡') if operation != 'create' else None
attempts = []
def fail_once(mapper, connection, target):
if target.calendar_kind == 'site':
attempts.append(target.id)
if len(attempts) == 1:
raise OperationalError('test', {}, Exception(1213, 'Deadlock found'))
hook = 'before_insert' if operation == 'create' else 'before_update'
event.listen(model, hook, fail_once)
try:
if operation == 'create':
source = create(db, origin='山峡')
elif operation == 'update':
svc.update_record(db, 't1', user(), source.id, Update(**payload(origin='云栋')))
else:
svc.delete_record(db, 't1', user(), source.id)
finally:
event.remove(model, hook, fail_once)
assert len(attempts) == 2
assert db.query(model).count() == 2
if operation == 'delete':
assert source.del_flag == 1 and site_rows(db) == []
else:
assert len(site_rows(db)) == 1
assert site_rows(db)[0]['sourceRecordId'] == source.id
assert site_rows(db)[0]['origin'] == ('云栋' if operation == 'update' else '山峡')
@pytest.mark.parametrize('error_code,expected_attempts', [(1213, 3), (1205, 1)])
def test_database_retry_is_bounded_and_only_for_deadlocks(db, error_code, expected_attempts):
model, _, _, _ = modules()
attempts = []
def reject_site(mapper, connection, target):
if target.calendar_kind == 'site':
attempts.append(target.id)
raise OperationalError('test', {}, Exception(error_code, 'database failure'))
event.listen(model, 'before_insert', reject_site)
try:
with pytest.raises(OperationalError):
create(db, origin='山峡')
finally:
event.remove(model, 'before_insert', reject_site)
assert len(attempts) == expected_attempts
assert db.query(model).count() == 0
def test_post_commit_refresh_failure_does_not_replay_a_committed_create(db, monkeypatch):
model, _, _, _ = modules()
refresh = db.refresh
calls = []
def fail_first_refresh(*args, **kwargs):
calls.append(1)
if len(calls) == 1:
raise OperationalError('test', {}, Exception(1213, 'post-commit read failed'))
return refresh(*args, **kwargs)
monkeypatch.setattr(db, 'refresh', fail_first_refresh)
try:
create(db, origin='山峡')
except OperationalError:
pass
assert db.query(model).count() == 2