nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: kubernetes-sigs/controller-tools
Pull request #495 (2020-10-01 00:39:15)

🐛 Remove unneeded caBundle: Cg== value
  - As per the comment in source, this field is no longer needed.



Patch:
diff --git a/pkg/crd/markers/zz_generated.markerhelp.go b/pkg/crd/markers/zz_generated.markerhelp.go
index 3acf3c98..61dc86cc 100644
--- a/pkg/crd/markers/zz_generated.markerhelp.go
+++ b/pkg/crd/markers/zz_generated.markerhelp.go
@@ -198,7 +198,7 @@ func (Minimum) Help() *markers.DefinitionHelp {
 	return &markers.DefinitionHelp{
 		Category: "CRD validation",
 		DetailedHelp: markers.DetailedHelp{
-			Summary: "specifies the minimum numeric value that this field can have.",
+			Summary: "specifies the minimum numeric value that this field can have. Negative integers are supported.",
 			Details: "",
 		},
 		FieldHelp: map[string]markers.DetailedHelp{},
diff --git a/pkg/webhook/parser.go b/pkg/webhook/parser.go
index dda54dc9..d9cfd632 100644
--- a/pkg/webhook/parser.go
+++ b/pkg/webhook/parser.go
@@ -244,10 +244,6 @@ func (c Config) clientConfig() admissionregv1.WebhookClientConfig {
 			Namespace: "system",
 			Path:      &path,
 		},
-		// OpenAPI marks the field as required before 1.13 because of a bug that got fixed in
-		// https://github.com/kubernetes/api/commit/e7d9121e9ffd63cea0288b36a82bcc87b073bd1b
-		// Put "\n" as an placeholder as a workaround til 1.13+ is almost everywhere.
-		CABundle: []byte("\n"),
 	}
 }
 


Test patch:
diff --git a/pkg/webhook/testdata/manifests.v1beta1.yaml b/pkg/webhook/testdata/manifests.v1beta1.yaml
index b8603f65..e6ea5f75 100644
--- a/pkg/webhook/testdata/manifests.v1beta1.yaml
+++ b/pkg/webhook/testdata/manifests.v1beta1.yaml
@@ -10,7 +10,6 @@ webhooks:
   - v1
   - v1beta1
   clientConfig:
-    caBundle: Cg==
     service:
       name: webhook-service
       namespace: system
@@ -38,7 +37,6 @@ metadata:
   name: validating-webhook-configuration
 webhooks:
 - clientConfig:
-    caBundle: Cg==
     service:
       name: webhook-service
       namespace: system
diff --git a/pkg/webhook/testdata/manifests.yaml b/pkg/webhook/testdata/manifests.yaml
index 6f6f92b5..285be024 100644
--- a/pkg/webhook/testdata/manifests.yaml
+++ b/pkg/webhook/testdata/manifests.yaml
@@ -10,7 +10,6 @@ webhooks:
   - v1
   - v1beta1
   clientConfig:
-    caBundle: Cg==
     service:
       name: webhook-service
       namespace: system
@@ -41,7 +40,6 @@ webhooks:
   - v1
   - v1beta1
   clientConfig:
-    caBundle: Cg==
     service:
       name: webhook-service
       namespace: system
Repository: planetlabs/planet-client-python
Pull request #33 (2015-07-28 17:31:11)

Issue32
Fixes the download cli.


Patch:
diff --git a/planet/scripts/__init__.py b/planet/scripts/__init__.py
index 38e24b8..39acdc2 100644
--- a/planet/scripts/__init__.py
+++ b/planet/scripts/__init__.py
@@ -12,18 +12,19 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import sys
+import time
 import json
 import logging
+import warnings
+from os import path
 
 import click
 
 import planet
 from planet import api
-from os import path
+
 from requests.packages.urllib3 import exceptions as urllib3exc
-import sys
-import time
-import warnings
 
 client_params = {}
 
@@ -212,7 +213,9 @@ def metadata(scene_id, scene_type, pretty):
 @cli.command('download')
 @click.pass_context
 def fetch_scene_geotiff(ctx, scene_ids, scene_type, product, dest):
-    '''Fetch full scene image(s)'''
+    """
+    Download full scene image(s).
+    """
 
     if len(scene_ids) == 0:
         src = click.open_file('-')
@@ -223,7 +226,7 @@ def fetch_scene_geotiff(ctx, scene_ids, scene_type, product, dest):
 
     start_time = time.time()
     futures = client().fetch_scene_geotiffs(scene_ids, scene_type, product,
-                                            api.write_to_file(dest))
+                                            api.utils.write_to_file(dest))
     check_futures(futures)
     summarize_throughput(total_bytes(futures), start_time)
 


Test patch:
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 08717f8..6625500 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -135,3 +135,9 @@ def test_metadata():
     result = runner.invoke(scripts.cli, ['metadata', '20150615_190229_0905'])
 
     assert_success(result, expected)
+
+
+def test_download():
+
+    result = runner.invoke(scripts.cli, ['download', '20150615_190229_0905'])
+    assert result.exit_code == 0
Repository: planetlabs/planet-client-python
Pull request #52 (2015-08-06 18:40:10)

adjust login status code handling
Don't merge yet - awaiting change deployment to API


Patch:
diff --git a/planet/api/client.py b/planet/api/client.py
index dad7594..edf0721 100644
--- a/planet/api/client.py
+++ b/planet/api/client.py
@@ -16,7 +16,7 @@ import base64
 import json
 from .dispatch import RequestsDispatcher
 from . import auth
-from .exceptions import InvalidIdentity
+from .exceptions import (InvalidIdentity, APIException)
 from . import models
 
 
@@ -56,13 +56,18 @@ class Client(object):
             'email': identity,
             'password': credentials
         }).result()
-        if result.status_code == 400:
+        status = result.status_code
+        if status == 400:
+            raise APIException('invalid parameters, login process has changed')
+        elif status == 401:
             # do our best to get something out to the user
             msg = result.text
             try:
                 msg = json.loads(result.text)['message']
             finally:
                 raise InvalidIdentity(msg)
+        elif status != 200:
+            raise APIException('%s: %s' % (status, result.text))
         jwt = result.text
         payload = jwt.split('.')[1]
         rem = len(payload) % 4


Test patch:
diff --git a/tests/test_mod.py b/tests/test_mod.py
index 999521b..d7543cd 100644
--- a/tests/test_mod.py
+++ b/tests/test_mod.py
@@ -108,7 +108,7 @@ def test_login_failure(client):
     with requests_mock.Mocker() as m:
         uri = os.path.join(client.base_url, 'auth/login')
         response = json.dumps({'message': 'invalid'})
-        m.post(uri, text=response, status_code=400)
+        m.post(uri, text=response, status_code=401)
         try:
             client.login('jimmy', 'crackcorn')
         except api.exceptions.InvalidIdentity as ex:
@@ -117,6 +117,20 @@ def test_login_failure(client):
             assert False
 
 
+def test_login_errors(client):
+    '''Verify login functionality'''
+    with requests_mock.Mocker() as m:
+        uri = os.path.join(client.base_url, 'auth/login')
+        response = 'An error occurred'
+        m.post(uri, text=response, status_code=500)
+        try:
+            client.login('jimmy', 'crackcorn')
+        except api.exceptions.APIException as ex:
+            assert str(ex) == '500: %s' % response
+        else:
+            assert False
+
+
 def test_get_scenes_list(client):
     with requests_mock.Mocker() as m:
         uri = os.path.join(client.base_url, 'scenes/ortho')
Repository: planetlabs/planet-client-python
Pull request #76 (2015-09-15 12:07:48)

fix mosaic-quads when no aoi passed, add test


Patch:
diff --git a/planet/scripts/__init__.py b/planet/scripts/__init__.py
index 1993ea3..7309326 100644
--- a/planet/scripts/__init__.py
+++ b/planet/scripts/__init__.py
@@ -407,8 +407,10 @@ def get_mosaic_quads(mosaic_name, aoi, limit, pretty):
     Get quad info for the specified mosaic
     """
     aoi = read_aoi(aoi)
-    # work around backend limitation of using a FeatureCollection
-    aoi = api.utils.geometry_from_json(aoi)
+
+    if aoi:
+        # work around backend limitation of using a FeatureCollection
+        aoi = api.utils.geometry_from_json(aoi)
 
     echo_json_response(
         call_and_wrap(client().get_mosaic_quads,


Test patch:
diff --git a/tests/test_cli.py b/tests/test_cli.py
index e9cbdb9..50512fc 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -252,6 +252,18 @@ def test_init():
             os.unlink(test_file)
 
 
+def test_mosaic_quads():
+    response = MagicMock(spec=models.JSON)
+    response.get_raw.return_value = '{"quads": []}'
+
+    client.get_mosaic_quads.return_value = response
+    result = runner.invoke(scripts.cli, ['mosaic-quads', 'some_mosaic_name'])
+    assert result.exit_code == 0
+    assert result.output == '{\n  "quads": []\n}\n'
+    called_with = client.get_mosaic_quads.call_args[0]
+    assert called_with[0] == 'some_mosaic_name'
+
+
 def _set_workspace(workspace, *args, **kw):
     response = MagicMock(spec=models.JSON)
     response.get_raw.return_value = '{"status": "OK"}'
Repository: planetlabs/planet-client-python
Pull request #95 (2016-02-12 06:34:41)

Enable querying by saved aoi.

jacobstr: cc @ischneider 
jacobstr: Any idea why the tests started failing?
jacobstr: Possibly flake8 was modified upstream and introduced new rules?
ischneider: @jacobstr It does look like flake8 changes mucked things up. Will look at now
ischneider: LGTM. Does it make sense to enable listing AOI as well? On that note, I see the version was bumped. I usually do this with a single release commit not that we cannot release this :smile: 
jacobstr: I'm going to bump the version separately.

Patch:
diff --git a/planet/api/client.py b/planet/api/client.py
index ff5bc43..1174a8b 100644
--- a/planet/api/client.py
+++ b/planet/api/client.py
@@ -97,7 +97,8 @@ class Client(object):
         return json.loads(payload.decode('utf-8'))
 
     def get_scenes_list(self, scene_type='ortho', order_by=None, count=None,
-                        intersects=None, workspace=None, **filters):
+                        intersects=None, workspace=None, aoi_id=None,
+                        **filters):
         '''Get scenes matching the specified parameters and filters.
 
         :param str scene_type: The type of scene, defaults to 'ortho'
@@ -117,6 +118,8 @@ class Client(object):
         }
         if workspace:
             params['workspace'] = workspace
+        if aoi_id:
+            params['aoi'] = aoi_id
         params.update(**filters)
         return self._get('scenes/%s/' % scene_type,
                          models.Scenes, params=params).get_body()
diff --git a/planet/scripts/__init__.py b/planet/scripts/__init__.py
index 8989cee..a171704 100644
--- a/planet/scripts/__init__.py
+++ b/planet/scripts/__init__.py
@@ -259,11 +259,14 @@ def init(email, password):
               help=('Provide additional search criteria. See '
                     'https://www.planet.com/docs/v0/scenes/#metadata for '
                     'search metadata fields.'))
-def get_scenes_list(scene_type, pretty, aoi, limit, where, workspace):
+@click.option('--aoi_id', help=(
+    'Provider the identifier of an uploaded geometry'))
+def get_scenes_list(scene_type, pretty, aoi, limit, where, workspace, aoi_id):
     '''Get a list of scenes.'''
 
     aoi = read_aoi(aoi)
     conditions = {'workspace': workspace}
+    conditions = {'aoi_id': aoi_id}
 
     if where:
         conditions.update([


Test patch:
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 508ce06..d346dc3 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -176,6 +176,12 @@ def test_search():
     assert_success(result, expected)
 
 
+def test_aoi_id_flag():
+    run_cli(['search', '--aoi_id', 'dangbat'])
+    client.get_scenes_list.assert_called_with(
+        aoi_id='dangbat', count=1000, intersects=None, scene_type='ortho')
+
+
 def test_search_by_aoi():
 
     aoi = read_fixture('search-by-aoi.geojson')
Repository: planetlabs/planet-client-python
Pull request #104 (2017-05-19 21:55:22)

date_range improvements, handle Z suffix in strp_lenient
- handle date/datetime predicate values
- add docs

cc @nateweisiger 


Patch:
diff --git a/planet/api/filters.py b/planet/api/filters.py
index d7cf48f..7d77cc1 100644
--- a/planet/api/filters.py
+++ b/planet/api/filters.py
@@ -12,6 +12,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+from .utils import strp_lenient
+
 
 def build_search_request(filter_like, item_types, name=None, interval=None):
     '''Build a data-api search request body for the specified item_types.
@@ -96,10 +98,25 @@ def not_filter(*predicates):
 
 
 def date_range(field_name, **kwargs):
+    '''Build a DateRangeFilter.
+
+    Predicate arguments accept a value str that in ISO-8601 format or a value
+    that has a `isoformat` callable that returns an ISO-8601 str.
+
+    :raises: ValueError if predicate value does not parse
+
+    >>> date_range('acquired', gt='2017') == \
+    {'config': {'gt': '2017-01-01T00:00:00Z'}, \
+    'field_name': 'acquired', 'type': 'DateRangeFilter'}
+    True
+    '''
     for k, v in kwargs.items():
-        if hasattr(v, 'isoformat'):
-            # @todo check timezone handling
-            kwargs[k] = v.isoformat() + 'Z'
+        dt = v
+        if not hasattr(v, 'isoformat'):
+            dt = strp_lenient(str(v))
+            if dt is None:
+                raise ValueError("unable to use provided time: " + str(v))
+        kwargs[k] = dt.isoformat() + 'Z'
     return _filter('DateRangeFilter', config=kwargs, field_name=field_name)
 
 
diff --git a/planet/api/utils.py b/planet/api/utils.py
index 062f02c..56850a1 100644
--- a/planet/api/utils.py
+++ b/planet/api/utils.py
@@ -132,6 +132,7 @@ def strf_timestamp(when):
 
 
 def strp_lenient(when):
+    when = when[:-1] if when[-1] == 'Z' else when
     for i in range(0, 9):
         try:
             return datetime.strptime(when, _ISO_FMT[:i*-3 or len(_ISO_FMT)])


Test patch:
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 1b4eeb3..5cec18d 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -30,8 +30,12 @@ def test_strp_lenient():
         '2017-02-02',
     ]:
         p = utils.strp_lenient(spec)
+        assert p is not None, spec + " failed"
         assert datetime.strftime(p, utils._ISO_FMT).startswith(spec)
 
+    withz = '2017-02-02T16:45:43Z'
+    assert utils.strp_lenient(withz) == utils.strp_lenient(withz[:-1])
+
 
 def test_geometry_from_json():
     # base case, no geometry
Repository: planetlabs/planet-client-python
Pull request #351 (2022-01-04 21:47:33)

Add missing asset type, clean up tests
This fixes the last failing test and improves the test that was failing. I'm going to make some comments inline that point out some defects in the original tests and suggest better patterns that we should use in future work.

cc @jreiberkyle @kevinlacaille @JuLeeAtPlanet @karrabatcheller @mkshah605 @sarasafavi


Patch:
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..0ef6a7e
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,13 @@
+language: python
+python:
+  - "2.7"
+  - "3.4"
+cache:
+  directories:
+    - $HOME/.cache/pip
+before_install:
+  - pip install setuptools pip pytest --upgrade
+install:
+  - pip install -e .[dev]
+script:
+  - make check html-docs
diff --git a/planet/scripts/item_asset_types.py b/planet/scripts/item_asset_types.py
index 9fb8444..d1d14b0 100644
--- a/planet/scripts/item_asset_types.py
+++ b/planet/scripts/item_asset_types.py
@@ -78,7 +78,7 @@ DEFAULT_ASSET_TYPES = [
     'ps4b_basic_analytic_nitf', 'ps4b_basic_analytic_rpc_nitf',
     'ps4b_basic_analytic_xml_nitf', 'ps4b_udm', 'udm', 'ortho_udm2',
     'video_file', 'video_frames', 'video_metadata', 'ortho_visual',
-    'visual', 'visual_xml'
+    'analytic', 'visual', 'visual_xml'
 ]
 
 


Test patch:
diff --git a/tests/test_types.py b/tests/test_types.py
index 2a0addd..3c825e7 100644
--- a/tests/test_types.py
+++ b/tests/test_types.py
@@ -46,18 +46,34 @@ def test_item_type():
     assert 'invalid choice: x' in str(e.value)
 
 
-@mock.patch('planet.scripts.types.get_asset_types',
-            new=mock.Mock(return_value=DEFAULT_ASSET_TYPES))
-def test_asset_type():
-    check = convert_asserter(AssetType())
-    check('visual*', ['visual', 'visual_xml'])
-    check('*data_*', ['metadata_aux', 'metadata_txt'])
-    check('analytic', ['analytic'])
-    check('analytic,visual', ['analytic', 'visual'])
+@mock.patch(
+    "planet.scripts.types.get_asset_types",
+    new=mock.Mock(return_value=DEFAULT_ASSET_TYPES),
+)
+@pytest.mark.parametrize(
+    "pattern,type_list",
+    [
+        ("visual*", ["visual", "visual_xml"]),
+        ("*data_*", ["metadata_aux", "metadata_txt"]),
+        ("analytic", ["analytic"]),
+        ("analytic,visual", ["analytic", "visual"]),
+    ],
+)
+def test_asset_type_convert(pattern, type_list):
+    """Patterns are correctly converted to a list of assert types."""
+    assert sorted(AssetType()(pattern)) == sorted(type_list)
 
-    with pytest.raises(Exception) as e:
-        AssetType().convert('x', None, None)
-    assert 'invalid choice: x' in str(e.value)
+
+@mock.patch(
+    "planet.scripts.types.get_asset_types",
+    new=mock.Mock(return_value=DEFAULT_ASSET_TYPES),
+)
+@pytest.mark.parametrize("pattern", ["x", "foo?", "?visual", "visual?"])
+def test_asset_type_convert_invalid(pattern):
+    """Invalid patterns result in an exception."""
+    with pytest.raises(Exception) as exc:
+        AssetType()(pattern)
+    assert "invalid choice:" in str(exc.value)
 
 
 def test_geom_type():