internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: googleapis/google-api-python-client

Issue:
BatchError is unprintable using default constructor (one string)
This one should be pretty simple, I hope.

Here's the constructor signature: `def __init__(self, reason, resp=None, content=None):`, which doesn't require `resp` to be defined, and I can see it is not defined most of the time, for example, in googleapiclient/http.py.

Then, given the representation method:

```
def __repr__(self):
      return '<BatchError %s "%s">' % (self.resp.status, self.reason)
```

Which is also the string method:

```
__str__ = __repr__
```

This results in unprintable exceptions where `resp` is undefined, which is not very helpful when attempting to understand the error (e.g. #164).



Discussion:
:+1:  I encountered this same issue. Fortunately, I could fix my problem because you documented another issue #164 very well

Thanks for reporting this. If anyone wants to send a PR to fix this, I'll be happy to review and merge.


Resolving patch:
diff --git a/googleapiclient/errors.py b/googleapiclient/errors.py
--- a/googleapiclient/errors.py
+++ b/googleapiclient/errors.py
@@ -126,6 +126,9 @@ def __init__(self, reason, resp=None, content=None):
     self.reason = reason
 
   def __repr__(self):
+    if getattr(self.resp, 'status', None) is None:
+      return '<BatchError "%s">' % (self.reason)
+    else:
       return '<BatchError %s "%s">' % (self.resp.status, self.reason)
 
   __str__ = __repr__


Test patch:
diff --git a/tests/test_http.py b/tests/test_http.py
--- a/tests/test_http.py
+++ b/tests/test_http.py
@@ -1053,7 +1053,9 @@ def test_add_fail_for_resumable(self):
     upload = MediaFileUpload(
         datafile('small.png'), chunksize=500, resumable=True)
     self.request1.resumable = upload
-    self.assertRaises(BatchError, batch.add, self.request1, request_id='1')
+    with self.assertRaises(BatchError) as batch_error:
+      batch.add(self.request1, request_id='1')
+    str(batch_error.exception)
 
   def test_execute_empty_batch_no_http(self):
     batch = BatchHttpRequest()
Repository: googleapis/google-api-python-client

Issue:
Suggest use of httplib2 v0.9.2 in readme if using python > 3
Python3.x implementations of the client, passes bytestring to httplib2 header encoding method. Httplib2 < 0.9.2 does not support this. 

Documentation should make a note that implementations in python3 should explicitly install httplib2 0.9.2. PyPi index targets 0.8.0, which is no bueno for those unaware of this issue. 



Discussion:
@sloan-dog do you think we should just bump the minimum version up in [`setup.py`](https://github.com/google/google-api-python-client/blob/master/setup.py#L66)?

@jonparrott That sounds like a good out-of-the-box fix.


Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -63,7 +63,7 @@ def _DetectBadness():
 ]
 
 install_requires = [
-    'httplib2>=0.8,<1dev',
+    'httplib2>=0.9.2,<1dev',
     'oauth2client>=1.5.0,<5.0.0dev',
     'six>=1.6.1,<2dev',
     'uritemplate>=3.0.0,<4dev',


Test patch:
Repository: googleapis/google-api-python-client

Issue:
v1.6.1 HttpError 403 "Insufficient Permission"
I happened to try updating google-api-python-client from 1.5.5 to 1.6.1. It causes my YouTube Data API v3 code to always fail with a HttpError. An example to reproduce is:

    from apiclient.discovery import build
    DEVELOPER_KEY = "<Insert key>"
    youtube = build("youtube", "v3", developerKey=DEVELOPER_KEY)
    youtube.videos().list(id="xGG56MWgbOA", part="id").execute()

This returns a successful response on 1.5.5, but raises a HttpError on 1.6.1:

    HttpError: <HttpError 403 when requesting https://www.googleapis.com/youtube/v3/videos?alt=json&part=id&id=xGG56MWgbOA&key=<Insert key> returned "Insufficient Permission">

Visiting the specified link in a browser returns a valid response. Is there some usage change I am not aware of?


Discussion:
@jmgirven interesting. If you pass in `http=httplib2.Http()` to `build` does that fix the issue?
It does, yep.
Alright. I know what's going on.

We added support for application default credentials in 1.6.0. What's happening is that you're getting default OAuth credentials attached to your requests, but you shouldn't be because you specified an API key. I'll try to get a fix out soon, in the meantime specifying your own http should short-circuit the application default credentials logic.

Resolving patch:
diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py
--- a/googleapiclient/discovery.py
+++ b/googleapiclient/discovery.py
@@ -355,8 +355,9 @@ def build_from_document(
     scopes = list(
       service.get('auth', {}).get('oauth2', {}).get('scopes', {}).keys())
 
-    # If so, then the we need to setup authentication.
-    if scopes:
+    # If so, then the we need to setup authentication if no developerKey is
+    # specified.
+    if scopes and not developerKey:
       # If the user didn't pass in credentials, attempt to acquire application
       # default credentials.
       if credentials is None:


Test patch:
diff --git a/tests/test_discovery.py b/tests/test_discovery.py
--- a/tests/test_discovery.py
+++ b/tests/test_discovery.py
@@ -437,6 +437,16 @@ def test_building_with_explicit_http(self):
       discovery, base="https://www.googleapis.com/", http=http)
     self.assertEquals(plus._http, http)
 
+  def test_building_with_developer_key_skips_adc(self):
+    discovery = open(datafile('plus.json')).read()
+    plus = build_from_document(
+      discovery, base="https://www.googleapis.com/", developerKey='123')
+    self.assertIsInstance(plus._http, httplib2.Http)
+    # It should not be an AuthorizedHttp, because that would indicate that
+    # application default credentials were used.
+    self.assertNotIsInstance(plus._http, google_auth_httplib2.AuthorizedHttp)
+
+
 class DiscoveryFromHttp(unittest.TestCase):
   def setUp(self):
     self.old_environ = os.environ.copy()
Repository: googleapis/google-api-python-client

Issue:
`googleapiclient.http.DEFAULT_CHUNK_SIZE` should be larger by default.
The default chunk size of 512kb is too small, and leads to slower-than-needed transfers, eg googlecolab/backend-container#1. 

Users can of course set the value larger as they'd like, but I suspect increasing it would lead to a better experience for users who don't know that there's a knob for them to twiddle.


Discussion:
Sounds reasonable. Send a PR? 

Resolving patch:
diff --git a/googleapiclient/http.py b/googleapiclient/http.py
--- a/googleapiclient/http.py
+++ b/googleapiclient/http.py
@@ -74,7 +74,7 @@
 
 LOGGER = logging.getLogger(__name__)
 
-DEFAULT_CHUNK_SIZE = 512*1024
+DEFAULT_CHUNK_SIZE = 100*1024*1024
 
 MAX_URI_LENGTH = 2048
 


Test patch:
Repository: googleapis/google-api-python-client

Issue:
library is using a deprecated batch endpoint
The libary currently has www.googleapis.com/batch hardcoded as the endpoint for batch API requests unless caller manually sets batch_uri. See:

https://github.com/google/google-api-python-client/blob/master/googleapiclient/http.py#L1089

per [Google Developers blog post](https://developers.googleblog.com/2018/03/discontinuing-support-for-json-rpc-and.html) this universal endpoint is being turned down in favor of per-API endpoints.

library needs to:
1. ensure all members of the batch are homogenous (same API) and throw an error if they're not.
2. utilize the batchPath from the individual API rather than the generic one, this would be something like:

service._rootDesc['rootUrl'] + service._rootDesc['batchPath']


Discussion:

Resolving patch:
diff --git a/googleapiclient/http.py b/googleapiclient/http.py
--- a/googleapiclient/http.py
+++ b/googleapiclient/http.py
@@ -82,6 +82,8 @@
 
 DEFAULT_HTTP_TIMEOUT_SEC = 60
 
+_LEGACY_BATCH_URI = 'https://www.googleapis.com/batch'
+
 
 def _should_retry_response(resp_status, content):
   """Determines whether a response should be retried.
@@ -1086,7 +1088,17 @@ def __init__(self, callback=None, batch_uri=None):
       batch_uri: string, URI to send batch requests to.
     """
     if batch_uri is None:
-      batch_uri = 'https://www.googleapis.com/batch'
+      batch_uri = _LEGACY_BATCH_URI
+
+    if batch_uri == _LEGACY_BATCH_URI:
+      LOGGER.warn(
+        "You have constructed a BatchHttpRequest using the legacy batch "
+        "endpoint %s. This endpoint will be turned down on March 25, 2019. "
+        "Please provide the API-specific endpoint or use "
+        "service.new_batch_http_request(). For more details see "
+        "https://developers.googleblog.com/2018/03/discontinuing-support-for-json-rpc-and.html"
+        "and https://developers.google.com/api-client-library/python/guide/batch.",
+        _LEGACY_BATCH_URI)
     self._batch_uri = batch_uri
 
     # Global callback to be called for each individual response in the batch.


Test patch:
Repository: googleapis/google-api-python-client

Issue:
Documentation not correct for "import" function for variants
Line 142 of google-api-python-client/googleapiclient/discovery.py
Reads:
_The name with a '\_' prefixed if the name is a reserved word._
Should read:
_The name with a '\_' appended if the name is a reserved word._

Also, the [suggested code in the docs](https://cloud.google.com/genomics/reference/rest/v1/variants/import)  for python is not correct about how to call this method.

The example line reading:
`request = service.variants().import(body=import_variants_request_body)
response = request.execute()`
Should be:
`request = service.variants().import_(body=import_variants_request_body)
response = request.execute()`



Discussion:

Resolving patch:
diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py
--- a/googleapiclient/discovery.py
+++ b/googleapiclient/discovery.py
@@ -138,7 +138,7 @@ def fix_method_name(name):
     name: string, method name.
 
   Returns:
-    The name with a '_' prefixed if the name is a reserved word.
+    The name with an '_' appended if the name is a reserved word.
   """
   if keyword.iskeyword(name) or name in RESERVED_WORDS:
     return name + '_'


Test patch:
Repository: googleapis/google-api-python-client

Issue:
Deprecation of oauth2client dependency
According to the readme google/oauth2client is deprecated. They suggest switching to [google-auth](https://google-auth.readthedocs.io/) or [oauthlib](http://oauthlib.readthedocs.io/). 

This probably means that this package and all of the docs should also be refactored into using these new packages?


Discussion:
+1 
Any other usage docs for using `google-auth` or `oauthlib` with the api client libraries?
This lib still has a pip dependency to `oauth2client` and the code dependency, too, e.g. in the `errors.py`. Please, remove these dependencies and update the doc.
See comments here: https://github.com/google/google-api-python-client/issues/415

Seems like contributors are up for help with this one, if you have time and wish for it.

Resolving patch:
diff --git a/googleapiclient/discovery_cache/file_cache.py b/googleapiclient/discovery_cache/file_cache.py
--- a/googleapiclient/discovery_cache/file_cache.py
+++ b/googleapiclient/discovery_cache/file_cache.py
@@ -36,9 +36,9 @@
   try:
     from oauth2client.locked_file import LockedFile
   except ImportError:
-    # oauth2client > 4.0.0
+    # oauth2client > 4.0.0 or google-auth
     raise ImportError(
-      'file_cache is unavailable when using oauth2client >= 4.0.0')
+      'file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth')
 
 from . import base
 from ..discovery_cache import DISCOVERY_DOC_MAX_AGE
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -64,7 +64,8 @@ def _DetectBadness():
 
 install_requires = [
     'httplib2>=0.9.2,<1dev',
-    'oauth2client>=1.5.0,<5.0.0dev',
+    'google-auth>=1.4.1',
+    'google-auth-httplib2>=0.0.3',
     'six>=1.6.1,<2dev',
     'uritemplate>=3.0.0,<4dev',
 ]


Test patch:
diff --git a/tests/__init__.py b/tests/__init__.py
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -16,12 +16,7 @@
 __author__ = 'afshar@google.com (Ali Afshar)'
 
 
-# Oauth2client < 3 has the positional helper in 'util', >= 3 has it
-# in '_helpers'.
-try:
-  from oauth2client import util
-except ImportError:
-  from oauth2client import _helpers as util
+from googleapiclient import _helpers as util
 
 
 def setup_package():
Repository: googleapis/google-api-python-client

Issue:
googleapiclient/channel.py has no license header
There is no license header at all in channel.py

googleapiclient/channel.py has no license header
There is no license header at all in channel.py



Discussion:
Thanks for letting us know.

Thanks for letting us know.


Resolving patch:
diff --git a/googleapiclient/channel.py b/googleapiclient/channel.py
--- a/googleapiclient/channel.py
+++ b/googleapiclient/channel.py
@@ -1,3 +1,17 @@
+# Copyright 2014 Google Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
 """Channel notifications support.
 
 Classes and functions to support channel subscriptions and notifications


Test patch:
Repository: googleapis/google-api-python-client

Issue:
Receive warnings "ResourceWarning: unclosed file" when using googleapiclient.http.MediaFileUpload
On google-api-python-client/googleapiclient/http.py:552, a file is opened. But this file is never closed. So I receive the following warning:

ResourceWarning: unclosed file <_io.BufferedReader name=<file_name> media_body = http.MediaFileUpload()



Discussion:
Hi @wangxf123456,

Thank you for reporting this! Would you be willing to submit a PR to fix it?
Sure I can do this.

Resolving patch:
diff --git a/googleapiclient/http.py b/googleapiclient/http.py
--- a/googleapiclient/http.py
+++ b/googleapiclient/http.py
@@ -558,9 +558,13 @@ def __init__(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE,
       if mimetype is None:
         # Guess failed, use octet-stream.
         mimetype = 'application/octet-stream'
-    super(MediaFileUpload, self).__init__(fd, mimetype, chunksize=chunksize,
+    super(MediaFileUpload, self).__init__(fd, mimetype,
+                                          chunksize=chunksize,
                                           resumable=resumable)
 
+  def __del__(self):
+    self._fd.close()
+
   def to_json(self):
     """Creating a JSON representation of an instance of MediaFileUpload.
 


Test patch:
diff --git a/tests/test_http.py b/tests/test_http.py
--- a/tests/test_http.py
+++ b/tests/test_http.py
@@ -31,6 +31,7 @@
 # Do not remove the httplib2 import
 import json
 import httplib2
+import io
 import logging
 import mock
 import os
@@ -209,6 +210,15 @@ def test_set_user_agent_nested(self):
 
 class TestMediaUpload(unittest.TestCase):
 
+  def test_media_file_upload_closes_fd_in___del__(self):
+    file_desc = mock.Mock(spec=io.TextIOWrapper)
+    opener = mock.mock_open(file_desc)
+    with mock.patch('__builtin__.open', return_value=opener):
+      upload = MediaFileUpload(datafile('test_close'), mimetype='text/plain')
+    self.assertIs(upload.stream(), file_desc)
+    del upload
+    file_desc.close.assert_called_once_with()
+
   def test_media_file_upload_mimetype_detection(self):
     upload = MediaFileUpload(datafile('small.png'))
     self.assertEqual('image/png', upload.mimetype())
@@ -861,7 +871,7 @@ def test_empty_content_type(self):
         headers={'content-type': ''})
     request.execute()
     self.assertEqual('', http.headers.get('content-type'))
-  
+
   def test_no_retry_connection_errors(self):
     model = JsonModel()
     request = HttpRequest(
Repository: googleapis/google-api-python-client

Issue:
discovery.build_from_document fails when running with Python3
The `discovery.build_from_document` function assumes that `service` is of type `str`, however when running in Python3 instead of `str` it can be of type `bytes`.

Because of this wrong assumption, the function fails on [line 337](https://github.com/googleapis/google-api-python-client/blob/master/googleapiclient/discovery.py#L337) where the bytes string is compared to an actual text string.

The google-api-python-client version where i've seen this problem is 1.7.7

## Solution

Add a check, if service is a bytes string convert it using UTF-8 format

```
  if isinstance(service, six.string_types):
      service = json.loads(service)
+ elif isinstance(service, six.binary_type):
+  service = json.loads(service.decode('utf8'))
```

This fixes my problem (observed when using this library in Google3)


Discussion:

Resolving patch:
diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py
--- a/googleapiclient/discovery.py
+++ b/googleapiclient/discovery.py
@@ -333,6 +333,8 @@ def build_from_document(
 
   if isinstance(service, six.string_types):
     service = json.loads(service)
+  elif isinstance(service, six.binary_type):
+    service = json.loads(service.decode('utf-8'))
 
   if  'rootUrl' not in service and (isinstance(http, (HttpMock,
                                                       HttpMockSequence))):


Test patch:
Repository: googleapis/google-api-python-client

Issue:
AttributeError: module 'googleapiclient' has no attribute '__version__'
When importing new version of google-api-python-client
`from apiclient import discovery`
i'm getting the error
`AttributeError: module 'googleapiclient' has no attribute '__version__'`

https://github.com/googleapis/google-api-python-client/blob/84d45619d753cb04d957651886231034194058b6/apiclient/__init__.py#L22

i guess this happens since you have removed `__version__` var from `googleapiclient/__init__.py`

https://github.com/googleapis/google-api-python-client/commit/f706cfd821ab7457e5db37abfc3619772657dd0e#diff-b926d296d4c856bcbf877809e4523562L15

can you please fix? @busunkim96 @mik-laj @crwilcox 

Traceback:
```    from apiclient import discovery
  File "/usr/local/lib/python3.7/site-packages/apiclient/__init__.py", line 22, in <module>
    __version__ = googleapiclient.__version__
AttributeError: module 'googleapiclient' has no attribute '__version__'


Discussion:
Thanks for the report.
https://github.com/googleapis/google-api-python-client/blob/master/apiclient/__init__.py#L22

Resolving patch:
diff --git a/apiclient/__init__.py b/apiclient/__init__.py
--- a/apiclient/__init__.py
+++ b/apiclient/__init__.py
@@ -19,8 +19,6 @@
     sample_tools = None
 from googleapiclient import schema
 
-__version__ = googleapiclient.__version__
-
 _SUBMODULES = {
     "channel": channel,
     "discovery": discovery,


Test patch:
Repository: googleapis/google-api-python-client

Issue:
Add a new mechanism to avoid calling the legacy memcache API
This API is only supported on the python27 runtime.  Lets only try to import it in environments that actually support it.

The problem I'm running into is a bit esoteric, but here goes.  We've built some GAE API shims to help move our apps to newer App Engine runtimes (like python3) that don't include these legacy APIs.  Because of that, when this library tries to import google.appengine.api.memcache, it imports and uses our shim, and that isn't always desirable.  Having some way to configure googleapiclient to not use this legacy API even if it is importable would be useful.

Despite this sorta niche use case, I figured I'd propose this change upstream since reducing reliance on a py2-only API shouldn't be too controversial these days.


Discussion:

Resolving patch:
diff --git a/googleapiclient/discovery_cache/__init__.py b/googleapiclient/discovery_cache/__init__.py
--- a/googleapiclient/discovery_cache/__init__.py
+++ b/googleapiclient/discovery_cache/__init__.py
@@ -18,7 +18,7 @@
 
 import logging
 import datetime
-
+import os
 
 LOGGER = logging.getLogger(__name__)
 
@@ -32,16 +32,18 @@ def autodetect():
     googleapiclient.discovery_cache.base.Cache, a cache object which
     is auto detected, or None if no cache object is available.
   """
-    try:
-        from google.appengine.api import memcache
-        from . import appengine_memcache
-
-        return appengine_memcache.cache
-    except Exception:
+    if 'APPENGINE_RUNTIME' in os.environ:
         try:
-            from . import file_cache
+            from google.appengine.api import memcache
+            from . import appengine_memcache
+
+            return appengine_memcache.cache
+        except Exception:
+            pass
+    try:
+        from . import file_cache
 
-            return file_cache.cache
-        except Exception as e:
-            LOGGER.warning(e, exc_info=True)
-            return None
+        return file_cache.cache
+    except Exception as e:
+        LOGGER.warning(e, exc_info=True)
+        return None


Test patch:
diff --git a/tests/test_discovery.py b/tests/test_discovery.py
--- a/tests/test_discovery.py
+++ b/tests/test_discovery.py
@@ -648,6 +648,14 @@ def test_api_endpoint_override_from_client_options_dict(self):
 
 
 class DiscoveryFromAppEngineCache(unittest.TestCase):
+
+    def setUp(self):
+        self.old_environ = os.environ.copy()
+        os.environ["APPENGINE_RUNTIME"] = "python27"
+
+    def tearDown(self):
+        os.environ = self.old_environ
+
     def test_appengine_memcache(self):
         # Hack module import
         self.orig_import = __import__
Repository: googleapis/google-api-python-client

Issue:
Fix typo in positional decorator method docstring
Thanks for stopping by to let us know something could be better!

**PLEASE READ**: If you have a support contract with Google, please create an issue in the [support console](https://cloud.google.com/support/) instead of filing on GitHub. This will ensure a timely response.

Please run down the following list and make sure you've tried the usual "quick fixes":

  - Search the issues already opened: https://github.com/googleapis/google-api-python-client/issues
  - Search StackOverflow: https://stackoverflow.com/questions/tagged/google-cloud-platform+python

If you are still having issues, please be sure to include as much information as possible:

#### Environment details

  - OS type and version:  irrelevant
  - Python version:  irrelevant
  - pip version:  irrelevant
  - `google-api-python-client` version:  irrelevant

#### Steps to reproduce

 irrelevant

#### Code example

 irrelevant

#### Stack trace

 irrelevant

Making sure to follow these steps will guarantee the quickest resolution possible.

Thanks!



Discussion:

Resolving patch:
diff --git a/googleapiclient/_helpers.py b/googleapiclient/_helpers.py
--- a/googleapiclient/_helpers.py
+++ b/googleapiclient/_helpers.py
@@ -40,7 +40,7 @@
 
 
 def positional(max_positional_args):
-    """A decorator to declare that only the first N arguments my be positional.
+    """A decorator to declare that only the first N arguments may be positional.
 
     This decorator makes it easy to support Python 3 style keyword-only
     parameters. For example, in Python 3 it is possible to write::


Test patch: