1# Copyright 2014 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import json
6import os
7import tempfile
8
9
10class MockAdb(object):
11  """Simple and effective mock for Android adb.
12
13  This module is meant to be used in integration tests in conjunction with the
14  other script named 'adb' living in the same directory.
15  The purpose of this class is preparing a dictionary of mocked responses to adb
16  commands. The dictionary is stored into a json file and read by the mock 'adb'
17  script. The path of the json dict is held in the MOCK_ADB_CFG env var.
18  """
19
20  def __init__(self):
21    self._responses = {}  # Maps expected_cmd (str) -> prepared_response (str).
22    self._cfg_file = None
23
24  def Start(self):
25    (fd_num, self._cfg_file) = tempfile.mkstemp()
26    with os.fdopen(fd_num, 'w') as f:
27      json.dump(self._responses, f)
28      f.close()
29    os.environ['MOCK_ADB_CFG'] = self._cfg_file
30
31  def Stop(self):
32    assert(self._cfg_file), 'Stop called before Start.'
33    os.unlink(self._cfg_file)
34
35  def PrepareResponse(self, cmd, response):
36    self._responses[cmd] = response
37