code: def test_save_best_model_by_val_score(dirname):
      acc_scores = [0.1, 0.2, 0.3, 0.4, 0.3, 0.5, 0.6, 0.61, 0.7, 0.5]
  
      def setup_trainer():
          trainer = Engine(lambda e, b: None)
          evaluator = Engine(lambda e, b: None)
          model = DummyModel()
  
          @trainer.on(Events.EPOCH_COMPLETED)
          def validate(engine):
              evaluator.run([0, 1])
  
          @evaluator.on(Events.EPOCH_COMPLETED)
          def set_eval_metric(engine):
              acc = acc_scores[trainer.state.epoch - 1]
              engine.state.metrics = {"acc": acc, "loss": 1 - acc}
  
          return trainer, evaluator, model
  
      trainer, evaluator, model = setup_trainer()
  
      save_best_model_by_val_score(
          dirname,
          evaluator,
          model,
          metric_name="acc",
          n_saved=2,
          trainer=trainer,
      )
  
      trainer.run([0, 1], max_epochs=len(acc_scores))
  
      assert set(os.listdir(dirname)) == {
          "best_model_8_val_acc=0.6100.pt",
          "best_model_9_val_acc=0.7000.pt",
      }
  
      for fname in os.listdir(dirname):
          os.unlink(f"{dirname}/{fname}")
  
      trainer, evaluator, model = setup_trainer()
  
      save_best_model_by_val_score(
          dirname,
          evaluator,
          model,
          metric_name="loss",
          n_saved=2,
          trainer=trainer,
          score_sign=-1.0,
      )
  
      trainer.run([0, 1], max_epochs=len(acc_scores))
  
      assert set(os.listdir(dirname)) == {
          "best_model_8_val_loss=-0.3900.pt",
          "best_model_9_val_loss=-0.3000.pt",
      }
  
imports: import os
  import sys
  from unittest.mock import call, MagicMock
  import pytest
  import torch
  import torch.nn
  from torch.utils.data.distributed import DistributedSampler
  import ignite.contrib.handlers
  import ignite.distributed
  from ignite.contrib.engines.common import _setup_logging, add_early_stopping_by_val_score, gen_save_best_models_by_val_score, save_best_model_by_val_score, setup_any_logging, setup_clearml_logging, setup_common_training_handlers, setup_mlflow_logging, setup_neptune_logging, setup_plx_logging, setup_tb_logging, setup_trains_logging, setup_visdom_logging, setup_wandb_logging
  from ignite.engine import Engine, Events
  from ignite.handlers import DiskSaver, TerminateOnNan
label_desc: Use image node_id 7 for calling a global function with example usage: test_save_best_model_by_val_score(dirname) and returns: trainer,  evaluator,  model