def test_callbacks_configured_in_model(tmp_path):
    """Test the callback system with callbacks added through the model hook."""
    model_callback_mock = Mock(spec=Callback, model=Callback())
    trainer_callback_mock = Mock(spec=Callback, model=Callback())

    class TestModel(BoringModel):
        def configure_callbacks(self):
            return [model_callback_mock]

    model = TestModel()
    trainer_options = {
        "default_root_dir": tmp_path,
        "enable_checkpointing": False,
        "fast_dev_run": True,
        "enable_progress_bar": False,
    }

    def assert_expected_calls(_trainer, model_callback, trainer_callback):
        # assert that the rest of calls are the same as for trainer callbacks
        expected_calls = [m for m in trainer_callback.method_calls if m]
        assert expected_calls
        assert model_callback.method_calls == expected_calls

    # .fit()
    trainer_options.update(callbacks=[trainer_callback_mock])
    trainer = Trainer(**trainer_options)

    assert trainer_callback_mock in trainer.callbacks
    assert model_callback_mock not in trainer.callbacks
    trainer.fit(model)

    assert model_callback_mock in trainer.callbacks
    assert trainer.callbacks[-1] == model_callback_mock
    assert_expected_calls(trainer, model_callback_mock, trainer_callback_mock)

    # .test()
    for fn in ("test", "validate"):
        model_callback_mock.reset_mock()
        trainer_callback_mock.reset_mock()

        trainer_options.update(callbacks=[trainer_callback_mock])
        trainer = Trainer(**trainer_options)

        trainer_fn = getattr(trainer, fn)
        trainer_fn(model)

        assert model_callback_mock in trainer.callbacks
        assert trainer.callbacks[-1] == model_callback_mock
        assert_expected_calls(trainer, model_callback_mock, trainer_callback_mock)
Test the callback system with callbacks added through the model hook.
tests/tests_pytorch/callbacks/test_callbacks.py