# Copyright 2021 Google LLC
#
# 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.

# Lint as: python3
"""Tests for storage."""

import datetime
import tempfile
import time
from unittest import mock

from absl.testing import absltest
from absl.testing import parameterized
from data_store import assignment_monitor
from data_store import data_store as data_store_module
from data_store import file_system as data_store_file_system
from learner import storage as storage_module
from learner import test_data

# pylint: disable=g-bad-import-order
import common.generate_protos  # pylint: disable=unused-import
import data_store_pb2


class StorageTest(parameterized.TestCase):

  def setUp(self):
    super().setUp()
    self.tmp_dir = tempfile.TemporaryDirectory()
    self.data_store_file_system = data_store_file_system.FileSystem(
        self.tmp_dir.name)
    self.data_store = data_store_module.DataStore(self.data_store_file_system)
    with mock.patch.object(assignment_monitor, 'AssignmentMonitor') as (
        mock_assignment_monitor):
      self.storage = storage_module.Storage(self.data_store,
                                            self.data_store_file_system)
      # Verify assignment monitor is constructed with the correct arguments.
      mock_assignment_monitor.assert_called_with(
          self.data_store_file_system, self.storage._enqueue_pending_assignment,
          self.storage._episode_chunk_notification)

    self.project = test_data.project()
    self.brain = test_data.brain()
    self.session = test_data.session()
    self.assignment = test_data.assignment()

  def tearDown(self):
    self.tmp_dir.cleanup()
    super().tearDown()

  def populate_datastore(self):
    self.data_store.write(self.project)
    self.data_store.write(self.brain)
    self.data_store.write(self.session)
    self.data_store.write(self.assignment)

  def test_get_brain_spec(self):
    """Tests reading a BrainSpec."""
    self.populate_datastore()
    brain_spec = self.storage.get_brain_spec(test_data.PROJECT_ID,
                                             test_data.BRAIN_ID)

    self.assertEqual(brain_spec, test_data.brain_spec())