summaryrefslogtreecommitdiff
path: root/emu_test/test_console/testcase_geo.py
blob: 93029085b68cf31bf936f24ba2333af64db96b57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
"""Tests for geo-related commands."""

import inspect
import json
import os
import time
import unittest

import requests
import testcase_base
from utils import util

TESTCASE_CALL_DIR = os.path.dirname(os.path.realpath(__file__))
SERVLET_GEO = 'http://localhost:8080/GeoManagerService'

CMD_GEO_FIX_PREFIX = 'geo fix'
SF_LONGITUDE = -122
SF_LATITUDE = 38
SF_ALTITUDE = 0
CMD_GEO_SF = ('%s %d %d %d\n' %
              (CMD_GEO_FIX_PREFIX, SF_LONGITUDE, SF_LATITUDE, SF_ALTITUDE))

class GeoTest(testcase_base.BaseConsoleTest):
  """This class aims to test geo-related emulator console commands."""

  def __init__(self, method_name=None, avd=None):
    if method_name:
      super(GeoTest, self).__init__(method_name)
    else:
      super(GeoTest, self).__init__()
    self.avd = avd

  @classmethod
  def setUpClass(cls):
    util.run_script_run_adb_shell(TESTCASE_CALL_DIR)

  @classmethod
  def tearDownClass(cls):
    util.unstall_apps(TESTCASE_CALL_DIR)

  def _process_request_geo_service(self, payload):
    """Processes post request to geo service.

    Sends post request to geo service, gets the last known location.

    Args:
        payload: The payload for sending POST request to geo server.

    Returns:
        longitude: The longitude of last know location.
        latitude: The latitude of last know location.
        altitude: The altitude of last know location.
    """
    r = requests.post(SERVLET_GEO, data=json.dumps(payload))

    if r.raise_for_status():
      error_msg = ('Servlet Error: Post request to %s failed' %
                   SERVLET_GEO)
      print error_msg
      return False, error_msg

    r_json = r.json()

    if r_json['isFail']:
      error_msg = ('Servlet Error: Failure occurred in servlet side => %s'
                   % SERVLET_GEO)
      print error_msg
      return False, False, False

    print 'Got longitude: ' + r_json['longitude']
    print 'Got latitude: ' + r_json['latitude']
    print 'Got altitude: ' + r_json['altitude']

    return (int(r_json['longitude']), int(r_json['latitude']),
            int(r_json['altitude']))

  def _poll_geo_and_verify(self,
                           expected_longitude,
                           expected_latitude,
                           expected_altitude):
    """Polls orientation/rotation information from emulator and verifies them.

    Args:
      expected_longitude: Expected longitude to get.
      expected_latitude: Expected latitude to get.
      expected_altitude: Expected altitude to get.
    """
    got_expected = False
    MAX_TRIES = 3
    for i in range(MAX_TRIES):
      got_longitude, got_latitude, got_altitude = \
        self._process_request_geo_service({})
      print ('got_longitude = %s, expected_longitude = %s' %
             (got_longitude, expected_longitude))
      print ('got_latitude = %s, expected_latitude = %s' %
             (got_latitude, expected_latitude))
      print ('got_altitude = %s, expected_altitude = %s' %
             (got_altitude, expected_altitude))
      if (got_longitude == expected_longitude and
              got_latitude == expected_latitude and
            got_altitude == expected_altitude):
        got_expected = True
        break
      else:
        time.sleep(util.TRIAL_WAIT_TIMEOUT_S)

    self.assertTrue(got_expected,
                    'Max tries reached, failed to get expected values.')

  def _initially_launch_google_maps_to_have_location_history(self, payload):
    print 'Launch Google Maps initially to make it has location history.'
    requests.post(SERVLET_GEO, data=json.dumps(payload))

  def test_geo(self):
    """Test command for: geo fix xxx

    Test Rail ID: C14595298
    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. Open Google Maps app and accept the terms and conditions
      6. Enable location service in Google Maps
      7. Tap on My Location
      8. Run: geo fix -122 37 0
    Verify:
      Check Maps location centers on San Francisco.
    """
    print 'Running test: %s' % (inspect.stack()[0][3])

    print 'api = ' + self.avd.api

    if self.avd.api in ['25', '24']:
      self._initially_launch_google_maps_to_have_location_history({'Initial': 1})

      is_command_successful, output = util.execute_console_command(
        self.telnet, CMD_GEO_SF, '')
      self.assert_cmd_successful(
        is_command_successful, 'Failed to properly set geo info.',
        False, '', '', output)
      self._process_request_geo_service({})
      self._poll_geo_and_verify(SF_LONGITUDE, SF_LATITUDE, SF_ALTITUDE)
    else:
      # TODO: Spend more time in future when having bandwith for it.
      print 'Currently, only test API greater than 23'
      print 'API is below 24, skip geo test for now.'
      pass


if __name__ == '__main__':
  print '======= geo Test ======='
  unittest.main()