# Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import threading
import unittest

from xmanager.xm import core
from xmanager.xm import job_blocks
from xmanager.xm import testing
from xmanager.xm import utils


class TestError(RuntimeError):
  """Exception which can be used in tests below."""


async def failing_job_generator(work_unit: core.WorkUnit):
  raise TestError


class ApplyArgsTest(unittest.TestCase):

  def test_wrong_job_args(self):
    with self.assertRaises(ValueError):
      core._apply_args(
          job_blocks.Job(
              job_blocks.Executable(name=''), testing.TestExecutor()),
          {'abra': 'kadabra'})

  def test_wrong_job_group_args(self):
    with self.assertRaises(ValueError):
      core._apply_args(
          job_blocks.JobGroup(
              learner=job_blocks.Job(
                  job_blocks.Executable(name=''), testing.TestExecutor())),
          {'eval': {
              'args': {
                  'batch_size': 32
              }
          }})


class ExperimentTest(unittest.TestCase):

  def test_single_job_launch(self):
    experiment = testing.TestExperiment()
    with experiment:
      job = job_blocks.Job(
          testing.TestExecutable(),
          testing.TestExecutor(),
          args={},
          name='name')
      experiment.add(job)

    self.assertEqual(experiment.launched_jobs, [job])

  def test_job_group_launch(self):
    experiment = testing.TestExperiment()
    with experiment:
      foo_job = job_blocks.Job(
          testing.TestExecutable(),
          testing.TestExecutor(),
          args={'foo': 1},
          name='1')
      bar_job = job_blocks.Job(
          testing.TestExecutable(),
          testing.TestExecutor(),
          args={'bar': 2},