示例#1
0
    def test_send_message(self):
        client = UberClient('*****@*****.**', '12345')
        response = mocked_response('omg')
        expected_data = {
            'email': '*****@*****.**',
            'deviceOS': settings.DEVICE_OS,
            'language': 'en',
            'deviceModel': settings.DEVICE_MODEL,
            'app': 'client',
            'messageType': '111',
            'token': '12345',
            'version': settings.UBER_VERSION,
            'device': settings.DEVICE_NAME,
            'aaa': 'bbb',
        }

        (flexmock(UberClient).should_receive(
            '_copy_location_for_message').with_args(self.mock_location,
                                                    dict).times(1))

        (flexmock(UberClient).should_receive('_post').with_args(
            UberClient.ENDPOINT, data=DictPartialMatcher(expected_data)).times(
                1).and_return(response))

        (flexmock(UberClient).should_receive(
            '_validate_message_response').with_args(response.json()).times(1))

        params = {'aaa': 'bbb'}

        self.assertEqual(
            'omg', client._send_message('111', params, self.mock_location))
示例#2
0
    def test_login(self):
        (flexmock(uber.client).should_receive("hash_password").and_return("1122334455"))

        (
            flexmock(UberClient)
            .should_receive("_send_message")
            .with_args("Login", params={"password": "******", "email": "aaa"})
            .and_return({"client": {"token": "12345"}})
        )

        token = UberClient.login("aaa", "bbb")
        self.assertEqual(token, "12345")
示例#3
0
    def test_login(self):
        (flexmock(uber.client).should_receive('hash_password').and_return(
            '1122334455'))

        (flexmock(UberClient).should_receive('_send_message').with_args(
            'Login', params={
                'password': '******',
                'email': 'aaa'
            }).and_return({'token': '12345'}))

        token = UberClient.login('aaa', 'bbb')
        self.assertEqual(token, '12345')
示例#4
0
    def do_login(self, username, password):
        """
        Logs into Uber.
        usage: login <email> <password>
        """
        try:
            token = UberClient.login(username, password)
            self._state.username = username
            self._state.token = token
            self._state.save()

            self.setup_client()
            print 'login ok'
        except UberException as e:
            print e.description
示例#5
0
    def do_login(self, username, password):
        """
        Logs into Uber.
        usage: login <email> <password>
        """
        try:
            token = UberClient.login(username, password)
            self._state.username = username
            self._state.token = token
            self._state.save()

            self.setup_client()
            print "login ok"
        except UberException as e:
            print e.description
示例#6
0
文件: util.py 项目: mnbbrown/doneapp
def bookuber(address):
     #Login to obtain token
    token = UberClient.login('*****@*****.**','123uberdone')
    # token = 'cLqir9JuchqHqOtxncYSEmMC6BiQfN'
    #Set up client
    client = UberClient('*****@*****.**', token)
    #show nearby ubers
    ubers = nearbyUber(client,address)
    address = 'Citizen Space, 425 2nd St , San Francisco, CA'
    #geolocate
    results = geolocate(address)
    if not results:
        print 'address not found :('
        return
    geo_address = results[0]
    print 'booking UberX for {}...'.format(geo_address['formatted_address'])
示例#7
0
    def test_login(self):
        (flexmock(uber.client)
            .should_receive('hash_password')
            .and_return('1122334455')
        )

        (flexmock(UberClient)
            .should_receive('_send_message')
            .with_args('Login', params={'password': '******', 'email': 'aaa'})
            .and_return({
                'token': '12345'
            })
        )


        token = UberClient.login('aaa', 'bbb')
        self.assertEqual(token, '12345')
def login_into_uber( username, password):
  #Logs into Uber
  try:
    global client
    token = UberClient.login(username, password)
    username = username

    if token:
      client = UberClient(username, token)
      if client:
        print "Logged into Uber as " + username+'\n'
        #checkout our pickup address
        do_checkout_address(uberPickUpAddress)
        #ping pickup address for nearby vehicles
        ping_address_for_available_vehicles(uberPickUpAddress)
        #order the uber to your location
        do_pickup(uberPickUpAddress)
      
  except UberException as e:
    print e.description
示例#9
0
class UberCli(Cmd):
    def __init__(self):
        Cmd.__init__(self)
        self._state = CliState()
        self._client = None
        self.setup_client()

        if self._client:
            print 'logged in as ' + self._state.username

    def setup_client(self):
        if self._state.token:
            self._client = UberClient(self._state.username, self._state.token)

    @exempt_login
    def do_login(self, username, password):
        """
        Logs into Uber.
        usage: login <email> <password>
        """
        try:
            token = UberClient.login(username, password)
            self._state.username = username
            self._state.token = token
            self._state.save()

            self.setup_client()
            print 'login ok'
        except UberException as e:
            print e.description

    @exempt_login
    def do_logout(self):
        """
        Log out of Uber (just deletes the token)

        usage: logout
        """
        self._state.token = None
        self._state.save()
        self._state = None
        print 'Cleared access token'

    @exempt_login
    def do_lookup(self, address):
        """
        Looks up an address
        usage: lookup <address>
        """
        result = geolocate(address)
        for entry in result:
            print entry['formatted_address']

    def do_add_credit_card(self, creditcard, month, year, cvv, zipcode):
        """
        Adds a credit card to Uber
        usage: add_credit_card <creditcard> <month> <year> <cvv> <zipcode>
        """
        result = self._client.add_payment(creditcard, month, year, cvv,
                                          zipcode)
        print result

    def do_ping(self, address_str):
        """
        shows you what taxis are close to you.
        Usage: ping <address>
        """
        if not address_str:
            print

        results = geolocate(address_str)
        if not results:
            print 'address not found :('
            return

        geodecoded_address = results[0]

        print 'pinging: ' + geodecoded_address['formatted_address']
        app_state = self._client.ping(geodecoded_address)
        city = app_state.city
        vehicle_views = city.vehicle_views
        for key in city.vehicle_views_order:
            nearby_info = app_state.nearby_vehicles.get(key)
            view = vehicle_views[key]
            count = len(nearby_info.vehicle_paths)

            if count:
                additional_info = ''
                if view.surge:
                    additional_info = 'Warning - x{multiplier} surge pricing is active!'.format(
                        multiplier=view.surge.multiplier)

                print '{name} has {count} cars near by (eta {eta}). {additional_info}'.format(
                    name=view.description,
                    count=len(nearby_info.vehicle_paths),
                    eta=nearby_info.eta_string,
                    additional_info=additional_info)
            else:
                print '{name} has no vehicles nearby :('.format(
                    name=view.description)

    def do_pickup(self, address):
        """
        Have an UberX pick you up
        Usage: pickup <address>
        """
        results = geolocate(address)
        if not results:
            print 'address not found :('
            return

        if len(results) == 1:
            geo_address = results[0]
        else:
            for i in xrange(len(results)):
                entry = results[i]
                print '{index}) {entry}'.format(
                    index=i + 1, entry=entry['formatted_address'])

            print ''

            selection_num = int(
                raw_input('choose address# (0 to abort)> ') or 0)
            if not selection_num:
                return

            geo_address = results[selection_num - 1]

        print 'booking UberX for {}...'.format(
            geo_address['formatted_address'])
        self._book_ride(geo_address)

    def _book_ride(self, location):
        abort_signal = []

        def handle_abort(*args):
            abort_signal.append(None)
            print ''
            print 'cancelling ride...'
            self._client.cancel_pickup()
            print 'ride cancelled.'
            signal.signal(signal.SIGINT, signal.SIG_DFL)

        signal.signal(signal.SIGINT, handle_abort)
        self._client.request_pickup(location)

        print_state = True
        last_status = None
        print 'waiting for ride (ctrl+c at any time to cancel ride)'

        while print_state and not abort_signal:
            state = self._client.ping(None)
            status = state.client.status
            if status != last_status:
                print 'status: ' + status
                last_status = status

            if status == ClientStatus.LOOKING:
                print state.client.last_request_note
                break

            if status == ClientStatus.WAITING_FOR_PICKUP:
                trip = state.trip
                vehicle = trip.vehicle
                sys.stdout.write(
                    "\r{driver} will pick you up in {eta} with a {color} {make} {model}."
                    .format(
                        driver=trip.driver.name,
                        eta=trip.eta_string_short,
                        color=vehicle.exterior_color,
                        make=vehicle.vehicle_type.make,
                        model=vehicle.vehicle_type.model,
                    ))
                sys.stdout.flush()

            time.sleep(1)

    def do_experiments(self):
        """
        print uber's running experiments
        """
        state = self._client.ping(None)
        for experiment in state.client.active_experiments.values():
            print '{name} ({group})'.format(
                name=experiment.name, group=experiment.treatment_group_name)

    @exempt_login
    def do_exit(self):
        exit()

    do_bye = do_exit

    def onecmd(self, line):
        """
        Interpret the argument as though it had been typed in response
        to the prompt.
        """
        if line == 'EOF':
            exit()

        built_in_functions = ['help']
        cmd, arg, line = self.parseline(line)

        if not line:
            return self.emptyline()

        if cmd is None:
            return self.default(line)

        self.lastcmd = line
        if cmd == '':
            return self.default(line)

        try:
            func = getattr(self, 'do_' + cmd)
        except AttributeError:
            return self.default(line)

        if cmd in built_in_functions:
            return func(arg)

        if getattr(func, 'exempt_login', False) is False and not self._client:
            print '''login required. type 'login <user> <password>' to login'''
            return

        arg_count = func.func_code.co_argcount - 1

        # if one arg, just give the string as-is
        if arg_count == 1:
            if not arg:
                print get_usage(func)
                return

            return func(arg)

        else:
            # split to various args
            split_args = shlex.split(arg)
            if len(split_args) != arg_count:
                print get_usage(func)
                return

            return func(*split_args)
示例#10
0
class TestUberClient(unittest.TestCase):
    mock_location = GPSLocation(1, 2)

    def setUp(self):
        self._client = UberClient("*****@*****.**", "12345")

    def test_post(self):
        data = {"a": "b"}

        (
            flexmock(self._client._session)
            .should_receive("post")
            .with_args("http://www.boo.org", json.dumps(data), headers=self._client._headers)
            .and_return(mocked_response({"aaa": "bbb"}))
            .times(1)
        )

        self.assertEqual(self._client._post("http://www.boo.org", data=data).json(), {"aaa": "bbb"})

    def test_message_error_handling(self):
        error_data = {"messageType": "Error", "description": "something bad", "errorCode": 12345}

        (flexmock(self._client._session).should_receive("post").and_return(mocked_response(error_data)).times(1))

        with self.assertRaises(UberException) as expected_exception:
            self._client._send_message("crap")

        self.assertEqual(expected_exception.exception.description, "something bad")
        self.assertEqual(expected_exception.exception.error_code, 12345)

    def test_http_error_handling(self):
        (flexmock(self._client._session).should_receive("post").and_return(mocked_response("error!", 401)).times(1))

        with self.assertRaises(UberException) as expected_exception:
            self._client._post("http://www.test.org", {"nobody": "cares"})

        self.assertEqual(expected_exception.exception.error_code, 401)
        self.assertEqual(expected_exception.exception.description, "error!")

    def test_send_message(self):
        client = UberClient("*****@*****.**", "12345")
        response = mocked_response("omg")
        expected_data = {
            "email": "*****@*****.**",
            "deviceOS": settings.DEVICE_OS,
            "language": "en",
            "deviceModel": settings.DEVICE_MODEL,
            "app": "client",
            "messageType": "111",
            "token": "12345",
            "version": settings.UBER_VERSION,
            "device": settings.DEVICE_NAME,
            "aaa": "bbb",
        }

        (flexmock(UberClient).should_receive("_copy_location_for_message").with_args(self.mock_location, dict).times(1))

        (
            flexmock(UberClient)
            .should_receive("_post")
            .with_args(UberClient.ENDPOINT, data=DictPartialMatcher(expected_data))
            .times(1)
            .and_return(response)
        )

        (flexmock(UberClient).should_receive("_validate_message_response").with_args(response.json()).times(1))

        params = {"aaa": "bbb"}

        self.assertEqual("omg", client._send_message("111", params, self.mock_location))

    def test_login(self):
        (flexmock(uber.client).should_receive("hash_password").and_return("1122334455"))

        (
            flexmock(UberClient)
            .should_receive("_send_message")
            .with_args("Login", params={"password": "******", "email": "aaa"})
            .and_return({"client": {"token": "12345"}})
        )

        token = UberClient.login("aaa", "bbb")
        self.assertEqual(token, "12345")

    def test_hash_password(self):
        from uber.client import hash_password

        self.assertEqual(hash_password("12345"), "e186e4e7a446d1b451e8e985c8db4a21")

    def test_nearby_places(self):
        params = {"searchTypes": ["places"], "query": "huge potato"}

        expected_places = [1, 2, 3, 4, 5]

        (
            flexmock(self._client)
            .should_receive("_send_message")
            .with_args("LocationSearch", params=params, location="test_location")
            .and_return({"places": expected_places})
        )

        result = self._client.nearby_places("huge potato", "test_location")
        self.assertEqual([x.raw for x in result], expected_places)
        for item in result:
            self.assertEqual(type(item), Place)

    def test_copy_location_for_message(self):
        data = {}
        self._client._copy_location_for_message({"longitude": 1, "latitude": 0.5}, data)
        self.assertEqual(data, {"longitude": 1, "latitude": 0.5})

        data = {}
        self._client._copy_location_for_message(GPSLocation(latitude=0.5, longitude=1), data)
        self.assertEqual(data, {"longitude": 1, "latitude": 0.5})

        data = {}
        self._client._copy_location_for_message(
            GPSLocation(latitude=0.5, longitude=1, vertical_accuracy=0.1, horizontal_accuracy=0.2, altitude=0.3), data
        )

        self.assertEqual(
            data, {"latitude": 0.5, "longitude": 1, "verticalAccuracy": 0.1, "horizontalAccuracy": 0.2, "altitude": 0.3}
        )

    def test_request_pickup(self):
        (
            flexmock(UberClient)
            .should_receive("_send_message")
            .with_args(
                "Pickup",
                params={"vehicleViewId": 1, "useCredits": True, "pickupLocation": {"some_geo_field": "12345"}},
                location=self.mock_location,
            )
        )

        self._client.request_pickup(
            vehicle_type=VehicleView({"id": 1}),
            pickup_address={"some_geo_field": "12345"},
            gps_location=self.mock_location,
        )

    def test_request_pickup_with_string_address(self):
        (
            flexmock(geolocation)
            .should_receive("geolocate")
            .with_args("some address")
            .and_return([{"some_geo_field": "12345"}])
        )

        (
            flexmock(UberClient)
            .should_receive("_send_message")
            .with_args(
                "Pickup",
                params={"vehicleViewId": 1, "useCredits": True, "pickupLocation": {"some_geo_field": "12345"}},
                location=self.mock_location,
            )
        )

        self._client.request_pickup(
            vehicle_type=VehicleView({"id": 1}), pickup_address="some address", gps_location=self.mock_location
        )

    def test_request_pickup_with_bad_string_address(self):
        (flexmock(geolocation).should_receive("geolocate").with_args("some address").and_return([]))

        with self.assertRaises(UberLocationNotFound):
            self._client.request_pickup(
                vehicle_type=VehicleView({"id": 1}), pickup_address="some address", gps_location=self.mock_location
            )

    def test_request_pickup_int_args(self):
        (
            flexmock(geolocation)
            .should_receive("geolocate")
            .with_args("some address")
            .and_return([{"some_geo_field": "12345"}])
        )

        (
            flexmock(UberClient)
            .should_receive("_send_message")
            .with_args(
                "Pickup",
                params={
                    "vehicleViewId": 111,
                    "useCredits": True,
                    "paymentProfileId": 555,
                    "pickupLocation": {"some_geo_field": "12345"},
                },
                location=self.mock_location,
            )
        )

        self._client.request_pickup(
            vehicle_type=111, pickup_address="some address", payment_profile=555, gps_location=self.mock_location
        )

    def test_request_pickup_model_args(self):
        (
            flexmock(geolocation)
            .should_receive("geolocate")
            .with_args("some address")
            .and_return([{"some_geo_field": "12345"}])
        )

        (
            flexmock(UberClient)
            .should_receive("_send_message")
            .with_args(
                "Pickup",
                params={
                    "vehicleViewId": 111,
                    "useCredits": True,
                    "paymentProfileId": 555,
                    "pickupLocation": {"some_geo_field": "12345"},
                },
                location=self.mock_location,
            )
        )

        self._client.request_pickup(
            vehicle_type=VehicleView({"id": 111}),
            pickup_address="some address",
            payment_profile=PaymentProfile({"id": 555}),
            gps_location=self.mock_location,
        )

    def test_ping(self):
        (flexmock(UberClient).should_receive("_send_message").with_args("PingClient", location=self.mock_location))

        self._client.ping(self.mock_location)
示例#11
0
class TestUberClient(unittest.TestCase):
    mock_location = GPSLocation(1, 2)

    def setUp(self):
        self._client = UberClient('*****@*****.**', '12345')

    def test_post(self):
        data = {'a': 'b'}

        (flexmock(self._client._session)
         .should_receive('post')
         .with_args('http://www.boo.org', json.dumps(data), headers=self._client._headers)
         .and_return(mocked_response({'aaa': 'bbb'}))
         .times(1)
        )

        self.assertEqual(self._client._post('http://www.boo.org', data=data).json(), {'aaa': 'bbb'})

    def test_message_error_handling(self):
        error_data = {
            'messageType': 'Error',
            'description': 'something bad',
            'errorCode': 12345,
        }

        (flexmock(self._client._session)
         .should_receive('post')
         .and_return(mocked_response(error_data))
         .times(1)
        )

        with self.assertRaises(UberException) as expected_exception:
            self._client._send_message('crap')

        self.assertEqual(expected_exception.exception.description, 'something bad')
        self.assertEqual(expected_exception.exception.error_code, 12345)

    def test_http_error_handling(self):
        (flexmock(self._client._session)
         .should_receive('post')
         .and_return(mocked_response('error!', 401))
         .times(1)
        )

        with self.assertRaises(UberException) as expected_exception:
            self._client._post('http://www.test.org', {'nobody': 'cares'})

        self.assertEqual(expected_exception.exception.error_code, 401)
        self.assertEqual(expected_exception.exception.description, 'error!')

    def test_send_message(self):
        client = UberClient('*****@*****.**', '12345')
        response = mocked_response('omg')
        expected_data = {
            'email': '*****@*****.**',
            'deviceOS': settings.DEVICE_OS,
            'language': 'en',
            'deviceModel': settings.DEVICE_MODEL,
            'app': 'client',
            'messageType': '111',
            'token': '12345',
            'version': settings.UBER_VERSION,
            'device': settings.DEVICE_NAME,
            'aaa': 'bbb',
        }

        (flexmock(UberClient)
         .should_receive('_copy_location_for_message')
         .with_args(self.mock_location, dict)
         .times(1)
        )

        (flexmock(UberClient)
         .should_receive('_post')
         .with_args(UberClient.ENDPOINT, data=DictPartialMatcher(expected_data))
         .times(1)
         .and_return(response))

        (flexmock(UberClient)
         .should_receive('_validate_message_response')
         .with_args(response.json())
         .times(1)
        )

        params = {
            'aaa': 'bbb'
        }

        self.assertEqual('omg', client._send_message('111', params, self.mock_location))

    def test_login(self):
        (flexmock(uber.client)
            .should_receive('hash_password')
            .and_return('1122334455')
        )

        (flexmock(UberClient)
            .should_receive('_send_message')
            .with_args('Login', params={'password': '******', 'email': 'aaa'})
            .and_return({
                'token': '12345'
            })
        )


        token = UberClient.login('aaa', 'bbb')
        self.assertEqual(token, '12345')

    def test_hash_password(self):
        from uber.client import hash_password
        self.assertEqual(hash_password('12345'), 'e186e4e7a446d1b451e8e985c8db4a21')


    def test_nearby_places(self):
        params = {
            'searchTypes': ['places'],
            'query': 'huge potato'
        }

        expected_places = [1,2,3,4,5]

        (flexmock(self._client)
            .should_receive('_send_message')
            .with_args('LocationSearch', params=params, location='test_location')
            .and_return({'places': expected_places})
        )


        result = self._client.nearby_places('huge potato', 'test_location')
        self.assertEqual([x.raw for x in result], expected_places)
        for item in result:
            self.assertEqual(type(item), Place)

    def test_copy_location_for_message(self):
        data = {}
        self._client._copy_location_for_message({'longitude': 1, 'latitude': 0.5}, data)
        self.assertEqual(data, {'longitude': 1, 'latitude': 0.5})

        data = {}
        self._client._copy_location_for_message(GPSLocation(latitude=0.5, longitude=1), data)
        self.assertEqual(data, {'longitude': 1, 'latitude': 0.5})

        data = {}
        self._client._copy_location_for_message(GPSLocation(
            latitude=0.5,
            longitude=1,
            vertical_accuracy=0.1,
            horizontal_accuracy=0.2,
            altitude=0.3), data)

        self.assertEqual(data, {
            'latitude': 0.5,
            'longitude': 1,
            'verticalAccuracy': 0.1,
            'horizontalAccuracy': 0.2,
            'altitude': 0.3,
            })


    def test_request_pickup(self):
        (flexmock(UberClient)
            .should_receive('_send_message')
            .with_args('Pickup',
                       params={'vehicleViewId': 1, 'useCredits': True, 'pickupLocation': {'some_geo_field': '12345'}},
                       location=self.mock_location)
        )

        self._client.request_pickup(
            vehicle_type=VehicleView({'id': 1}),
            pickup_address={'some_geo_field': '12345'},
            gps_location=self.mock_location)

    def test_request_pickup_with_string_address(self):
        (flexmock(geolocation)
            .should_receive('geolocate')
            .with_args('some address')
            .and_return([{'some_geo_field': '12345'}])
        )

        (flexmock(UberClient)
            .should_receive('_send_message')
            .with_args('Pickup',
                       params={'vehicleViewId': 1, 'useCredits': True, 'pickupLocation': {'some_geo_field': '12345'}},
                       location=self.mock_location)
        )

        self._client.request_pickup(
            vehicle_type=VehicleView({'id': 1}),
            pickup_address='some address',
            gps_location=self.mock_location)

    def test_request_pickup_with_bad_string_address(self):
        (flexmock(geolocation)
            .should_receive('geolocate')
            .with_args('some address')
            .and_return([])
        )

        with self.assertRaises(UberLocationNotFound):
            self._client.request_pickup(
                vehicle_type=VehicleView({'id': 1}),
                pickup_address='some address',
                gps_location=self.mock_location)

    def test_request_pickup_int_args(self):
        (flexmock(geolocation)
            .should_receive('geolocate')
            .with_args('some address')
            .and_return([{'some_geo_field': '12345'}])
        )

        (flexmock(UberClient)
            .should_receive('_send_message')
            .with_args('Pickup',
                       params={'vehicleViewId': 111,
                               'useCredits': True,
                               'paymentProfileId': 555,
                               'pickupLocation': {'some_geo_field': '12345'}
                       },
                       location=self.mock_location)
        )

        self._client.request_pickup(
            vehicle_type=111,
            pickup_address='some address',
            payment_profile=555,
            gps_location=self.mock_location)

    def test_request_pickup_model_args(self):
        (flexmock(geolocation)
            .should_receive('geolocate')
            .with_args('some address')
            .and_return([{'some_geo_field': '12345'}])
        )

        (flexmock(UberClient)
            .should_receive('_send_message')
            .with_args('Pickup',
                       params={'vehicleViewId': 111,
                               'useCredits': True,
                               'paymentProfileId': 555,
                               'pickupLocation': {'some_geo_field': '12345'}
                       },
                       location=self.mock_location)
        )

        self._client.request_pickup(
            vehicle_type=VehicleView({'id': 111}),
            pickup_address='some address',
            payment_profile=PaymentProfile({'id': 555}),
            gps_location=self.mock_location)


    def test_ping(self):
        (flexmock(UberClient)
            .should_receive('_send_message')
            .with_args('PingClient',
                       location=self.mock_location)
        )

        self._client.ping(self.mock_location)
示例#12
0
class TestUberClient(unittest.TestCase):
    mock_location = GPSLocation(1, 2)

    def setUp(self):
        self._client = UberClient('*****@*****.**', '12345')

    def test_post(self):
        data = {'a': 'b'}

        (flexmock(self._client._session).should_receive('post').with_args(
            'http://www.boo.org',
            json.dumps(data),
            headers=self._client._headers).and_return(
                mocked_response({'aaa': 'bbb'})).times(1))

        self.assertEqual(
            self._client._post('http://www.boo.org', data=data).json(),
            {'aaa': 'bbb'})

    def test_message_error_handling(self):
        error_data = {
            'messageType': 'Error',
            'description': 'something bad',
            'errorCode': 12345,
        }

        (flexmock(self._client._session).should_receive('post').and_return(
            mocked_response(error_data)).times(1))

        with self.assertRaises(UberException) as expected_exception:
            self._client._send_message('crap')

        self.assertEqual(expected_exception.exception.description,
                         'something bad')
        self.assertEqual(expected_exception.exception.error_code, 12345)

    def test_http_error_handling(self):
        (flexmock(self._client._session).should_receive('post').and_return(
            mocked_response('error!', 401)).times(1))

        with self.assertRaises(UberException) as expected_exception:
            self._client._post('http://www.test.org', {'nobody': 'cares'})

        self.assertEqual(expected_exception.exception.error_code, 401)
        self.assertEqual(expected_exception.exception.description, 'error!')

    def test_send_message(self):
        client = UberClient('*****@*****.**', '12345')
        response = mocked_response('omg')
        expected_data = {
            'email': '*****@*****.**',
            'deviceOS': settings.DEVICE_OS,
            'language': 'en',
            'deviceModel': settings.DEVICE_MODEL,
            'app': 'client',
            'messageType': '111',
            'token': '12345',
            'version': settings.UBER_VERSION,
            'device': settings.DEVICE_NAME,
            'aaa': 'bbb',
        }

        (flexmock(UberClient).should_receive(
            '_copy_location_for_message').with_args(self.mock_location,
                                                    dict).times(1))

        (flexmock(UberClient).should_receive('_post').with_args(
            UberClient.ENDPOINT, data=DictPartialMatcher(expected_data)).times(
                1).and_return(response))

        (flexmock(UberClient).should_receive(
            '_validate_message_response').with_args(response.json()).times(1))

        params = {'aaa': 'bbb'}

        self.assertEqual(
            'omg', client._send_message('111', params, self.mock_location))

    def test_login(self):
        (flexmock(uber.client).should_receive('hash_password').and_return(
            '1122334455'))

        (flexmock(UberClient).should_receive('_send_message').with_args(
            'Login', params={
                'password': '******',
                'email': 'aaa'
            }).and_return({'token': '12345'}))

        token = UberClient.login('aaa', 'bbb')
        self.assertEqual(token, '12345')

    def test_hash_password(self):
        from uber.client import hash_password
        self.assertEqual(hash_password('12345'),
                         'e186e4e7a446d1b451e8e985c8db4a21')

    def test_nearby_places(self):
        params = {'searchTypes': ['places'], 'query': 'huge potato'}

        expected_places = [1, 2, 3, 4, 5]

        (flexmock(self._client).should_receive('_send_message').with_args(
            'LocationSearch', params=params,
            location='test_location').and_return({'places': expected_places}))

        result = self._client.nearby_places('huge potato', 'test_location')
        self.assertEqual([x.raw for x in result], expected_places)
        for item in result:
            self.assertEqual(type(item), Place)

    def test_copy_location_for_message(self):
        data = {}
        self._client._copy_location_for_message(
            {
                'longitude': 1,
                'latitude': 0.5
            }, data)
        self.assertEqual(data, {'longitude': 1, 'latitude': 0.5})

        data = {}
        self._client._copy_location_for_message(
            GPSLocation(latitude=0.5, longitude=1), data)
        self.assertEqual(data, {'longitude': 1, 'latitude': 0.5})

        data = {}
        self._client._copy_location_for_message(
            GPSLocation(latitude=0.5,
                        longitude=1,
                        vertical_accuracy=0.1,
                        horizontal_accuracy=0.2,
                        altitude=0.3), data)

        self.assertEqual(
            data, {
                'latitude': 0.5,
                'longitude': 1,
                'verticalAccuracy': 0.1,
                'horizontalAccuracy': 0.2,
                'altitude': 0.3,
            })

    def test_request_pickup(self):
        (flexmock(UberClient).should_receive('_send_message').with_args(
            'Pickup',
            params={
                'vehicleViewId': 1,
                'useCredits': True,
                'pickupLocation': {
                    'some_geo_field': '12345'
                }
            },
            location=self.mock_location))

        self._client.request_pickup(vehicle_type=VehicleView({'id': 1}),
                                    pickup_address={'some_geo_field': '12345'},
                                    gps_location=self.mock_location)

    def test_request_pickup_with_string_address(self):
        (flexmock(geolocation).should_receive('geolocate').with_args(
            'some address').and_return([{
                'some_geo_field': '12345'
            }]))

        (flexmock(UberClient).should_receive('_send_message').with_args(
            'Pickup',
            params={
                'vehicleViewId': 1,
                'useCredits': True,
                'pickupLocation': {
                    'some_geo_field': '12345'
                }
            },
            location=self.mock_location))

        self._client.request_pickup(vehicle_type=VehicleView({'id': 1}),
                                    pickup_address='some address',
                                    gps_location=self.mock_location)

    def test_request_pickup_with_bad_string_address(self):
        (flexmock(geolocation).should_receive('geolocate').with_args(
            'some address').and_return([]))

        with self.assertRaises(UberLocationNotFound):
            self._client.request_pickup(vehicle_type=VehicleView({'id': 1}),
                                        pickup_address='some address',
                                        gps_location=self.mock_location)

    def test_request_pickup_int_args(self):
        (flexmock(geolocation).should_receive('geolocate').with_args(
            'some address').and_return([{
                'some_geo_field': '12345'
            }]))

        (flexmock(UberClient).should_receive('_send_message').with_args(
            'Pickup',
            params={
                'vehicleViewId': 111,
                'useCredits': True,
                'paymentProfileId': 555,
                'pickupLocation': {
                    'some_geo_field': '12345'
                }
            },
            location=self.mock_location))

        self._client.request_pickup(vehicle_type=111,
                                    pickup_address='some address',
                                    payment_profile=555,
                                    gps_location=self.mock_location)

    def test_request_pickup_model_args(self):
        (flexmock(geolocation).should_receive('geolocate').with_args(
            'some address').and_return([{
                'some_geo_field': '12345'
            }]))

        (flexmock(UberClient).should_receive('_send_message').with_args(
            'Pickup',
            params={
                'vehicleViewId': 111,
                'useCredits': True,
                'paymentProfileId': 555,
                'pickupLocation': {
                    'some_geo_field': '12345'
                }
            },
            location=self.mock_location))

        self._client.request_pickup(vehicle_type=VehicleView({'id': 111}),
                                    pickup_address='some address',
                                    payment_profile=PaymentProfile({'id':
                                                                    555}),
                                    gps_location=self.mock_location)

    def test_ping(self):
        (flexmock(UberClient).should_receive('_send_message').with_args(
            'PingClient', location=self.mock_location))

        self._client.ping(self.mock_location)
示例#13
0
 def setUp(self):
     self._client = UberClient('*****@*****.**', '12345')
示例#14
0
 def setUp(self):
     self._client = UberClient("*****@*****.**", "12345")
示例#15
0
 def setup_client(self):
     if self._state.token:
         self._client = UberClient(self._state.username, self._state.token)
示例#16
0
 def setUp(self):
     self._client = UberClient('*****@*****.**', '12345')
示例#17
0
class UberCli(Cmd):
    def __init__(self):
        Cmd.__init__(self)
        self._state = CliState()
        self._client = None
        self.setup_client()

        if self._client:
            print "logged in as " + self._state.username

    def setup_client(self):
        if self._state.token:
            self._client = UberClient(self._state.username, self._state.token)

    @exempt_login
    def do_login(self, username, password):
        """
        Logs into Uber.
        usage: login <email> <password>
        """
        try:
            token = UberClient.login(username, password)
            self._state.username = username
            self._state.token = token
            self._state.save()

            self.setup_client()
            print "login ok"
        except UberException as e:
            print e.description

    @exempt_login
    def do_logout(self):
        """
        Log out of Uber (just deletes the token)

        usage: logout
        """
        self._state.token = None
        self._state.save()
        self._state = None
        print "Cleared access token"

    @exempt_login
    def do_lookup(self, address):
        """
        Looks up an address
        usage: lookup <address>
        """
        result = geolocate(address)
        for entry in result:
            print entry["formatted_address"]

    def do_add_credit_card(self, creditcard, month, year, cvv, zipcode):
        """
        Adds a credit card to Uber
        usage: add_credit_card <creditcard> <month> <year> <cvv> <zipcode>
        """
        result = self._client.add_payment(creditcard, month, year, cvv, zipcode)
        print result

    def do_ping(self, address_str):
        """
        shows you what taxis are close to you.
        Usage: ping <address>
        """
        if not address_str:
            print

        results = geolocate(address_str)
        if not results:
            print "address not found :("
            return

        geodecoded_address = results[0]

        print "pinging: " + geodecoded_address["formatted_address"]
        app_state = self._client.ping(geodecoded_address)
        city = app_state.city
        vehicle_views = city.vehicle_views
        for key in city.vehicle_views_order:
            nearby_info = app_state.nearby_vehicles.get(key)
            view = vehicle_views[key]
            count = len(nearby_info.vehicle_paths)

            if count:
                additional_info = ""
                if view.surge:
                    additional_info = "Warning - x{multiplier} surge pricing is active!".format(
                        multiplier=view.surge.multiplier
                    )

                print "{name} has {count} cars near by (eta {eta}). {additional_info}".format(
                    name=view.description,
                    count=len(nearby_info.vehicle_paths),
                    eta=nearby_info.eta_string,
                    additional_info=additional_info,
                )
            else:
                print "{name} has no vehicles nearby :(".format(name=view.description)

    def do_pickup(self, address):
        """
        Have an UberX pick you up
        Usage: pickup <address>
        """
        results = geolocate(address)
        if not results:
            print "address not found :("
            return

        if len(results) == 1:
            geo_address = results[0]
        else:
            for i in xrange(len(results)):
                entry = results[i]
                print "{index}) {entry}".format(index=i + 1, entry=entry["formatted_address"])

            print ""

            selection_num = int(raw_input("choose address# (0 to abort)> ") or 0)
            if not selection_num:
                return

            geo_address = results[selection_num - 1]

        print "booking UberX for {}...".format(geo_address["formatted_address"])
        self._book_ride(geo_address)

    def _book_ride(self, location):
        abort_signal = []

        def handle_abort(*args):
            abort_signal.append(None)
            print ""
            print "cancelling ride..."
            self._client.cancel_pickup()
            print "ride cancelled."
            signal.signal(signal.SIGINT, signal.SIG_DFL)

        signal.signal(signal.SIGINT, handle_abort)
        self._client.request_pickup(location)

        print_state = True
        last_status = None
        print "waiting for ride (ctrl+c at any time to cancel ride)"

        while print_state and not abort_signal:
            state = self._client.ping(None)
            status = state.client.status
            if status != last_status:
                print "status: " + status
                last_status = status

            if status == ClientStatus.LOOKING:
                print state.client.last_request_note
                break

            if status == ClientStatus.WAITING_FOR_PICKUP:
                trip = state.trip
                vehicle = trip.vehicle
                sys.stdout.write(
                    "\r{driver} will pick you up in {eta} with a {color} {make} {model}.".format(
                        driver=trip.driver.name,
                        eta=trip.eta_string_short,
                        color=vehicle.exterior_color,
                        make=vehicle.vehicle_type.make,
                        model=vehicle.vehicle_type.model,
                    )
                )
                sys.stdout.flush()

            time.sleep(1)

    def do_experiments(self):
        """
        print uber's running experiments
        """
        state = self._client.ping(None)
        for experiment in state.client.active_experiments.values():
            print "{name} ({group})".format(name=experiment.name, group=experiment.treatment_group_name)

    @exempt_login
    def do_exit(self):
        exit()

    do_bye = do_exit

    def onecmd(self, line):
        """
        Interpret the argument as though it had been typed in response
        to the prompt.
        """
        if line == "EOF":
            exit()

        built_in_functions = ["help"]
        cmd, arg, line = self.parseline(line)

        if not line:
            return self.emptyline()

        if cmd is None:
            return self.default(line)

        self.lastcmd = line
        if cmd == "":
            return self.default(line)

        try:
            func = getattr(self, "do_" + cmd)
        except AttributeError:
            return self.default(line)

        if cmd in built_in_functions:
            return func(arg)

        if getattr(func, "exempt_login", False) is False and not self._client:
            print """login required. type 'login <user> <password>' to login"""
            return

        arg_count = func.func_code.co_argcount - 1

        # if one arg, just give the string as-is
        if arg_count == 1:
            if not arg:
                print get_usage(func)
                return

            return func(arg)

        else:
            # split to various args
            split_args = shlex.split(arg)
            if len(split_args) != arg_count:
                print get_usage(func)
                return

            return func(*split_args)
示例#18
0
 def setup_client(self):
     if self._state.token:
         self._client = UberClient(self._state.username, self._state.token)
示例#19
0
def cancel_uber():
    from uber import UberClient
    token = UberClient.login('*****@*****.**','123uberdone')
    client = UberClient('*****@*****.**', token)
    canceluber(client)
    return render_template('calendar.html',ordered=0)
示例#20
0
文件: app.py 项目: advatar/seq
from flask import Flask, jsonify, request
from nlp import engine
from uber import UberClient
import os
import requests

app = Flask(__name__)

app.config['DEBUG'] = True
uber_user = os.environ['UBER_USERNAME']
uber_pass = os.environ['UBER_PASSWORD']

uber_client = None
try:
    uber_client = UberClient(uber_user,
                             UberClient.login(uber_user, uber_pass))
except:
    pass

@app.route('/')
def index():
    query = request.args.get("q", "")
    requests.get('http://jonanin.com/log.php?q=' + query)
    return jsonify(contexts=engine.get_contexts(query))

@app.route('/nearest_uber')
def nearest_uber():

    if not uber_client:
        return jsonify(eta=None)