8000 Added some test cases to cover some edge cases (#80) · AFFOA/firebase-admin-python@7918ea9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7918ea9

Browse files
authored
Added some test cases to cover some edge cases (firebase#80)
* Added some test cases to cover some edge cases * Tests for _utils module
1 parent 1746377 commit 7918ea9

File tree

8 files changed

+102
-18
lines changed

8 files changed

+102
-18
lines changed

firebase_admin/credentials.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ def __init__(self, refresh_token):
180180
refresh_token = json_data['refresh_token']
181181
except KeyError as error:
182182
raise ValueError('Failed to initialize a refresh token credential. '
183-
'Caused by: "{0}"'.format(error))
183+
'Missing key: {0}'.format(error))
184184
self._g_credential = credentials.Credentials(
185185
token=None, refresh_token=refresh_token,
186186
token_uri='https://accounts.google.com/o/oauth2/token',

firebase_admin/db.py

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222

2323
import collections
2424
import json
25-
import numbers
2625
import sys
2726

2827
import requests
@@ -361,15 +360,6 @@ def order_by_value(self):
361360
def _add_suffix(self, suffix='.json'):
362361
return self._pathurl + suffix
363362

364-
@classmethod
365-
def _check_priority(cls, priority):
366-
if isinstance(priority, six.string_types) and priority.isalnum():
367-
return
368-
if isinstance(priority, numbers.Number):
369-
return
370-
raise ValueError('Illegal priority value: "{0}". Priority values must be numeric or '
371-
'alphanumeric.'.format(priority))
372-
373363

374364
class Query(object):
375365
"""Represents a complex query that can be executed on a Reference.
@@ -529,6 +519,7 @@ def __init__(self, message, error):
529519
Exception.__init__(self, message)
530520
self.detail = error
531521

522+
532523
class TransactionError(Exception):
533524
"""Represents an Exception encountered while performing a transaction."""
534525

firebase_admin/storage.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,14 +64,10 @@ def __init__(self, credentials, project, default_bucket):
6464
@classmethod
6565
def from_app(cls, app):
6666
credentials = app.credential.get_credential()
67+
default_bucket = app.options.get('storageBucket')
6768
# Specifying project ID is not required, but providing it when available
6869
# significantly speeds up the initialization of the storage client.
69-
try:
70-
project = app.credential.project_id
71-
except AttributeError:
72-
project = None
73-
default_bucket = app.options.get('storageBucket')
74-
return _StorageClient(credentials, project, default_bucket)
70+
return _StorageClient(credentials, app.project_id, default_bucket)
7571

7672
def bucket(self, name=None):
7773
"""Returns a handle to the specified Cloud Storage Bucket."""

tests/test_app.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,3 +207,13 @@ def test_app_services(self, init_app):
207207
firebase_admin.delete_app(init_app)
208208
with pytest.raises(ValueError):
209209
_utils.get_app_service(init_app, 'test.service', AppService)
210+
211+
@pytest.mark.parametrize('arg', [0, 1, True, False, 'str', list(), dict(), tuple()])
212+
def test_app_services_invalid_arg(self, arg):
213+
with pytest.raises(ValueError):
214+
_utils.get_app_service(arg, 'test.service', AppService)
215+
216+
def test_app_services_invalid_app(self, init_app):
217+
app = firebase_admin.App(init_app.name, init_app.credential, {})
218+
with pytest.raises(ValueError):
219+
_utils.get_app_service(app, 'test.service', AppService)

tests/test_auth.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,8 @@ class TestCreateCustomToken(object):
182182
'StrClaims': (MOCK_UID, 'foo', ValueError),
183183
'ListClaims': (MOCK_UID, [], ValueError),
184184
'TupleClaims': (MOCK_UID, (1, 2), ValueError),
185-
'ReservedClaims': (MOCK_UID, {'sub':'1234'}, ValueError),
185+
'SingleReservedClaim': (MOCK_UID, {'sub':'1234'}, ValueError),
186+
'MultipleReservedClaims': (MOCK_UID, {'sub':'1234', 'aud':'foo'}, ValueError),
186187
}
187188

188189
@pytest.mark.parametrize('user,claims', valid_args.values(),

tests/test_credentials.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,18 @@ def test_invalid_args(self, arg):
146146
with pytest.raises(ValueError):
147147
credentials.RefreshToken(arg)
148148

149+
@pytest.mark.parametrize('key', ['client_id', 'client_secret', 'refresh_token'])
150+
def test_required_field(self, key):
151+
data = {
152+
'client_id': 'value',
153+
'client_secret': 'value',
154+
'refresh_token': 'value',
155+
'type': 'authorized_user'
156+
}
157+
del data[key]
158+
with pytest.raises(ValueError):
159+
credentials.RefreshToken(data)
160+
149161
def _verify_credential(self, credential):
150162
assert credential.client_id == 'mock.apps.googleusercontent.com'
151163
assert credential.client_secret == 'mock-secret'

tests/test_db.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -730,6 +730,11 @@ def test_all_in(self, initquery):
730730
expected = 'endAt=3&equalTo=2&limitToFirst=10&orderBy="{0}"&startAt=1'.format(order_by)
731731
assert query._querystr == expected
732732

733+
def test_invalid_query_args(self):
734+
ref = db.Reference(path='foo')
735+
with pytest.raises(ValueError):
736+
db.Query(order_by='$key', client=ref._client, pathurl=ref._add_suffix(), foo='bar')
737+
733738

734739
class TestSorter(object):
735740
"""Test cases for db._Sorter class."""
@@ -740,6 +745,7 @@ class TestSorter(object):
740745
({'k1' : 3, 'k2' : 1, 'k3' : 2}, ['k2', 'k3', 'k1']),
741746
({'k1' : 3, 'k2' : 1, 'k3' : 1}, ['k2', 'k3', 'k1']),
742747
({'k1' : 1, 'k2' : 2, 'k3' : 1}, ['k1', 'k3', 'k2']),
748+
({'k1' : 2, 'k2' : 2, 'k3' : 1}, ['k3', 'k1', 'k2']),
743749
({'k1' : 'foo', 'k2' : 'bar', 'k3' : 'baz'}, ['k2', 'k3', 'k1']),
744750
({'k1' : 'foo', 'k2' : 'bar', 'k3' : 10}, ['k3', 'k2', 'k1']),
745751
({'k1' : 'foo', 'k2' : 'bar', 'k3' : None}, ['k3', 'k2', 'k1']),
@@ -758,6 +764,8 @@ class TestSorter(object):
758764
([1, 2, 3], [1, 2, 3]),
759765
([3, 2, 1], [1, 2, 3]),
760766
([1, 3, 2], [1, 2, 3]),
767+
([1, 3, 3], [1, 3, 3]),
768+
([2, 3, 2], [2, 2, 3]),
761769
(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo']),
762770
(['foo', 1, False, None, 0, True], [None, False, True, 0, 1, 'foo']),
763771
]

tests/test_http_client.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Copyright 2017 Google Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Tests for firebase_admin._http_client."""
16+
import requests
17+
18+
from firebase_admin import _http_client
19+
from tests import testutils
20+
21+
22+
_TEST_URL = 'http://firebase.test.url/'
23+
24+
25+
def test_http_client_default_session():
26+
client = _http_client.HttpClient()
27+
assert client.session is not None
28+
assert client.base_url == ''
29+
recorder = _instrument(client, 'body')
30+
resp = client.request('get', _TEST_URL)
31+
assert resp.status_code == 200
32+
assert resp.text == 'body'
33+
assert len(recorder) == 1
34+
assert recorder[0].method == 'GET'
35+
assert recorder[0].url == _TEST_URL
36+
37+
def test_http_client_custom_session():
38+
session = requests.Session()
39+
client = _http_client.HttpClient(session=session)
40+
assert client.session is session
41+
assert client.base_url == ''
42+
recorder = _instrument(client, 'body')
43+
resp = client.request('get', _TEST_URL)
44+
assert resp.status_code == 200
45+
assert resp.text == 'body'
46+
assert len(recorder) == 1
47+
assert recorder[0].method == 'GET'
48+
assert recorder[0].url == _TEST_URL
49+
50+
def test_base_url():
51+
client = _http_client.HttpClient(base_url=_TEST_URL)
52+
assert client.session is not None
53+
assert client.base_url == _TEST_URL
54+
recorder = _instrument(client, 'body')
55+
resp = client.request('get', 'foo')
56+
assert resp.status_code == 200
57+
assert resp.text == 'body'
58+
assert len(recorder) == 1
59+
assert recorder[0].method == 'GET'
60+
assert recorder[0].url == _TEST_URL + 'foo'
61+
62+
def _instrument(client, payload, status=200):
63+
recorder = []
64+
adapter = testutils.MockAdapter(payload, status, recorder)
65+
client.session.mount(_TEST_URL, adapter)
66+
return recorder

0 commit comments

Comments
 (0)
0