async def occurrence(event: OccurrenceEvent): dto = ReportThreatDto( name=event["monsterName"], danger_level=event["dangerLevel"].lower(), location=event["location"][0], ) threat = await threat_service.report_threat(deps.threat_monitor, deps.threat_repository, dto) logger.info(f"Reported threat of name {threat.name}")
async def upsert(dto: ReportThreatDto) -> Threat: threat = await fetch_by_name(dto.name) if threat: # Update values = dto.dict(exclude={"name"}) query = (ThreatModel.update().where( ThreatModel.c.id == threat.id).values(**values)) await database.execute(query) await register_history_change(threat.id, dto) return await fetch_or_raise(threat.id) else: # Create values = dto.dict() query = ThreatModel.insert().values(**values) last_record_id = await database.execute(query) await register_history_change(last_record_id, dto) return Threat.parse_obj({ **values, "id": last_record_id, "occurrences": () })
def test_is_required(self, valid_report_threat_dto): with pytest.raises(ValidationError) as excinfo: ReportThreatDto(**dissoc(valid_report_threat_dto, "location")) self.assert_validation_error("value_error.missing", excinfo)
def test_must_be_danger_level(self, valid_report_threat_dto): with pytest.raises(ValidationError) as excinfo: ReportThreatDto(**{**valid_report_threat_dto, "danger_level": 9000}) self.assert_validation_error("type_error.enum", excinfo)
def test_must_be_str(self, valid_report_threat_dto): with pytest.raises(ValidationError) as excinfo: ReportThreatDto(**{**valid_report_threat_dto, "name": ["Some name"]}) self.assert_validation_error("type_error.str", excinfo)
def test_immutability(self, valid_report_threat_dto): entity = ReportThreatDto(**valid_report_threat_dto) for key in entity.dict().keys(): with pytest.raises(TypeError): setattr(entity, key, "some value")
def test_invalidation(self, invalid_report_threat_dto): with pytest.raises(ValidationError): ReportThreatDto(**invalid_report_threat_dto)
def test_validation(self, valid_report_threat_dto): assert ReportThreatDto(**valid_report_threat_dto)
async def register_history_change(threat_id, dto: ReportThreatDto) -> ThreatHistory: values = assoc(dto.dict(exclude={"name"}), "threat_id", threat_id) query = ThreatRecordModel.insert().values(**values) await database.execute(query) return await fetch_history_or_raise(threat_id)