Skip to content

Commit

Permalink
add blacken to noxfile (#6795)
Browse files Browse the repository at this point in the history
  • Loading branch information
crwilcox authored Nov 30, 2018
1 parent 6d16b71 commit 2549af1
Show file tree
Hide file tree
Showing 10 changed files with 270 additions and 317 deletions.
2 changes: 2 additions & 0 deletions packages/google-cloud-resource-manager/google/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@

try:
import pkg_resources

pkg_resources.declare_namespace(__name__)
except ImportError:
import pkgutil

__path__ = pkgutil.extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@

try:
import pkg_resources

pkg_resources.declare_namespace(__name__)
except ImportError:
import pkgutil

__path__ = pkgutil.extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@


from pkg_resources import get_distribution
__version__ = get_distribution('google-cloud-resource-manager').version

__version__ = get_distribution("google-cloud-resource-manager").version

from google.cloud.resource_manager.client import Client
from google.cloud.resource_manager.project import Project


SCOPE = Client.SCOPE

__all__ = ['__version__', 'Client', 'Project', 'SCOPE']
__all__ = ["__version__", "Client", "Project", "SCOPE"]
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,13 @@ class Connection(_http.JSONConnection):
:param client: The client that owns the current connection.
"""

API_BASE_URL = 'https://cloudresourcemanager.googleapis.com'
API_BASE_URL = "https://cloudresourcemanager.googleapis.com"
"""The base of the API call URL."""

API_VERSION = 'v1beta1'
API_VERSION = "v1beta1"
"""The version of the API, used in building the API call's URL."""

API_URL_TEMPLATE = '{api_base_url}/{api_version}{path}'
API_URL_TEMPLATE = "{api_base_url}/{api_version}{path}"
"""A template for the URL of a particular API call."""

_EXTRA_HEADERS = {
_http.CLIENT_INFO_HEADER: _CLIENT_INFO,
}
_EXTRA_HEADERS = {_http.CLIENT_INFO_HEADER: _CLIENT_INFO}
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,11 @@ class Client(BaseClient):
change in the future.
"""

SCOPE = ('https://www.googleapis.com/auth/cloud-platform',)
SCOPE = ("https://www.googleapis.com/auth/cloud-platform",)
"""The scopes required for authenticating as a Resouce Manager consumer."""

def __init__(self, credentials=None, _http=None):
super(Client, self).__init__(
credentials=credentials, _http=_http)
super(Client, self).__init__(credentials=credentials, _http=_http)
self._connection = Connection(self)

def new_project(self, project_id, name=None, labels=None):
Expand Down Expand Up @@ -85,8 +84,7 @@ def new_project(self, project_id, name=None, labels=None):
:class:`~google.cloud.resource_manager.project.Project`
**without** any metadata loaded.
"""
return Project(project_id=project_id,
client=self, name=name, labels=labels)
return Project(project_id=project_id, client=self, name=name, labels=labels)

def fetch_project(self, project_id):
"""Fetch an existing project and it's relevant metadata by ID.
Expand Down Expand Up @@ -160,21 +158,22 @@ def list_projects(self, filter_params=None, page_size=None):
extra_params = {}

if page_size is not None:
extra_params['pageSize'] = page_size
extra_params["pageSize"] = page_size

if filter_params is not None:
extra_params['filter'] = [
'{}:{}'.format(key, value)
extra_params["filter"] = [
"{}:{}".format(key, value)
for key, value in six.iteritems(filter_params)
]

return page_iterator.HTTPIterator(
client=self,
api_request=self._connection.api_request,
path='/projects',
path="/projects",
item_to_value=_item_to_project,
items_key='projects',
extra_params=extra_params)
items_key="projects",
extra_params=extra_params,
)


def _item_to_project(iterator, resource):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ class Project(object):
:type labels: dict
:param labels: A list of labels associated with the project.
"""

def __init__(self, project_id, client, name=None, labels=None):
self._client = client
self.project_id = project_id
Expand All @@ -61,7 +62,7 @@ def __init__(self, project_id, client, name=None, labels=None):
self.parent = None

def __repr__(self):
return '<Project: %r (%r)>' % (self.name, self.project_id)
return "<Project: %r (%r)>" % (self.name, self.project_id)

@classmethod
def from_api_repr(cls, resource, client):
Expand All @@ -76,30 +77,30 @@ def from_api_repr(cls, resource, client):
:rtype: :class:`google.cloud.resource_manager.project.Project`
:returns: The project created.
"""
project = cls(project_id=resource['projectId'], client=client)
project = cls(project_id=resource["projectId"], client=client)
project.set_properties_from_api_repr(resource)
return project

def set_properties_from_api_repr(self, resource):
"""Update specific properties from its API representation."""
self.name = resource.get('name')
self.number = resource['projectNumber']
self.labels = resource.get('labels', {})
self.status = resource['lifecycleState']
if 'parent' in resource:
self.parent = resource['parent']
self.name = resource.get("name")
self.number = resource["projectNumber"]
self.labels = resource.get("labels", {})
self.status = resource["lifecycleState"]
if "parent" in resource:
self.parent = resource["parent"]

@property
def full_name(self):
"""Fully-qualified name (ie, ``'projects/purple-spaceship-123'``)."""
if not self.project_id:
raise ValueError('Missing project ID.')
return 'projects/%s' % (self.project_id)
raise ValueError("Missing project ID.")
return "projects/%s" % (self.project_id)

@property
def path(self):
"""URL for the project (ie, ``'/projects/purple-spaceship-123'``)."""
return '/%s' % (self.full_name)
return "/%s" % (self.full_name)

def _require_client(self, client):
"""Check client or verify over-ride.
Expand Down Expand Up @@ -129,13 +130,10 @@ def create(self, client=None):
"""
client = self._require_client(client)

data = {
'projectId': self.project_id,
'name': self.name,
'labels': self.labels,
}
resp = client._connection.api_request(method='POST', path='/projects',
data=data)
data = {"projectId": self.project_id, "name": self.name, "labels": self.labels}
resp = client._connection.api_request(
method="POST", path="/projects", data=data
)
self.set_properties_from_api_repr(resource=resp)

def reload(self, client=None):
Expand Down Expand Up @@ -164,7 +162,7 @@ def reload(self, client=None):

# We assume the project exists. If it doesn't it will raise a NotFound
# exception.
resp = client._connection.api_request(method='GET', path=self.path)
resp = client._connection.api_request(method="GET", path=self.path)
self.set_properties_from_api_repr(resource=resp)

def exists(self, client=None):
Expand All @@ -186,7 +184,7 @@ def exists(self, client=None):
try:
# Note that we have to request the entire resource as the API
# doesn't provide a way tocheck for existence only.
client._connection.api_request(method='GET', path=self.path)
client._connection.api_request(method="GET", path=self.path)
except NotFound:
return False
else:
Expand All @@ -205,14 +203,9 @@ def update(self, client=None):
"""
client = self._require_client(client)

data = {
'name': self.name,
'labels': self.labels,
'parent': self.parent,
}
data = {"name": self.name, "labels": self.labels, "parent": self.parent}

resp = client._connection.api_request(
method='PUT', path=self.path, data=data)
resp = client._connection.api_request(method="PUT", path=self.path, data=data)
self.set_properties_from_api_repr(resp)

def delete(self, client=None, reload_data=False):
Expand Down Expand Up @@ -240,7 +233,7 @@ def delete(self, client=None, reload_data=False):
Default: :data:`False`.
"""
client = self._require_client(client)
client._connection.api_request(method='DELETE', path=self.path)
client._connection.api_request(method="DELETE", path=self.path)

# If the reload flag is set, reload the project.
if reload_data:
Expand Down Expand Up @@ -270,8 +263,7 @@ def undelete(self, client=None, reload_data=False):
Default: :data:`False`.
"""
client = self._require_client(client)
client._connection.api_request(
method='POST', path=self.path + ':undelete')
client._connection.api_request(method="POST", path=self.path + ":undelete")

# If the reload flag is set, reload the project.
if reload_data:
Expand Down
60 changes: 39 additions & 21 deletions packages/google-cloud-resource-manager/noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,45 @@
)


@nox.session(python="3.7")
def lint(session):
"""Run linters.
Returns a failure if the linters find linting errors or sufficiently
serious code quality issues.
"""
session.install("flake8", "black", *LOCAL_DEPS)
session.run(
"black",
"--check",
"google",
"tests",
"docs",
)
session.run("flake8", "google", "tests")


@nox.session(python="3.6")
def blacken(session):
"""Run black.
Format code to uniform standard.
"""
session.install("black")
session.run(
"black",
"google",
"tests",
"docs",
)


@nox.session(python='3.6')
def lint_setup_py(session):
"""Verify that setup.py is valid (including RST check)."""
session.install('docutils', 'Pygments')
session.run(
'python', 'setup.py', 'check', '--restructuredtext', '--strict')


def default(session):
"""Default unit test session.
Expand Down Expand Up @@ -58,27 +97,6 @@ def unit(session):
default(session)


@nox.session(python='3.6')
def lint(session):
"""Run linters.
Returns a failure if the linters find linting errors or sufficiently
serious code quality issues.
"""
session.install('flake8', *LOCAL_DEPS)
session.install('.')
session.run('flake8', 'google', 'tests')


@nox.session(python='3.6')
def lint_setup_py(session):
"""Verify that setup.py is valid (including RST check)."""

session.install('docutils', 'Pygments')
session.run(
'python', 'setup.py', 'check', '--restructuredtext', '--strict')


@nox.session(python='3.6')
def cover(session):
"""Run the final coverage report.
Expand Down
38 changes: 14 additions & 24 deletions packages/google-cloud-resource-manager/tests/unit/test__http.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@


class TestConnection(unittest.TestCase):

@staticmethod
def _get_target_class():
from google.cloud.resource_manager._http import Connection
Expand All @@ -30,25 +29,20 @@ def _make_one(self, *args, **kw):

def test_build_api_url_no_extra_query_params(self):
conn = self._make_one(object())
URI = '/'.join([
conn.API_BASE_URL,
conn.API_VERSION,
'foo',
])
self.assertEqual(conn.build_api_url('/foo'), URI)
URI = "/".join([conn.API_BASE_URL, conn.API_VERSION, "foo"])
self.assertEqual(conn.build_api_url("/foo"), URI)

def test_build_api_url_w_extra_query_params(self):
from six.moves.urllib.parse import parse_qsl
from six.moves.urllib.parse import urlsplit

conn = self._make_one(object())
uri = conn.build_api_url('/foo', {'bar': 'baz'})
uri = conn.build_api_url("/foo", {"bar": "baz"})
scheme, netloc, path, qs, _ = urlsplit(uri)
self.assertEqual('%s://%s' % (scheme, netloc), conn.API_BASE_URL)
self.assertEqual(path,
'/'.join(['', conn.API_VERSION, 'foo']))
self.assertEqual("%s://%s" % (scheme, netloc), conn.API_BASE_URL)
self.assertEqual(path, "/".join(["", conn.API_VERSION, "foo"]))
parms = dict(parse_qsl(qs))
self.assertEqual(parms['bar'], 'baz')
self.assertEqual(parms["bar"], "baz")

def test_extra_headers(self):
import requests
Expand All @@ -59,26 +53,22 @@ def test_extra_headers(self):
http = mock.create_autospec(requests.Session, instance=True)
response = requests.Response()
response.status_code = 200
data = b'brent-spiner'
data = b"brent-spiner"
response._content = data
http.request.return_value = response
client = mock.Mock(_http=http, spec=['_http'])
client = mock.Mock(_http=http, spec=["_http"])

conn = self._make_one(client)
req_data = 'req-data-boring'
result = conn.api_request(
'GET', '/rainbow', data=req_data, expect_json=False)
req_data = "req-data-boring"
result = conn.api_request("GET", "/rainbow", data=req_data, expect_json=False)
self.assertEqual(result, data)

expected_headers = {
'Accept-Encoding': 'gzip',
"Accept-Encoding": "gzip",
base_http.CLIENT_INFO_HEADER: MUT._CLIENT_INFO,
'User-Agent': conn.USER_AGENT,
"User-Agent": conn.USER_AGENT,
}
expected_uri = conn.build_api_url('/rainbow')
expected_uri = conn.build_api_url("/rainbow")
http.request.assert_called_once_with(
data=req_data,
headers=expected_headers,
method='GET',
url=expected_uri,
data=req_data, headers=expected_headers, method="GET", url=expected_uri
)
Loading

0 comments on commit 2549af1

Please sign in to comment.