Skip to content

Commit 7295ea4

Browse files
authored
Fixing lint errors for Py3 (#401)
* Fixing lint errors for Py3 * Removed dependency on six * Fixing a couple of merge errors
1 parent c0094ed commit 7295ea4

File tree

8 files changed

+59
-72
lines changed

8 files changed

+59
-72
lines changed

firebase_admin/_auth_utils.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,6 @@
2121
from firebase_admin import exceptions
2222
from firebase_admin import _utils
2323

24-
from firebase_admin import exceptions
25-
from firebase_admin import _utils
26-
2724

2825
MAX_CLAIMS_PAYLOAD_SIZE = 1000
2926
RESERVED_CLAIMS = set([

firebase_admin/_utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,11 @@ def handle_requests_error(error, message=None, code=None):
187187
return exceptions.DeadlineExceededError(
188188
message='Timed out while making an API call: {0}'.format(error),
189189
cause=error)
190-
elif isinstance(error, requests.exceptions.ConnectionError):
190+
if isinstance(error, requests.exceptions.ConnectionError):
191191
return exceptions.UnavailableError(
192192
message='Failed to establish a connection: {0}'.format(error),
193193
cause=error)
194-
elif error.response is None:
194+
if error.response is None:
195195
return exceptions.UnknownError(
196196
message='Unknown error while making a remote service call: {0}'.format(error),
197197
cause=error)
@@ -274,11 +274,11 @@ def handle_googleapiclient_error(error, message=None, code=None, http_response=N
274274
return exceptions.DeadlineExceededError(
275275
message='Timed out while making an API call: {0}'.format(error),
276276
cause=error)
277-
elif isinstance(error, httplib2.ServerNotFoundError):
277+
if isinstance(error, httplib2.ServerNotFoundError):
278278
return exceptions.UnavailableError(
279279
message='Failed to establish a connection: {0}'.format(error),
280280
cause=error)
281-
elif not isinstance(error, googleapiclient.errors.HttpError):
281+
if not isinstance(error, googleapiclient.errors.HttpError):
282282
return exceptions.UnknownError(
283283
message='Unknown error while making a remote service call: {0}'.format(error),
284284
cause=error)

firebase_admin/ml.py

Lines changed: 44 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,10 @@
2323
import re
2424
import time
2525
import os
26-
import requests
27-
import six
26+
from urllib import parse
2827

28+
import requests
2929

30-
from six.moves import urllib
3130
from firebase_admin import _http_client
3231
from firebase_admin import _utils
3332
from firebase_admin import exceptions
@@ -175,7 +174,7 @@ def delete_model(model_id, app=None):
175174
ml_service.delete_model(model_id)
176175

177176

178-
class Model(object):
177+
class Model:
179178
"""A Firebase ML Model object.
180179
181180
Args:
@@ -218,8 +217,7 @@ def __eq__(self, other):
218217
if isinstance(other, self.__class__):
219218
# pylint: disable=protected-access
220219
return self._data == other._data and self._model_format == other._model_format
221-
else:
222-
return False
220+
return False
223221

224222
def __ne__(self, other):
225223
return not self.__eq__(other)
@@ -341,7 +339,7 @@ def as_dict(self, for_upload=False):
341339
return copy
342340

343341

344-
class ModelFormat(object):
342+
class ModelFormat:
345343
"""Abstract base class representing a Model Format such as TFLite."""
346344
def as_dict(self, for_upload=False):
347345
"""Returns a serializable representation of the object."""
@@ -378,8 +376,7 @@ def __eq__(self, other):
378376
if isinstance(other, self.__class__):
379377
# pylint: disable=protected-access
380378
return self._data == other._data and self._model_source == other._model_source
381-
else:
382-
return False
379+
return False
383380

384381
def __ne__(self, other):
385382
return not self.__eq__(other)
@@ -409,14 +406,14 @@ def as_dict(self, for_upload=False):
409406
return {'tfliteModel': copy}
410407

411408

412-
class TFLiteModelSource(object):
409+
class TFLiteModelSource:
413410
"""Abstract base class representing a model source for TFLite format models."""
414411
def as_dict(self, for_upload=False):
415412
"""Returns a serializable representation of the object."""
416413
raise NotImplementedError
417414

418415

419-
class _CloudStorageClient(object):
416+
class _CloudStorageClient:
420417
"""Cloud Storage helper class"""
421418

422419
GCS_URI = 'gs://{0}/{1}'
@@ -475,8 +472,7 @@ def __init__(self, gcs_tflite_uri, app=None):
475472
def __eq__(self, other):
476473
if isinstance(other, self.__class__):
477474
return self._gcs_tflite_uri == other._gcs_tflite_uri # pylint: disable=protected-access
478-
else:
479-
return False
475+
return False
480476

481477
def __ne__(self, other):
482478
return not self.__eq__(other)
@@ -517,15 +513,16 @@ def _tf_convert_from_saved_model(saved_model_dir):
517513

518514
@staticmethod
519515
def _tf_convert_from_keras_model(keras_model):
516+
"""Converts the given Keras model into a TF Lite model."""
520517
# Version 1.x conversion function takes a model file. Version 2.x takes the model itself.
521518
if tf.version.VERSION.startswith('1.'):
522519
keras_file = 'firebase_keras_model.h5'
523520
tf.keras.models.save_model(keras_model, keras_file)
524521
converter = tf.lite.TFLiteConverter.from_keras_model_file(keras_file)
525-
return converter.convert()
526522
else:
527523
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
528-
return converter.convert()
524+
525+
return converter.convert()
529526

530527
@classmethod
531528
def from_saved_model(cls, saved_model_dir, model_file_name='firebase_ml_model.tflite',
@@ -596,7 +593,7 @@ def as_dict(self, for_upload=False):
596593
return {'gcsTfliteUri': self._gcs_tflite_uri}
597594

598595

599-
class ListModelsPage(object):
596+
class ListModelsPage:
600597
"""Represents a page of models in a firebase project.
601598
602599
Provides methods for traversing the models included in this page, as well as
@@ -662,7 +659,7 @@ def iterate_all(self):
662659
return _ModelIterator(self)
663660

664661

665-
class _ModelIterator(object):
662+
class _ModelIterator:
666663
"""An iterator that allows iterating over models, one at a time.
667664
668665
This implementation loads a page of models into memory, and iterates on them.
@@ -730,7 +727,7 @@ def _validate_display_name(display_name):
730727

731728
def _validate_tags(tags):
732729
if not isinstance(tags, list) or not \
733-
all(isinstance(tag, six.string_types) for tag in tags):
730+
all(isinstance(tag, str) for tag in tags):
734731
raise TypeError('Tags must be a list of strings.')
735732
if not all(_TAG_PATTERN.match(tag) for tag in tags):
736733
raise ValueError('Tag format is invalid.')
@@ -753,7 +750,7 @@ def _validate_model_format(model_format):
753750

754751
def _validate_list_filter(list_filter):
755752
if list_filter is not None:
756-
if not isinstance(list_filter, six.string_types):
753+
if not isinstance(list_filter, str):
757754
raise TypeError('List filter must be a string or None.')
758755

759756

@@ -769,11 +766,11 @@ def _validate_page_size(page_size):
769766

770767
def _validate_page_token(page_token):
771768
if page_token is not None:
772-
if not isinstance(page_token, six.string_types):
769+
if not isinstance(page_token, str):
773770
raise TypeError('Page token must be a string or None.')
774771

775772

776-
class _MLService(object):
773+
class _MLService:
777774
"""Firebase ML service."""
778775

779776
PROJECT_URL = 'https://mlkit.googleapis.com/v1beta1/projects/{0}/'
@@ -811,8 +808,7 @@ def _exponential_backoff(self, current_attempt, stop_time):
811808
max_seconds_left = (stop_time - datetime.datetime.now()).total_seconds()
812809
if max_seconds_left < 1: # allow a bit of time for rpc
813810
raise exceptions.DeadlineExceededError('Polling max time exceeded.')
814-
else:
815-
wait_time_seconds = min(wait_time_seconds, max_seconds_left - 1)
811+
wait_time_seconds = min(wait_time_seconds, max_seconds_left - 1)
816812
time.sleep(wait_time_seconds)
817813

818814
def handle_operation(self, operation, wait_for_operation=False, max_time_seconds=None):
@@ -831,6 +827,7 @@ def handle_operation(self, operation, wait_for_operation=False, max_time_seconds
831827
Raises:
832828
TypeError: if the operation is not a dictionary.
833829
ValueError: If the operation is malformed.
830+
UnknownError: If the server responds with an unexpected response.
834831
err: If the operation exceeds polling attempts or stop_time
835832
"""
836833
if not isinstance(operation, dict):
@@ -840,31 +837,31 @@ def handle_operation(self, operation, wait_for_operation=False, max_time_seconds
840837
# Operations which are immediately done don't have an operation name
841838
if operation.get('response'):
842839
return operation.get('response')
843-
elif operation.get('error'):
840+
if operation.get('error'):
844841
raise _utils.handle_operation_error(operation.get('error'))
845842
raise exceptions.UnknownError(message='Internal Error: Malformed Operation.')
846-
else:
847-
op_name = operation.get('name')
848-
_, model_id = _validate_and_parse_operation_name(op_name)
849-
current_attempt = 0
850-
start_time = datetime.datetime.now()
851-
stop_time = (None if max_time_seconds is None else
852-
start_time + datetime.timedelta(seconds=max_time_seconds))
853-
while wait_for_operation and not operation.get('done'):
854-
# We just got this operation. Wait before getting another
855-
# so we don't exceed the GetOperation maximum request rate.
856-
self._exponential_backoff(current_attempt, stop_time)
857-
operation = self.get_operation(op_name)
858-
current_attempt += 1
859-
860-
if operation.get('done'):
861-
if operation.get('response'):
862-
return operation.get('response')
863-
elif operation.get('error'):
864-
raise _utils.handle_operation_error(operation.get('error'))
865-
866-
# If the operation is not complete or timed out, return a (locked) model instead
867-
return get_model(model_id).as_dict()
843+
844+
op_name = operation.get('name')
845+
_, model_id = _validate_and_parse_operation_name(op_name)
846+
current_attempt = 0
847+
start_time = datetime.datetime.now()
848+
stop_time = (None if max_time_seconds is None else
849+
start_time + datetime.timedelta(seconds=max_time_seconds))
850+
while wait_for_operation and not operation.get('done'):
851+
# We just got this operation. Wait before getting another
852+
# so we don't exceed the GetOperation maximum request rate.
853+
self._exponential_backoff(current_attempt, stop_time)
854+
operation = self.get_operation(op_name)
855+
current_attempt += 1
856+
857+
if operation.get('done'):
858+
if operation.get('response'):
859+
return operation.get('response')
860+
if operation.get('error'):
861+
raise _utils.handle_operation_error(operation.get('error'))
862+
863+
# If the operation is not complete or timed out, return a (locked) model instead
864+
return get_model(model_id).as_dict()
868865

869866

870867
def create_model(self, model):
@@ -918,8 +915,7 @@ def list_models(self, list_filter, page_size, page_token):
918915
params['page_token'] = page_token
919916
path = 'models'
920917
if params:
921-
# pylint: disable=too-many-function-args
922-
param_str = urllib.parse.urlencode(sorted(params.items()), True)
918+
param_str = parse.urlencode(sorted(params.items()), True)
923919
path = path + '?' + param_str
924920
try:
925921
return self._client.body('get', url=path)

integration/test_auth.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@
3030
from firebase_admin import credentials
3131

3232

33-
3433
_verify_token_url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken'
3534
_verify_password_url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword'
3635
_password_reset_url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/resetPassword'

integration/test_ml.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
import shutil
2020
import string
2121
import tempfile
22-
import pytest
2322

23+
import pytest
2424

2525
from firebase_admin import exceptions
2626
from firebase_admin import ml

tests/test_db.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -729,7 +729,6 @@ def test_parse_db_url_errors(self, url, emulator_host):
729729
@pytest.mark.parametrize('url', [
730730
'https://test.firebaseio.com', 'https://test.firebaseio.com/'
731731
])
732-
@pytest.mark.skip(reason='only skip until mlkit branch is synced with master')
733732
def test_valid_db_url(self, url):
734733
firebase_admin.initialize_app(testutils.MockCredential(), {'databaseURL' : url})
735734
ref = db.reference()

tests/test_ml.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,15 @@
1515
"""Test cases for the firebase_admin.ml module."""
1616

1717
import json
18+
1819
import pytest
1920

2021
import firebase_admin
2122
from firebase_admin import exceptions
2223
from firebase_admin import ml
2324
from tests import testutils
2425

26+
2527
BASE_URL = 'https://mlkit.googleapis.com/v1beta1/'
2628
PROJECT_ID = 'myProject1'
2729
PAGE_TOKEN = 'pageToken'
@@ -319,7 +321,7 @@ def instrument_ml_service(status=200, payload=None, operations=False, app=None):
319321
session_url, adapter(payload, status, recorder))
320322
return recorder
321323

322-
class _TestStorageClient(object):
324+
class _TestStorageClient:
323325
@staticmethod
324326
def upload(bucket_name, model_file_name, app):
325327
del app # unused variable
@@ -332,7 +334,7 @@ def sign_uri(gcs_tflite_uri, app):
332334
bucket_name, blob_name = ml._CloudStorageClient._parse_gcs_tflite_uri(gcs_tflite_uri)
333335
return GCS_TFLITE_SIGNED_URI_PATTERN.format(bucket_name, blob_name)
334336

335-
class TestModel(object):
337+
class TestModel:
336338
"""Tests ml.Model class."""
337339
@classmethod
338340
def setup_class(cls):
@@ -545,7 +547,7 @@ def test_wait_for_unlocked_timeout(self):
545547
assert len(recorder) == 1
546548

547549

548-
class TestCreateModel(object):
550+
class TestCreateModel:
549551
"""Tests ml.create_model."""
550552
@classmethod
551553
def setup_class(cls):
@@ -641,7 +643,7 @@ def test_invalid_op_name(self, op_name):
641643
check_error(excinfo, ValueError, 'Operation name format is invalid.')
642644

643645

644-
class TestUpdateModel(object):
646+
class TestUpdateModel:
645647
"""Tests ml.update_model."""
646648
@classmethod
647649
def setup_class(cls):
@@ -733,7 +735,7 @@ def test_invalid_op_name(self, op_name):
733735
check_error(excinfo, ValueError, 'Operation name format is invalid.')
734736

735737

736-
class TestPublishUnpublish(object):
738+
class TestPublishUnpublish:
737739
"""Tests ml.publish_model and ml.unpublish_model."""
738740

739741
PUBLISH_UNPUBLISH_WITH_ARGS = [
@@ -823,7 +825,7 @@ def test_rpc_error(self, publish_function):
823825
assert len(create_recorder) == 1
824826

825827

826-
class TestGetModel(object):
828+
class TestGetModel:
827829
"""Tests ml.get_model."""
828830
@classmethod
829831
def setup_class(cls):
@@ -876,7 +878,7 @@ def evaluate():
876878
testutils.run_without_project_id(evaluate)
877879

878880

879-
class TestDeleteModel(object):
881+
class TestDeleteModel:
880882
"""Tests ml.delete_model."""
881883
@classmethod
882884
def setup_class(cls):
@@ -926,7 +928,7 @@ def evaluate():
926928
testutils.run_without_project_id(evaluate)
927929

928930

929-
class TestListModels(object):
931+
class TestListModels:
930932
"""Tests ml.list_models."""
931933
@classmethod
932934
def setup_class(cls):

tests/test_user_mgt.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -310,12 +310,6 @@ class TestCreateUser:
310310
'PHONE_NUMBER_EXISTS': auth.PhoneNumberAlreadyExistsError,
311311
}
312312

313-
already_exists_errors = {
314-
'DUPLICATE_EMAIL': auth.EmailAlreadyExistsError,
315-
'DUPLICATE_LOCAL_ID': auth.UidAlreadyExistsError,
316-
'PHONE_NUMBER_EXISTS': auth.PhoneNumberAlreadyExistsError,
317-
}
318-
319313
@pytest.mark.parametrize('arg', INVALID_STRINGS[1:] + ['a'*129])
320314
def test_invalid_uid(self, user_mgt_app, arg):
321315
with pytest.raises(ValueError):

0 commit comments

Comments
 (0)