Jeandrew Swart
Jeandrew Swart

Reputation: 1

Optapy constraint testing

Started out using Optapy as I am slightly more familiar with python than java. I would like to write some tests for my constraints to ensure they work correctly but I can't seem to find any documentation or examples of a test class in python and how to execute/run it?

Not sure if this is supported in Octapy or only in octaplanner.

Any help or guidance would be appreciated.

Thanks

Upvotes: 0

Views: 218

Answers (1)

Christopher Chianelli
Christopher Chianelli

Reputation: 2013

As of 8.30.0b0, ConstraintVerifier testing is now supported in optapy. First, create a ConstraintVerifier from your @constraint_provider function:

from optapy.test import ConstraintVerifier, constraint_verifier_build
from domain import Timeslot, Room, Lesson, TimeTable
from constraints import define_constraints

constraint_verifier: ConstraintVerifier = constraint_verifier_build(define_constraints, TimeTable, Lesson)

(or alternatively, from your SolverConfig)

from optapy.test import ConstraintVerifier, constraint_verifier_create
constraint_verifier = constraint_verifier_create(solver_config)

Then you can create tests for particular constraints:

from constraints import room_conflict

ROOM1 = Room(1, "Room1")
ROOM2 = Room(2, "Room2")
TIMESLOT1 = Timeslot(1, 'MONDAY', time(12, 0), time(13, 0))
TIMESLOT2 = Timeslot(2, 'TUESDAY', time(12, 0), time(13, 0))
TIMESLOT3 = Timeslot(3, 'TUESDAY', time(13, 0), time(14, 0))
TIMESLOT4 = Timeslot(4, 'TUESDAY', time(15, 0), time(16, 0))

def test_room_conflict():
    first_lesson = Lesson(1, "Subject1", "Teacher1", "Group1", TIMESLOT1, ROOM1)
    conflicting_lesson = Lesson(2, "Subject2", "Teacher2", "Group2", TIMESLOT1, ROOM1)
    non_conflicting_lesson = Lesson(3, "Subject3", "Teacher3", "Group3", TIMESLOT2, ROOM1)
    constraint_verifier.verify_that(room_conflict) \
        .given(first_lesson, conflicting_lesson, non_conflicting_lesson) \
        .penalizes_by(1)

This tests the constraint room_conflict in isolation from all the other constraints. You can also test all constraints using verify_that() (no parameters) and replace penalizes_by with scores.

For a complete example, see the tests in the optapy school timetabling quickstart.

Upvotes: 1

Related Questions