Optapy约束测试支持情况及Python测试类编写执行咨询
Optapy约束逻辑测试实现指南
Optapy完全支持约束逻辑的单元测试,和OptaPlanner的测试逻辑对齐,只是用Python语法实现。以下是具体的实现步骤和示例:
核心测试思路
通过Optapy提供的ConstraintVerifier工具,构建测试用的规划实体、问题事实数据,验证约束触发后的得分是否符合预期,以此确认约束逻辑的正确性。
测试步骤与代码示例
1. 准备约束提供者(示例)
假设你有一个排班场景,约束是员工每周工作时长不得超过40小时,约束提供者代码如下:
from optapy import constraint_provider, HardSoftScore from your_model import Shift, Employee @constraint_provider def define_constraints(constraint_factory): return [ # 硬约束:超时时长每小时扣1分硬惩罚 constraint_factory.for_each(Shift) .group_by(Shift.employee, sum(Shift.duration)) .filter(lambda employee, total_hours: total_hours > 40) .penalize("员工每周超时工作", HardSoftScore.ONE_HARD, lambda _, over_hours: over_hours - 40) ]
2. 编写测试类(用unittest框架)
import unittest from optapy import ConstraintVerifier from your_module import define_constraints, Shift, Employee class TestShiftConstraints(unittest.TestCase): def setUp(self): # 初始化约束验证器,关联约束提供者、实体类和事实类 self.constraint_verifier = ConstraintVerifier.build(define_constraints, Shift, Employee) def test_no_overtime_no_penalty(self): # 测试无超时场景:员工工作40小时,得分为0 alice = Employee("Alice") normal_shifts = [Shift(alice, 8) for _ in range(5)] # 5*8=40小时 self.constraint_verifier.verify_that(define_constraints) \ .given(normal_shifts) \ .scores(HardSoftScore.ZERO) def test_overtime_triggers_penalty(self): # 测试超时场景:员工工作48小时,扣8分硬惩罚 alice = Employee("Alice") overtime_shifts = [Shift(alice, 8) for _ in range(6)] # 6*8=48小时 self.constraint_verifier.verify_that(define_constraints) \ .given(overtime_shifts) \ .scores(HardSoftScore.of(-8, 0)) def test_single_constraint_validation(self): # 单独测试某一个约束(而非全部约束) alice = Employee("Alice") overtime_shifts = [Shift(alice, 8) for _ in range(6)] # 从约束提供者中提取目标约束 overtime_constraint = define_constraints(None)[0] self.constraint_verifier.verify_that(overtime_constraint) \ .given(overtime_shifts) \ .penalizes_with(HardSoftScore.ONE_HARD, 8) if __name__ == '__main__': unittest.main()
3. 执行测试
- 直接运行测试文件:
python test_shift_constraints.py - 若使用pytest框架,只需将测试改成函数式风格,执行
pytest test_shift_constraints.py即可
额外说明
ConstraintVerifier支持所有OptaPlanner测试中的常用断言,比如penalizes_with、rewards_with等- 复杂场景(多实体关联、交叉约束)的测试逻辑与上述示例一致,只需构建对应的数据组合即可
内容的提问来源于stack exchange,提问作者Jeandrew Swart
相关产品推荐
相关产品推荐

