Merge "Migrates Email System"
diff --git a/build/scripts/common/presubmit/constants.py b/build/scripts/common/presubmit/constants.py
index 399cbed..b9c69fb 100644
--- a/build/scripts/common/presubmit/constants.py
+++ b/build/scripts/common/presubmit/constants.py
@@ -12,12 +12,3 @@
   CHANGE_ID = "CHANGE_ID"
   CHANGE_REVISION = "CHANGE_REVISION"
   CHANGE_FILES = "CHANGE_FILES"
-
-  # Variables needed to communicate with Gerrit REST API.
-  HOST = "https://googleplex-android-review.googlesource.com/"
-  # TODO: Assign platform-dependent value once Windows and Mac presubmit bots are up
-  COOKIE_PATH = os.path.join(os.path.expanduser('~'), '.gitcookies')
-  PROJECTS = [] # Intentionally empty since slave only calls verify() (i.e. does not query).
-  BRANCH = "studio-master-dev"
-  PATH = ".*"
-  AGENT_LIB = AgentLib(HOST, COOKIE_PATH, PROJECTS, BRANCH, PATH)
diff --git a/emu_test/test_console/installAPK.py b/emu_test/test_console/installAPK.py
deleted file mode 100644
index 98de6da..0000000
--- a/emu_test/test_console/installAPK.py
+++ /dev/null
@@ -1,36 +0,0 @@
-import os
-import subprocess
-import sys
-import time
-
-installAPK_script_dir = os.path.dirname(os.path.realpath(__file__))
-servlet_launcher_dir = os.path.join(installAPK_script_dir, 'Server')
-mainAPK_path = os.path.join(servlet_launcher_dir, 'app', 'build', 'outputs', 'apk', 'app-debug.apk')
-androidTestAPK_path = os.path.join(servlet_launcher_dir, 'app', 'build', 'outputs', 'apk', 'app-debug-androidTest-unaligned.apk')
-
-gradle = ""
-if os.name == 'nt':
-    gradle = "gradlew.bat"
-else:
-    gradle = "./gradlew"
-
-TRIAL_WAIT_TIME = 2
-NUM_MAX_TRIALS = 5
-num_trials = 1
-
-os.chdir(servlet_launcher_dir)
-
-while True:
-    if num_trials is NUM_MAX_TRIALS:
-        sys.exit(-1)
-    try:
-        print "Run APK install command, trial num: " + str(num_trials)
-        res_gradlew_buildMain = subprocess.check_call([gradle, "assemble"])
-        res_gradlew_buildAndroidTest = subprocess.check_call([gradle, "assembleAndroidTest"])
-        res_installMain = subprocess.check_call(["adb", "install", "-r", mainAPK_path])
-        res_installAndroidTest = subprocess.check_call(["adb", "install", "-r", androidTestAPK_path])
-        break
-    except subprocess.CalledProcessError as err:
-        print("Subprocess call error: {0}".format(err))
-        time.sleep(TRIAL_WAIT_TIME)
-        num_trials = num_trials + 1
diff --git a/emu_test/test_console/install_apk.py b/emu_test/test_console/install_apk.py
new file mode 100644
index 0000000..1e73ae0
--- /dev/null
+++ b/emu_test/test_console/install_apk.py
@@ -0,0 +1,44 @@
+"""This script is to install apk."""
+
+import os
+import subprocess
+import sys
+import time
+
+from utils import util
+
+install_apk_script_dir = os.path.dirname(os.path.realpath(__file__))
+servlet_launcher_dir = os.path.join(install_apk_script_dir, 'Server')
+main_apk_path = os.path.join(servlet_launcher_dir,
+                             'app', 'build', 'outputs', 'apk', 'app-debug.apk')
+android_test_apk_path = os.path.join(servlet_launcher_dir,
+                                     'app', 'build', 'outputs', 'apk',
+                                     'app-debug-androidTest-unaligned.apk')
+
+gradle = ''
+if os.name == util.WINDOWS_OS_NAME:
+  gradle = 'gradlew.bat'
+else:
+  gradle = './gradlew'
+
+os.chdir(servlet_launcher_dir)
+
+num_trials = 1
+while True:
+  if num_trials is util.ADB_NUM_MAX_TRIALS:
+    sys.exit(-1)
+  try:
+    print 'Run APK install command, trial num: %s' % str(num_trials)
+    res_gradlew_build_main = subprocess.check_call([gradle, 'assemble'])
+    res_gradlew_build_android_test = (subprocess
+                                      .check_call([gradle,
+                                                   'assembleAndroidTest']))
+    res_install_main = subprocess.check_call(['adb', 'install', '-r',
+                                              main_apk_path])
+    res_install_android_test = subprocess.check_call(['adb', 'install', '-r',
+                                                      android_test_apk_path])
+    break
+  except subprocess.CalledProcessError as err:
+    print 'Subprocess call error: {0}'.format(err)
+    time.sleep(util.ADB_TRIAL_WAIT_TIME_S)
+    num_trials += 1
diff --git a/emu_test/test_console/runADBShell.py b/emu_test/test_console/runADBShell.py
deleted file mode 100644
index 0ffdb15..0000000
--- a/emu_test/test_console/runADBShell.py
+++ /dev/null
@@ -1,23 +0,0 @@
-import os
-import subprocess
-
-
-mainAPK_package = "com.android.devtools.server"
-launcherClass_name = mainAPK_package + ".Server"
-instrumentation_runner = "android.support.test.runner.AndroidJUnitRunner"
-
-TRIAL_WAIT_TIME = 2
-NUM_MAX_TRIALS = 5
-num_trials = 1
-
-while True:
-    if num_trials is NUM_MAX_TRIALS:
-        sys.exit(-1)
-    try:
-        print "Run adb shell instrumentation test command, trial num: " + str(num_trials)
-        res_runADBShell = subprocess.call(["adb", "shell", "am", "instrument", "-w", "-e", "class", launcherClass_name, mainAPK_package + ".test/" + instrumentation_runner])
-        break
-    except subprocess.CalledProcessError as err:
-        print("Subprocess call error: {0}".format(err))
-        time.sleep(TRIAL_WAIT_TIME)
-        num_trials = num_trials + 1
diff --git a/emu_test/test_console/run_adb_shell.py b/emu_test/test_console/run_adb_shell.py
new file mode 100644
index 0000000..00d3240
--- /dev/null
+++ b/emu_test/test_console/run_adb_shell.py
@@ -0,0 +1,30 @@
+"""This script is to run adb shell instrumentation test."""
+
+import subprocess
+import sys
+import time
+
+from utils import util
+
+main_apk_package = 'com.android.devtools.server'
+launcher_class_name = '%s.Server' % main_apk_package
+instrumentation_runner = 'android.support.test.runner.AndroidJUnitRunner'
+
+num_trials = 1
+while True:
+  if num_trials is util.ADB_NUM_MAX_TRIALS:
+    sys.exit(-1)
+  try:
+    print ('Run adb shell instrumentation test command, trial num: %s'
+           % str(num_trials))
+    res_run_adb_shell = subprocess.call(['adb', 'shell', 'am', 'instrument',
+                                         '-w', '-e' 'class',
+                                         launcher_class_name,
+                                         ('%s.test/%s'
+                                          % (main_apk_package,
+                                             instrumentation_runner))])
+    break
+  except subprocess.CalledProcessError as err:
+    print 'Subprocess call error: {0}'.format(err)
+    time.sleep(util.ADB_TRIAL_WAIT_TIME_S)
+    num_trials += 1
diff --git a/emu_test/test_console/test_console.py b/emu_test/test_console/test_console.py
index 55a98e2..8ef4aa8 100644
--- a/emu_test/test_console/test_console.py
+++ b/emu_test/test_console/test_console.py
@@ -1,176 +1,213 @@
-"""
-This class is the entry point for console tests from dotest.py.
+"""This class is the entry point for console tests from dotest.py.
+
 When the class is instantiated, it sets up logger and runs emulator for tests.
 Then, using unittest loader, it loads all the console test cases
-that are written in the python files with filename starting with "testcase_" in the same directory.
+that are written in the python files with filename starting with "testcase_"
+in the same directory.
 """
 
-import unittest
+
 import os
-import time
-import psutil
 import shutil
-import sys
-import re
-from emu_test.utils.emu_error import *
-from emu_test.utils.emu_argparser import emu_args
-import emu_test.utils.emu_testcase
-from emu_test.utils.emu_testcase import EmuBaseTestCase, AVDConfig, create_test_case_from_file
-from emu_test.utils import emu_unittest
 import subprocess
+import sys
+import time
+import unittest
 import xml.etree.ElementTree as ET
 
+import emu_test
+from emu_test.utils import emu_argparser
+from emu_test.utils import emu_testcase
+from emu_test.utils import emu_unittest
+import psutil
+
 CUR_DIR = os.path.dirname(os.path.realpath(__file__))
-CONSOLE_RESULT_XML_FILE = "consoleTestResult.xml"
-CONSOLE_CSS_FILE = os.path.join(CUR_DIR, "static", "console.css")
-CONSOLE_XSL_FILE =  os.path.join(CUR_DIR, "static", "console.xsl")
-
-class ConsoleTestCase(EmuBaseTestCase):
-
-    def __init__(self, *args, **kwargs):
-        super(ConsoleTestCase, self).__init__(*args, **kwargs)
-        self.avd_config = None
-
-    @classmethod
-
-    def setUpClass(cls):
-        super(ConsoleTestCase, cls).setUpClass()
-
-    def tearDown(self):
-        self.m_logger.debug('First try - quit emulator by adb emu kill')
-        kill_proc = psutil.Popen(["adb", "emu", "kill"])
-        # check emulator process is terminated
-        result = self.term_check(timeout=5)
-        if not result:
-            self.m_logger.debug('Second try - quit emulator by psutil')
-            self.kill_proc_by_name(["emulator", "qemu-system"])
-            result = self.term_check(timeout=10)
-            self.m_logger.debug("term_check after psutil.kill - %s", result)
-        self.m_logger.info("Remove AVD inside of tear down")
-        # avd should be found $HOME/.android/avd/
-        avd_dir = os.path.join(os.path.expanduser('~'), '.android', 'avd')
-        try:
-            if result and self.start_proc:
-                self.start_proc.wait()
-            time.sleep(1)
-            self.kill_proc_by_name(["crash-service", "adb"])
-            os.remove(os.path.join(avd_dir, '%s.ini' % self.avd_config.name()))
-            shutil.rmtree(os.path.join(avd_dir, '%s.avd' % self.avd_config.name()), ignore_errors=True)
-        except Exception, e:
-            self.m_logger.error("Error in cleanup - %r", e)
-            pass
-
-    def getTestName(self, id):
-        return id.rsplit('.', 1)[-1]
-
-    def createResultXml(self, emuResult):
-        dst_path = os.path.join(emu_args.session_dir, CONSOLE_RESULT_XML_FILE)
-        xsl_path = os.path.join(emu_args.session_dir, "console.xsl")
-        subprocess.call(['cp', CONSOLE_XSL_FILE, xsl_path])
-        css_path = os.path.join(emu_args.session_dir, "console.css")
-        subprocess.call(['cp', CONSOLE_CSS_FILE, css_path])
-
-        result = ET.Element("result")
-
-        test_method_name = ET.SubElement(result, "testMethodName", name=self._testMethodName)
-        avd_config_name = ET.SubElement(result, "avdConfigName", name=self.avd_config.name())
-
-        resultSummary = ET.SubElement(result, "resultSummary")
-        ET.SubElement(resultSummary, "total", num=str(emuResult.testsRun))
-        ET.SubElement(resultSummary, "passes", num=str(len(emuResult.passes)))
-        ET.SubElement(resultSummary, "failures", num=str(len(emuResult.failures)))
-        ET.SubElement(resultSummary, "errors", num=str(len(emuResult.errors)))
-        ET.SubElement(resultSummary, "expectedFailures", num=str(len(emuResult.expectedFailures)))
-        ET.SubElement(resultSummary, "unexpectedSuccesses", num=str(len(emuResult.unexpectedSuccesses)))
-
-        passes = ET.SubElement(result, "Passes")
-        for x in emuResult.passes:
-            ET.SubElement(passes, "test", name=self.getTestName(x.id()), test_result="pass")
-
-        failures = ET.SubElement(result, "Failures")
-        for x in emuResult.failures:
-            ET.SubElement(failures, "test", name=self.getTestName(x[0].id()), test_result="fail")
-
-        errors = ET.SubElement(result, "Errors")
-        for x in emuResult.errors:
-            ET.SubElement(errors, "test", name=self.getTestName(x[0].id()), test_result="error")
-
-        expectedFailures = ET.SubElement(result, "ExpectedFailures")
-        for x in emuResult.expectedFailures:
-            ET.SubElement(expectedFailures, "test", name=self.getTestName(x[0].id()), test_result="expected failure")
-
-        unexpectedSuccesses = ET.SubElement(result, "UnexpectedSuccesses")
-        for x in emuResult.unexpectedSuccesses:
-            ET.SubElement(unexpectedSuccesses, "test", name=self.getTestName(x.id()), test_result="unexpected failure")
-
-        tree = ET.ElementTree(result)
-        tree.write(dst_path)
-        with file(dst_path, 'r') as original: data = original.read()
-        with file(dst_path, 'w') as modified: modified.write('<?xml-stylesheet type="text/xsl" href="console.xsl"?>\n' + data)
-
-    def printConsoleResult(self, emuResult):
-        self.m_logger.info("Run %d tests (%d fail, %d pass, %d xfail, %d xpass)",
-               emuResult.testsRun, len(emuResult.failures)+len(emuResult.errors), len(emuResult.passes),
-               len(emuResult.expectedFailures), len(emuResult.unexpectedSuccesses))
-        if len(emuResult.passes) > 0:
-            self.m_logger.info('------------------------------------------------------')
-        for x in emuResult.passes:
-            self.m_logger.info("PASS: %s", self.getTestName(x.id()))
-
-        if len(emuResult.failures) + len(emuResult.errors) > 0:
-            self.m_logger.info('------------------------------------------------------')
-        for x in emuResult.failures:
-            self.m_logger.info("Failure: %s", self.getTestName(x[0].id()))
-        for x in emuResult.errors:
-            self.m_logger.info("Error: %s", self.getTestName(x[0].id()))
-
-        if len(emuResult.expectedFailures) > 0:
-            self.m_logger.info('------------------------------------------------------')
-        for x in emuResult.expectedFailures:
-            self.m_logger.info("Expected Failure: %s", self.getTestName(x[0].id()))
-
-        if len(emuResult.unexpectedSuccesses) > 0:
-            self.m_logger.info('------------------------------------------------------')
-        for x in emuResult.unexpectedSuccesses:
-            self.m_logger.info("Unexpected Success: %s", self.getTestName(x.id()))
-
-        self.m_logger.info('')
-        self.createResultXml(emuResult)
-
-    def console_test_check(self, avd):
-        """
-        1) Run emulator with self.launch_emu_and_wait(avd)
-        2) Print to logger that the test begins
-        3) Load all the console tests using unittest.TestLoader()
-        4) Verify whether every individual testcase was successful
-        """
-        self.launch_emu_and_wait(avd)
-        self.m_logger.info('Console tests (%s) start.' % self._testMethodName)
-        test_root_dir=os.path.dirname(os.path.realpath(__file__))
-        emuSuite = unittest.TestLoader().discover(start_dir=test_root_dir, pattern="testcase_*")
-        emuRunner = emu_unittest.EmuTextTestRunner(stream=sys.stdout)
-        emuResult = emuRunner.run(emuSuite)
-        self.printConsoleResult(emuResult)
-        self.assertTrue(emuResult.wasSuccessful(), self._testMethodName + " was failed.")
-
-    def run_console_test(self, avd_config):
-        """
-        Run console test with the given avd_config.
-        This function first make sure whether avd is properly up or not.
-        """
-        self.avd_config = avd_config
-        self.assertEqual(self.create_avd(avd_config), 0)
-        self.console_test_check(avd_config)
+CONSOLE_RESULT_XML_FILE = 'consoleTestResult.xml'
+CONSOLE_CSS_FILE = os.path.join(CUR_DIR, 'static', 'console.css')
+CONSOLE_XSL_FILE = os.path.join(CUR_DIR, 'static', 'console.xsl')
 
 
-if emu_args.config_file is None:
-    sys.exit(-1)
+class ConsoleTestCase(emu_testcase.EmuBaseTestCase):
+  """This class helps for run all console tests."""
+
+  def __init__(self, *args, **kwargs):
+    super(ConsoleTestCase, self).__init__(*args, **kwargs)
+    self.avd_config = None
+
+  @classmethod
+  def setUpClass(cls):
+    super(ConsoleTestCase, cls).setUpClass()
+
+  def tearDown(self):
+    self.m_logger.debug('First try - quit emulator by adb emu kill')
+    psutil.Popen(['adb', 'emu', 'kill'])
+    # check emulator process is terminated
+    result = self.term_check(timeout=5)
+    if not result:
+      self.m_logger.debug('Second try - quit emulator by psutil')
+      self.kill_proc_by_name(['emulator', 'qemu-system'])
+      result = self.term_check(timeout=10)
+      self.m_logger.debug('term_check after psutil.kill - %s', result)
+    self.m_logger.info('Remove AVD inside of tear down')
+    # avd should be found $HOME/.android/avd/
+    avd_dir = os.path.join(os.path.expanduser('~'), '.android', 'avd')
+    try:
+      if result and self.start_proc:
+        self.start_proc.wait()
+      time.sleep(1)
+      self.kill_proc_by_name(['crash-service' 'adb'])
+      os.remove(os.path.join(avd_dir, '%s.ini' % self.avd_config.name()))
+      shutil.rmtree(os.path.join(avd_dir,
+                                 '%s.avd' % self.avd_config.name()),
+                    ignore_errors=True)
+    except Exception, e:
+      self.m_logger.error('Error in cleanup - %r' % e)
+
+  def get_test_name(self, failed_test_id):
+    return failed_test_id.rsplit('.', 1)[-1]
+
+  def create_result_xml(self, emu_result):
+    dst_path = os.path.join(emu_argparser.emu_args.session_dir,
+                            CONSOLE_RESULT_XML_FILE)
+    xsl_path = os.path.join(emu_argparser.emu_args.session_dir,
+                            'console.xsl')
+    subprocess.call(['cp', CONSOLE_XSL_FILE, xsl_path])
+    css_path = os.path.join(emu_argparser.emu_args.session_dir, 'console.css')
+    subprocess.call(['cp', CONSOLE_CSS_FILE, css_path])
+
+    result = ET.Element('result')
+
+    ET.SubElement(result, 'testMethodName', name=self._testMethodName)
+    ET.SubElement(result, 'avdConfigName', name=self.avd_config.name())
+
+    result_summary = ET.SubElement(result, 'resultSummary')
+    ET.SubElement(result_summary, 'total', num=str(emu_result.testsRun))
+    ET.SubElement(result_summary, 'passes', num=str(len(emu_result.passes)))
+    ET.SubElement(result_summary, 'failures',
+                  num=str(len(emu_result.failures)))
+    ET.SubElement(result_summary, 'errors', num=str(len(emu_result.errors)))
+    ET.SubElement(result_summary, 'expectedFailures',
+                  num=str(len(emu_result.expectedFailures)))
+    ET.SubElement(result_summary, 'unexpectedSuccesses',
+                  num=str(len(emu_result.unexpectedSuccesses)))
+
+    passes = ET.SubElement(result, 'Passes')
+    for x in emu_result.passes:
+      ET.SubElement(passes, 'test', name=self.get_test_name(x.id()),
+                    test_result='pass')
+
+    failures = ET.SubElement(result, 'Failures')
+    for x in emu_result.failures:
+      ET.SubElement(failures, 'test', name=self.get_test_name(x[0].id()),
+                    test_result='fail')
+
+    errors = ET.SubElement(result, 'Errors')
+    for x in emu_result.errors:
+      ET.SubElement(errors, 'test', name=self.get_test_name(x[0].id()),
+                    test_result='error')
+
+    expected_failures = ET.SubElement(result, 'ExpectedFailures')
+    for x in emu_result.expectedFailures:
+      ET.SubElement(expected_failures, 'test',
+                    name=self.get_test_name(x[0].id()),
+                    test_result='expected failure')
+
+    unexpected_successes = ET.SubElement(result, 'UnexpectedSuccesses')
+    for x in emu_result.unexpectedSuccesses:
+      ET.SubElement(unexpected_successes, 'test',
+                    name=self.get_test_name(x.id()),
+                    test_result='unexpected failure')
+
+    tree = ET.ElementTree(result)
+    tree.write(dst_path)
+    with file(dst_path, 'r') as original:
+      data = original.read()
+    with file(dst_path, 'w') as modified:
+      modified.write(('<?xml-stylesheet type="text/xsl"'
+                      'href="console.xsl"?>\n%s' % data))
+
+  def print_console_result(self, emu_result):
+    self.m_logger.info(
+        'Run %d tests (%d fail, %d pass, %d xfail, %d xpass)' %
+        (emu_result.testsRun,
+         len(emu_result.failures) + len(emu_result.errors),
+         len(emu_result.passes),
+         len(emu_result.expectedFailures),
+         len(emu_result.unexpectedSuccesses)))
+
+    border_line = '------------------------------------------------------'
+    if emu_result.passes:
+      self.m_logger.info(border_line)
+    for x in emu_result.passes:
+      self.m_logger.info('PASS: %s' % self.get_test_name(x.id()))
+
+    if len(emu_result.failures) + len(emu_result.errors) > 0:
+      self.m_logger.info(border_line)
+    for x in emu_result.failures:
+      self.m_logger.info('Failure: %s' % self.get_test_name(x[0].id()))
+    for x in emu_result.errors:
+      self.m_logger.info('Error: %s' % self.get_test_name(x[0].id()))
+
+    if emu_result.expectedFailures:
+      self.m_logger.info(border_line)
+    for x in emu_result.expectedFailures:
+      self.m_logger.info('Expected Failure: %s' %
+                         self.get_test_name(x[0].id()))
+
+    if emu_result.unexpectedSuccesses:
+      self.m_logger.info(border_line)
+    for x in emu_result.unexpectedSuccesses:
+      self.m_logger.info('Unexpected Success: %s' %
+                         self.get_test_name(x.id()))
+
+    self.m_logger.info('')
+    self.create_result_xml(emu_result)
+
+  def console_test_check(self, avd):
+    """Checks console test.
+
+    1) Run emulator with self.launch_emu_and_wait(avd)
+    2) Print to logger that the test begins
+    3) Load all the console tests using unittest.TestLoader()
+    4) Verify whether every individual testcase was successful
+
+    Args:
+      avd: The running avd.
+    """
+    self.launch_emu_and_wait(avd)
+    self.m_logger.info('Console tests (%s) start.' % self._testMethodName)
+    test_root_dir = os.path.dirname(os.path.realpath(__file__))
+    emu_suite = unittest.TestLoader().discover(start_dir=test_root_dir,
+                                               pattern='testcase_*')
+    emu_runner = emu_unittest.EmuTextTestRunner(stream=sys.stdout)
+    emu_result = emu_runner.run(emu_suite)
+    self.print_console_result(emu_result)
+    self.assertTrue(emu_result.wasSuccessful(),
+                    '%s was failed.' % self._testMethodName)
+
+  def run_console_test(self, avd_config):
+    """Run console test.
+
+    Run console test with the given avd_config.
+    This function first make sure whether avd is properly up or not.
+
+    Args:
+      avd_config: The avd configuration.
+    """
+    self.avd_config = avd_config
+    self.assertEqual(self.create_avd(avd_config), 0)
+    self.console_test_check(avd_config)
+
+
+if emu_argparser.emu_args.config_file is None:
+  sys.exit(-1)
 else:
-    emu_test.utils.emu_testcase.create_test_case_from_file("console", ConsoleTestCase, ConsoleTestCase.run_console_test)
+  emu_test.utils.emu_testcase.create_test_case_from_file(
+      'console', ConsoleTestCase, ConsoleTestCase.run_console_test)
 
 if __name__ == '__main__':
-    os.environ["SHELL"] = "/bin/bash"
-    emu_argparser.emu_args = emu_argparser.get_parser().parse_args()
-    print emu_argparser.emu_args
-    sys.argv[1:] = emu_args.unittest_args
-    unittest.main()
+  os.environ['SHELL'] = '/bin/bash'
+  emu_argparser.emu_args = emu_argparser.get_parser().parse_args()
+  print emu_argparser.emu_args
+  sys.argv[1:] = emu_argparser.emu_args.unittest_args
+  unittest.main()
diff --git a/emu_test/test_console/testcase_auth.py b/emu_test/test_console/testcase_auth.py
index 29bf4fa..e32bd4e 100644
--- a/emu_test/test_console/testcase_auth.py
+++ b/emu_test/test_console/testcase_auth.py
@@ -1,242 +1,209 @@
-#!/usr/bin/env python
-
 """Test for auth-related commands."""
 
 import inspect
 import os
-import sys
 import telnetlib
 import unittest
 
+import testcase_base
 from utils import util
-from os.path import expanduser
-from testcase_base import BaseConsoleTest
 
 AUTH_OUTPUT = 'Android Console: type \\\'help\\\' for a list of commands\r\nOK'
-AUTH_ERROR_OUTPUT = 'KO: authentication token does not match ' \
-    '~/.emulator_console_auth_token'
+AUTH_ERROR_OUTPUT = ('KO: authentication token does not match '
+                     '~/.emulator_console_auth_token')
 AUTH_TOKEN_MISSING_OUTPUT = 'KO: missing authentication token'
 
 
-class AuthTest(BaseConsoleTest):
-    """This class aims to test auth-related emulator console commands."""
+class AuthTest(testcase_base.BaseConsoleTest):
+  """This class aims to test auth-related emulator console commands."""
 
-    def setUp(self):
-        """There is nothing to do in setUp()."""
-        pass
+  def setUp(self):
+    """There is nothing to do in setUp()."""
+    pass
 
-    def tearDown(self):
-        """There is nothing to do in tearDown()."""
-        pass
+  def tearDown(self):
+    """There is nothing to do in tearDown()."""
+    pass
 
-    def _exit_emulator_console(self):
-        self.telnet.write('exit\n')
-        self.wait_on_windows()
-        self.telnet.close()
+  def _auth_user_for_emulator_console(self, cmd_auth, expected_output):
+    is_command_successful, output = util.execute_console_command(
+        self.telnet, cmd_auth, expected_output)
+    self.assert_cmd_successful(is_command_successful,
+                               'Failed to properly authentication.',
+                               False, '', expected_output, output)
 
-    def _telnet_emulator(self):
-        """Only telnet to emulator, initially not need to run auth command."""
-        self.telnet = telnetlib.Telnet(util.SERVER_NAME,
-                                       util.CONSOLE_PORT)
-        if not util.checkReadUntil(
-              self.telnet.read_until(util.OK,
-                                     util.TIMEOUT_S)):
-            sys.exit(-1)
+  def _verify_auth_command_by_enter_help_command(self, expected_output):
+    is_command_successful, output = util.execute_console_command(
+        self.telnet, util.CMD_HELP, expected_output)
 
-    def _auth_user_for_emulator_console(self, cmd_auth, expected_output):
-        is_command_successful, output = util.execute_console_command(
-            self.telnet,
-            cmd_auth,
-            expected_output)
-        self.assertCmdSuccessful(
-            is_command_successful,
-            'Failed to properly authentication.',
-            False,
-            '',
-            expected_output,
-            output)
+    self.assert_cmd_successful(
+        is_command_successful, 'Failed to properly list all command options.',
+        False, '', 'Pattern: \n%s' % expected_output, output)
 
-    def _verify_auth_command_by_enter_help_command(self, expected_output):
-        is_command_successful, output = util.execute_console_command(
-                self.telnet,
-                util.CMD_HELP,
-                expected_output)
+  def _telnet_emulator_with_failure(self):
+    self.telnet = telnetlib.Telnet(util.SERVER_NAME, util.CONSOLE_PORT)
 
-        self.assertCmdSuccessful(
-            is_command_successful,
-            'Failed to properly list all command options.',
-            False,
-            '',
-            'Pattern: \n%s' % expected_output,
-            output)
+    try:
+      self.telnet.read_until(
+          'Connection closed by foreign host.', util.TIMEOUT_S).strip()
+    except EOFError:
+      print ('Cannot connect to emulator because auth toke file is not.'
+             'accessible.')
 
-    def _telnet_emulator_with_failure(self):
-        self.telnet = telnetlib.Telnet(util.SERVER_NAME,
-                                       util.CONSOLE_PORT)
+  def test_auth_token_file_exists(self):
+    """Test command for: auth <auth_token>.
 
-        try:
-            self.telnet.read_until(
-                'Connection closed by foreign host.',
-                util.TIMEOUT_S)\
-                .strip()
-        except EOFError:
-            print('Cannot connect to emulator because auth toke file is not.'\
-                  'accessible.')
+    Test Rail ID: C14595293
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. verify 1
+      4. Exist emulator console
+    Verify:
+      1. .emulator_console_auth_token file is created in home folder
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self.telnet = util.telnet_emulator()
+    assert os.path.isfile(util.TOKEN_PATH)
+    util.exit_emulator_console(self.telnet)
 
-    def test_auth_token_file_exists(self):
-        """
-        Test command for: auth <auth_token>
-        Test Rail ID: C14595293
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. verify 1
-            4. Exist emulator console
-        Verify:
-            1. .emulator_console_auth_token file is created in home folder
-        """
-        print('Running test: %s' % inspect.stack()[0][3])
-        self._telnet_emulator()
-        assert os.path.isfile(util.TOKEN_PATH)
-        self._exit_emulator_console()
+  def test_auth_without_authorization_by_run_help_command(self):
+    """Test command for: auth <auth_token>.
 
-    def test_auth_without_authorization_by_run_help_command(self):
-        """
-        Test command for: auth <auth_token>
-        Test Rail ID: C14595293
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Run: help, verify 1
-            4. Exist emulator console
-        Verify:
-            1. Short help information is displayed.
-        """
-        print('Running test: %s' % inspect.stack()[0][3])
-        self._telnet_emulator()
-        self._verify_auth_command_by_enter_help_command(
-            util.REGEX_HELP_DISPLAY_NO_AUTH)
-        self._exit_emulator_console()
+    Test Rail ID: C14595293
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Run: help, verify 1
+      4. Exist emulator console
+    Verify:
+      1. Short help information is displayed.
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self.telnet = util.telnet_emulator()
+    self._verify_auth_command_by_enter_help_command(
+        util.REGEX_HELP_DISPLAY_NO_AUTH)
+    util.exit_emulator_console(self.telnet)
 
-    def test_auth_user_with_random_auth_token(self):
-        """
-        Test command for: auth <auth_token>
-        Test Rail ID: C14595293
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Run: help, verify 1
-            4. Run: auth <random_auth_token>, verify 1
-            5. Exist emulator console
-        Verify:
-            1. User is not authorized, and warning message is displayed.
-        """
-        print('Running test: %s' % inspect.stack()[0][3])
-        self._telnet_emulator()
-        self._auth_user_for_emulator_console(
-            util.CMD_RANDOM_AUTH_TOKEN,
-            AUTH_ERROR_OUTPUT)
-        self._exit_emulator_console()
+  def test_auth_user_with_random_auth_token(self):
+    """Test command for: auth <auth_token>.
 
-    def test_auth_user_with_empty_auth_token(self):
-        """
-        Test command for: auth <auth_token>
-        Test Rail ID: C14595293
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Run: help, verify 1
-            4. Run: auth <empty_string>, verify 1
-            5. Exist emulator console
-        Verify:
-            1. User is not authorized, and "missing authentication token"
-               is displayed.
-        """
-        print('Running test: %s' % inspect.stack()[0][3])
-        self._telnet_emulator()
-        self._auth_user_for_emulator_console(util.CMD_EMPTY_AUTH_TOKEN,
-                                             AUTH_TOKEN_MISSING_OUTPUT)
-        self._exit_emulator_console()
+    Test Rail ID: C14595293
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Run: help, verify 1
+      4. Run: auth <random_auth_token>, verify 1
+      5. Exist emulator console
+    Verify:
+      1. User is not authorized, and warning message is displayed.
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self.telnet = util.telnet_emulator()
+    self._auth_user_for_emulator_console(util.CMD_RANDOM_AUTH_TOKEN,
+                                         AUTH_ERROR_OUTPUT)
+    util.exit_emulator_console(self.telnet)
 
-    def test_auth_user_with_valid_auth_token(self):
-        """
-        Test command for: auth <auth_token>
-        Test Rail ID: C14595293
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Run: help, verify 1
-            4. Run: auth <valid auth token>, verify 1
-            5. Run: help, verify 2
-            5. Exist emulator console
-        Verify:
-            1. User is not authorized
-            2. The full help commands information is displayed
-        """
-        print('Running test: %s' % inspect.stack()[0][3])
-        self._telnet_emulator()
-        auth_token = util.get_auth_token()
-        valid_auth_cmd = '%s %s\n' % (util.AUTH, auth_token)
-        self._auth_user_for_emulator_console(valid_auth_cmd, AUTH_OUTPUT)
-        self._verify_auth_command_by_enter_help_command(
-            util.REGEX_HELP_DISPLAY_AUTH)
-        self._exit_emulator_console()
+  def test_auth_user_with_empty_auth_token(self):
+    """Test command for: auth <auth_token>.
 
-    def test_auth_empty_auth_token_file(self):
-        """
-        Test command for: auth <auth_token>
-        Test Rail ID: C14595293
-        Test steps:
-            0. Save valid auth token, and empty the contents of auth token file
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Run: help, verify 1
-            4. Reset auth token file
-            5. Exist emulator console
-        Verify:
-            1. Emulator authentication is skipped and emulator console is usable
-               (Here, we run help command to check.)
-        """
-        print('Running test: %s' % inspect.stack()[0][3])
+    Test Rail ID: C14595293
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Run: help, verify 1
+      4. Run: auth <empty_string>, verify 1
+      5. Exist emulator console
+    Verify:
+      1. User is not authorized, and "missing authentication token"
+         is displayed.
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self.telnet = util.telnet_emulator()
+    self._auth_user_for_emulator_console(util.CMD_EMPTY_AUTH_TOKEN,
+                                         AUTH_TOKEN_MISSING_OUTPUT)
+    util.exit_emulator_console(self.telnet)
 
-        # save auth token value and empty contents of auth token file
-        valid_auth_token = util.get_auth_token()
-        f = open(util.TOKEN_PATH, 'w')
-        f.close()
+  def test_auth_user_with_valid_auth_token(self):
+    """Test command for: auth <auth_token>.
 
-        # telnet and verify
-        self._telnet_emulator()
-        self._verify_auth_command_by_enter_help_command(
-            util.REGEX_HELP_DISPLAY_AUTH)
+    Test Rail ID: C14595293
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Run: help, verify 1
+      4. Run: auth <valid auth token>, verify 1
+      5. Run: help, verify 2
+      6. Exist emulator console
+    Verify:
+      1. User is not authorized
+      2. The full help commands information is displayed
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self.telnet = util.telnet_emulator()
+    auth_token = util.get_auth_token()
+    valid_auth_cmd = '%s %s\n' % (util.AUTH, auth_token)
+    self._auth_user_for_emulator_console(valid_auth_cmd, AUTH_OUTPUT)
+    self._verify_auth_command_by_enter_help_command(
+        util.REGEX_HELP_DISPLAY_AUTH)
+    util.exit_emulator_console(self.telnet)
 
-        # reset auth token file
-        f = open(util.TOKEN_PATH, 'w')
-        f.write(valid_auth_token)
-        f.close()
+  def test_auth_empty_auth_token_file(self):
+    """Test command for: auth <auth_token>.
 
-        self._exit_emulator_console()
+    Test Rail ID: C14595293
+    Test steps:
+      0. Save valid auth token, and empty the contents of auth token file
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Run: help, verify 1
+      4. Reset auth token file
+      5. Exist emulator console
+    Verify:
+      1. Emulator authentication is skipped and emulator console is usable
+         (Here, we run help command to check.)
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
 
-    def test_auth_by_change_auth_token_file_permissions(self):
-        """
-        Test command for: auth <auth_token>
-        Test Rail ID: C14595293
-        Test steps:
-            0. Deny read and write permissions on the auth token file,
-                chmod 000 .emulator_console_auth_token
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>, and verify 1
-            4. Reset auth token file permissions
-                chmod 666 .emulator_console_auth_token
-            5. Exist emulator console
-        Verify:
-            1. Connection to host would be disconnected when auth_token file
-            is inaccessible
-        """
-        print('Running test: %s' % inspect.stack()[0][3])
-        os.chmod(util.TOKEN_PATH, 0000)
-        self._telnet_emulator_with_failure()
-        os.chmod(util.TOKEN_PATH, 0600)
+    # save auth token value and empty contents of auth token file
+    valid_auth_token = util.get_auth_token()
+    f = open(util.TOKEN_PATH, 'w')
+    f.close()
+
+    # telnet and verify
+    self.telnet = util.telnet_emulator()
+    self._verify_auth_command_by_enter_help_command(
+        util.REGEX_HELP_DISPLAY_AUTH)
+
+    # reset auth token file
+    f = open(util.TOKEN_PATH, 'w')
+    f.write(valid_auth_token)
+    f.close()
+
+    util.exit_emulator_console(self.telnet)
+
+  def test_auth_by_change_auth_token_file_permissions(self):
+    """Test command for: auth <auth_token>.
+
+    Test Rail ID: C14595293
+    Test steps:
+      0. Deny read and write permissions on the auth token file,
+         chmod 000 .emulator_console_auth_token
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>, and verify 1
+      4. Reset auth token file permissions
+         chmod 666 .emulator_console_auth_token
+      5. Exist emulator console
+    Verify:
+      1. Connection to host would be disconnected when auth_token file
+         is inaccessible
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    os.chmod(util.TOKEN_PATH, 0000)
+    self._telnet_emulator_with_failure()
+    os.chmod(util.TOKEN_PATH, 0600)
+
 
 if __name__ == '__main__':
-    print('======= auth Test =======')
-    unittest.main()
+  print '======= auth Test ======='
+  unittest.main()
diff --git a/emu_test/test_console/testcase_avd.py b/emu_test/test_console/testcase_avd.py
index 016b7de..020fb78 100644
--- a/emu_test/test_console/testcase_avd.py
+++ b/emu_test/test_console/testcase_avd.py
@@ -1,11 +1,9 @@
-#!/usr/bin/env python
-
 """Test for avd-related emulator console commands."""
 
 import inspect
-import time
 import unittest
-from testcase_base import BaseConsoleTest
+
+import testcase_base
 from utils import util
 
 CMD_HELP_AVD = 'help avd\n'
@@ -13,92 +11,71 @@
 CMD_AVD_START = 'avd start\n'
 CMD_AVD_STATUS = 'avd status\n'
 
-REGEX_HELP_AVD_DISPLAY = \
-  '.*\n.*\n.*\n.*stop.*\n.*start.*\n.*status.*\n.*name.*\n.*snapshot.*\n.*\nOK'
+REGEX_HELP_AVD_DISPLAY = ('.*\n.*\n.*\n.*stop.*\n.*start.*\n.*status.*\n'
+                          '.*name.*\n.*snapshot.*\n.*\nOK')
 AVD_STOPPED = 'virtual device is stopped.*\nOK'
 AVD_RUNNING = 'virtual device is running.*\nOK'
 
 
-class AvdTest(BaseConsoleTest):
-    """This class aims to test avd-related emulator console commands."""
+class AvdTest(testcase_base.BaseConsoleTest):
+  """This class aims to test avd-related emulator console commands."""
 
-    def test_help_avd(self):
-        """
-        Test command for: help avd
-        Test Rail ID: C14595362
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: help avd
-        Verify:
-            Available avd sub commands are listed:
-                stop, start, status, name, snapshot
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._execute_console_command_and_verify(CMD_HELP_AVD,
-                                                 REGEX_HELP_AVD_DISPLAY)
+  def test_help_avd(self):
+    """Test command for: help avd.
 
-    def test_avd_stop_and_start(self):
-        """
-        Test command for: avd stop, avd start, avd status
-        Test Rail ID: C14595362
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: avd stop
-            6. Run: avd status and verify 1
-            7. Run: avd start
-            8. Run avd status and verify 2
-        Verify:
-            1. Check console output is 'virtual device is stopped'
-            2. Check console output is 'virtual device is running'
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._execute_console_command_and_verify(CMD_AVD_STOP, util.OK)
-        self._execute_console_command_and_verify(CMD_AVD_STATUS, AVD_STOPPED)
-        self._execute_console_command_and_verify(CMD_AVD_START, util.OK)
-        self._execute_console_command_and_verify(CMD_AVD_STATUS, AVD_RUNNING)
+    Test Rail ID: C14595362
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: help avd
+    Verify:
+      Available avd sub commands are listed:
+        stop, start, status, name, snapshot
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._execute_console_command_and_verify(CMD_HELP_AVD,
+                                             REGEX_HELP_AVD_DISPLAY)
 
-    def _execute_console_command_and_verify(self,
-                                            command,
-                                            expected_output):
-        """Executes emulator console command and verify the command output.
+  def test_avd_stop_and_start(self):
+    """Test command for: avd stop, avd start, avd status.
 
-        Args:
-            command: Console command to be executed.
-            expected_output: The expected command output.
-        """
-        is_command_successful = False
+    Test Rail ID: C14595362
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: avd stop
+      6. Run: avd status and verify 1
+      7. Run: avd start
+      8. Run avd status and verify 2
+    Verify:
+      1. Check console output is 'virtual device is stopped'
+      2. Check console output is 'virtual device is running'
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._execute_console_command_and_verify(CMD_AVD_STOP, util.OK)
+    self._execute_console_command_and_verify(CMD_AVD_STATUS, AVD_STOPPED)
+    self._execute_console_command_and_verify(CMD_AVD_START, util.OK)
+    self._execute_console_command_and_verify(CMD_AVD_STATUS, AVD_RUNNING)
 
-        for i in range(util.NUM_MAX_TRIALS):
-            print('execute command: %s, trial #%d' % (inspect.stack()[0][3], i))
+  def _execute_console_command_and_verify(self, command, expected_output):
+    """Executes emulator console command and verify the command output.
 
-            self.telnet.write(command)
-            time.sleep(util.CMD_WAIT_TIMEOUT_S)
+    Args:
+        command: Console command to be executed.
+        expected_output: The expected command output.
+    """
+    is_command_successful, output = util.execute_console_command(
+        self.telnet, command, expected_output)
 
-            output = util.parseOutput(self.telnet)
+    self.assert_cmd_successful(
+        is_command_successful, 'Failed to properly execute: %s' % command,
+        False, '', expected_output, output)
 
-            is_command_successful = util.patternMatchOutput(
-                output,
-                expected_output)
-
-            if is_command_successful:
-                break
-
-            time.sleep(util.TRIAL_WAIT_TIMEOUT_S)
-
-        self.assertCmdSuccessful(
-            is_command_successful,
-            'Failed to properly execute: %s' % command,
-            False,
-            '',
-            expected_output,
-            output)
 
 if __name__ == '__main__':
-    print('======= avd Test =======')
-    unittest.main()
+  print '======= avd Test ======='
+  unittest.main()
diff --git a/emu_test/test_console/testcase_base.py b/emu_test/test_console/testcase_base.py
index 744ce00..471ea34 100644
--- a/emu_test/test_console/testcase_base.py
+++ b/emu_test/test_console/testcase_base.py
@@ -1,62 +1,55 @@
-"""
+"""This class is a parent class for all subordniate "testcase_" classes.
+
 This class is a parent class for all subordniate "testcase_" classes such as
 testcase_battery.py, testcase_call.py, testcase_event.py, and testcaes_port.py.
 It uses telnetlib to connect to telnet in order to communicate with emulator.
-There is some sync problem or potential bug in emualtor, particularly observable when run on Windows machine:
+There is some sync problem or potential bug in emualtor, particularly observable
+when run on Windows machine:
 (https://code.google.com/p/android/issues/detail?id=220171)
-The issue was handled by giving timeout parameter to the read_until function of python telnetlib
-and give wait time of 0.5 after each write onto the telnet stream.
+The issue was handled by giving timeout parameter to the read_until function
+of python telnetlib and give wait time of 0.5 after each write onto the telnet
+stream.
 """
 
-import unittest
-import telnetlib
-from subprocess import check_output
-import subprocess
-import os
-from os.path import expanduser
-import utils.util as console_utils
-import time
 import inspect
+import sys
+import unittest
 
-TIMEOUT = 1
+from utils import util
+
 
 class BaseConsoleTest(unittest.TestCase):
-    def wait_on_windows(self):
-        if os.name == "nt":
-            time.sleep(0.5)
+  """This is the base clase for fall console test."""
 
-    def setUp(self):
-        home = expanduser("~")
-        token_path = os.path.join(home, ".emulator_console_auth_token")
-        with open(token_path) as f:
-            content = f.readlines()
-        auth_token = content[0]
-        self.telnet = telnetlib.Telnet("localhost", 5554)
-        if not console_utils.checkReadUntil(self.telnet.read_until("OK", TIMEOUT)):
-            sys.exit(-1)
-        self.telnet.write("auth " + auth_token + "\n")
-        self.wait_on_windows()
-        if not console_utils.checkReadUntil(self.telnet.read_until("OK", TIMEOUT)):
-            sys.exit(-1)
+  def setUp(self):
+    auth_token = util.get_auth_token()
+    self.telnet = util.telnet_emulator()
+    self.telnet.write('%s %s\n' % (util.AUTH, auth_token))
+    util.wait_on_windows()
+    if (not util.check_read_until(
+        self.telnet.read_until(util.OK, util.TIMEOUT_S))):
+      sys.exit(-1)
 
-    def tearDown(self):
-        self.telnet.write("exit\n")
-        self.wait_on_windows()
-        self.telnet.close()
+  def tearDown(self):
+    util.exit_emulator_console(self.telnet)
 
-    def assertCmdSuccessful(self, isCmdSuccessful, assertionMsg, hasStatus, status, expected, actual):
-        if hasStatus:
-            print "Test result: " + inspect.stack()[0][3] + " status matches " + status + " => " + str(isCmdSuccessful)
-        else:
-            print "Test result: " + inspect.stack()[0][3] + " => " + str(isCmdSuccessful)
-        if not isCmdSuccessful:
-            print "Expected output:"
-            print expected
-            print "Actual Output:"
-            print actual
-        self.assertTrue(isCmdSuccessful, assertionMsg)
+  def assert_cmd_successful(self, is_cmd_successful, assertion_msg, has_status,
+                            status, expected, actual):
+    if has_status:
+      print ('Test result: %s status matches %s => %s' %
+             (inspect.stack()[0][3], status, str(is_cmd_successful)))
+    else:
+      print ('Test result: %s => %s' %
+             (inspect.stack()[0][3], str(is_cmd_successful)))
+
+    if not is_cmd_successful:
+      print 'Expected output:'
+      print expected
+      print 'Actual Output:'
+      print actual
+    self.assertTrue(is_cmd_successful, assertion_msg)
 
 
 if __name__ == '__main__':
-    print "======= Base Console Test ======="
-    unittest.main()
+  print '======= Base Console Test ======='
+  unittest.main()
diff --git a/emu_test/test_console/testcase_battery.py b/emu_test/test_console/testcase_battery.py
index 322fdbe..9f408f8 100644
--- a/emu_test/test_console/testcase_battery.py
+++ b/emu_test/test_console/testcase_battery.py
@@ -1,12 +1,10 @@
-#!/usr/bin/env python
-
-"""Tests for battery-related commands"""
+"""Tests for battery-related commands."""
 
 import inspect
 import time
 import unittest
 
-from testcase_base import BaseConsoleTest
+import testcase_base
 from utils import util
 
 CMD_POWER_DISPLAY = 'power display\n'
@@ -20,386 +18,350 @@
 PRESENCE_ASSERT_MSG_PREFIX = 'Failed to set power presence to'
 HEATH_ASSERT_MSG_PREFIX = 'Failed to set power health to'
 REMAINING_75 = '75'
-CAPACITY_ASSERT_MSG_PREFIX = 'Failed to set remaining battery to %s' \
-                             % REMAINING_75
+CAPACITY_ASSERT_MSG_PREFIX = ('Failed to set remaining battery to %s'
+                              % REMAINING_75)
 
 
-class BatteryTest(BaseConsoleTest):
-    def _execute_command_and_verify(self, command, expected_output, assert_msg):
-        """Executes console command and verify output.
+class BatteryTest(testcase_base.BaseConsoleTest):
 
-        Args:
-            command: Console command to be executed.
-            expected_output: Expected console output.
-            assert_msg: Assertion message.
-        """
-        is_command_successful, output = \
-            util.execute_console_command(
-                self.telnet,
-                command,
-                expected_output)
+  def _execute_command_and_verify(self, command, expected_output, assert_msg):
+    """Executes console command and verify output.
 
-        self.assertCmdSuccessful(
-            is_command_successful,
-            assert_msg,
-            False,
-            '',
-            'Pattern: \n%s' % expected_output,
-            output)
+    Args:
+        command: Console command to be executed.
+        expected_output: Expected console output.
+        assert_msg: Assertion message.
+    """
+    is_command_successful, output = util.execute_console_command(
+        self.telnet, command, expected_output)
 
-    def _get_power_display(self):
-        """Gets the console output for 'power display' command.
+    self.assert_cmd_successful(is_command_successful, assert_msg, False, '',
+                               'Pattern: \n%s' % expected_output, output)
 
-        Returns:
-            output_pwr_display: The console output for 'power display' command.
-        """
-        self.telnet.write(CMD_POWER_DISPLAY)
-        time.sleep(util.CMD_WAIT_TIMEOUT_S)
-        output_pwr_display = util.parseOutput(self.telnet)
-        return output_pwr_display
+  def _get_power_display(self):
+    """Gets the console output for 'power display' command.
 
-    def _set_power_test(self, command_prefix, status, assert_msg, keyword):
-        """Sets the test scenario for power.
+    Returns:
+        output_pwr_display: The console output for 'power display' command.
+    """
+    self.telnet.write(CMD_POWER_DISPLAY)
+    time.sleep(util.CMD_WAIT_TIMEOUT_S)
+    output_pwr_display = util.parse_output(self.telnet)
+    return output_pwr_display
 
-        Args:
-            command_prefix: The sub command prefix for power.
-            status: The status to be set.
-            assert_msg: The assertion message.
-            keyword: Keyword used for searching in the console output.
-        """
-        is_command_successful, output = \
-            util.execute_console_command(
-                self.telnet,
-                '%s %s\n' % (command_prefix, status),
-                util.OK)
-        self.assertCmdSuccessful(
-            is_command_successful,
-            assert_msg,
-            False,
-            '',
-            'Pattern: \n%s' % util.OK,
-            output)
+  def _set_power_test(self, command_prefix, status, assert_msg, keyword):
+    """Sets the test scenario for power.
 
-        is_cmd_successful = False
-        for i in range(0, util.NUM_MAX_TRIALS):
-            print('Running test: %s, retrieve status %s, trial # %s'
-                  % (inspect.stack()[0][3], status, str(i + 1)))
-            output_pwr_display = self._get_power_display()
-            output_extracted = util.extractFieldFromOutput(
-                output_pwr_display,
-                keyword)
+    Args:
+        command_prefix: The sub command prefix for power.
+        status: The status to be set.
+        assert_msg: The assertion message.
+        keyword: Keyword used for searching in the console output.
+    """
+    is_command_successful, output = util.execute_console_command(
+        self.telnet, '%s %s\n' % (command_prefix, status), util.OK)
+    self.assert_cmd_successful(is_command_successful, assert_msg, False, '',
+                               'Pattern: \n%s' % util.OK, output)
 
-            if CMD_POWER_AC_PREFIX == command_prefix:
-                is_cmd_successful = (output_extracted == ('%sline' % status))
-            elif command_prefix in \
-                    (CMD_POWER_STATUS_PREFIX, CMD_POWER_HEALTH_PREFIX):
-                correct_output = util.checkBatteryStatus(status)
-                is_cmd_successful = (output_extracted == correct_output)
-            elif CMD_POWER_PRESENT_PREFIX == command_prefix:
-                is_cmd_successful = output_extracted
-            elif CMD_POWER_CAPACITY_PREFIX == command_prefix:
-                is_cmd_successful = (output_extracted == status)
-            else:
-                print('Un-handled command prefix: %s' % command_prefix)
+    is_cmd_successful = False
+    for i in range(util.NUM_MAX_TRIALS):
+      print ('Running: %s, retrieve status %s, trial # %s'
+             % (inspect.stack()[0][3], status, str(i + 1)))
+      output_pwr_display = self._get_power_display()
+      output_extracted = util.extract_field_from_output(
+          output_pwr_display, keyword)
 
-            if is_cmd_successful:
-                break
-            time.sleep(util.TRIAL_WAIT_TIMEOUT_S)
-        print('Test result: %s %s => %s'
-              % (inspect.stack()[0][3], status, str(is_cmd_successful)))
-        self.assertCmdSuccessful(
-            is_cmd_successful,
-            'Failed to retrieve power status as %s' % status,
-            True,
-            status,
-            '%s' % status,
-            output_extracted)
+      if CMD_POWER_AC_PREFIX == command_prefix:
+        is_cmd_successful = (output_extracted == ('%sline' % status))
+      elif (command_prefix in
+            (CMD_POWER_STATUS_PREFIX, CMD_POWER_HEALTH_PREFIX)):
+        correct_output = util.check_battery_status(status)
+        is_cmd_successful = (output_extracted == correct_output)
+      elif CMD_POWER_PRESENT_PREFIX == command_prefix:
+        is_cmd_successful = output_extracted
+      elif CMD_POWER_CAPACITY_PREFIX == command_prefix:
+        is_cmd_successful = (output_extracted == status)
+      else:
+        print 'Un-handled command prefix: %s' % command_prefix
 
-    def _set_battery_status(self, status):
-        assert_msg = '%s %s' % (STATUS_ASSERT_MSG_PREFIX, status)
-        self._set_power_test(CMD_POWER_STATUS_PREFIX,
-                             status,
-                             assert_msg,
-                             util.STATUS)
+      if is_cmd_successful:
+        break
+      time.sleep(util.TRIAL_WAIT_TIMEOUT_S)
+    print ('Test result: %s %s => %s'
+           % (inspect.stack()[0][3], status, str(is_cmd_successful)))
+    self.assert_cmd_successful(is_cmd_successful,
+                               'Failed to retrieve power status as %s' % status,
+                               True, status, '%s' % status, output_extracted)
 
-    def _set_presence_state(self, status):
-        assert_msg = '%s %s' % (PRESENCE_ASSERT_MSG_PREFIX, status)
-        self._set_power_test(CMD_POWER_PRESENT_PREFIX,
-                             status,
-                             assert_msg,
-                             util.PRESENT)
+  def _set_battery_status(self, status):
+    assert_msg = '%s %s' % (STATUS_ASSERT_MSG_PREFIX, status)
+    self._set_power_test(CMD_POWER_STATUS_PREFIX, status,
+                         assert_msg, util.STATUS)
 
-    def _set_health_state(self, status):
-        assert_msg = '%s %s' % (HEATH_ASSERT_MSG_PREFIX, status)
-        self._set_power_test(CMD_POWER_HEALTH_PREFIX,
-                             status,
-                             assert_msg,
-                             util.HEALTH)
+  def _set_presence_state(self, status):
+    assert_msg = '%s %s' % (PRESENCE_ASSERT_MSG_PREFIX, status)
+    self._set_power_test(CMD_POWER_PRESENT_PREFIX, status,
+                         assert_msg, util.PRESENT)
 
-    def test_power_display(self):
-        """
-        Test for command: power ac <on_or_off>
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power display, and verify 1
-        Verify:
-            1. Power details are displayed
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        assert_msg = 'Failed to properly display power details.'
-        self._execute_command_and_verify(CMD_POWER_DISPLAY,
-                                         util.REGEX_PWR_DISPLAY,
-                                         assert_msg)
+  def _set_health_state(self, status):
+    assert_msg = '%s %s' % (HEATH_ASSERT_MSG_PREFIX, status)
+    self._set_power_test(CMD_POWER_HEALTH_PREFIX, status,
+                         assert_msg, util.HEALTH)
 
-    def test_set_ac_charge_state(self):
-        """
-        Test for command: power ac <on_or_off>
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power ac on
-            6. Run: power display, and verify 1
-            7. Run: power ac off
-            8. Run: power display, and verify 2
-        Verify:
-            1. Emulator displays AC as online
-            2. Emulator displays AC as offline
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        assert_msg = 'Failed to properly display power details.'
-        self._set_power_test(CMD_POWER_AC_PREFIX,
-                             'on',
-                             assert_msg,
-                             util.AC)
-        self._set_power_test(CMD_POWER_AC_PREFIX,
-                             'off',
-                             assert_msg,
-                             util.AC)
+  def test_power_display(self):
+    """Test for command: power ac <on_or_off>.
 
-    def test_set_battery_status_to_unknown(self):
-        """
-        Test for command: power status unknown
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power status unknown, and verify 1
-        Verify:
-            1. Success to set power status to unknown
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._set_battery_status('unknown')
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power display, and verify 1
+    Verify:
+      1. Power details are displayed
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    assert_msg = 'Failed to properly display power details.'
+    self._execute_command_and_verify(CMD_POWER_DISPLAY, util.REGEX_PWR_DISPLAY,
+                                     assert_msg)
 
-    def test_set_battery_status_to_charging(self):
-        """
-        Test for command: power status charging
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power status charging, and verify 1
-        Verify:
-            1. Success to set power status to charging
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._set_battery_status('charging')
+  def test_set_ac_charge_state(self):
+    """Test for command: power ac <on_or_off>.
 
-    def test_set_battery_status_to_discharging(self):
-        """
-        Test for command: power status discharging
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power status discharging, and verify 1
-        Verify:
-            1. Success to set power status to discharging
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        status = 'discharging'
-        self._set_battery_status('charging')
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power ac on
+      6. Run: power display, and verify 1
+      7. Run: power ac off
+      8. Run: power display, and verify 2
+    Verify:
+      1. Emulator displays AC as online
+      2. Emulator displays AC as offline
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    assert_msg = 'Failed to properly display power details.'
+    self._set_power_test(CMD_POWER_AC_PREFIX, 'on', assert_msg, util.AC)
+    self._set_power_test(CMD_POWER_AC_PREFIX, 'off', assert_msg, util.AC)
 
-    def test_set_battery_status_to_not_charging(self):
-        """
-        Test for command: power status not-charging
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power status not-charging, and verify 1
-        Verify:
-            1. Success to set power status to not-charging
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._set_battery_status('not-charging')
+  def test_set_battery_status_to_unknown(self):
+    """Test for command: power status unknown.
 
-    def test_set_battery_status_to_full(self):
-        """
-        Test for command: power status full
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power status full, and verify 1
-        Verify:
-            1. Success to set power status to full
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._set_battery_status('full')
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power status unknown, and verify 1
+    Verify:
+      1. Success to set power status to unknown
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_battery_status('unknown')
 
-    def test_set_presence_state(self):
-        """
-        Test for command: power present <true_or_false>
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power present true, and verify 1
-            6. Run: power present false, and verify 2
-        Verify:
-            1. Success to set power presence to True
-            2. Success to set power presence to False
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._set_presence_state('true')
-        self._set_presence_state('false')
+  def test_set_battery_status_to_charging(self):
+    """Test for command: power status charging.
 
-    def test_set_battery_health_to_unknown(self):
-        """
-        Test for command: power health unknown
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power health unknown, and verify 1
-        Verify:
-            1. Success to set power health to unknown
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._set_health_state('unknown')
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power status charging, and verify 1
+    Verify:
+      1. Success to set power status to charging
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_battery_status('charging')
 
-    def test_set_battery_health_to_good(self):
-        """
-        Test for command: power health good
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power health good, and verify 1
-        Verify:
-            1. Success to set power health to good
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._set_health_state('good')
+  def test_set_battery_status_to_discharging(self):
+    """Test for command: power status discharging.
 
-    def test_set_battery_health_to_overheat(self):
-        """
-        Test for command: power health overheat
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power health overheat, and verify 1
-        Verify:
-            1. Success to set power health to overheat
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._set_health_state('overheat')
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power status discharging, and verify 1
+    Verify:
+      1. Success to set power status to discharging
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_battery_status('discharging')
 
-    def test_set_battery_health_to_dead(self):
-        """
-        Test for command: power health dead
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power health dead, and verify 1
-        Verify:
-            1. Success to set power health to dead
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._set_health_state('dead')
+  def test_set_battery_status_to_not_charging(self):
+    """Test for command: power status not-charging.
 
-    def test_set_battery_health_to_overvoltage(self):
-        """
-        Test for command: power health overvoltage
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power health overvoltage, and verify 1
-        Verify:
-            1. Success to set power health to overvoltage
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._set_health_state('overvoltage')
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power status not-charging, and verify 1
+    Verify:
+      1. Success to set power status to not-charging
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_battery_status('not-charging')
 
-    def test_set_battery_health_to_failure(self):
-        """
-        Test for command: power health failure
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power health failure, and verify 1
-        Verify:
-            1. Success to set power health to failure
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        self._set_health_state('failure')
+  def test_set_battery_status_to_full(self):
+    """Test for command: power status full.
 
-    def test_set_remaining_battery_capacity(self):
-        """
-        Test for command: power capacity 75
-        Test Rail ID: C14595300
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: power capacity 75, and verify 1
-        Verify:
-            1. Success to set power capacity to 75
-        """
-        print('Running test: %s' % (inspect.stack()[0][3]))
-        assert_msg = '%s %s' % (HEATH_ASSERT_MSG_PREFIX, REMAINING_75)
-        self._set_power_test(CMD_POWER_CAPACITY_PREFIX,
-                             REMAINING_75,
-                             assert_msg,
-                             util.CAPACITY)
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power status full, and verify 1
+    Verify:
+      1. Success to set power status to full
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_battery_status('full')
+
+  def test_set_presence_state(self):
+    """Test for command: power present <true_or_false>.
+
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power present true, and verify 1
+      6. Run: power present false, and verify 2
+    Verify:
+      1. Success to set power presence to True
+      2. Success to set power presence to False
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_presence_state('true')
+    self._set_presence_state('false')
+
+  def test_set_battery_health_to_unknown(self):
+    """Test for command: power health unknown.
+
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power health unknown, and verify 1
+    Verify:
+      1. Success to set power health to unknown
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_health_state('unknown')
+
+  def test_set_battery_health_to_good(self):
+    """Test for command: power health good.
+
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power health good, and verify 1
+    Verify:
+      1. Success to set power health to good
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_health_state('good')
+
+  def test_set_battery_health_to_overheat(self):
+    """Test for command: power health overheat.
+
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power health overheat, and verify 1
+    Verify:
+      1. Success to set power health to overheat
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_health_state('overheat')
+
+  def test_set_battery_health_to_dead(self):
+    """Test for command: power health dead.
+
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power health dead, and verify 1
+    Verify:
+      1. Success to set power health to dead
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_health_state('dead')
+
+  def test_set_battery_health_to_overvoltage(self):
+    """Test for command: power health overvoltage.
+
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power health overvoltage, and verify 1
+    Verify:
+      1. Success to set power health to overvoltage
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_health_state('overvoltage')
+
+  def test_set_battery_health_to_failure(self):
+    """Test for command: power health failure.
+
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power health failure, and verify 1
+    Verify:
+      1. Success to set power health to failure
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._set_health_state('failure')
+
+  def test_set_remaining_battery_capacity(self):
+    """Test for command: power capacity 75.
+
+    Test Rail ID: C14595300
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: power capacity 75, and verify 1
+    Verify:
+      1. Success to set power capacity to 75
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    assert_msg = '%s %s' % (HEATH_ASSERT_MSG_PREFIX, REMAINING_75)
+    self._set_power_test(CMD_POWER_CAPACITY_PREFIX, REMAINING_75,
+                         assert_msg, util.CAPACITY)
 
 
 if __name__ == '__main__':
-    print('======= Battery Test =======')
-    unittest.main()
+  print '======= Battery Test ======='
+  unittest.main()
diff --git a/emu_test/test_console/testcase_call.py b/emu_test/test_console/testcase_call.py
index ee106dd..1c1f48b 100644
--- a/emu_test/test_console/testcase_call.py
+++ b/emu_test/test_console/testcase_call.py
@@ -1,173 +1,158 @@
-"""
-Tests for call-related commands
-"""
+"""Tests for call-related commands."""
 
-import unittest
-import telnetlib
-from subprocess import check_output
-import utils.util as console_utils
-import subprocess
+import inspect
+import json
 import os
 import time
+import unittest
+
 import requests
-import json
-from os.path import expanduser
-import inspect
-from testcase_base import BaseConsoleTest
+import testcase_base
+from utils import util
 
 TESTCASE_CALL_DIR = os.path.dirname(os.path.realpath(__file__))
-SERVLET_TELEPHONY = "http://localhost:8080/TelephonyManagerService"
-
-SCRIPT_INSTALL_APK = TESTCASE_CALL_DIR + "/installAPK.sh"
-SCRIPT_RUN_ADB_SHELL = TESTCASE_CALL_DIR + "/runADBShell.sh"
-
-NUM_MAX_TRIALS = 3
-SETUP_WAIT_TIMEOUT = 5
-TRIAL_WAIT_TIMEOUT = 0.5
-CMD_WAIT_TIMEOUT = 3
+SERVLET_TELEPHONY = 'http://localhost:8080/TelephonyManagerService'
 
 CALL_STATE_IDLE = 0
 CALL_STATE_RINGING = 1
 CALL_STATE_OFFHOOK = 2
 
-CALL_NUMBER = "1234567890"
+CALL_NUMBER = '1234567890'
+CMD_GSM_CANCEL = 'gsm cancel %s\n' % CALL_NUMBER
+CMD_GSM_CALL = 'gsm call %s\n' % CALL_NUMBER
+CMD_GSM_ACCEPT = 'gsm accept %s\n' % CALL_NUMBER
 
-class PhoneCallTest(BaseConsoleTest):
 
-    @classmethod
-    def runScriptRunADBShell(cls):
-        proc_installAPK = subprocess.Popen(["python", TESTCASE_CALL_DIR + "/runADBShell.py"])
-        return proc_installAPK
+class PhoneCallTest(testcase_base.BaseConsoleTest):
+  """This class aims to test call-related emulator console commands."""
 
-    @classmethod
-    def setUpClass(cls):
-        res_portRedirect = subprocess.call(["adb", "-s", "emulator-5554", "-e", "forward", "tcp:8080", "tcp:8081"])
-        res_runInstallAPKScript = subprocess.call(["python", TESTCASE_CALL_DIR + "/installAPK.py"])
-        cls.runScriptRunADBShell()
-        time.sleep(SETUP_WAIT_TIMEOUT)
+  @classmethod
+  def setUpClass(cls):
+    util.run_script_run_adb_shell(TESTCASE_CALL_DIR)
 
-    def processRequestTelephonyService(self, payload):
-        r = requests.post(SERVLET_TELEPHONY, data=json.dumps(payload))
-        if r.raise_for_status():
-            print "Servlet Error: Post request to " + SERVLET_TELEPHONY + " failed"
-            return False
-        r_json = r.json()
-        if r_json["isFail"]:
-            print "Servlet Error: Failure occurred in servlet side => " + SERVLET_TELEPHONY
-            return False
-        return int(r_json["description"])
+  def _process_request_telephony_service(self, payload):
+    r = requests.post(SERVLET_TELEPHONY, data=json.dumps(payload))
+    if r.raise_for_status():
+      print ('Servlet Error: Post request to %s failed' %
+             SERVLET_TELEPHONY)
+      return False
+    r_json = r.json()
+    if r_json['isFail']:
+      print ('Servlet Error: Failure occurred in servlet side => %s' %
+             SERVLET_TELEPHONY)
+      return False
+    call_state = int(r_json['description'])
+    print 'call_state = %d' % call_state
+    return call_state
 
-    def cancel_inbound_call(self):
-        self.telnet.write("gsm cancel " + CALL_NUMBER + "\n")
-        time.sleep(CMD_WAIT_TIMEOUT)
+  def _cancel_inbound_call(self):
+    self.telnet.write(CMD_GSM_CANCEL)
+    time.sleep(util.CMD_WAIT_TIMEOUT_S)
 
-    def cancel_inbound_call_verification(self):
-        isCmdSuccessful = True
-        for i in range(0, NUM_MAX_TRIALS):
-            print "Running test: " + inspect.stack()[0][3] + ", trial #" + str(i+1)
-            self.telnet.write("gsm cancel " + CALL_NUMBER + "\n")
-            time.sleep(CMD_WAIT_TIMEOUT)
-            output_cancel_inbound = console_utils.parseOutput(self.telnet)
-            isCmdSuccessful = (output_cancel_inbound == console_utils.OK)
-            if isCmdSuccessful:
-                break
-            time.sleep(TRIAL_WAIT_TIMEOUT)
-        self.assertCmdSuccessful(isCmdSuccessful, "Failed to properly cancel an inbound call", False, "", console_utils.OK, output_cancel_inbound)
-        self.assertTrue(self.processRequestTelephonyService({}) == CALL_STATE_IDLE, "Call state idle not matched")
-        time.sleep(CMD_WAIT_TIMEOUT)
+  def _cancel_inbound_call_verification(self):
+    is_cmd_successful, output_cancel_inbound = util.execute_console_command(
+        self.telnet, CMD_GSM_CANCEL, util.OK)
 
-    def make_inbound_call(self):
-        self.assertTrue(self.processRequestTelephonyService({}) == CALL_STATE_IDLE, "Call state idle not matched")
-        isCmdSuccessful = True
-        for i in range(0, NUM_MAX_TRIALS):
-            print "Running test: " + inspect.stack()[0][3] + ", trial #" + str(i+1)
-            self.telnet.write("gsm call " + CALL_NUMBER +"\n")
-            time.sleep(CMD_WAIT_TIMEOUT)
-            output_inbound_call = console_utils.parseOutput(self.telnet)
-            isCmdSuccessful = (output_inbound_call == console_utils.OK)
-            if isCmdSuccessful:
-                break
-            time.sleep(TRIAL_WAIT_TIMEOUT)
-        self.assertCmdSuccessful(isCmdSuccessful, "Failed to properly set up an inbound call", False, "", console_utils.OK, output_inbound_call)
-        self.assertTrue(self.processRequestTelephonyService({}) == CALL_STATE_RINGING, "Call state ringing not matched")
-        time.sleep(CMD_WAIT_TIMEOUT)
+    self.assert_cmd_successful(is_cmd_successful,
+                               'Failed to properly cancel an inbound call',
+                               False, '', util.OK, output_cancel_inbound)
+    self.assertTrue(
+        self._process_request_telephony_service({}) == CALL_STATE_IDLE,
+        'Call state idle not matched')
+    time.sleep(util.CMD_WAIT_TIMEOUT_S)
 
-    def accept_inbound_call(self):
-        isCmdSuccessful = True
-        for i in range(0, NUM_MAX_TRIALS):
-            print "Running test: " + inspect.stack()[0][3] + ", trial #" + str(i+1)
-            self.telnet.write("gsm accept " + CALL_NUMBER + "\n")
-            time.sleep(CMD_WAIT_TIMEOUT)
-            output_accept_inbound = console_utils.parseOutput(self.telnet)
-            isCmdSuccessful = (output_accept_inbound == console_utils.OK)
-            if isCmdSuccessful:
-                break
-            time.sleep(TRIAL_WAIT_TIMEOUT)
-        self.assertCmdSuccessful(isCmdSuccessful, "Failed to properly accept an inbound call", False, "", console_utils.OK, output_accept_inbound)
-        self.assertTrue(self.processRequestTelephonyService({}) == CALL_STATE_OFFHOOK, "Call state offhook not matched")
-        time.sleep(CMD_WAIT_TIMEOUT)
+  def _make_inbound_call(self):
+    self.assertTrue(
+        self._process_request_telephony_service({}) == CALL_STATE_IDLE,
+        'Call state idle not matched')
 
-    def test_inboundCall(self):
-        """
-        Test for command: gsm call <phonenumber>
-        Test Rail ID: C14595296
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: gsm call <phonenumber>, verify 1
-            6. Run: gsm cancel <phonenumber>, verify 2
-        Verify:
-            1. Emulator displays an incoming call from the <phonenumber>
-            2. Phone call is terminated.
-        """
-        self.make_inbound_call()
-        self.cancel_inbound_call()
+    is_cmd_successful, output_inbound_call = util.execute_console_command(
+        self.telnet, CMD_GSM_CALL, util.OK)
 
-    def test_acceptCall(self):
-        """
-        Test for command: gsm accept <phonenumber>
-        Test Rail ID: C14595296
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: gsm call <phonenumber>, verify 1
-            5. Run: gsm accept <phonenumber>, verify 2
-            6. Run: gsm cancel <phonenumber>
-        Verify:
-            1. Emulator displays an incoming call from the <phonenumber>
-            2. Emulator displays that the incoming call is accepted
-        """
-        self.make_inbound_call()
-        self.accept_inbound_call()
-        self.cancel_inbound_call()
+    self.assert_cmd_successful(is_cmd_successful,
+                               'Failed to properly set up an inbound call',
+                               False, '', util.OK, output_inbound_call)
 
-    def test_terminateCall(self):
-        """
-        Test for command: gsm cancel <phonenumber>
-        Test Rail ID: C14595296
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: gsm call <phonenumber>, verify 1
-            6. Run: gsm accept <phonenumber>, verify 2
-            7. Run: gsm cancel <phonenumber>, verify 3
-        Verify:
-            1. Emulator displays an incoming call from the <phonenumber>
-            2. Emulator displays that the incoming call is accepted
-            3. Phone call is terminated. The emulator displays the phone
-               hang-up icon in the notification bar.
-        """
-        self.make_inbound_call()
-        self.accept_inbound_call()
-        self.cancel_inbound_call_verification()
+    self.assertTrue(
+        self._process_request_telephony_service({}) == CALL_STATE_RINGING,
+        'Call state ringing not matched')
+    time.sleep(util.CMD_WAIT_TIMEOUT_S)
+
+  def _accept_inbound_call(self):
+    is_cmd_successful, output_accept_inbound = util.execute_console_command(
+        self.telnet, CMD_GSM_ACCEPT, util.OK)
+    self.assert_cmd_successful(is_cmd_successful,
+                               'Failed to properly accept an inbound call',
+                               False, '', util.OK, output_accept_inbound)
+    self.assertTrue(
+        self._process_request_telephony_service({}) == CALL_STATE_OFFHOOK,
+        'Call state offhook not matched')
+    time.sleep(util.CMD_WAIT_TIMEOUT_S)
+
+  def test_inbound_call(self):
+    """Test for command: gsm call <phonenumber>.
+
+    Test Rail ID: C14595296
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: gsm call <phonenumber>, verify 1
+      6. Run: gsm cancel <phonenumber>, verify 2
+    Verify:
+      1. Emulator displays an incoming call from the <phonenumber>
+      2. Phone call is terminated.
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._make_inbound_call()
+    self._cancel_inbound_call()
+
+  def test_accept_call(self):
+    """Test for command: gsm accept <phonenumber>.
+
+    Test Rail ID: C14595296
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: gsm call <phonenumber>, verify 1
+      6. Run: gsm accept <phonenumber>, verify 2
+      7. Run: gsm cancel <phonenumber>
+    Verify:
+      1. Emulator displays an incoming call from the <phonenumber>
+      2. Emulator displays that the incoming call is accepted
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._make_inbound_call()
+    self._accept_inbound_call()
+    self._cancel_inbound_call()
+
+  def test_terminate_call(self):
+    """Test for command: gsm cancel <phonenumber>.
+
+    Test Rail ID: C14595296
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: gsm call <phonenumber>, verify 1
+      6. Run: gsm accept <phonenumber>, verify 2
+      7. Run: gsm cancel <phonenumber>, verify 3
+    Verify:
+      1. Emulator displays an incoming call from the <phonenumber>
+      2. Emulator displays that the incoming call is accepted
+      3. Phone call is terminated. The emulator displays the phone
+         hang-up icon in the notification bar.
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._make_inbound_call()
+    self._accept_inbound_call()
+    self._cancel_inbound_call_verification()
 
 
 if __name__ == '__main__':
-    print "======= Call Test ======="
-    unittest.main()
+  print '======= Call Test ======='
+  unittest.main()
diff --git a/emu_test/test_console/testcase_event.py b/emu_test/test_console/testcase_event.py
index c7f3f0a..1d569c9 100644
--- a/emu_test/test_console/testcase_event.py
+++ b/emu_test/test_console/testcase_event.py
@@ -1,118 +1,144 @@
-"""
-Tests for event-related commands
-"""
+"""Tests for event-related commands."""
 
-import unittest
-import telnetlib
-from subprocess import check_output
-import subprocess
-import utils.util as console_utils
-import time
 import inspect
-from testcase_base import BaseConsoleTest
+import time
+import unittest
 
-NUM_MAX_TRIALS = 3
-TRIAL_WAIT_TIMEOUT = 0.5
-CMD_WAIT_TIMEOUT = 0.5
+import testcase_base
+from utils import util
 
-class EventTest(BaseConsoleTest):
+EVENT = 'event'
+CMD_EVENT_TYPES = '%s types\n' % EVENT
+CMD_EVENT_CODES_PRE = '%s codes' % EVENT
+CMD_EVENT_CODES_EV_SYN = '%s EV_SYN\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_MSC = '%s EV_MSC\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_SW = '%s EV_SW\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_LED = '%s EV_LED\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_SND = '%s EV_SND\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_REP = '%s EV_REP\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_FF = '%s EV_FF\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_PWR = '%s EV_PWR\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_FF_STATUS = '%s EV_FF_STATUS\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_MAX = '%s EV_MAX\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_KEY = '%s EV_KEY\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_REL = '%s EV_REL\n' % CMD_EVENT_CODES_PRE
+CMD_EVENT_CODES_EV_ABS = '%s EV_ABS\n' % CMD_EVENT_CODES_PRE
 
-    def test_listEventAliases(self):
-        """
-        Test for command: event types
-        Test Rail ID: C14595360
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: event types
-            6. verify 1
-        Verify:
-            1. Available event types are listed
-        """
-        isCmdSuccessful = True
-        for i in range(0, NUM_MAX_TRIALS):
-            print "Running test: " + inspect.stack()[0][3] + ", trial #" + str(i+1)
-            self.telnet.write("event types\n")
-            time.sleep(CMD_WAIT_TIMEOUT)
-            output_event_aliases = console_utils.removeAllSpaces(console_utils.parseOutputForEV(self.telnet))
-            correct_output = console_utils.removeAllSpaces(console_utils.readStringFromFile(console_utils.EVENTS_EV_TYPES_FILENAME))
-            isCmdSuccessful = (output_event_aliases == correct_output)
-            if isCmdSuccessful:
-                break
-            time.sleep(TRIAL_WAIT_TIMEOUT)
-        self.assertCmdSuccessful(isCmdSuccessful, "Listing all aliases of events failed", False, "", correct_output, output_event_aliases)
 
-    def verifyEventsNoAlias(self, command):
-        isCmdSuccessful = True
-        for i in range(0, NUM_MAX_TRIALS):
-            print "Running test: " + inspect.stack()[0][3] + " " + command.strip() + ", trial #" + str(i+1)
-            self.telnet.write(command)
-            time.sleep(CMD_WAIT_TIMEOUT)
-            output_event_listAll = console_utils.parseOutput(self.telnet)
-            isCmdSuccessful = (output_event_listAll == console_utils.EVENTS_CODE_NO_ALIAS)
-            if isCmdSuccessful:
-                break
-            time.sleep(TRIAL_WAIT_TIMEOUT)
-        self.assertCmdSuccessful(isCmdSuccessful, "test_listAllCodeAliases failed, output mismatch: fail to run " + command + " properly", False, "", console_utils.EVENTS_CODE_NO_ALIAS, output_event_listAll)
+class EventTest(testcase_base.BaseConsoleTest):
+  """This class aims to test event-related emulator console commands."""
 
-    def verifyAllEventsNoAlias(self):
-        self.verifyEventsNoAlias("event codes EV_SYN\n")
-        self.verifyEventsNoAlias("event codes EV_MSC\n")
-        self.verifyEventsNoAlias("event codes EV_SW\n")
-        self.verifyEventsNoAlias("event codes EV_LED\n")
-        self.verifyEventsNoAlias("event codes EV_SND\n")
-        self.verifyEventsNoAlias("event codes EV_REP\n")
-        self.verifyEventsNoAlias("event codes EV_FF\n")
-        self.verifyEventsNoAlias("event codes EV_PWR\n")
-        self.verifyEventsNoAlias("event codes EV_FF_STATUS\n")
-        self.verifyEventsNoAlias("event codes EV_MAX\n")
+  def _verify_events_no_alias(self, command):
+    is_cmd_successful, output_event_list_all = util.execute_console_command(
+        self.telnet, command, util.EVENTS_CODE_NO_ALIAS)
 
-    def verifyEventCodes(self, command, filename):
-        isCmdSuccessful = True
-        for i in range(0, NUM_MAX_TRIALS):
-            print "Running test: " + inspect.stack()[0][3] + " " + command.strip() + " verified against " + filename.strip() + ", trial #" + str(i+1)
-            self.telnet.write(command)
-            time.sleep(CMD_WAIT_TIMEOUT)
-            output_event_listAll = console_utils.removeAllSpaces(console_utils.parseOutputForEV(self.telnet))
-            correct_output = console_utils.removeAllSpaces(console_utils.readStringFromFile(filename))
-            isCmdSuccessful = (output_event_listAll == correct_output)
-            if isCmdSuccessful:
-                break
-            time.sleep(TRIAL_WAIT_TIMEOUT)
-        self.assertCmdSuccessful(isCmdSuccessful, "test_listAllCodeAliases failed, output mismatch: fail to run " + command + " properly", False, "", correct_output, output_event_listAll)
+    self.assert_cmd_successful(
+        is_cmd_successful,
+        'output mismatch: fail to run %s properly' % command,
+        False, '', util.EVENTS_CODE_NO_ALIAS, output_event_list_all)
 
-    def verifyAllEventCodes(self):
-        self.verifyEventCodes("event codes EV_KEY\n", console_utils.EVENTS_CODE_EV_KEY_FILENAME)
-        self.verifyEventCodes("event codes EV_REL\n", console_utils.EVENTS_CODE_EV_REL_FILENAME)
-        self.verifyEventCodes("event codes EV_ABS\n", console_utils.EVENTS_CODE_EV_ABS_FILENAME)
+  def _verify_all_events_no_allias(self):
+    self._verify_events_no_alias(CMD_EVENT_CODES_EV_SYN)
+    self._verify_events_no_alias(CMD_EVENT_CODES_EV_MSC)
+    self._verify_events_no_alias(CMD_EVENT_CODES_EV_SW)
+    self._verify_events_no_alias(CMD_EVENT_CODES_EV_LED)
+    self._verify_events_no_alias(CMD_EVENT_CODES_EV_SND)
+    self._verify_events_no_alias(CMD_EVENT_CODES_EV_REP)
+    self._verify_events_no_alias(CMD_EVENT_CODES_EV_FF)
+    self._verify_events_no_alias(CMD_EVENT_CODES_EV_PWR)
+    self._verify_events_no_alias(CMD_EVENT_CODES_EV_FF_STATUS)
+    self._verify_events_no_alias(CMD_EVENT_CODES_EV_MAX)
 
-    def test_listAllCodeAliases(self):
-        """
-        Test for command: event codes <type>" (for example: event codes EV_REL)
-        Test Rail ID: C14595360
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run several "event codes <type>" commands
-            6. verify 1
-        Verify:
-            1. Available event code alias for the selected type are listed
-        """
-        self.verifyAllEventCodes()
-        self.verifyAllEventsNoAlias()
+  def _verify_event_codes(self, command, filename):
+    is_cmd_successful = False
+    for i in range(util.NUM_MAX_TRIALS):
+      print ('Running: %s verified against %s, trial #%s' %
+             (inspect.stack()[0][3], filename.strip(), str(i + 1)))
+      self.telnet.write(command)
+      time.sleep(util.CMD_WAIT_TIMEOUT_S)
+      output_event_list_all = util.remove_all_spaces(
+          util.parse_output_for_ev(self.telnet))
+      correct_output = util.remove_all_spaces(
+          util.read_string_from_file(filename))
+      is_cmd_successful = (output_event_list_all == correct_output)
+      if is_cmd_successful:
+        break
+      time.sleep(util.TRIAL_WAIT_TIMEOUT_S)
+    self.assert_cmd_successful(
+        is_cmd_successful, 'output mismatch: fail to run %s properly' % command,
+        False, '', correct_output, output_event_list_all)
 
-    def test_simulateKeyPresses(self):
-        """
-        Test for command: event text <message>
-        """
-        # b/204884
-        pass
+  def _verify_all_event_codes(self):
+    self._verify_event_codes(CMD_EVENT_CODES_EV_KEY,
+                             util.EVENTS_CODE_EV_KEY_FILENAME)
+    self._verify_event_codes(CMD_EVENT_CODES_EV_REL,
+                             util.EVENTS_CODE_EV_REL_FILENAME)
+    self._verify_event_codes(CMD_EVENT_CODES_EV_ABS,
+                             util.EVENTS_CODE_EV_ABS_FILENAME)
+
+  def test_list_event_aliases(self):
+    """Test for command: event types.
+
+    Test Rail ID: C14595360
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: event types
+      6. verify 1
+    Verify:
+      1. Available event types are listed
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    is_cmd_successful = False
+    for i in range(util.NUM_MAX_TRIALS):
+      print ('Running: %s, trial #%s' %
+             (inspect.stack()[0][3], str(i + 1)))
+      self.telnet.write(CMD_EVENT_TYPES)
+      time.sleep(util.CMD_WAIT_TIMEOUT_S)
+      output_event_aliases = util.remove_all_spaces(
+          util.parse_output_for_ev(self.telnet))
+      correct_output = util.remove_all_spaces(
+          util.read_string_from_file(util.EVENTS_EV_TYPES_FILENAME))
+      is_cmd_successful = (output_event_aliases == correct_output)
+
+      if is_cmd_successful:
+        break
+      time.sleep(util.TRIAL_WAIT_TIMEOUT_S)
+
+    self.assert_cmd_successful(
+        is_cmd_successful, 'Listing all aliases of events failed',
+        False, '', correct_output, output_event_aliases)
+
+  def test_list_all_code_aliases(self):
+    """Test for command: event codes <type>" (for example: event codes EV_REL).
+
+    Test Rail ID: C14595360
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run several "event codes <type>" commands
+      6. verify 1
+    Verify:
+      1. Available event code alias for the selected type are listed
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._verify_all_event_codes()
+    self._verify_all_events_no_allias()
+
+  def test_simulate_key_presses(self):
+    """Test for command: event text <message>.
+
+    Test Rail ID: C14595360
+    """
+    # b/204884
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    pass
 
 
 if __name__ == '__main__':
-    print "======= Event Test ======="
-    unittest.main()
+  print '======= Event Test ======='
+  unittest.main()
diff --git a/emu_test/test_console/testcase_help.py b/emu_test/test_console/testcase_help.py
index ddfdf2f..d7c177e 100644
--- a/emu_test/test_console/testcase_help.py
+++ b/emu_test/test_console/testcase_help.py
@@ -1,85 +1,70 @@
-#!/usr/bin/env python
-
 """Test for help-related commands."""
 
-import os
+import inspect
 import sys
 import telnetlib
 import unittest
 
+import testcase_base
 from utils import util
-from os.path import expanduser
-from testcase_base import BaseConsoleTest
 
 
-class HelpTest(BaseConsoleTest):
-    """This class aims to test help-related emulator console commands."""
+class HelpTest(testcase_base.BaseConsoleTest):
+  """This class aims to test help-related emulator console commands."""
 
-    def setUp(self):
-        """Only telnet to emulator, initially not need to run auth command."""
-        self.telnet = telnetlib.Telnet(util.SERVER_NAME,
-                                       util.CONSOLE_PORT)
-        if not util.checkReadUntil(
-                self.telnet.read_until(util.OK,
-                                       util.TIMEOUT_S)):
-            sys.exit(-1)
+  def setUp(self):
+    """Only telnet to emulator, initially not need to run auth command."""
+    self.telnet = telnetlib.Telnet(util.SERVER_NAME, util.CONSOLE_PORT)
+    if not util.check_read_until(
+        self.telnet.read_until(util.OK, util.TIMEOUT_S)):
+      sys.exit(-1)
 
-    def _help_command(self, expected_output):
-        """Executes help command and verifies output.
+  def _help_command(self, expected_output):
+    """Executes help command and verifies output.
 
-        Args:
-            expected_output: Expected console output for help commands.
-        """
-        is_command_successful, output = \
-            util.execute_console_command(
-                self.telnet,
-                util.CMD_HELP,
-                expected_output)
+    Args:
+        expected_output: Expected console output for help commands.
+    """
+    is_command_successful, output = util.execute_console_command(
+        self.telnet, util.CMD_HELP, expected_output)
 
-        self.assertCmdSuccessful(
-            is_command_successful,
-            'Failed to properly list all command options.',
-            False,
-            '',
-            'Pattern: \n%s' % expected_output,
-            output)
+    self.assert_cmd_successful(
+        is_command_successful,
+        'Failed to properly list all command options.',
+        False, '', 'Pattern: \n%s' % expected_output, output)
 
-    def _auth_user_for_emulator_console(self):
-        """Authorization user."""
-        home = expanduser('~')
-        token_path = os.path.join(home,
-                                  util.CONSOLE_AUTH_TOKEN_FILE_NAME)
-        with open(token_path) as f:
-            content = f.readlines()
-        auth_token = content[0]
-        cmd_auth = 'auth %s\n' % (auth_token)
-        self.telnet.write(cmd_auth)
-        self.wait_on_windows()
-        if not util.checkReadUntil(
-                self.telnet.read_until(util.OK,
-                                       util.TIMEOUT_S)):
-            sys.exit(-1)
+  def _auth_user_for_emulator_console(self):
+    """Authorization user."""
+    auth_token = util.get_auth_token()
+    self.telnet = util.telnet_emulator()
+    self.telnet.write('%s %s\n' % (util.AUTH, auth_token))
+    util.wait_on_windows()
+    if (not util.check_read_until(
+        self.telnet.read_until(util.OK, util.TIMEOUT_S))):
+      sys.exit(-1)
 
-    def test_help_command(self):
-        """
-        Test command for: help
-        Test Rail ID: C14578962
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Run: help, and verify 1
-            4. Copy the auth_token value from ~/.emulator_console_auth_token
-            5. Run: auth auth_token
-            6. Run: help, and verify 2
-        Verify:
-            1. help, auth, avd and quit/exit commands are available
-            2. crash, kill, redir, power, event, avd ,finger, geo, sms, cdma,
-               gsm and rotate commands are available
-        """
-        self._help_command(util.REGEX_HELP_DISPLAY_NO_AUTH)
-        self._auth_user_for_emulator_console()
-        self._help_command(util.REGEX_HELP_DISPLAY_AUTH)
+  def test_help_command(self):
+    """Test command for: help.
+
+    Test Rail ID: C14578962
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Run: help, and verify 1
+      4. Copy the auth_token value from ~/.emulator_console_auth_token
+      5. Run: auth auth_token
+      6. Run: help, and verify 2
+    Verify:
+      1. help, auth, avd and quit/exit commands are available
+      2. crash, kill, redir, power, event, avd ,finger, geo, sms, cdma,
+         gsm and rotate commands are available
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._help_command(util.REGEX_HELP_DISPLAY_NO_AUTH)
+    self._auth_user_for_emulator_console()
+    self._help_command(util.REGEX_HELP_DISPLAY_AUTH)
+
 
 if __name__ == '__main__':
-    print('======= help Test =======')
-    unittest.main()
+  print '======= help Test ======='
+  unittest.main()
diff --git a/emu_test/test_console/testcase_port.py b/emu_test/test_console/testcase_port.py
index 0fe73a1..aec591c 100644
--- a/emu_test/test_console/testcase_port.py
+++ b/emu_test/test_console/testcase_port.py
@@ -1,132 +1,103 @@
-"""
-Tests for port-related commands
-"""
+"""Tests for port-related commands."""
 
-import unittest
-import utils.util as console_utils
-import time
 import inspect
-from testcase_base import BaseConsoleTest
+import time
+import unittest
 
-NUM_MAX_TRIALS = 3
-TRIAL_WAIT_TIMEOUT = 0.5
-CMD_WAIT_TIMEOUT = 0.5
+import testcase_base
+from utils import util
 
-EMULATOR_PORT = "5554"
-HOST_PORT = "5556"
+EMULATOR_PORT = '5554'
+HOST_PORT = '5556'
 
-CMD_REDIR_LIST = "redir list\n"
-CMD_REDIR_ADD = "redir add tcp:%s:%s\n" % (HOST_PORT, EMULATOR_PORT)
-CMD_REDIR_DEL = "redir del tcp:%s\n" % (HOST_PORT)
+CMD_REDIR_LIST = 'redir list\n'
+CMD_REDIR_ADD = 'redir add tcp:%s:%s\n' % (HOST_PORT, EMULATOR_PORT)
+CMD_REDIR_DEL = 'redir del tcp:%s\n' % HOST_PORT
 
 
-class PortTest(BaseConsoleTest):
+class PortTest(testcase_base.BaseConsoleTest):
+  """This class aims to test redir-related emulator console commands."""
 
-    def _list_redir_cmd(self):
-        is_cmd_succ = False
+  def _list_redir_cmd(self):
+    is_cmd_succ, output_redir_list = util.execute_console_command(
+        self.telnet, CMD_REDIR_LIST, util.PORT_NO_REDIR)
+    self.assert_cmd_successful(
+        is_cmd_succ, 'Failed to properly list port redirection.',
+        False, '', util.PORT_NO_REDIR, output_redir_list)
+    return output_redir_list
 
-        for i in range(NUM_MAX_TRIALS):
-            print("Running %s,  trial #%s" %
-                  (inspect.stack()[0][3], str(i + 1)))
-            self.telnet.write(CMD_REDIR_LIST)
-            time.sleep(CMD_WAIT_TIMEOUT)
-            output_redir_list = console_utils.parseOutput(self.telnet)
-            is_cmd_succ = (output_redir_list == console_utils.PORT_NO_REDIR)
+  def _add_port_redir_cmd(self):
+    is_cmd_succ = False
 
-            if is_cmd_succ:
-                break
+    for i in range(util.NUM_MAX_TRIALS):
+      print ('Running %s, trial #%s' %
+             (inspect.stack()[0][3], str(i + 1)))
 
-            time.sleep(TRIAL_WAIT_TIMEOUT)
+      self.telnet.write(CMD_REDIR_ADD)
+      time.sleep(util.CMD_WAIT_TIMEOUT_S)
+      output_redir_add = util.parse_output(self.telnet)
+      assert output_redir_add == util.OK
 
-        self.assertCmdSuccessful(
-            is_cmd_succ,
-            "Failed to properly list port redirection.",
-            False,
-            "",
-            console_utils.PORT_NO_REDIR, output_redir_list)
+      self.telnet.write(CMD_REDIR_LIST)
+      time.sleep(util.CMD_WAIT_TIMEOUT_S)
+      output_redir_list = util.parse_output(self.telnet)
 
-        return output_redir_list
+      is_cmd_succ = (output_redir_list == util.PORT_REDIR_ADD)
 
-    def _add_port_redir_cmd(self):
-        is_cmd_succ = False
+      if is_cmd_succ:
+        break
 
-        for i in range(NUM_MAX_TRIALS):
-            print("Running %s, trial #%s" %
-                  (inspect.stack()[0][3], str(i + 1)))
+      time.sleep(util.TRIAL_WAIT_TIMEOUT)
 
-            self.telnet.write(CMD_REDIR_ADD)
-            time.sleep(CMD_WAIT_TIMEOUT)
-            output_redir_add = console_utils.parseOutput(self.telnet)
-            assert output_redir_add == console_utils.OK
+    self.assert_cmd_successful(
+        is_cmd_succ, 'Failed to properly add a new port redirection',
+        False, '', util.PORT_REDIR_ADD, output_redir_add)
 
-            self.telnet.write(CMD_REDIR_LIST)
-            time.sleep(CMD_WAIT_TIMEOUT)
-            output_redir_list = console_utils.parseOutput(self.telnet)
+  def _del_port_redir_cmd(self):
+    is_cmd_succ = False
 
-            is_cmd_succ = (output_redir_list == console_utils.PORT_REDIR_ADD)
+    for i in range(util.NUM_MAX_TRIALS):
+      print ('Running : %s, trial #%s' %
+             (inspect.stack()[0][3], str(i + 1)))
 
-            if is_cmd_succ:
-                break
+      self.telnet.write(CMD_REDIR_DEL)
+      time.sleep(util.CMD_WAIT_TIMEOUT_S)
+      output_redir_del = util.parse_output(self.telnet)
+      assert output_redir_del == util.OK
 
-            time.sleep(TRIAL_WAIT_TIMEOUT)
+      is_cmd_succ = (self._list_redir_cmd() == util.PORT_NO_REDIR)
 
-        self.assertCmdSuccessful(
-            is_cmd_succ,
-            "Failed to properly add a new port redirection",
-            False,
-            "",
-            console_utils.PORT_REDIR_ADD,
-            output_redir_add)
+      if is_cmd_succ:
+        break
 
-    def _del_port_redir_cmd(self):
-        is_cmd_succ = False
+      time.sleep(util.TRIAL_WAIT_TIMEOUT_S)
 
-        for i in range(NUM_MAX_TRIALS):
-            print("Running : %s, trial #%s" %
-                  (inspect.stack()[0][3], str(i+1)))
+    self.assert_cmd_successful(
+        is_cmd_succ, 'Failed to properly delete a port redirection',
+        False, '', util.OK, output_redir_del)
 
-            self.telnet.write(CMD_REDIR_DEL)
-            time.sleep(CMD_WAIT_TIMEOUT)
-            output_redir_del = console_utils.parseOutput(self.telnet)
-            assert output_redir_del == console_utils.OK
+  def test_list_port_redir(self):
+    """Test for command: redir list.
 
-            is_cmd_succ = (self._list_redir_cmd() == console_utils.PORT_NO_REDIR)
+    TR ID: C14594979
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._list_redir_cmd()
 
-            if is_cmd_succ:
-                break
+  def test_add_new_port_and_delete_port_redir(self):
+    """Test for commands: redir.
 
-            time.sleep(TRIAL_WAIT_TIMEOUT)
-
-        self.assertCmdSuccessful(
-            is_cmd_succ,
-            "Failed to properly delete a port redirection",
-            False,
-            "",
-            console_utils.OK,
-            output_redir_del)
-
-    def test_list_port_redir(self):
-        """
-        Test for command: redir list
-        TR ID: C14594979
-        """
-        print("Running test: %s" % (inspect.stack()[0][3]))
-        self._list_redir_cmd()
-
-    def test_add_new_port_and_delete_port_redir(self):
-        """
-        Test for commands: redir add <tcp_or_udp>:<5556>:<port_of_emulator>
-                           redir def <tcp_or_udp>:<5556>
-        TR ID: C14594979
-        b/210442:
-            command "redir del" doesn't work on API 23/24 on Windows; but Linux.
-        """
-
-        print("Running test: %s" % (inspect.stack()[0][3]))
-        self._add_port_redir_cmd()
-        self._del_port_redir_cmd()
+    redir add <tcp_or_udp>:<5556>:<port_of_emulator>
+    redir def <tcp_or_udp>:<5556>
+    TR ID: C14594979
+    b/210442:
+      command "redir del" doesn't work on API 23/24 on Windows; but Linux.
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._add_port_redir_cmd()
+    self._del_port_redir_cmd()
 
 
 if __name__ == '__main__':
-    print "======= Port Test ======="
-    unittest.main()
+  print '======= Port Test ======='
+  unittest.main()
diff --git a/emu_test/test_console/testcase_quit.py b/emu_test/test_console/testcase_quit.py
index d84bab6..466f4de 100644
--- a/emu_test/test_console/testcase_quit.py
+++ b/emu_test/test_console/testcase_quit.py
@@ -1,62 +1,76 @@
-#!/usr/bin/env python
+"""Test for quit/exit-related commands."""
 
-"""
-Test for quit/exit-related commands.
-"""
-
+import inspect
 import unittest
-import utils.util as console_utils
-from testcase_base import BaseConsoleTest
+
+import testcase_base
+from utils import util
 
 CMD_QUIT = 'quit\n'
 CMD_EXIT = 'exit\n'
 EMPTY_OUTPUT = ''
 
 
-class QuitTest(BaseConsoleTest):
+class QuitTest(testcase_base.BaseConsoleTest):
+  """This class aims to test quit/exit-related emulator console commands."""
+
+  def tearDown(self):
+    """Override superclass's method.
+
+    In the end of each test case, it already exited from emulator.
     """
-    This class aims to test quit/exit-related emulator console commands.
+    pass
+
+  def _execute_command_and_verify(self, command):
+    is_command_successful = False
+
+    self.telnet.write(command)
+    util.wait_on_windows()
+
+    output_exit = util.parse_output(self.telnet)
+    is_command_successful = (output_exit == EMPTY_OUTPUT)
+
+    self.telnet.close()
+
+    self.assert_cmd_successful(
+        is_command_successful, 'Failed to properly quit/exit emulator.',
+        False, '', EMPTY_OUTPUT, output_exit)
+
+  def test_quit_command(self):
+    """Test command for: quit.
+
+    Test Rail ID: 14595303
+    Steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from
+         /Users/<username>/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: quit (Verify)
+    Verify:
+      We have quited from console.
     """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._execute_command_and_verify(CMD_QUIT)
 
-    def tearDown(self):
-        """
-        Override superclass's method:
-          In the end of each test case, it already exited from emulator.
-        """
+  def test_exit_command(self):
+    """Test command for: exit.
 
-    def _execute_command_and_verify(self, command):
-        is_command_successful = False
+    Test Rail ID: 14595303
+    Steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from
+         /Users/<username>/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: exit (Verify)
+    Verify:
+      We have exited from console.
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    self._execute_command_and_verify(CMD_EXIT)
 
-        self.telnet.write(command)
-        self.wait_on_windows()
-
-        output_exit = console_utils.parseOutput(self.telnet)
-        is_command_successful = (output_exit == EMPTY_OUTPUT)
-
-        self.telnet.close()
-
-        self.assertCmdSuccessful(
-            is_command_successful,
-            'Failed to properly quit/exit emulator.',
-            False,
-            '',
-            EMPTY_OUTPUT,
-            output_exit)
-
-    def test_quit_command(self):
-        """
-        Test command for: quit
-        Test Rail ID: 14595303
-        """
-        self._execute_command_and_verify(CMD_QUIT)
-
-    def test_exit_command(self):
-        """
-        Test command for: exit
-        Test Rail ID: 14595303
-        """
-        self._execute_command_and_verify(CMD_EXIT)
 
 if __name__ == '__main__':
-    print('======= Quit/Exit Test =======')
-    unittest.main()
+  print '======= Quit/Exit Test ======='
+  unittest.main()
diff --git a/emu_test/test_console/testcase_sms.py b/emu_test/test_console/testcase_sms.py
index 490d6d9..23bb0b9 100644
--- a/emu_test/test_console/testcase_sms.py
+++ b/emu_test/test_console/testcase_sms.py
@@ -1,14 +1,12 @@
-#!/usr/bin/env python
-
 """Tests for sms-related commands."""
 
+import inspect
 import json
 import os
-import requests
-import subprocess
-import time
 import unittest
-from testcase_base import BaseConsoleTest
+
+import requests
+import testcase_base
 from utils import util
 
 TESTCASE_CALL_DIR = os.path.dirname(os.path.realpath(__file__))
@@ -17,128 +15,108 @@
 SENDER_PHONE_NUMBER = '2345678910'
 TEXT_MESSAGE = 'Hello there'
 CMD_SMS_SEND = 'sms send %s %s\n' % (SENDER_PHONE_NUMBER, TEXT_MESSAGE)
-CMD_SMS_PDU = 'sms pdu 07911326040000F0040B911346610089F6000020806291'\
-              '7314080CC8F71D14969741F977FD07\n'
+CMD_SMS_PDU = ('sms pdu 07911326040000F0040B911346610089F6000020806291'
+               '7314080CC8F71D14969741F977FD07\n')
 PDU_MESSAGE = 'How are you?'
 PDU_PHONE_NUMBER = '+31641600986'
 
 
-class SmsTest(BaseConsoleTest):
-    """This class aims to test sms-related emulator console commands."""
+class SmsTest(testcase_base.BaseConsoleTest):
+  """This class aims to test sms-related emulator console commands."""
 
-    @classmethod
-    def run_script_run_adb_shell(cls):
-        proc_install_apk = subprocess.Popen(
-            ['python', TESTCASE_CALL_DIR + '/runADBShell.py'])
-        return proc_install_apk
+  @classmethod
+  def setUpClass(cls):
+    util.run_script_run_adb_shell(TESTCASE_CALL_DIR)
 
-    @classmethod
-    def setUpClass(cls):
-        subprocess.call(
-            ['adb', '-s', 'emulator-5554', '-e', 'forward', 'tcp:8080',
-             'tcp:8081'])
-        subprocess.call(['python', TESTCASE_CALL_DIR + '/installAPK.py'])
-        cls.run_script_run_adb_shell()
-        time.sleep(util.SETUP_WAIT_TIMEOUT_S)
+  def _process_request_sms_service(self, payload):
+    """Processes post request to sms service.
 
-    def _process_request_sms_service(self, payload):
-        """Processes post request to sms service.
+    Sends post request to sms service, gets the newest sms message,
+    then parses the result to get phone number and text message.
 
-        Sends post request to sms service, gets the newest sms message,
-        then parses the result to get phone number and text message.
+    Args:
+        payload: The payload for sending POST request to sms server.
 
-        Args:
-            payload: The payload for sending POST request to sms server.
+    Returns:
+        phone_number: The sender's phone number in the sms message.
+        text_message: The text message in the sms.
+    """
+    r = requests.post(SERVLET_SMS, data=json.dumps(payload))
 
-        Returns:
-            phone_number: The sender's phone number in the sms message.
-            text_message: The text message in the sms.
-        """
-        r = requests.post(SERVLET_SMS, data=json.dumps(payload))
+    if r.raise_for_status():
+      error_msg = 'Servlet Error: Post request to %s failed' % SERVLET_SMS
+      print error_msg
+      return False, error_msg
 
-        if r.raise_for_status():
-            print('Servlet Error: Post request to %s failed' % SERVLET_SMS)
-            return False
+    r_json = r.json()
 
-        r_json = r.json()
+    if r_json['isFail']:
+      error_msg = ('Servlet Error: Failure occurred in servlet side => %s'
+                   % SERVLET_SMS)
+      print error_msg
+      return False, error_msg
 
-        if r_json['isFail']:
-            print('Servlet Error: Failure occurred in servlet side => %s'
-                  % SERVLET_SMS)
-            return False
+    return r_json['smsAddress'], r_json['smsTextMessage']
 
-        return r_json['smsAddress'], r_json['smsTextMessage']
+  def test_send_inbound_sms_text_message(self):
+    """Test command for: sms send <phone number> <text message>.
 
-    def test_send_inbound_sms_text_message(self):
-        """
-        Test command for: sms send <phone number> <text message>
-        Test Rail ID: C14595297
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: sms send <phone number> <text message>, and verify
-        Verify:
-            An sms is received from <phone number> with the text <text message>.
-        """
-        is_command_successful, output = \
-            util.execute_console_command(self.telnet,
-                                         CMD_SMS_SEND,
-                                         util.OK)
-        self.assertCmdSuccessful(is_command_successful,
-                                 'Failed to properly send sms text message',
-                                 False,
-                                 '',
-                                 util.OK,
-                                 output)
+    Test Rail ID: C14595297
+    Test steps:
+      1. Launch an emulator avd
+      2. From command prompt, run: telnet localhost <port>
+      3. Copy the auth_token value from ~/.emulator_console_auth_token
+      4. Run: auth auth_token
+      5. Run: sms send <phone number> <text message>, and verify
+    Verify:
+      An sms is received from <phone number> with the text <text message>.
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    is_command_successful, output = util.execute_console_command(
+        self.telnet, CMD_SMS_SEND, util.OK)
+    self.assert_cmd_successful(
+        is_command_successful, 'Failed to properly send sms text message',
+        False, '', util.OK, output)
 
-        got_phone_number, got_sms_message = self._process_request_sms_service({})
-        print('got_phone_number = %s, got_sms_message=%s'
-              % (got_phone_number, got_sms_message))
-        self.assertTrue(
-            got_phone_number == SENDER_PHONE_NUMBER,
-            'Sender phone number is wrong.')
-        self.assertTrue(
-            got_sms_message == TEXT_MESSAGE,
-            'The received text message is wrong.')
+    got_phone_number, got_sms_message = self._process_request_sms_service({})
+    print ('got_phone_number = %s, got_sms_message=%s'
+           % (got_phone_number, got_sms_message))
+    self.assertTrue(got_phone_number == SENDER_PHONE_NUMBER,
+                    'Sender phone number is wrong.')
+    self.assertTrue(got_sms_message == TEXT_MESSAGE,
+                    'The received text message is wrong.')
 
-    def test_send_inbound_sms_pdu(self):
-        """
-        Test command for: sms send <phone number> <text message>
-        Test Rail ID: C14595297
-        Test steps:
-            1. Launch an emulator avd
-            2. From command prompt, run: telnet localhost <port>
-            3. Copy the auth_token value from ~/.emulator_console_auth_token
-            4. Run: auth auth_token
-            5. Run: sms pdu <pdu message>
-               and verify
-        Verify:
-            An sms is received from <expected phone number> with
-            <expected text> ('How are you?').
-        """
-        is_command_successful, output = \
-            util.execute_console_command(self.telnet,
-                                         CMD_SMS_PDU,
-                                         util.OK)
-        self.assertCmdSuccessful(is_command_successful,
-                                 'Failed to properly send sms pdu',
-                                 False,
-                                 '',
-                                 util.OK,
-                                 output)
+  def test_send_inbound_sms_pdu(self):
+    """Test command for: sms send <phone number> <text message>.
 
-        got_phone_number, got_sms_message = self._process_request_sms_service({})
-        print('got_phone_number = %s, got_sms_message=%s'
-              % (got_phone_number, got_sms_message))
-        self.assertTrue(
-            got_phone_number == PDU_PHONE_NUMBER,
-            'Sender phone number is wrong.')
-        self.assertTrue(
-            got_sms_message == PDU_MESSAGE,
-            'The received text message is wrong.')
+    Test Rail ID: C14595297
+    Test steps:
+        1. Launch an emulator avd
+        2. From command prompt, run: telnet localhost <port>
+        3. Copy the auth_token value from ~/.emulator_console_auth_token
+        4. Run: auth auth_token
+        5. Run: sms pdu <pdu message>
+           and verify
+    Verify:
+        An sms is received from <expected phone number> with
+        <expected text> ('How are you?').
+    """
+    print 'Running test: %s' % (inspect.stack()[0][3])
+    is_command_successful, output = util.execute_console_command(
+        self.telnet, CMD_SMS_PDU, util.OK)
+    self.assert_cmd_successful(
+        is_command_successful, 'Failed to properly send sms pdu',
+        False, '', util.OK, output)
+
+    got_phone_number, got_sms_message = self._process_request_sms_service({})
+    print ('got_phone_number = %s, got_sms_message=%s'
+           % (got_phone_number, got_sms_message))
+    self.assertTrue(got_phone_number == PDU_PHONE_NUMBER,
+                    'Sender phone number is wrong.')
+    self.assertTrue(got_sms_message == PDU_MESSAGE,
+                    'The received text message is wrong.')
+
 
 if __name__ == '__main__':
-    print('======= sms Test =======')
-    unittest.main()
+  print '======= sms Test ======='
+  unittest.main()
diff --git a/emu_test/test_console/utils/util.py b/emu_test/test_console/utils/util.py
index 8f9323d..ef94269 100644
--- a/emu_test/test_console/utils/util.py
+++ b/emu_test/test_console/utils/util.py
@@ -1,14 +1,17 @@
-"""
-This module contains utility helper functions and constants for running each console test.
-Particularly, parseOutput(telnet) function is extensively used throughout
-the entire console test in order to parse the console output until "OK" message.
+"""This module contains utility helper functions and constants for console test.
+
+Particularly, parseOutput(telnet) function is extensively used
+throughout the entire console test in order to parse the console output until
+"OK" message.
 """
 
 import os
-import re
-import time
-
 from os.path import expanduser
+import re
+import subprocess
+import sys
+import telnetlib
+import time
 
 NEWLINE = '\n'
 OK = 'OK'
@@ -19,20 +22,24 @@
 CAPACITY = 'capacity: '
 REGEX_PWR_DISPLAY = 'AC:.*\nstatus:.*\nhealth:.*\npresent:.*\ncapacity:.*\nOK'
 COMPARE_CMD = ''
-if os.name == 'nt':
-    COMPARE_CMD = 'FC'
+WINDOWS_OS_NAME = 'nt'
+if os.name == WINDOWS_OS_NAME:
+  COMPARE_CMD = 'FC'
 else:
-    COMPARE_CMD = 'diff'
+  COMPARE_CMD = 'diff'
 
 SERVER_NAME = 'localhost'
 CONSOLE_PORT = 5554
 
 NUM_MAX_TRIALS = 3
 TRIAL_WAIT_TIMEOUT_S = 0.5
-CMD_WAIT_TIMEOUT_S = 0.5
+CMD_WAIT_TIMEOUT_S = 3
 SETUP_WAIT_TIMEOUT_S = 5
 
-TIMEOUT_S = 1 # in second
+ADB_TRIAL_WAIT_TIME_S = 2
+ADB_NUM_MAX_TRIALS = 5
+
+TIMEOUT_S = 1
 
 HOME = expanduser('~')
 CONSOLE_AUTH_TOKEN_FILE_NAME = '.emulator_console_auth_token'
@@ -48,198 +55,246 @@
 PORT_NO_REDIR = 'no active redirections\r\nOK'
 PORT_REDIR_ADD = 'tcp:5556  => 5554 \r\nOK'
 CMD_HELP = 'help\n'
-REGEX_HELP_DISPLAY_NO_AUTH = \
-    '.*\n.*\n.*help.*\n.*avd.*\n.*auth.*\n.*quit\|exit.*\n.*\n.*\nOK'
-REGEX_HELP_DISPLAY_AUTH = \
-    '.*\n.*\n.*help.*\n.*event.*\n.*geo.*\n.*gsm.*\n.*cdma.*\n.*crash.*\n' \
-    '.*kill.*\n.*network.*\n.*power.*\n.*quit\|exit.*\n.*redir.*\n' \
-    '.*sms.*\n.*avd.*\n.*qemu.*\n.*sensor.*\n.*finger.*\n.*debug.*\n.*\n.*\nOK'
+REGEX_HELP_DISPLAY_NO_AUTH = (r'.*\n.*\n.*help.*\n.*avd.*\n.*auth.*\n'
+                              r'.*quit\|exit.*\n.*\n.*\nOK')
+REGEX_HELP_DISPLAY_AUTH = (r'.*\n.*\n.*help.*\n.*event.*\n.*geo.*\n.*gsm.*\n'
+                           r'.*cdma.*\n.*crash.*\n.*kill.*\n.*network.*\n'
+                           r'.*power.*\n.*quit\|exit.*\n.*redir.*\n'
+                           r'.*sms.*\n.*avd.*\n.*qemu.*\n.*sensor.*\n.'
+                           r'*finger.*\n.*debug.*\n.*\n.*\nOK')
 AUTH = 'auth'
 CMD_RANDOM_AUTH_TOKEN = '%s axxB123cc\n' % AUTH
 CMD_EMPTY_AUTH_TOKEN = '%s \n' % AUTH
+CMD_EXIT = 'exit\n'
+SCRIPT_TO_INSTALL_APK = 'install_apk.py'
+SCRIPT_TO_RUN_ADB_SHELL = 'run_adb_shell.py'
+PYTHON_INTERPRETER = 'python'
 
 
-def checkReadUntil(consoleOutput):
-    """Checks whether the console output ends with 'OK' message.
+def check_read_until(console_output):
+  """Checks whether the console output ends with 'OK' message.
 
-    Args:
-        consoleOutput: The console output to be checked.
+  Args:
+    console_output: The console output to be checked.
 
-    Returns:
-        A boolean value: It indicates the console output ends with 'OK' message
-            or not.
-    """
-    consoleOutput = consoleOutput.strip()
-    index_OK = consoleOutput.rfind(OK)
-    return index_OK == len(consoleOutput) - len(OK)
+  Returns:
+    A boolean value: It indicates the console output ends with 'OK' message
+    or not.
+  """
+  console_output = console_output.strip()
+  index_ok = console_output.rfind(OK)
+  return index_ok == len(console_output) - len(OK)
 
 
-def parseOutput(telnet):
-    """Parses console output until 'OK' appears
+def parse_output(telnet):
+  """Parses console output until 'OK' appears.
 
-    Args:
-        telnet: The telnet connection to emulator.
+  Args:
+    telnet: The telnet connection to emulator.
 
-    Returns:
-        parsed_output: The parsed output until 'OK' message.
-    """
-    parsed_output = telnet.read_until(OK).strip()
-    return parsed_output
+  Returns:
+    parsed_output: The parsed output until 'OK' message.
+  """
+  parsed_output = telnet.read_until(OK).strip()
+  return parsed_output
 
 
-def extractFieldFromOutput(output, keyword):
-    """Extract value of specific field from battery command.
+def extract_field_from_output(output, keyword):
+  """Extract value of specific field from battery command.
 
-    Args:
-        output: The output for extracting certain field.
-        keyword: The keyword for searching.
+  Args:
+    output: The output for extracting certain field.
+    keyword: The keyword for searching.
 
-    Returns:
-        A string value: The field from output searching by given keyword.
-    """
-    keyword_idx = output.find(keyword)
-    return output[keyword_idx + len(keyword):output.find(NEWLINE, keyword_idx)].strip()
+  Returns:
+    A string value: The field from output searching by given keyword.
+  """
+  keyword_idx = output.find(keyword)
+  return (output[keyword_idx + len(keyword):output.find(NEWLINE, keyword_idx)]
+          .strip())
 
 
-def patternMatchOutput(output, regex):
-    """Check whether console output matches with a given regex.
+def pattern_match_output(output, regex):
+  """Check whether console output matches with a given regex.
 
-    Args:
-        output: The console output of a command.
-        regex: The regular pattern to use for searching.
+  Args:
+    output: The console output of a command.
+    regex: The regular pattern to use for searching.
 
-    Returns:
-        A boolean value: It indicates the pattern is found in the output or not.
-    """
-    if re.match(regex, output):
-        return True
-    else:
-        return False
+  Returns:
+    A boolean value: It indicates the pattern is found in the output or not.
+  """
+  if re.match(regex, output):
+    return True
+  else:
+    return False
 
 
-def checkBatteryStatus(status):
-    """Checking each battery status, used in testcase_battery.py
+def check_battery_status(status):
+  """Checking each battery status, used in testcase_battery.py.
 
-    Args:
-        status: A battery status to map.
+  Args:
+    status: A battery status to map.
 
-    Returns:
-        A string value: The capitalized/mapped battery status.
-    """
-    if status == 'not-charging':
-        return 'Not charging'
-    if status == 'failure':
-        return 'Unspecified failure'
-    if status == 'overheat':
-        return 'Overheat'
-    return status.capitalize()
+  Returns:
+    A string value: The capitalized/mapped battery status.
+  """
+  if status == 'not-charging':
+    return 'Not charging'
+  if status == 'failure':
+    return 'Unspecified failure'
+  if status == 'overheat':
+    return 'Overheat'
+  return status.capitalize()
 
 
-def parseOutputForEV(telnet):
-    """Parses console output until 'OK' appears for 'event' command.
+def parse_output_for_ev(telnet):
+  """Parses console output until 'OK' appears for 'event' command.
 
-    Args:
-        telnet: The telnet connection to emulator.
+  Args:
+    telnet: The telnet connection to emulator.
 
-    Returns:
-        parsed_output: The parsed console output.
-    """
-    parsed_output = telnet.read_until("\n"+OK).strip()
-    return parsed_output
+  Returns:
+    parsed_output: The parsed console output.
+  """
+  parsed_output = telnet.read_until('\n%s' % OK).strip()
+  return parsed_output
 
 
-def getEventsCodeEvKey():
-    """Gets event codes from a static file.
+def get_events_code_ev_key():
+  """Gets event codes from a static file.
 
-    Returns:
-        A string value: The event codes getting from a static file.
-    """
-    with open(EVENTS_CODE_EV_KEY_FILENAME) as f:
-        lines = f.readlines()
-    EVENTS_CODE_EV_KEY = ""
-    for line in lines:
-        EVENTS_CODE_EV_KEY += ('\r\n    ' + line.strip())
-    return EVENTS_CODE_EV_KEY.strip() + '\r\nOK'
+  Returns:
+    A string value: The event codes getting from a static file.
+  """
+  with open(EVENTS_CODE_EV_KEY_FILENAME) as f:
+    lines = f.readlines()
+  events_code_ev_key = ''
+  for line in lines:
+    events_code_ev_key += ('\r\n    %s' % line.strip())
+  return '%s\r\n%s' % (events_code_ev_key.strip(), OK)
 
 
-def readStringFromFile(filename):
-    """Reads strings written in the file by appending each line.
+def read_string_from_file(filename):
+  """Reads strings written in the file by appending each line.
 
-    Args:
-        filename: The file name to read strings from.
+  Args:
+    filename: The file name to read strings from.
 
-    Returns:
-        stringRead: A single string value containing each line in the file.
-    """
-    with open(filename) as f:
-        lines = f.readlines()
-    stringRead = ""
-    for line in lines:
-        stringRead += line
-    return stringRead
+  Returns:
+    stringRead: A single string value containing each line in the file.
+  """
+  with open(filename) as f:
+    lines = f.readlines()
+  string_read = ''
+  for line in lines:
+    string_read += line
+  return string_read
 
 
-def removeAllSpaces(string):
-    """Removes all the trailing spaces and spaces within the string.
+def remove_all_spaces(string):
+  """Removes all the trailing spaces and spaces within the string.
 
-    Args:
-        string: A string to remove training spaces.
+  Args:
+    string: A string to remove training spaces.
 
-    Returns:
-        A string value: A parsed string after removing all trailing spaces.
-    """
-    return re.sub('[\s+]', '', string.strip(' \t\n\r'))
+  Returns:
+    A string value: A parsed string after removing all trailing spaces.
+  """
+  return re.sub(r'[\s+]', '', string.strip(' \t\n\r'))
 
 
 def execute_console_command(telnet, command, expected_output):
-    """Executes emulator console command.
+  """Executes emulator console command.
 
-    Executes emulator console command through telnet connection,
-    compare command output and expected command output.
+  Executes emulator console command through telnet connection,
+  compare command output and expected command output.
 
-    Args:
-        telnet: The telnet connection to emulator.
-        command: The console command to execute.
-        expected_output: The expected output for the executed command.
+  Args:
+    telnet: The telnet connection to emulator.
+    command: The console command to execute.
+    expected_output: The expected output for the executed command.
 
-    Returns:
-        is_command_successful: It indicates command executed successfully or not.
-        output: The command output in the terminal.
-    """
-    is_command_successful = False
+  Returns:
+    is_command_successful: It indicates command executed successfully or not.
+    output: The command output in the terminal.
+  """
+  is_command_successful = False
 
-    for i in range(NUM_MAX_TRIALS):
-        print('execute console command: %s, trial #%d' % (command.strip(), i))
+  for i in range(NUM_MAX_TRIALS):
+    print 'execute console command: %s, trial #%d' % (command.strip(), i)
 
-        telnet.write(command)
-        time.sleep(CMD_WAIT_TIMEOUT_S)
+    telnet.write(command)
+    time.sleep(CMD_WAIT_TIMEOUT_S)
 
-        if command == 'crash\n':
-            output = telnet.read_all()
-        elif command == CMD_EMPTY_AUTH_TOKEN:
-            output = telnet.read_until('missing authentication token').strip()
-        elif command == CMD_RANDOM_AUTH_TOKEN:
-            output = telnet.read_until('emulator_console_auth_token').strip()
-        else:
-            output = parseOutput(telnet)
+    if command == 'crash\n':
+      output = telnet.read_all()
+    elif command == CMD_EMPTY_AUTH_TOKEN:
+      output = telnet.read_until('missing authentication token').strip()
+    elif command == CMD_RANDOM_AUTH_TOKEN:
+      output = telnet.read_until('emulator_console_auth_token').strip()
+    else:
+      output = parse_output(telnet)
 
-        is_command_successful = patternMatchOutput(output, expected_output)
+    is_command_successful = pattern_match_output(output, expected_output)
 
-        if is_command_successful:
-            break
+    if is_command_successful:
+      break
 
-        time.sleep(TRIAL_WAIT_TIMEOUT_S)
+    time.sleep(TRIAL_WAIT_TIMEOUT_S)
 
-    return is_command_successful, output
+  return is_command_successful, output
 
 
 def get_auth_token():
-    """Gets auth token value from auth token file.
+  """Gets auth token value from auth token file.
 
-    Returns:
-        auth_token: The value of auth token.
-    """
-    with open(TOKEN_PATH) as f:
-        content = f.readlines()
-    auth_token = content[0]
-    return auth_token
+  Returns:
+    auth_token: The value of auth token.
+  """
+  with open(TOKEN_PATH) as f:
+    content = f.readlines()
+  auth_token = content[0]
+  return auth_token
+
+
+def telnet_emulator():
+  """Only telnet to emulator, initially not need to run auth command."""
+  telnet = telnetlib.Telnet(SERVER_NAME, CONSOLE_PORT)
+  if not check_read_until(telnet.read_until(OK, TIMEOUT_S)):
+    sys.exit(-1)
+
+  return telnet
+
+
+def wait_on_windows():
+  """Waits for few seconds on Windows machine."""
+  if os.name == WINDOWS_OS_NAME:
+    time.sleep(0.5)
+
+
+def exit_emulator_console(telnet):
+  """Exits from emulator console."""
+  telnet.write(CMD_EXIT)
+  wait_on_windows()
+  telnet.close()
+
+
+def run_script_run_adb_shell(testcase_call_dir):
+  """Run Python script to install apk.
+
+  Run Python script to install Rest Service app and corresponding test on
+  Emulator; on emulator, do a port forwarding from tcp:8080 to tcp:8081.
+
+  Args:
+    testcase_call_dir: The directory where the test case is called from.
+  """
+  script_run_adb_shell = ('%s/%s' %
+                          (testcase_call_dir, SCRIPT_TO_RUN_ADB_SHELL))
+  script_install_apk = '%s/%s' % (testcase_call_dir, SCRIPT_TO_INSTALL_APK)
+
+  subprocess.call(['adb', '-s', 'emulator-%s' % str(CONSOLE_PORT),
+                   '-e', 'forward', 'tcp:8080', 'tcp:8081'])
+  subprocess.call([PYTHON_INTERPRETER, script_install_apk])
+  subprocess.Popen([PYTHON_INTERPRETER, script_run_adb_shell])
+  time.sleep(SETUP_WAIT_TIMEOUT_S)
diff --git a/system_image_uitests/app/src/androidTest/java/com/android/devtools/systemimage/uitest/smoke/SettingsTest.java b/system_image_uitests/app/src/androidTest/java/com/android/devtools/systemimage/uitest/smoke/SettingsTest.java
index 446ce85..508c4b2 100644
--- a/system_image_uitests/app/src/androidTest/java/com/android/devtools/systemimage/uitest/smoke/SettingsTest.java
+++ b/system_image_uitests/app/src/androidTest/java/com/android/devtools/systemimage/uitest/smoke/SettingsTest.java
@@ -52,9 +52,9 @@
     public final SystemImageTestFramework testFramework = new SystemImageTestFramework();
 
     // Tests under this class may take more than 60 seconds depending on buildbot infrastructure.
-    // 90 seconds is a more reliable setup here.
+    // 120 seconds is a more reliable setup here.
     @Rule
-    public Timeout globalTimeout = Timeout.seconds(90);
+    public Timeout globalTimeout = Timeout.seconds(120);
 
 
     /**