Skip to content

SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]

Make instance a dataclass

Kilian Lieret97bf5e3058c2
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index cb39c463..4a986b31 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -1,3 +1,4 @@
+import dataclasses
from pathlib import Path
import random
import config
@@ -19,6 +20,7 @@ from rich.logging import RichHandler
from simple_parsing.helpers.serialization.serializable import FrozenSerializable
import yaml
from sweagent.environment.utils import (
+ Instance,
copy_anything_to_container,
copy_file_to_container,
format_trajectory_markdown,
@@ -35,7 +37,7 @@ from swebench import (
get_requirements,
MAP_VERSION_TO_INSTALL
)
-from typing import Optional, Tuple
+from typing import List, Optional, Tuple
LONG_TIMEOUT = 500
PATH_TO_REQS = "/root/requirements.txt"
@@ -111,9 +113,9 @@ class SWEEnv(gym.Env):
# Load Task Instances
self.data_path = self.args.data_path
- self.data = get_instances(self.data_path, self.args.base_commit, self.args.split, token=self._github_token, repo_path=self.args.repo_path)
+ self.data: List[Instance] = get_instances(self.data_path, self.args.base_commit, self.args.split, token=self._github_token, repo_path=self.args.repo_path)
#: Instance we're currently processing. Gets set in self.reset.
- self.record = None
+ self.record: Optional[Instance] = None
self.logger.info(f"💽 Loaded dataset from {self.data_path}")
# Establish connection with execution container
@@ -129,7 +131,7 @@ class SWEEnv(gym.Env):
def _repo_name(self) -> str:
"""Name of the local copy of the repository"""
assert self.record is not None
- return self.record["repo"].replace("/", "__")
+ return self.record.repo.replace("/", "__")
def _copy_repo(self) -> str:
"""Clone/copy repository/codebase in container
@@ -137,19 +139,19 @@ class SWEEnv(gym.Env):
folder name of clone
"""
assert self.record is not None # mypy
- if self.record["repo_type"] == "local":
- copy_anything_to_container(self.container_obj, self.record["repo"].removeprefix("local://"), "/"+self._repo_name)
+ if self.record.repo_type == "local":
+ copy_anything_to_container(self.container_obj, self.record.repo, "/"+self._repo_name)
self.communicate_with_handling(
input=f"chown -R root:root {self._repo_name}",
error_msg="Failed to change permissions on copied repository",
)
return self._repo_name
- assert self.record["repo_type"] == "github"
+ assert self.record.repo_type == "github"
token_prefix = ""
if self._github_token:
token_prefix = f"{self._github_token}@"
# fixme: This if statement is brittle and should probably be replaced with better logic
- if not self.args.no_mirror and self.record["problem_statement_source"] == "swe-bench":
+ if not self.args.no_mirror and self.record.problem_statement_source == "swe-bench":
self.logger.info(f"{self._repo_name} not found in container, cloning...")
self.communicate_with_handling(
input=f"git clone https://{token_prefix}github.com/swe-bench/{self._repo_name}.git",
@@ -160,7 +162,7 @@ class SWEEnv(gym.Env):
else:
logger.info(f"Trying to clone from non-mirror...")
self.communicate_with_handling(
- input=f"git clone https://{token_prefix}github.com/{self.record['repo']}.git {self._repo_name}",
+ input=f"git clone https://{token_prefix}github.com/{self.record.repo}.git {self._repo_name}",
error_msg="Failed to clone repository from non-mirror",
timeout_duration=LONG_TIMEOUT,
)
@@ -189,8 +191,8 @@ class SWEEnv(gym.Env):
self.idx += 1
# Set query, gold command
- self.base_commit = self.record["base_commit"]
- self.query = self.record["problem_statement"]
+ self.base_commit = self.record.base_commit
+ self.query = self.record.problem_statement
self.reward = None
### Reset Container ###
@@ -257,7 +259,7 @@ class SWEEnv(gym.Env):
if apply_test_patch:
path_to_patch = "test.patch"
with open(path_to_patch, "w") as f:
- f.write(self.record["test_patch"])
+ f.write(self.record.test_patch)
subprocess.run(
f"docker cp {path_to_patch} {self.container_name}:/root/test.patch",
shell=True,
@@ -546,7 +548,7 @@ class SWEEnv(gym.Env):
pids = [x for x in pids if x[1] != "ps" and x[0] not in self.parent_pids]
return pids
- def get_submission(self, action, output: str) -> str:
+ def get_submission(self, action, output: str) -> Optional[str]:
"""
Function for extracting diff patch submission at the end of an episode.
@@ -590,8 +592,8 @@ class SWEEnv(gym.Env):
Creates conda environment and installs third party dependencies to allow code execution
"""
assert self.record is not None # mypy
- if (self.record["problem_statement_source"] != "swe-bench" or \
- self.record["repo_type"] == "local") and self.args.environment_setup is None:
+ if (self.record.problem_statement_source != "swe-bench" or \
+ self.record.repo_type == "local") and self.args.environment_setup is None:
logger.warning((
"install_environment is set to True, but the data path is a GitHub URL "
"without an environment config file (environment_config key/flag). "
@@ -613,8 +615,8 @@ class SWEEnv(gym.Env):
raise ValueError("Environment config file needs to be a yaml file or shell script")
else:
try:
- install_configs = MAP_VERSION_TO_INSTALL[self.record["repo"]][
- str(self.record["version"])
+ install_configs = MAP_VERSION_TO_INSTALL[self.record.repo][
+ str(self.record.version)
]
except KeyError as e:
msg = (
@@ -623,7 +625,7 @@ class SWEEnv(gym.Env):
)
raise ValueError(msg) from e
# Create environment if does not exist yet
- env_name = f"{self._repo_name}__{self.record['version']}"
+ env_name = f"{self._repo_name}__{self.record.version}"
env_check = self.communicate(
f"conda env list | grep {env_name}", timeout_duration=LONG_TIMEOUT
)
@@ -640,7 +642,7 @@ class SWEEnv(gym.Env):
timeout_duration=LONG_TIMEOUT,
)
# Write reqs to requirements.txt in docker container
- content_reqs = get_requirements(self.record)
+ content_reqs = get_requirements(dataclasses.asdict(self.record))
copy_file_to_container(self.container_obj, content_reqs, PATH_TO_REQS)
# Create conda environment + install reqs
self.communicate_with_handling(
@@ -655,7 +657,7 @@ class SWEEnv(gym.Env):
self.communicate(f"rm {PATH_TO_REQS}")
elif packages == "environment.yml":
# Write environment.yml to file
- content_env_yml = get_environment_yml(self.record, env_name)
+ content_env_yml = get_environment_yml(dataclasses.asdict(self.record), env_name)
copy_file_to_container(self.container_obj, content_env_yml, PATH_TO_ENV_YML)
if "no_use_env" in install_configs and install_configs["no_use_env"]:
# Create conda environment
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index 22c657a9..f5ae513c 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -1,5 +1,6 @@
import hashlib
import shlex
+from attr import field
import docker
import json
import logging
@@ -397,6 +398,8 @@ class Instance:
version: str
problem_statement: str
instance_id: str
+ created_at: str = ""
+ test_patch: str = ""
# todo: This field is only needed while swe_env is using some questionable logic
# to determine whether to clone from a mirror or not. This should be removed in the future.
# Values: 'swe-bench' (loaded from json/jsonl for swe-bench style inference),
@@ -412,6 +415,30 @@ class Instance:
def __post_init__(self):
self._validate()
+
+ @classmethod
+ def from_dict(cls, d: Dict[str, Any], strict=False) -> "Instance":
+ """Get an instance object from a dictionary
+ For backwards compatibility, any keys in the dictionary that are not fields of the class
+ will be added as attributes.
+
+ Args:
+ d: Dictionary with keys corresponding to fields of the class
+ strict: If True, raise an error if any keys in the dictionary are not fields of the class
+ """
+ field_names = [field.name for field in dataclasses.fields(cls)]
+ missing_fields = set(d.keys()) - set(field_names)
+ if missing_fields:
+ if strict:
+ msg = f"Missing fields in Instance dataclass: {missing_fields}"
+ raise ValueError(msg)
+ logger.warning(f"Missing fields in Instance dataclass: {missing_fields}")
+ new_cls = dataclasses.make_dataclass(
+ 'Instance',
+ fields=list([(f, type(f), field(init=False)) for f in missing_fields]), bases=(cls,)
+ )
+ return new_cls(**d)
+ return cls(**d)
class InstanceBuilder:
@@ -491,7 +518,7 @@ def get_instances(
token: Optional[str] = None,
*,
repo_path: str = "",
- ) -> List[Dict[str, Any]]:
+ ) -> List[Instance]:
"""
Getter function for handling json, jsonl files
@@ -501,8 +528,8 @@ def get_instances(
Returns:
List of instances as dictionaries
"""
- def set_missing_keys(instances):
- return [dataclasses.asdict(Instance(**inst)) for inst in instances]
+ def to_instances(list_of_dict):
+ return [Instance.from_dict(inst) for inst in list_of_dict]
# If file_path is a directory, attempt load from disk
@@ -510,8 +537,8 @@ def get_instances(
try:
dataset_or_dict = load_from_disk(file_path)
if isinstance(dataset_or_dict, dict):
- return set_missing_keys(dataset_or_dict[split])
- return set_missing_keys(dataset_or_dict)
+ return to_instances(dataset_or_dict[split])
+ return to_instances(dataset_or_dict)
except FileNotFoundError:
# Raised by load_from_disk if the directory is not a dataset directory
pass
@@ -527,16 +554,16 @@ def get_instances(
else:
raise ValueError(f"Could not determine repo path from {file_path=}, {repo_path=}")
- return [dataclasses.asdict(ib.build())]
+ return [ib.build()]
if base_commit is not None:
raise ValueError("base_commit must be None if data_path is not a github issue url")
# If file_path is a file, load the file
if file_path.endswith(".json"):
- return set_missing_keys(json.load(open(file_path)))
+ return to_instances(json.load(open(file_path)))
if file_path.endswith(".jsonl"):
- return set_missing_keys([json.loads(x) for x in open(file_path, 'r').readlines()])
+ return to_instances([json.loads(x) for x in open(file_path, 'r').readlines()])
if repo_path:
msg = "repo_path must be empty if data_path is not a github url or local repo url"
@@ -544,7 +571,7 @@ def get_instances(
# Attempt load from HF datasets as a last resort
try:
- return set_missing_keys(load_dataset(file_path, split=split))
+ return to_instances(load_dataset(file_path, split=split))
except:
raise ValueError(
f"Could not load instances from {file_path}. "
@@ -608,4 +635,4 @@ def format_trajectory_markdown(trajectory: List[Dict[str, str]]):
"",
"</details>",
]
- return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)
\ No newline at end of file
+ return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)
diff --git a/tests/test_data/data_sources/debug_20240322.json b/tests/test_data/data_sources/debug_20240322.json
new file mode 100644
index 00000000..5d1b6054
--- /dev/null
+++ b/tests/test_data/data_sources/debug_20240322.json
@@ -0,0 +1 @@
+[{"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-11574", "base_commit": "dd69361a0d9c6ccde0d2353b00b86e0e7541a3e3", "patch": "diff --git a/sklearn/ensemble/iforest.py b/sklearn/ensemble/iforest.py\n--- a/sklearn/ensemble/iforest.py\n+++ b/sklearn/ensemble/iforest.py\n@@ -70,6 +70,10 @@ class IsolationForest(BaseBagging, OutlierMixin):\n on the decision function. If 'auto', the decision function threshold is\n determined as in the original paper.\n \n+ .. versionchanged:: 0.20\n+ The default value of ``contamination`` will change from 0.1 in 0.20\n+ to ``'auto'`` in 0.22.\n+\n max_features : int or float, optional (default=1.0)\n The number of features to draw from X to train each base estimator.\n \n@@ -150,12 +154,6 @@ def __init__(self,\n n_jobs=n_jobs,\n random_state=random_state,\n verbose=verbose)\n-\n- if contamination == \"legacy\":\n- warnings.warn('default contamination parameter 0.1 will change '\n- 'in version 0.22 to \"auto\". This will change the '\n- 'predict method behavior.',\n- DeprecationWarning)\n self.contamination = contamination\n \n def _set_oob_score(self, X, y):\n@@ -178,6 +176,15 @@ def fit(self, X, y=None, sample_weight=None):\n -------\n self : object\n \"\"\"\n+ if self.contamination == \"legacy\":\n+ warnings.warn('default contamination parameter 0.1 will change '\n+ 'in version 0.22 to \"auto\". This will change the '\n+ 'predict method behavior.',\n+ FutureWarning)\n+ self._contamination = 0.1\n+ else:\n+ self._contamination = self.contamination\n+\n X = check_array(X, accept_sparse=['csc'])\n if issparse(X):\n # Pre-sort indices to avoid that each individual tree of the\n@@ -219,19 +226,16 @@ def fit(self, X, y=None, sample_weight=None):\n max_depth=max_depth,\n sample_weight=sample_weight)\n \n- if self.contamination == \"auto\":\n+ if self._contamination == \"auto\":\n # 0.5 plays a special role as described in the original paper.\n # we take the opposite as we consider the opposite of their score.\n self.offset_ = -0.5\n # need to save (depreciated) threshold_ in this case:\n self._threshold_ = sp.stats.scoreatpercentile(\n self.score_samples(X), 100. * 0.1)\n- elif self.contamination == \"legacy\": # to be rm in 0.22\n- self.offset_ = sp.stats.scoreatpercentile(\n- self.score_samples(X), 100. * 0.1)\n else:\n self.offset_ = sp.stats.scoreatpercentile(\n- self.score_samples(X), 100. * self.contamination)\n+ self.score_samples(X), 100. * self._contamination)\n \n return self\n \n", "test_patch": "diff --git a/sklearn/ensemble/tests/test_iforest.py b/sklearn/ensemble/tests/test_iforest.py\n--- a/sklearn/ensemble/tests/test_iforest.py\n+++ b/sklearn/ensemble/tests/test_iforest.py\n@@ -62,6 +62,7 @@ def test_iforest():\n **params).fit(X_train).predict(X_test)\n \n \[email protected]('ignore:default contamination')\n def test_iforest_sparse():\n \"\"\"Check IForest for various parameter settings on sparse input.\"\"\"\n rng = check_random_state(0)\n@@ -89,6 +90,7 @@ def test_iforest_sparse():\n assert_array_equal(sparse_results, dense_results)\n \n \[email protected]('ignore:default contamination')\n def test_iforest_error():\n \"\"\"Test that it gives proper exception on deficient input.\"\"\"\n X = iris.data\n@@ -127,6 +129,7 @@ def test_iforest_error():\n assert_raises(ValueError, IsolationForest().fit(X).predict, X[:, 1:])\n \n \[email protected]('ignore:default contamination')\n def test_recalculate_max_depth():\n \"\"\"Check max_depth recalculation when max_samples is reset to n_samples\"\"\"\n X = iris.data\n@@ -135,6 +138,7 @@ def test_recalculate_max_depth():\n assert_equal(est.max_depth, int(np.ceil(np.log2(X.shape[0]))))\n \n \[email protected]('ignore:default contamination')\n def test_max_samples_attribute():\n X = iris.data\n clf = IsolationForest().fit(X)\n@@ -150,6 +154,7 @@ def test_max_samples_attribute():\n assert_equal(clf.max_samples_, 0.4*X.shape[0])\n \n \[email protected]('ignore:default contamination')\n def test_iforest_parallel_regression():\n \"\"\"Check parallel regression.\"\"\"\n rng = check_random_state(0)\n@@ -174,6 +179,7 @@ def test_iforest_parallel_regression():\n assert_array_almost_equal(y1, y3)\n \n \[email protected]('ignore:default contamination')\n def test_iforest_performance():\n \"\"\"Test Isolation Forest performs well\"\"\"\n \n@@ -213,6 +219,7 @@ def test_iforest_works():\n assert_array_equal(pred, 6 * [1] + 2 * [-1])\n \n \[email protected]('ignore:default contamination')\n def test_max_samples_consistency():\n # Make sure validated max_samples in iforest and BaseBagging are identical\n X = iris.data\n@@ -220,6 +227,7 @@ def test_max_samples_consistency():\n assert_equal(clf.max_samples_, clf._max_samples)\n \n \[email protected]('ignore:default contamination')\n def test_iforest_subsampled_features():\n # It tests non-regression for #5732 which failed at predict.\n rng = check_random_state(0)\n@@ -244,6 +252,7 @@ def test_iforest_average_path_length():\n [1., result_one, result_two], decimal=10)\n \n \[email protected]('ignore:default contamination')\n def test_score_samples():\n X_train = [[1, 1], [1, 2], [2, 1]]\n clf1 = IsolationForest(contamination=0.1).fit(X_train)\n@@ -257,12 +266,15 @@ def test_score_samples():\n \n \n def test_deprecation():\n- assert_warns_message(DeprecationWarning,\n+ X = [[0.0], [1.0]]\n+ clf = IsolationForest()\n+\n+ assert_warns_message(FutureWarning,\n 'default contamination parameter 0.1 will change '\n 'in version 0.22 to \"auto\"',\n- IsolationForest, )\n- X = [[0.0], [1.0]]\n- clf = IsolationForest().fit(X)\n+ clf.fit, X)\n+\n+ clf = IsolationForest(contamination='auto').fit(X)\n assert_warns_message(DeprecationWarning,\n \"threshold_ attribute is deprecated in 0.20 and will\"\n \" be removed in 0.22.\",\ndiff --git a/sklearn/linear_model/tests/test_sag.py b/sklearn/linear_model/tests/test_sag.py\n--- a/sklearn/linear_model/tests/test_sag.py\n+++ b/sklearn/linear_model/tests/test_sag.py\n@@ -17,6 +17,7 @@\n from sklearn.utils.extmath import row_norms\n from sklearn.utils.testing import assert_almost_equal\n from sklearn.utils.testing import assert_array_almost_equal\n+from sklearn.utils.testing import assert_allclose\n from sklearn.utils.testing import assert_greater\n from sklearn.utils.testing import assert_raise_message\n from sklearn.utils.testing import ignore_warnings\n@@ -269,7 +270,6 @@ def test_classifier_matching():\n assert_array_almost_equal(intercept2, clf.intercept_, decimal=9)\n \n \n-@ignore_warnings\n def test_regressor_matching():\n n_samples = 10\n n_features = 5\n@@ -295,10 +295,10 @@ def test_regressor_matching():\n dloss=squared_dloss,\n fit_intercept=fit_intercept)\n \n- assert_array_almost_equal(weights1, clf.coef_, decimal=10)\n- assert_array_almost_equal(intercept1, clf.intercept_, decimal=10)\n- assert_array_almost_equal(weights2, clf.coef_, decimal=10)\n- assert_array_almost_equal(intercept2, clf.intercept_, decimal=10)\n+ assert_allclose(weights1, clf.coef_)\n+ assert_allclose(intercept1, clf.intercept_)\n+ assert_allclose(weights2, clf.coef_)\n+ assert_allclose(intercept2, clf.intercept_)\n \n \n @ignore_warnings\n", "problem_statement": "IsolationForest contamination deprecation in __init__ not in fit\nneed to move the deprecation and fix the tests.\n", "hints_text": "", "created_at": "2018-07-16T22:39:16Z", "version": "0.20", "FAIL_TO_PASS": ["sklearn/ensemble/tests/test_iforest.py::test_deprecation"], "PASS_TO_PASS": ["sklearn/ensemble/tests/test_iforest.py::test_iforest", "sklearn/ensemble/tests/test_iforest.py::test_iforest_sparse", "sklearn/ensemble/tests/test_iforest.py::test_iforest_error", "sklearn/ensemble/tests/test_iforest.py::test_recalculate_max_depth", "sklearn/ensemble/tests/test_iforest.py::test_max_samples_attribute", "sklearn/ensemble/tests/test_iforest.py::test_iforest_parallel_regression", "sklearn/ensemble/tests/test_iforest.py::test_iforest_performance", "sklearn/ensemble/tests/test_iforest.py::test_iforest_works", "sklearn/ensemble/tests/test_iforest.py::test_max_samples_consistency", "sklearn/ensemble/tests/test_iforest.py::test_iforest_subsampled_features", "sklearn/ensemble/tests/test_iforest.py::test_iforest_average_path_length", "sklearn/ensemble/tests/test_iforest.py::test_score_samples", "sklearn/linear_model/tests/test_sag.py::test_classifier_matching", "sklearn/linear_model/tests/test_sag.py::test_regressor_matching", "sklearn/linear_model/tests/test_sag.py::test_sag_pobj_matches_logistic_regression", "sklearn/linear_model/tests/test_sag.py::test_sag_pobj_matches_ridge_regression", "sklearn/linear_model/tests/test_sag.py::test_sag_regressor_computed_correctly", "sklearn/linear_model/tests/test_sag.py::test_get_auto_step_size", "sklearn/linear_model/tests/test_sag.py::test_sag_regressor", "sklearn/linear_model/tests/test_sag.py::test_sag_classifier_computed_correctly", "sklearn/linear_model/tests/test_sag.py::test_sag_multiclass_computed_correctly", "sklearn/linear_model/tests/test_sag.py::test_classifier_results", "sklearn/linear_model/tests/test_sag.py::test_binary_classifier_class_weight", "sklearn/linear_model/tests/test_sag.py::test_multiclass_classifier_class_weight", "sklearn/linear_model/tests/test_sag.py::test_classifier_single_class", "sklearn/linear_model/tests/test_sag.py::test_step_size_alpha_error", "sklearn/linear_model/tests/test_sag.py::test_multinomial_loss", "sklearn/linear_model/tests/test_sag.py::test_multinomial_loss_ground_truth"], "environment_setup_commit": "55bf5d93e5674f13a1134d93a11fd0cd11aabcd1"}, {"repo": "django/django", "instance_id": "django__django-15136", "base_commit": "ed2018037d152eef7e68f339b4562f8aadc2b7a0", "patch": "diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py\n--- a/django/contrib/admin/widgets.py\n+++ b/django/contrib/admin/widgets.py\n@@ -8,7 +8,7 @@\n from django.conf import settings\n from django.core.exceptions import ValidationError\n from django.core.validators import URLValidator\n-from django.db.models import CASCADE\n+from django.db.models import CASCADE, UUIDField\n from django.urls import reverse\n from django.urls.exceptions import NoReverseMatch\n from django.utils.html import smart_urlquote\n@@ -149,7 +149,10 @@ def get_context(self, name, value, attrs):\n context['related_url'] = related_url\n context['link_title'] = _('Lookup')\n # The JavaScript code looks for this class.\n- context['widget']['attrs'].setdefault('class', 'vForeignKeyRawIdAdminField')\n+ css_class = 'vForeignKeyRawIdAdminField'\n+ if isinstance(self.rel.get_related_field(), UUIDField):\n+ css_class += ' vUUIDField'\n+ context['widget']['attrs'].setdefault('class', css_class)\n else:\n context['related_url'] = None\n if context['widget']['value']:\n", "test_patch": "diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py\n--- a/tests/admin_widgets/tests.py\n+++ b/tests/admin_widgets/tests.py\n@@ -26,7 +26,7 @@\n \n from .models import (\n Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual,\n- Inventory, Member, MyFileField, Profile, School, Student,\n+ Inventory, Member, MyFileField, Profile, ReleaseEvent, School, Student,\n UnsafeLimitChoicesTo, VideoStream,\n )\n from .widgetadmin import site as widget_admin_site\n@@ -538,19 +538,27 @@ def test_render(self):\n band.album_set.create(\n name='Hybrid Theory', cover_art=r'albums\\hybrid_theory.jpg'\n )\n- rel = Album._meta.get_field('band').remote_field\n-\n- w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)\n+ rel_uuid = Album._meta.get_field('band').remote_field\n+ w = widgets.ForeignKeyRawIdWidget(rel_uuid, widget_admin_site)\n self.assertHTMLEqual(\n w.render('test', band.uuid, attrs={}),\n '<input type=\"text\" name=\"test\" value=\"%(banduuid)s\" '\n- 'class=\"vForeignKeyRawIdAdminField\">'\n+ 'class=\"vForeignKeyRawIdAdminField vUUIDField\">'\n '<a href=\"/admin_widgets/band/?_to_field=uuid\" class=\"related-lookup\" '\n 'id=\"lookup_id_test\" title=\"Lookup\"></a>&nbsp;<strong>'\n '<a href=\"/admin_widgets/band/%(bandpk)s/change/\">Linkin Park</a>'\n '</strong>' % {'banduuid': band.uuid, 'bandpk': band.pk}\n )\n \n+ rel_id = ReleaseEvent._meta.get_field('album').remote_field\n+ w = widgets.ForeignKeyRawIdWidget(rel_id, widget_admin_site)\n+ self.assertHTMLEqual(\n+ w.render('test', None, attrs={}),\n+ '<input type=\"text\" name=\"test\" class=\"vForeignKeyRawIdAdminField\">'\n+ '<a href=\"/admin_widgets/album/?_to_field=id\" class=\"related-lookup\" '\n+ 'id=\"lookup_id_test\" title=\"Lookup\"></a>',\n+ )\n+\n def test_relations_to_non_primary_key(self):\n # ForeignKeyRawIdWidget works with fields which aren't related to\n # the model's primary key.\n", "problem_statement": "Admin foreign key raw inputs are too small when referring to a UUID field\nDescription\n\t\nPR: \u200bhttps://github.com/django/django/pull/12926\n", "hints_text": "", "created_at": "2021-11-28T06:59:22Z", "version": "4.1", "FAIL_TO_PASS": ["test_render (admin_widgets.tests.ForeignKeyRawIdWidgetTest)"], "PASS_TO_PASS": ["test_CharField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_DateField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_DateTimeField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_EmailField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_FileField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_ForeignKey (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_IntegerField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_TextField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_TimeField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_URLField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_choices_with_radio_fields (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_field_with_choices (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_filtered_many_to_many (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_formfield_overrides (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "formfield_overrides works for a custom field class.", "Overriding the widget for DateTimeField doesn't overrides the default", "The autocomplete_fields, raw_id_fields, filter_vertical, and", "Widget instances in formfield_overrides are not shared between", "test_inheritance (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "m2m fields help text as it applies to admin app (#9321).", "test_many_to_many (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_radio_fields_ForeignKey (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_raw_id_ForeignKey (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_raw_id_many_to_many (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_attrs (admin_widgets.tests.AdminTimeWidgetTest)", "test_attrs (admin_widgets.tests.AdminUUIDWidgetTests)", "test_attrs (admin_widgets.tests.AdminDateWidgetTest)", "test_render (admin_widgets.tests.FilteredSelectMultipleWidgetTest)", "test_stacked_render (admin_widgets.tests.FilteredSelectMultipleWidgetTest)", "test_localization (admin_widgets.tests.AdminSplitDateTimeWidgetTest)", "test_render (admin_widgets.tests.AdminSplitDateTimeWidgetTest)", "test_get_context_validates_url (admin_widgets.tests.AdminURLWidgetTest)", "test_render (admin_widgets.tests.AdminURLWidgetTest)", "test_render_idn (admin_widgets.tests.AdminURLWidgetTest)", "WARNING: This test doesn't use assertHTMLEqual since it will get rid", "test_custom_widget_render (admin_widgets.tests.RelatedFieldWidgetWrapperTests)", "test_no_can_add_related (admin_widgets.tests.RelatedFieldWidgetWrapperTests)", "test_on_delete_cascade_rel_cant_delete_related (admin_widgets.tests.RelatedFieldWidgetWrapperTests)", "test_select_multiple_widget_cant_change_delete_related (admin_widgets.tests.RelatedFieldWidgetWrapperTests)", "test_widget_delegates_value_omitted_from_data (admin_widgets.tests.RelatedFieldWidgetWrapperTests)", "test_widget_is_hidden (admin_widgets.tests.RelatedFieldWidgetWrapperTests)", "test_widget_is_not_hidden (admin_widgets.tests.RelatedFieldWidgetWrapperTests)", "test_fk_related_model_not_in_admin (admin_widgets.tests.ForeignKeyRawIdWidgetTest)", "test_fk_to_self_model_not_in_admin (admin_widgets.tests.ForeignKeyRawIdWidgetTest)", "test_proper_manager_for_label_lookup (admin_widgets.tests.ForeignKeyRawIdWidgetTest)", "test_relations_to_non_primary_key (admin_widgets.tests.ForeignKeyRawIdWidgetTest)", "test_render_fk_as_pk_model (admin_widgets.tests.ForeignKeyRawIdWidgetTest)", "test_render_unsafe_limit_choices_to (admin_widgets.tests.ForeignKeyRawIdWidgetTest)", "test_m2m_related_model_not_in_admin (admin_widgets.tests.ManyToManyRawIdWidgetTest)", "test_render (admin_widgets.tests.ManyToManyRawIdWidgetTest)", "Ensure the user can only see their own cars in the foreign key dropdown.", "test_changelist_ForeignKey (admin_widgets.tests.AdminForeignKeyWidgetChangeList)", "File widgets should render as a link when they're marked \"read only.\"", "test_render (admin_widgets.tests.AdminFileWidgetTests)", "test_render_disabled (admin_widgets.tests.AdminFileWidgetTests)", "test_render_required (admin_widgets.tests.AdminFileWidgetTests)", "test_invalid_target_id (admin_widgets.tests.AdminForeignKeyRawIdWidget)", "test_label_and_url_for_value_invalid_uuid (admin_widgets.tests.AdminForeignKeyRawIdWidget)", "test_nonexistent_target_id (admin_widgets.tests.AdminForeignKeyRawIdWidget)", "test_url_params_from_lookup_dict_any_iterable (admin_widgets.tests.AdminForeignKeyRawIdWidget)", "test_url_params_from_lookup_dict_callable (admin_widgets.tests.AdminForeignKeyRawIdWidget)"], "environment_setup_commit": "647480166bfe7532e8c471fef0146e3a17e6c0c9"}, {"repo": "django/django", "instance_id": "django__django-13841", "base_commit": "cfe47b7686df0c4c87270a83d6d7f933323ed7e6", "patch": "diff --git a/django/contrib/auth/password_validation.py b/django/contrib/auth/password_validation.py\n--- a/django/contrib/auth/password_validation.py\n+++ b/django/contrib/auth/password_validation.py\n@@ -8,7 +8,7 @@\n from django.core.exceptions import (\n FieldDoesNotExist, ImproperlyConfigured, ValidationError,\n )\n-from django.utils.functional import lazy\n+from django.utils.functional import cached_property, lazy\n from django.utils.html import format_html, format_html_join\n from django.utils.module_loading import import_string\n from django.utils.translation import gettext as _, ngettext\n@@ -167,9 +167,14 @@ class CommonPasswordValidator:\n https://gist.github.com/roycewilliams/281ce539915a947a23db17137d91aeb7\n The password list must be lowercased to match the comparison in validate().\n \"\"\"\n- DEFAULT_PASSWORD_LIST_PATH = Path(__file__).resolve().parent / 'common-passwords.txt.gz'\n+\n+ @cached_property\n+ def DEFAULT_PASSWORD_LIST_PATH(self):\n+ return Path(__file__).resolve().parent / 'common-passwords.txt.gz'\n \n def __init__(self, password_list_path=DEFAULT_PASSWORD_LIST_PATH):\n+ if password_list_path is CommonPasswordValidator.DEFAULT_PASSWORD_LIST_PATH:\n+ password_list_path = self.DEFAULT_PASSWORD_LIST_PATH\n try:\n with gzip.open(password_list_path, 'rt', encoding='utf-8') as f:\n self.passwords = {x.strip() for x in f}\ndiff --git a/django/forms/renderers.py b/django/forms/renderers.py\n--- a/django/forms/renderers.py\n+++ b/django/forms/renderers.py\n@@ -7,8 +7,6 @@\n from django.utils.functional import cached_property\n from django.utils.module_loading import import_string\n \n-ROOT = Path(__file__).parent\n-\n \n @functools.lru_cache()\n def get_default_renderer():\n@@ -33,7 +31,7 @@ def get_template(self, template_name):\n def engine(self):\n return self.backend({\n 'APP_DIRS': True,\n- 'DIRS': [ROOT / self.backend.app_dirname],\n+ 'DIRS': [Path(__file__).parent / self.backend.app_dirname],\n 'NAME': 'djangoforms',\n 'OPTIONS': {},\n })\ndiff --git a/django/utils/version.py b/django/utils/version.py\n--- a/django/utils/version.py\n+++ b/django/utils/version.py\n@@ -77,6 +77,10 @@ def get_git_changeset():\n This value isn't guaranteed to be unique, but collisions are very unlikely,\n so it's sufficient for generating the development version numbers.\n \"\"\"\n+ # Repository may not be found if __file__ is undefined, e.g. in a frozen\n+ # module.\n+ if '__file__' not in globals():\n+ return None\n repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n git_log = subprocess.run(\n 'git log --pretty=format:%ct --quiet -1 HEAD',\ndiff --git a/django/views/debug.py b/django/views/debug.py\n--- a/django/views/debug.py\n+++ b/django/views/debug.py\n@@ -26,7 +26,15 @@\n libraries={'i18n': 'django.templatetags.i18n'},\n )\n \n-CURRENT_DIR = Path(__file__).parent\n+\n+def builtin_template_path(name):\n+ \"\"\"\n+ Return a path to a builtin template.\n+\n+ Avoid calling this function at the module level or in a class-definition\n+ because __file__ may not exist, e.g. in frozen environments.\n+ \"\"\"\n+ return Path(__file__).parent / 'templates' / name\n \n \n class ExceptionCycleWarning(UserWarning):\n@@ -248,11 +256,11 @@ class ExceptionReporter:\n \n @property\n def html_template_path(self):\n- return CURRENT_DIR / 'templates' / 'technical_500.html'\n+ return builtin_template_path('technical_500.html')\n \n @property\n def text_template_path(self):\n- return CURRENT_DIR / 'templates' / 'technical_500.txt'\n+ return builtin_template_path('technical_500.txt')\n \n def __init__(self, request, exc_type, exc_value, tb, is_email=False):\n self.request = request\n@@ -534,7 +542,7 @@ def technical_404_response(request, exception):\n module = obj.__module__\n caller = '%s.%s' % (module, caller)\n \n- with Path(CURRENT_DIR, 'templates', 'technical_404.html').open(encoding='utf-8') as fh:\n+ with builtin_template_path('technical_404.html').open(encoding='utf-8') as fh:\n t = DEBUG_ENGINE.from_string(fh.read())\n reporter_filter = get_default_exception_reporter_filter()\n c = Context({\n@@ -553,7 +561,7 @@ def technical_404_response(request, exception):\n \n def default_urlconf(request):\n \"\"\"Create an empty URLconf 404 error response.\"\"\"\n- with Path(CURRENT_DIR, 'templates', 'default_urlconf.html').open(encoding='utf-8') as fh:\n+ with builtin_template_path('default_urlconf.html').open(encoding='utf-8') as fh:\n t = DEBUG_ENGINE.from_string(fh.read())\n c = Context({\n 'version': get_docs_version(),\n", "test_patch": "diff --git a/tests/version/tests.py b/tests/version/tests.py\n--- a/tests/version/tests.py\n+++ b/tests/version/tests.py\n@@ -1,17 +1,37 @@\n+from unittest import skipUnless\n+\n+import django.utils.version\n from django import get_version\n from django.test import SimpleTestCase\n-from django.utils.version import get_complete_version, get_version_tuple\n+from django.utils.version import (\n+ get_complete_version, get_git_changeset, get_version_tuple,\n+)\n \n \n class VersionTests(SimpleTestCase):\n \n def test_development(self):\n+ get_git_changeset.cache_clear()\n ver_tuple = (1, 4, 0, 'alpha', 0)\n # This will return a different result when it's run within or outside\n # of a git clone: 1.4.devYYYYMMDDHHMMSS or 1.4.\n ver_string = get_version(ver_tuple)\n self.assertRegex(ver_string, r'1\\.4(\\.dev[0-9]+)?')\n \n+ @skipUnless(\n+ hasattr(django.utils.version, '__file__'),\n+ 'test_development() checks the same when __file__ is already missing, '\n+ 'e.g. in a frozen environments'\n+ )\n+ def test_development_no_file(self):\n+ get_git_changeset.cache_clear()\n+ version_file = django.utils.version.__file__\n+ try:\n+ del django.utils.version.__file__\n+ self.test_development()\n+ finally:\n+ django.utils.version.__file__ = version_file\n+\n def test_releases(self):\n tuples_to_strings = (\n ((1, 4, 0, 'alpha', 1), '1.4a1'),\n", "problem_statement": "Access __file__ lazily rather than at module level\nDescription\n\t \n\t\t(last modified by William Schwartz)\n\t \nSo-called frozen Python environments (such as those mentioned in #30950) that do not set all modules' \u200b__file__ variable, which \u200bneed not be defined, cannot even import Django (without some workarounds) because a small number of Django modules use __file__ at the module level, in a class defined at the module level, or in a function that is called automatically upon import.\nFive modules that use __file__ like this are likely to be imported when using Django and thereby cause a frozen Python to crash with a NameError or similar exception.\nImporting django.forms.renderers can be avoided only by avoiding both forms and the ORM altogether as it's imported from django.db.models.\nImporting django.views.debug might be avoidable if DEBUG=False or by avoiding all of the views and URLs APIs.\ndjango.utils.version's get_git_changeset is called when django is imported in pre-alpha development versions.\nImporting django.contrib.auth.password_validation is only avoidable by not using the Auth app.\ndjango.utils.translation.trans_real uses __file__ to find Django's localization files upon activation; this avoidable only by setting USE_I18N=False. Dealing with trans_real is sufficiently thorny (and, being an English speaker with English-speaking clients, I can avoid it for now) that I will not address it further here except to say that it might need to be part of the larger discussion at #30950.\nWhat this ticket is not\nI am not proposing removing use of __file__ at this time. That would require a longer discussion of intended semantics such as #30950. This ticket is only about removing use of __file__ at the module (or class definition) level in Django application code (not test code). Further I am not proposing banning use of __file__ at the module level at this time, hence minimal new tests and no update to the Django coding style documentation. That too would require a longer conversation.\nProposed fixes\nI have pushed \u200bPR GH-13841 to address the four of those modules other than trans_real. I dealt with each module's use of __file__ in separate commits to make them easier to discuss and separate/cherry-pick if needed. Below I link to the individual commits as I discuss each of the four modules. These first two are fairly easy, but the second two may require further consideration.\ndjango.forms.renders (\u200b54d539c)\nRemove the undocumented module constant ROOT and replace its single use.\ndjango.utils.version (\u200bf4edc6e)\nTreat the lack of module-global __file__ the same as a failure of git log by returning None from get_git_changeset.\ndjango.views.debug (\u200b07f46b7)\nThe module-level constant CURRENT_DIR is used only in the module itself and is undocumented, so I'm assuming it's an obscure private symbol that no one will miss. I've replaced it with a module-level private function _builtin_template_path that refactors and centralizes finding built-in templates for the entire module.\nThe one tricky part is that #32105 added the html_template_path and text_template_path attributes django.views.debug.ExceptionReporter. I didn't want to disturb #32105's goal of making the template paths easily override-able, so I avoided calling _builtin_template_path in the class definition by making detecting the presence of the attributes in __init__ and setting defaults there. Alternatives include making the attributes properties with setters or cached properties without setters.\ndjango.contrib.auth.password_validation (\u200b24aa80b)\nThe CommonPasswordValidator-class constant DEFAULT_PASSWORD_LIST_PATH is used only in one place, the class's instance constructor. While the nature of DEFAULT_PASSWORD_LIST_PATH is not documented, its existence is inside the docs for the \u200bconstructor's signature. I've changed DEFAULT_PASSWORD_LIST_PATH from a class constant into an instance attribute. Another possibility is making DEFAULT_PASSWORD_LIST_PATH be a django.utils.functional.classproperty.\n", "hints_text": "", "created_at": "2021-01-04T20:40:02Z", "version": "4.0", "FAIL_TO_PASS": ["test_development_no_file (version.tests.VersionTests)"], "PASS_TO_PASS": ["test_development (version.tests.VersionTests)", "test_get_version_invalid_version (version.tests.VersionTests)", "test_get_version_tuple (version.tests.VersionTests)", "test_releases (version.tests.VersionTests)"], "environment_setup_commit": "475cffd1d64c690cdad16ede4d5e81985738ceb4"}, {"repo": "django/django", "instance_id": "django__django-17029", "base_commit": "953f29f700a60fc09b08b2c2270c12c447490c6a", "patch": "diff --git a/django/apps/registry.py b/django/apps/registry.py\n--- a/django/apps/registry.py\n+++ b/django/apps/registry.py\n@@ -373,6 +373,7 @@ def clear_cache(self):\n \n This is mostly used in tests.\n \"\"\"\n+ self.get_swappable_settings_name.cache_clear()\n # Call expire cache on each model. This will purge\n # the relation tree and the fields cache.\n self.get_models.cache_clear()\n", "test_patch": "diff --git a/tests/apps/tests.py b/tests/apps/tests.py\n--- a/tests/apps/tests.py\n+++ b/tests/apps/tests.py\n@@ -197,6 +197,17 @@ def test_get_model(self):\n with self.assertRaises(ValueError):\n apps.get_model(\"admin_LogEntry\")\n \n+ @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)\n+ def test_clear_cache(self):\n+ # Set cache.\n+ self.assertIsNone(apps.get_swappable_settings_name(\"admin.LogEntry\"))\n+ apps.get_models()\n+\n+ apps.clear_cache()\n+\n+ self.assertEqual(apps.get_swappable_settings_name.cache_info().currsize, 0)\n+ self.assertEqual(apps.get_models.cache_info().currsize, 0)\n+\n @override_settings(INSTALLED_APPS=[\"apps.apps.RelabeledAppsConfig\"])\n def test_relabeling(self):\n self.assertEqual(apps.get_app_config(\"relabeled\").name, \"apps\")\n", "problem_statement": "Apps.clear_cache() does not clear get_swappable_settings_name cache.\nDescription\n\t\nWe use apps.clear_cache() in django-stubs to be able to reset the previous state on consequential mypy runs.\nCode: \u200bhttps://github.com/typeddjango/django-stubs/pull/1601/files#diff-c49d8fe2cd0a58fad3c36ab3a88c7745e9622f3098e60cd512953eb17b8a1994R63-R64\nBut, looks like we don't clear all the object's cache this way, because get_swappable_settings_name (which is a functools._lru_cache_wrapper) is not cleared.\nI think that this is not correct. .clear_cache doc states: Clear all internal caches, for methods that alter the app registry.\nLooks like that is not the case.\nI propose to add: self.get_swappable_settings_name.cache_clear() line to def clear_cache.\nIf others agree, I will make a PR.\nOriginal discussion: \u200bhttps://github.com/typeddjango/django-stubs/pull/1601#discussion_r1246344533\n", "hints_text": "Thanks for the report, tentatively accepted.", "created_at": "2023-06-29T13:18:26Z", "version": "5.0", "FAIL_TO_PASS": ["test_clear_cache (apps.tests.AppsTests.test_clear_cache)"], "PASS_TO_PASS": ["test_app_default_auto_field (apps.tests.AppConfigTests.test_app_default_auto_field)", "test_default_auto_field_setting (apps.tests.AppConfigTests.test_default_auto_field_setting)", "If single element in __path__, use it (in preference to __file__).", "If the __path__ attr contains duplicate paths and there is no", "If the __path__ attr is empty, use __file__ if set.", "If the __path__ attr is empty and there is no __file__, raise.", "If path set as class attr, overrides __path__ and __file__.", "test_invalid_label (apps.tests.AppConfigTests.test_invalid_label)", "If the __path__ attr is length>1, use __file__ if set.", "If the __path__ attr is length>1 and there is no __file__, raise.", "If there is no __path__ attr, use __file__.", "If there is no __path__ or __file__, raise ImproperlyConfigured.", "If subclass sets path as class attr, no module attributes needed.", "test_repr (apps.tests.AppConfigTests.test_repr)", "A Py3.3+ namespace package with multiple locations cannot be an app.", "Multiple locations are ok only if app-config has explicit path.", "A Py3.3+ namespace package can be an app if it has only one path.", "Tests when INSTALLED_APPS contains an incorrect app config.", "test_duplicate_labels (apps.tests.AppsTests.test_duplicate_labels)", "test_duplicate_names (apps.tests.AppsTests.test_duplicate_names)", "Makes a new model at runtime and ensures it goes into the right place.", "Tests apps.get_app_config().", "Tests apps.get_app_configs().", "apps.get_containing_app_config() should raise an exception if", "Tests apps.get_model().", "App discovery should preserve stack traces. Regression test for #22920.", "Tests apps.is_installed().", "Tests apps.lazy_model_operation().", "Test for behavior when two models clash in the app registry.", "apps.get_models() raises an exception if apps.models_ready isn't True.", "The models in the models.py file were loaded correctly.", "Load an app that doesn't provide an AppConfig class.", "Tests when INSTALLED_APPS contains an app that doesn't exist, either", "test_no_such_app_config (apps.tests.AppsTests.test_no_such_app_config)", "test_no_such_app_config_with_choices (apps.tests.AppsTests.test_no_such_app_config_with_choices)", "Tests when INSTALLED_APPS contains a class that isn't an app config.", "Load an app that provides an AppConfig class.", "Tests the ready property of the main registry.", "test_relabeling (apps.tests.AppsTests.test_relabeling)", "Only one main registry can exist.", "Load an app that provides two AppConfig classes.", "Load an app that provides two AppConfig classes, one being the default.", "Load an app that provides two default AppConfig classes."], "environment_setup_commit": "4a72da71001f154ea60906a2f74898d32b7322a7"}, {"repo": "django/django", "instance_id": "django__django-13251", "base_commit": "b6dfdaff33f19757b1cb9b3bf1d17f28b94859d4", "patch": "diff --git a/django/db/models/query.py b/django/db/models/query.py\n--- a/django/db/models/query.py\n+++ b/django/db/models/query.py\n@@ -204,7 +204,7 @@ def __init__(self, model=None, query=None, using=None, hints=None):\n def query(self):\n if self._deferred_filter:\n negate, args, kwargs = self._deferred_filter\n- self._filter_or_exclude_inplace(negate, *args, **kwargs)\n+ self._filter_or_exclude_inplace(negate, args, kwargs)\n self._deferred_filter = None\n return self._query\n \n@@ -939,7 +939,7 @@ def filter(self, *args, **kwargs):\n set.\n \"\"\"\n self._not_support_combined_queries('filter')\n- return self._filter_or_exclude(False, *args, **kwargs)\n+ return self._filter_or_exclude(False, args, kwargs)\n \n def exclude(self, *args, **kwargs):\n \"\"\"\n@@ -947,9 +947,9 @@ def exclude(self, *args, **kwargs):\n set.\n \"\"\"\n self._not_support_combined_queries('exclude')\n- return self._filter_or_exclude(True, *args, **kwargs)\n+ return self._filter_or_exclude(True, args, kwargs)\n \n- def _filter_or_exclude(self, negate, *args, **kwargs):\n+ def _filter_or_exclude(self, negate, args, kwargs):\n if args or kwargs:\n assert not self.query.is_sliced, \\\n \"Cannot filter a query once a slice has been taken.\"\n@@ -959,10 +959,10 @@ def _filter_or_exclude(self, negate, *args, **kwargs):\n self._defer_next_filter = False\n clone._deferred_filter = negate, args, kwargs\n else:\n- clone._filter_or_exclude_inplace(negate, *args, **kwargs)\n+ clone._filter_or_exclude_inplace(negate, args, kwargs)\n return clone\n \n- def _filter_or_exclude_inplace(self, negate, *args, **kwargs):\n+ def _filter_or_exclude_inplace(self, negate, args, kwargs):\n if negate:\n self._query.add_q(~Q(*args, **kwargs))\n else:\n@@ -983,7 +983,7 @@ def complex_filter(self, filter_obj):\n clone.query.add_q(filter_obj)\n return clone\n else:\n- return self._filter_or_exclude(False, **filter_obj)\n+ return self._filter_or_exclude(False, args=(), kwargs=filter_obj)\n \n def _combinator_query(self, combinator, *other_qs, all=False):\n # Clone the query to inherit the select list and everything\n", "test_patch": "diff --git a/tests/queries/models.py b/tests/queries/models.py\n--- a/tests/queries/models.py\n+++ b/tests/queries/models.py\n@@ -42,6 +42,7 @@ class Note(models.Model):\n note = models.CharField(max_length=100)\n misc = models.CharField(max_length=10)\n tag = models.ForeignKey(Tag, models.SET_NULL, blank=True, null=True)\n+ negate = models.BooleanField(default=True)\n \n class Meta:\n ordering = ['note']\ndiff --git a/tests/queries/tests.py b/tests/queries/tests.py\n--- a/tests/queries/tests.py\n+++ b/tests/queries/tests.py\n@@ -47,7 +47,7 @@ def setUpTestData(cls):\n \n cls.n1 = Note.objects.create(note='n1', misc='foo', id=1)\n cls.n2 = Note.objects.create(note='n2', misc='bar', id=2)\n- cls.n3 = Note.objects.create(note='n3', misc='foo', id=3)\n+ cls.n3 = Note.objects.create(note='n3', misc='foo', id=3, negate=False)\n \n ann1 = Annotation.objects.create(name='a1', tag=cls.t1)\n ann1.notes.add(cls.n1)\n@@ -1216,6 +1216,13 @@ def test_field_with_filterable(self):\n [self.a3, self.a4],\n )\n \n+ def test_negate_field(self):\n+ self.assertSequenceEqual(\n+ Note.objects.filter(negate=True),\n+ [self.n1, self.n2],\n+ )\n+ self.assertSequenceEqual(Note.objects.exclude(negate=True), [self.n3])\n+\n \n class Queries2Tests(TestCase):\n @classmethod\n", "problem_statement": "Filtering on a field named `negate` raises a TypeError\nDescription\n\t\nFiltering on a model with a field named negate raises a TypeError.\nFor example:\nclass Foo(models.Model):\n\tnegate = models.BooleanField()\nFoo.objects.filter(negate=True)\nraises TypeError: _filter_or_exclude() got multiple values for argument 'negate'\nnegate is not documented as a reserved argument for .filter(). I'm currently using .filter(negate__exact=True) as a workaround.\n", "hints_text": "We should either document this limitation or change _filter_or_exclude and friends signature from (negate, *args, **kwargs) to (negate, args, kwargs). I think the second approach is favourable as there's not much benefits in using arguments unpacking in these private methods as long as the public methods filter and exclude preserve their signature.\nAaron, would you be interested in submitting a PR with the changes below plus a regression test in tests/query/tests.py? django/db/models/query.py diff --git a/django/db/models/query.py b/django/db/models/query.py index 07d6ffd4ca..d655ede8d9 100644 a b class QuerySet: 204204 def query(self): 205205 if self._deferred_filter: 206206 negate, args, kwargs = self._deferred_filter 207 self._filter_or_exclude_inplace(negate, *args, **kwargs) 207 self._filter_or_exclude_inplace(negate, args, kwargs) 208208 self._deferred_filter = None 209209 return self._query 210210 \u2026 \u2026 class QuerySet: 939939 set. 940940 \"\"\" 941941 self._not_support_combined_queries('filter') 942 return self._filter_or_exclude(False, *args, **kwargs) 942 return self._filter_or_exclude(False, args, kwargs) 943943 944944 def exclude(self, *args, **kwargs): 945945 \"\"\" \u2026 \u2026 class QuerySet: 947947 set. 948948 \"\"\" 949949 self._not_support_combined_queries('exclude') 950 return self._filter_or_exclude(True, *args, **kwargs) 950 return self._filter_or_exclude(True, args, kwargs) 951951 952 def _filter_or_exclude(self, negate, *args, **kwargs): 952 def _filter_or_exclude(self, negate, args, kwargs): 953953 if args or kwargs: 954954 assert not self.query.is_sliced, \\ 955955 \"Cannot filter a query once a slice has been taken.\" \u2026 \u2026 class QuerySet: 959959 self._defer_next_filter = False 960960 clone._deferred_filter = negate, args, kwargs 961961 else: 962 clone._filter_or_exclude_inplace(negate, *args, **kwargs) 962 clone._filter_or_exclude_inplace(negate, args, kwargs) 963963 return clone 964964 965 def _filter_or_exclude_inplace(self, negate, *args, **kwargs): 965 def _filter_or_exclude_inplace(self, negate, args, kwargs): 966966 if negate: 967967 self._query.add_q(~Q(*args, **kwargs)) 968968 else: \u2026 \u2026 class QuerySet: 983983 clone.query.add_q(filter_obj) 984984 return clone 985985 else: 986 return self._filter_or_exclude(False, **filter_obj) 986 return self._filter_or_exclude(False, args=(), kwargs=filter_obj) 987987 988988 def _combinator_query(self, combinator, *other_qs, all=False): 989989 # Clone the query to inherit the select list and everything\nReplying to Simon Charette: Aaron, would you be interested in submitting a PR with the changes below plus a regression test in tests/query/tests.py? Sure! I can do that this evening. Thanks for the patch :)", "created_at": "2020-07-28T11:59:53Z", "version": "3.2", "FAIL_TO_PASS": ["test_negate_field (queries.tests.Queries1Tests)"], "PASS_TO_PASS": ["test_ticket7371 (queries.tests.CustomPkTests)", "test_no_extra_params (queries.tests.DefaultValuesInsertTest)", "test_ticket_21879 (queries.tests.ReverseM2MCustomPkTests)", "test_invalid_values (queries.tests.TestInvalidValuesRelation)", "test_ticket_7302 (queries.tests.EscapingTests)", "test_emptyqueryset_values (queries.tests.EmptyQuerySetTests)", "test_ticket_19151 (queries.tests.EmptyQuerySetTests)", "test_values_subquery (queries.tests.EmptyQuerySetTests)", "test_ticket14729 (queries.tests.RawQueriesTests)", "test_empty_full_handling_conjunction (queries.tests.WhereNodeTest)", "test_empty_full_handling_disjunction (queries.tests.WhereNodeTest)", "test_empty_nodes (queries.tests.WhereNodeTest)", "test_evaluated_proxy_count (queries.tests.ProxyQueryCleanupTest)", "#13227 -- If a queryset is already evaluated, it can still be used as a query arg", "test_no_fields_cloning (queries.tests.CloneTests)", "test_no_model_options_cloning (queries.tests.CloneTests)", "test_in_list_limit (queries.tests.ConditionalTests)", "test_infinite_loop (queries.tests.ConditionalTests)", "test_double_subquery_in (queries.tests.DoubleInSubqueryTests)", "test_ticket8597 (queries.tests.ComparisonTests)", "test_ticket22023 (queries.tests.Queries3Tests)", "test_ticket7107 (queries.tests.Queries3Tests)", "test_ticket8683 (queries.tests.Queries3Tests)", "test_ticket7872 (queries.tests.DisjunctiveFilterTests)", "test_ticket8283 (queries.tests.DisjunctiveFilterTests)", "test_ticket10432 (queries.tests.GeneratorExpressionTests)", "test_ticket15786 (queries.tests.Exclude15786)", "test_ticket_24278 (queries.tests.TestTicket24279)", "test_tickets_3045_3288 (queries.tests.SelectRelatedTests)", "test_ticket_18785 (queries.tests.Ticket18785Tests)", "test_ticket_14056 (queries.tests.Ticket14056Tests)", "test_invalid_order_by (queries.tests.QuerySetExceptionTests)", "test_invalid_queryset_model (queries.tests.QuerySetExceptionTests)", "test_iter_exceptions (queries.tests.QuerySetExceptionTests)", "test_21001 (queries.tests.EmptyStringsAsNullTest)", "test_direct_exclude (queries.tests.EmptyStringsAsNullTest)", "test_joined_exclude (queries.tests.EmptyStringsAsNullTest)", "test_exists (queries.tests.ExistsSql)", "test_ticket_18414 (queries.tests.ExistsSql)", "test_ticket_21203 (queries.tests.Ticket21203Tests)", "test_annotated_ordering (queries.tests.QuerysetOrderedTests)", "test_cleared_default_ordering (queries.tests.QuerysetOrderedTests)", "test_empty_queryset (queries.tests.QuerysetOrderedTests)", "test_explicit_ordering (queries.tests.QuerysetOrderedTests)", "test_no_default_or_explicit_ordering (queries.tests.QuerysetOrderedTests)", "test_order_by_extra (queries.tests.QuerysetOrderedTests)", "test_reverse_trimming (queries.tests.ReverseJoinTrimmingTest)", "test_empty_string_promotion (queries.tests.EmptyStringPromotionTests)", "test_join_already_in_query (queries.tests.NullableRelOrderingTests)", "test_ticket10028 (queries.tests.NullableRelOrderingTests)", "test_values_in_subquery (queries.tests.ValuesSubqueryTests)", "test_ticket_12807 (queries.tests.Ticket12807Tests)", "test_ticket_24605 (queries.tests.TestTicket24605)", "test_ticket_21787 (queries.tests.ForeignKeyToBaseExcludeTests)", "test_ticket_19964 (queries.tests.RelabelCloneTest)", "test_ticket7778 (queries.tests.SubclassFKTests)", "test_primary_key (queries.tests.IsNullTests)", "test_to_field (queries.tests.IsNullTests)", "test_ticket_22429 (queries.tests.Ticket22429Tests)", "test_double_exclude (queries.tests.NullInExcludeTest)", "test_null_in_exclude_qs (queries.tests.NullInExcludeTest)", "test_ticket_20788 (queries.tests.Ticket20788Tests)", "test_ticket_20101 (queries.tests.Ticket20101Tests)", "test_non_nullable_fk_not_promoted (queries.tests.ValuesJoinPromotionTests)", "test_ticket_21376 (queries.tests.ValuesJoinPromotionTests)", "test_values_no_promotion_for_existing (queries.tests.ValuesJoinPromotionTests)", "test_fk_reuse (queries.tests.JoinReuseTest)", "test_fk_reuse_annotation (queries.tests.JoinReuseTest)", "test_fk_reuse_disjunction (queries.tests.JoinReuseTest)", "test_fk_reuse_order_by (queries.tests.JoinReuseTest)", "test_fk_reuse_select_related (queries.tests.JoinReuseTest)", "test_inverted_q_across_relations (queries.tests.JoinReuseTest)", "test_revfk_noreuse (queries.tests.JoinReuseTest)", "test_revo2o_reuse (queries.tests.JoinReuseTest)", "test_ticket_20955 (queries.tests.Ticket20955Tests)", "test_empty_resultset_sql (queries.tests.WeirdQuerysetSlicingTests)", "test_empty_sliced_subquery (queries.tests.WeirdQuerysetSlicingTests)", "test_empty_sliced_subquery_exclude (queries.tests.WeirdQuerysetSlicingTests)", "test_tickets_7698_10202 (queries.tests.WeirdQuerysetSlicingTests)", "test_zero_length_values_slicing (queries.tests.WeirdQuerysetSlicingTests)", "test_correct_lookup (queries.tests.RelatedLookupTypeTests)", "test_values_queryset_lookup (queries.tests.RelatedLookupTypeTests)", "test_wrong_backward_lookup (queries.tests.RelatedLookupTypeTests)", "test_wrong_type_lookup (queries.tests.RelatedLookupTypeTests)", "test_exclude_plain (queries.tests.ExcludeTest17600)", "test_exclude_plain_distinct (queries.tests.ExcludeTest17600)", "test_exclude_with_q_is_equal_to_plain_exclude (queries.tests.ExcludeTest17600)", "test_exclude_with_q_is_equal_to_plain_exclude_variation (queries.tests.ExcludeTest17600)", "test_exclude_with_q_object_distinct (queries.tests.ExcludeTest17600)", "test_exclude_with_q_object_no_distinct (queries.tests.ExcludeTest17600)", "test_can_combine_queries_using_and_and_or_operators (queries.tests.QuerySetSupportsPythonIdioms)", "test_can_get_items_using_index_and_slice_notation (queries.tests.QuerySetSupportsPythonIdioms)", "test_can_get_number_of_items_in_queryset_using_standard_len (queries.tests.QuerySetSupportsPythonIdioms)", "test_invalid_index (queries.tests.QuerySetSupportsPythonIdioms)", "test_slicing_can_slice_again_after_slicing (queries.tests.QuerySetSupportsPythonIdioms)", "test_slicing_cannot_combine_queries_once_sliced (queries.tests.QuerySetSupportsPythonIdioms)", "test_slicing_cannot_filter_queryset_once_sliced (queries.tests.QuerySetSupportsPythonIdioms)", "test_slicing_cannot_reorder_queryset_once_sliced (queries.tests.QuerySetSupportsPythonIdioms)", "hint: inverting your ordering might do what you need", "test_slicing_with_steps_can_be_used (queries.tests.QuerySetSupportsPythonIdioms)", "test_slicing_with_tests_is_not_lazy (queries.tests.QuerySetSupportsPythonIdioms)", "test_slicing_without_step_is_lazy (queries.tests.QuerySetSupportsPythonIdioms)", "test_ticket12239 (queries.tests.Queries2Tests)", "test_ticket4289 (queries.tests.Queries2Tests)", "test_ticket7759 (queries.tests.Queries2Tests)", "test_ticket_23605 (queries.tests.Ticket23605Tests)", "test_exclude_many_to_many (queries.tests.ManyToManyExcludeTest)", "test_ticket_12823 (queries.tests.ManyToManyExcludeTest)", "test_or_with_both_slice (queries.tests.QuerySetBitwiseOperationTests)", "test_or_with_both_slice_and_ordering (queries.tests.QuerySetBitwiseOperationTests)", "test_or_with_lhs_slice (queries.tests.QuerySetBitwiseOperationTests)", "test_or_with_rhs_slice (queries.tests.QuerySetBitwiseOperationTests)", "test_disjunction_promotion1 (queries.tests.DisjunctionPromotionTests)", "test_disjunction_promotion2 (queries.tests.DisjunctionPromotionTests)", "test_disjunction_promotion3 (queries.tests.DisjunctionPromotionTests)", "test_disjunction_promotion3_demote (queries.tests.DisjunctionPromotionTests)", "test_disjunction_promotion4 (queries.tests.DisjunctionPromotionTests)", "test_disjunction_promotion4_demote (queries.tests.DisjunctionPromotionTests)", "test_disjunction_promotion5_demote (queries.tests.DisjunctionPromotionTests)", "test_disjunction_promotion6 (queries.tests.DisjunctionPromotionTests)", "test_disjunction_promotion7 (queries.tests.DisjunctionPromotionTests)", "test_disjunction_promotion_fexpression (queries.tests.DisjunctionPromotionTests)", "test_disjunction_promotion_select_related (queries.tests.DisjunctionPromotionTests)", "test_in_query (queries.tests.ToFieldTests)", "test_in_subquery (queries.tests.ToFieldTests)", "test_nested_in_subquery (queries.tests.ToFieldTests)", "test_recursive_fk (queries.tests.ToFieldTests)", "test_recursive_fk_reverse (queries.tests.ToFieldTests)", "test_reverse_in (queries.tests.ToFieldTests)", "test_single_object (queries.tests.ToFieldTests)", "test_single_object_reverse (queries.tests.ToFieldTests)", "test_extra_select_literal_percent_s (queries.tests.Queries5Tests)", "test_ordering (queries.tests.Queries5Tests)", "test_ticket5261 (queries.tests.Queries5Tests)", "test_ticket7045 (queries.tests.Queries5Tests)", "test_ticket7256 (queries.tests.Queries5Tests)", "test_ticket9848 (queries.tests.Queries5Tests)", "test_distinct_ordered_sliced_subquery_aggregation (queries.tests.Queries6Tests)", "test_multiple_columns_with_the_same_name_slice (queries.tests.Queries6Tests)", "test_nested_queries_sql (queries.tests.Queries6Tests)", "test_parallel_iterators (queries.tests.Queries6Tests)", "test_ticket3739 (queries.tests.Queries6Tests)", "test_ticket_11320 (queries.tests.Queries6Tests)", "test_tickets_8921_9188 (queries.tests.Queries6Tests)", "test_extra_multiple_select_params_values_order_by (queries.tests.ValuesQuerysetTests)", "test_extra_select_params_values_order_in_extra (queries.tests.ValuesQuerysetTests)", "test_extra_values (queries.tests.ValuesQuerysetTests)", "test_extra_values_list (queries.tests.ValuesQuerysetTests)", "test_extra_values_order_in_extra (queries.tests.ValuesQuerysetTests)", "test_extra_values_order_multiple (queries.tests.ValuesQuerysetTests)", "test_extra_values_order_twice (queries.tests.ValuesQuerysetTests)", "test_field_error_values_list (queries.tests.ValuesQuerysetTests)", "test_flat_extra_values_list (queries.tests.ValuesQuerysetTests)", "test_flat_values_list (queries.tests.ValuesQuerysetTests)", "test_named_values_list_bad_field_name (queries.tests.ValuesQuerysetTests)", "test_named_values_list_expression (queries.tests.ValuesQuerysetTests)", "test_named_values_list_expression_with_default_alias (queries.tests.ValuesQuerysetTests)", "test_named_values_list_flat (queries.tests.ValuesQuerysetTests)", "test_named_values_list_with_fields (queries.tests.ValuesQuerysetTests)", "test_named_values_list_without_fields (queries.tests.ValuesQuerysetTests)", "test_AB_ACB (queries.tests.UnionTests)", "test_A_AB (queries.tests.UnionTests)", "test_A_AB2 (queries.tests.UnionTests)", "test_BAB_BAC (queries.tests.UnionTests)", "test_BAB_BACB (queries.tests.UnionTests)", "test_BA_BCA__BAB_BAC_BCA (queries.tests.UnionTests)", "test_distinct_ordered_sliced_subquery (queries.tests.SubqueryTests)", "Subselects honor any manual ordering", "test_related_sliced_subquery (queries.tests.SubqueryTests)", "test_slice_subquery_and_query (queries.tests.SubqueryTests)", "Delete queries can safely contain sliced subqueries", "test_isnull_filter_promotion (queries.tests.NullJoinPromotionOrTest)", "test_null_join_demotion (queries.tests.NullJoinPromotionOrTest)", "test_ticket_17886 (queries.tests.NullJoinPromotionOrTest)", "test_ticket_21366 (queries.tests.NullJoinPromotionOrTest)", "test_ticket_21748 (queries.tests.NullJoinPromotionOrTest)", "test_ticket_21748_complex_filter (queries.tests.NullJoinPromotionOrTest)", "test_ticket_21748_double_negated_and (queries.tests.NullJoinPromotionOrTest)", "test_ticket_21748_double_negated_or (queries.tests.NullJoinPromotionOrTest)", "test_exclude_nullable_fields (queries.tests.ExcludeTests)", "test_exclude_reverse_fk_field_ref (queries.tests.ExcludeTests)", "test_exclude_with_circular_fk_relation (queries.tests.ExcludeTests)", "test_subquery_exclude_outerref (queries.tests.ExcludeTests)", "test_ticket14511 (queries.tests.ExcludeTests)", "test_to_field (queries.tests.ExcludeTests)", "test_combine_join_reuse (queries.tests.Queries4Tests)", "test_filter_reverse_non_integer_pk (queries.tests.Queries4Tests)", "test_join_reuse_order (queries.tests.Queries4Tests)", "test_order_by_resetting (queries.tests.Queries4Tests)", "test_order_by_reverse_fk (queries.tests.Queries4Tests)", "test_ticket10181 (queries.tests.Queries4Tests)", "test_ticket11811 (queries.tests.Queries4Tests)", "test_ticket14876 (queries.tests.Queries4Tests)", "test_ticket15316_exclude_false (queries.tests.Queries4Tests)", "test_ticket15316_exclude_true (queries.tests.Queries4Tests)", "test_ticket15316_filter_false (queries.tests.Queries4Tests)", "test_ticket15316_filter_true (queries.tests.Queries4Tests)", "test_ticket15316_one2one_exclude_false (queries.tests.Queries4Tests)", "test_ticket15316_one2one_exclude_true (queries.tests.Queries4Tests)", "test_ticket15316_one2one_filter_false (queries.tests.Queries4Tests)", "test_ticket15316_one2one_filter_true (queries.tests.Queries4Tests)", "test_ticket24525 (queries.tests.Queries4Tests)", "test_ticket7095 (queries.tests.Queries4Tests)", "test_avoid_infinite_loop_on_too_many_subqueries (queries.tests.Queries1Tests)", "test_common_mixed_case_foreign_keys (queries.tests.Queries1Tests)", "test_deferred_load_qs_pickling (queries.tests.Queries1Tests)", "test_double_exclude (queries.tests.Queries1Tests)", "test_error_raised_on_filter_with_dictionary (queries.tests.Queries1Tests)", "test_exclude (queries.tests.Queries1Tests)", "test_exclude_in (queries.tests.Queries1Tests)", "test_excluded_intermediary_m2m_table_joined (queries.tests.Queries1Tests)", "test_field_with_filterable (queries.tests.Queries1Tests)", "test_get_clears_ordering (queries.tests.Queries1Tests)", "test_heterogeneous_qs_combination (queries.tests.Queries1Tests)", "test_lookup_constraint_fielderror (queries.tests.Queries1Tests)", "test_nested_exclude (queries.tests.Queries1Tests)", "test_order_by_join_unref (queries.tests.Queries1Tests)", "test_order_by_raw_column_alias_warning (queries.tests.Queries1Tests)", "test_order_by_rawsql (queries.tests.Queries1Tests)", "test_order_by_tables (queries.tests.Queries1Tests)", "test_reasonable_number_of_subq_aliases (queries.tests.Queries1Tests)", "test_subquery_condition (queries.tests.Queries1Tests)", "test_ticket10205 (queries.tests.Queries1Tests)", "test_ticket10432 (queries.tests.Queries1Tests)", "test_ticket1050 (queries.tests.Queries1Tests)", "test_ticket10742 (queries.tests.Queries1Tests)", "test_ticket17429 (queries.tests.Queries1Tests)", "test_ticket1801 (queries.tests.Queries1Tests)", "test_ticket19672 (queries.tests.Queries1Tests)", "test_ticket2091 (queries.tests.Queries1Tests)", "test_ticket2253 (queries.tests.Queries1Tests)", "test_ticket2306 (queries.tests.Queries1Tests)", "test_ticket2400 (queries.tests.Queries1Tests)", "test_ticket2496 (queries.tests.Queries1Tests)", "test_ticket3037 (queries.tests.Queries1Tests)", "test_ticket3141 (queries.tests.Queries1Tests)", "test_ticket4358 (queries.tests.Queries1Tests)", "test_ticket4464 (queries.tests.Queries1Tests)", "test_ticket4510 (queries.tests.Queries1Tests)", "test_ticket6074 (queries.tests.Queries1Tests)", "test_ticket6154 (queries.tests.Queries1Tests)", "test_ticket6981 (queries.tests.Queries1Tests)", "test_ticket7076 (queries.tests.Queries1Tests)", "test_ticket7096 (queries.tests.Queries1Tests)", "test_ticket7098 (queries.tests.Queries1Tests)", "test_ticket7155 (queries.tests.Queries1Tests)", "test_ticket7181 (queries.tests.Queries1Tests)", "test_ticket7235 (queries.tests.Queries1Tests)", "test_ticket7277 (queries.tests.Queries1Tests)", "test_ticket7323 (queries.tests.Queries1Tests)", "test_ticket7378 (queries.tests.Queries1Tests)", "test_ticket7791 (queries.tests.Queries1Tests)", "test_ticket7813 (queries.tests.Queries1Tests)", "test_ticket8439 (queries.tests.Queries1Tests)", "test_ticket9411 (queries.tests.Queries1Tests)", "test_ticket9926 (queries.tests.Queries1Tests)", "test_ticket9985 (queries.tests.Queries1Tests)", "test_ticket9997 (queries.tests.Queries1Tests)", "test_ticket_10790_1 (queries.tests.Queries1Tests)", "test_ticket_10790_2 (queries.tests.Queries1Tests)", "test_ticket_10790_3 (queries.tests.Queries1Tests)", "test_ticket_10790_4 (queries.tests.Queries1Tests)", "test_ticket_10790_5 (queries.tests.Queries1Tests)", "test_ticket_10790_6 (queries.tests.Queries1Tests)", "test_ticket_10790_7 (queries.tests.Queries1Tests)", "test_ticket_10790_8 (queries.tests.Queries1Tests)", "test_ticket_10790_combine (queries.tests.Queries1Tests)", "test_ticket_20250 (queries.tests.Queries1Tests)", "test_tickets_1878_2939 (queries.tests.Queries1Tests)", "test_tickets_2076_7256 (queries.tests.Queries1Tests)", "test_tickets_2080_3592 (queries.tests.Queries1Tests)", "test_tickets_2874_3002 (queries.tests.Queries1Tests)", "test_tickets_4088_4306 (queries.tests.Queries1Tests)", "test_tickets_5321_7070 (queries.tests.Queries1Tests)", "test_tickets_5324_6704 (queries.tests.Queries1Tests)", "test_tickets_6180_6203 (queries.tests.Queries1Tests)", "test_tickets_7087_12242 (queries.tests.Queries1Tests)", "test_tickets_7204_7506 (queries.tests.Queries1Tests)", "test_tickets_7448_7707 (queries.tests.Queries1Tests)"], "environment_setup_commit": "65dfb06a1ab56c238cc80f5e1c31f61210c4577d"}]
diff --git a/tests/test_data/data_sources/human_eval.json b/tests/test_data/data_sources/human_eval.json
new file mode 100644
index 00000000..9a6bb24d
--- /dev/null
+++ b/tests/test_data/data_sources/human_eval.json
@@ -0,0 +1 @@
+[{"instance_id": "swe-bench__humaneval-30", "problem_statement": "I have a function that needs implementing, can you help?", "created_at": "2023110716", "version": "1.0", "test_patch": "diff --git a/test.py b/test.py\nnew file mode 100644\nindex 0000000..52ecda2\n--- /dev/null\n+++ b/test.py\n@@ -0,0 +1,13 @@\n+from main import get_positive\n+\n+\n+METADATA = {}\n+\n+\n+def check(candidate):\n+ assert candidate([-1, -2, 4, 5, 6]) == [4, 5, 6]\n+ assert candidate([5, 3, -5, 2, 3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 3, 9, 123, 1]\n+ assert candidate([-1, -2]) == []\n+ assert candidate([]) == []\n+\n+check(get_positive)\n", "base_commit": "0880311", "base_commit_with_tests": "b2e380b", "environment_setup_commit": null, "hints_text": null, "repo": "swe-bench/humaneval", "FAIL_TO_PASS": "", "PASS_TO_PASS": ""}, {"instance_id": "swe-bench__humaneval-85", "problem_statement": "I have a function that needs implementing, can you help?", "created_at": "2023110716", "version": "1.0", "test_patch": "diff --git a/test.py b/test.py\nnew file mode 100644\nindex 0000000..13d6e1f\n--- /dev/null\n+++ b/test.py\n@@ -0,0 +1,12 @@\n+from main import add\n+def check(candidate):\n+\n+ # Check some simple cases\n+ assert candidate([4, 88]) == 88\n+ assert candidate([4, 5, 6, 7, 2, 122]) == 122\n+ assert candidate([4, 0, 6, 7]) == 0\n+ assert candidate([4, 4, 6, 8]) == 12\n+\n+ # Check some edge cases that are easy to work out by hand.\n+ \n+check(add)\n", "base_commit": "2de55bc", "base_commit_with_tests": "c8c997b", "environment_setup_commit": null, "hints_text": null, "repo": "swe-bench/humaneval", "FAIL_TO_PASS": "", "PASS_TO_PASS": ""}, {"instance_id": "swe-bench__humaneval-22", "problem_statement": "I have a function that needs implementing, can you help?", "created_at": "2023110716", "version": "1.0", "test_patch": "diff --git a/test.py b/test.py\nnew file mode 100644\nindex 0000000..d881459\n--- /dev/null\n+++ b/test.py\n@@ -0,0 +1,14 @@\n+from main import filter_integers\n+\n+\n+METADATA = {\n+ 'author': 'jt',\n+ 'dataset': 'test'\n+}\n+\n+\n+def check(candidate):\n+ assert candidate([]) == []\n+ assert candidate([4, {}, [], 23.2, 9, 'adasd']) == [4, 9]\n+ assert candidate([3, 'c', 3, 3, 'a', 'b']) == [3, 3, 3]\n+check(filter_integers)\n", "base_commit": "f0dbe5e", "base_commit_with_tests": "55cc474", "environment_setup_commit": null, "hints_text": null, "repo": "swe-bench/humaneval", "FAIL_TO_PASS": "", "PASS_TO_PASS": ""}, {"instance_id": "swe-bench__humaneval-104", "problem_statement": "I have a function that needs implementing, can you help?", "created_at": "2023110716", "version": "1.0", "test_patch": "diff --git a/test.py b/test.py\nnew file mode 100644\nindex 0000000..617da5a\n--- /dev/null\n+++ b/test.py\n@@ -0,0 +1,13 @@\n+from main import unique_digits\n+def check(candidate):\n+\n+ # Check some simple cases\n+ assert candidate([15, 33, 1422, 1]) == [1, 15, 33]\n+ assert candidate([152, 323, 1422, 10]) == []\n+ assert candidate([12345, 2033, 111, 151]) == [111, 151]\n+ assert candidate([135, 103, 31]) == [31, 135]\n+\n+ # Check some edge cases that are easy to work out by hand.\n+ assert True\n+\n+check(unique_digits)\n", "base_commit": "b52ee85", "base_commit_with_tests": "4a92a50", "environment_setup_commit": null, "hints_text": null, "repo": "swe-bench/humaneval", "FAIL_TO_PASS": "", "PASS_TO_PASS": ""}, {"instance_id": "swe-bench__humaneval-0", "problem_statement": "I have a function that needs implementing, can you help?", "created_at": "2023110716", "version": "1.0", "test_patch": "diff --git a/test.py b/test.py\nnew file mode 100644\nindex 0000000..2d57340\n--- /dev/null\n+++ b/test.py\n@@ -0,0 +1,19 @@\n+from main import has_close_elements\n+\n+\n+METADATA = {\n+ 'author': 'jt',\n+ 'dataset': 'test'\n+}\n+\n+\n+def check(candidate):\n+ assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3) == True\n+ assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05) == False\n+ assert candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.95) == True\n+ assert candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.8) == False\n+ assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0], 0.1) == True\n+ assert candidate([1.1, 2.2, 3.1, 4.1, 5.1], 1.0) == True\n+ assert candidate([1.1, 2.2, 3.1, 4.1, 5.1], 0.5) == False\n+\n+check(has_close_elements)\n", "base_commit": "afba737", "base_commit_with_tests": "c7e41b2", "environment_setup_commit": null, "hints_text": null, "repo": "swe-bench/humaneval", "FAIL_TO_PASS": "", "PASS_TO_PASS": ""}]
diff --git a/tests/test_data/data_sources/swe-bench-dev-easy.json b/tests/test_data/data_sources/swe-bench-dev-easy.json
new file mode 100644
index 00000000..44beb784
--- /dev/null
+++ b/tests/test_data/data_sources/swe-bench-dev-easy.json
@@ -0,0 +1 @@
+[{"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1458", "base_commit": "8da0b9b215ebfad5756051c891def88e426787e7", "patch": "diff --git a/pydicom/pixel_data_handlers/numpy_handler.py b/pydicom/pixel_data_handlers/numpy_handler.py\n--- a/pydicom/pixel_data_handlers/numpy_handler.py\n+++ b/pydicom/pixel_data_handlers/numpy_handler.py\n@@ -43,7 +43,9 @@\n | (0028,0100) | BitsAllocated | 1 | 1, 8, 16, 32, | Required |\n | | | | 64 | |\n +-------------+---------------------------+------+---------------+----------+\n-| (0028,0103) | PixelRepresentation | 1 | 0, 1 | Required |\n+| (0028,0101) | BitsStored | 1 | 1, 8, 12, 16 | Optional |\n++-------------+---------------------------+------+---------------+----------+\n+| (0028,0103) | PixelRepresentation | 1C | 0, 1 | Optional |\n +-------------+---------------------------+------+---------------+----------+\n \n \"\"\"\n@@ -284,16 +286,28 @@ def get_pixeldata(ds: \"Dataset\", read_only: bool = False) -> \"np.ndarray\":\n \"the dataset\"\n )\n \n+ # Attributes required by both Floating Point Image Pixel Module Attributes\n+ # and Image Pixel Description Macro Attributes\n required_elements = [\n- 'BitsAllocated', 'Rows', 'Columns', 'PixelRepresentation',\n+ 'BitsAllocated', 'Rows', 'Columns',\n 'SamplesPerPixel', 'PhotometricInterpretation'\n ]\n+ if px_keyword[0] == 'PixelData':\n+ # Attributess required by Image Pixel Description Macro Attributes\n+ required_elements.extend(['PixelRepresentation', 'BitsStored'])\n missing = [elem for elem in required_elements if elem not in ds]\n if missing:\n raise AttributeError(\n \"Unable to convert the pixel data as the following required \"\n \"elements are missing from the dataset: \" + \", \".join(missing)\n )\n+ if ds.SamplesPerPixel > 1:\n+ if not hasattr(ds, 'PlanarConfiguration'):\n+ raise AttributeError(\n+ \"Unable to convert the pixel data as the following \"\n+ \"conditionally required element is missing from the dataset: \"\n+ \"PlanarConfiguration\"\n+ )\n \n # May be Pixel Data, Float Pixel Data or Double Float Pixel Data\n pixel_data = getattr(ds, px_keyword[0])\n", "test_patch": "diff --git a/pydicom/tests/test_numpy_pixel_data.py b/pydicom/tests/test_numpy_pixel_data.py\n--- a/pydicom/tests/test_numpy_pixel_data.py\n+++ b/pydicom/tests/test_numpy_pixel_data.py\n@@ -26,6 +26,8 @@\n * PlanarConfiguration\n \"\"\"\n \n+from copy import deepcopy\n+\n import pytest\n \n from pydicom import config\n@@ -1068,6 +1070,7 @@ def test_endianness_not_set(self):\n ds.Rows = 10\n ds.Columns = 10\n ds.BitsAllocated = 16\n+ ds.BitsStored = 16\n ds.PixelRepresentation = 0\n ds.SamplesPerPixel = 1\n ds.PhotometricInterpretation = 'MONOCHROME2'\n@@ -1105,16 +1108,60 @@ def test_no_pixel_data_raises(self):\n with pytest.raises(AttributeError, match=msg):\n get_pixeldata(ds)\n \n- def test_missing_required_elem(self):\n+ def test_missing_required_elem_pixel_data_monochrome(self):\n \"\"\"Tet get_pixeldata raises if dataset missing required element.\"\"\"\n- ds = dcmread(EXPL_16_1_1F)\n- del ds.BitsAllocated\n+ required_attrs = (\n+ 'BitsAllocated',\n+ 'BitsStored',\n+ 'Rows',\n+ 'Columns',\n+ 'SamplesPerPixel',\n+ 'PhotometricInterpretation',\n+ 'PixelRepresentation',\n+ )\n+ for attr in required_attrs:\n+ ds = dcmread(EXPL_16_1_1F)\n+ delattr(ds, attr)\n+ msg = (\n+ r\"Unable to convert the pixel data as the following required \"\n+ r\"elements are missing from the dataset: {}\".format(attr)\n+ )\n+ with pytest.raises(AttributeError, match=msg):\n+ get_pixeldata(ds)\n+\n+ def test_missing_required_elem_pixel_data_color(self):\n+ \"\"\"Tet get_pixeldata raises if dataset missing required element.\"\"\"\n+ ds = dcmread(EXPL_8_3_1F)\n+ del ds.Rows\n+ del ds.Columns\n+ msg = (\n+ r\"Unable to convert the pixel data as the following required \"\n+ r\"elements are missing from the dataset: Rows, Columns\"\n+ )\n+ with pytest.raises(AttributeError, match=msg):\n+ get_pixeldata(ds)\n+\n+ def test_missing_conditionally_required_elem_pixel_data_color(self):\n+ \"\"\"Tet get_pixeldata raises if dataset missing required element.\"\"\"\n+ ds = dcmread(EXPL_8_3_1F)\n+ del ds.PlanarConfiguration\n+ msg = (\n+ r\"Unable to convert the pixel data as the following conditionally \"\n+ r\"required element is missing from the dataset: \"\n+ r\"PlanarConfiguration\"\n+ )\n+ with pytest.raises(AttributeError, match=msg):\n+ get_pixeldata(ds)\n+\n+ def test_missing_required_elem_float_pixel_data_monochrome(self):\n+ \"\"\"Tet get_pixeldata raises if dataset missing required element.\"\"\"\n+ ds = dcmread(IMPL_32_1_1F)\n+ ds.FloatPixelData = ds.PixelData\n+ del ds.PixelData\n del ds.Rows\n- del ds.SamplesPerPixel\n msg = (\n r\"Unable to convert the pixel data as the following required \"\n- r\"elements are missing from the dataset: BitsAllocated, Rows, \"\n- r\"SamplesPerPixel\"\n+ r\"elements are missing from the dataset: Rows\"\n )\n with pytest.raises(AttributeError, match=msg):\n get_pixeldata(ds)\n", "problem_statement": "Pixel Representation attribute should be optional for pixel data handler\n**Describe the bug**\r\nThe NumPy pixel data handler currently [requires the Pixel Representation attribute](https://github.com/pydicom/pydicom/blob/8da0b9b215ebfad5756051c891def88e426787e7/pydicom/pixel_data_handlers/numpy_handler.py#L46). This is problematic, because in case of Float Pixel Data or Double Float Pixel Data the attribute shall be absent. Compare [Floating Point Image Pixel Module Attributes](http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.24.html) versus [Image Pixel Description Macro Attributes](http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.3.html#table_C.7-11c)\r\n\r\n**Expected behavior**\r\nI would expect the `Dataset.pixel_array` property to be able to decode a Float Pixel Data or Double Float Pixel Data element without presence of the Pixel Representation element in the metadata.\r\n\r\n**Steps To Reproduce**\r\n```python\r\nimport numpy as np\r\nfrom pydicom.dataset import Dataset, FileMetaDataset\r\n\r\n\r\nds = Dataset()\r\nds.file_meta = FileMetaDataset()\r\nds.file_meta.TransferSyntaxUID = '1.2.840.10008.1.2.1'\r\n\r\nds.BitsAllocated = 32\r\nds.SamplesPerPixel = 1\r\nds.Rows = 5\r\nds.Columns = 5\r\nds.PhotometricInterpretation = 'MONOCHROME2'\r\n\r\npixel_array = np.zeros((ds.Rows, ds.Columns), dtype=np.float32)\r\nds.FloatPixelData = pixel_array.flatten().tobytes()\r\n\r\nnp.array_equal(ds.pixel_array, pixel_array)\r\n```\n", "hints_text": "", "created_at": "2021-08-04T15:22:07Z", "version": "2.2", "FAIL_TO_PASS": ["pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_required_elem_pixel_data_monochrome", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_conditionally_required_elem_pixel_data_color"], "PASS_TO_PASS": ["pydicom/tests/test_numpy_pixel_data.py::test_unsupported_syntaxes", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_environment", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_supported_dataset", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_rgb_jpeg_dcmtk.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/JPEG-lossy.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_rgb_jpeg_gdcm.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/guest/jy1682/.pydicom/data/emri_small_jpeg_2k_lossless.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/JPEG2000.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small_RLE.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_pixel_array_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_environment", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_unsupported_syntax_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_dataset_pixel_array_handler_needs_convert", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_dataset_pixel_array_no_pixels", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_rgb_jpeg_dcmtk.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/JPEG-lossy.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_rgb_jpeg_gdcm.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/guest/jy1682/.pydicom/data/emri_small_jpeg_2k_lossless.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/JPEG2000.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small_RLE.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_8bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[numpy]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[NumPy]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[np]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[np_handler]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[numpy_handler]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_16bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_32bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_1sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_1frame_odd_size", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_1frame_ybr422", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/liver_1frame.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/liver.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_rgb_small_odd.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_ybr_full_422_uncompressed.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A_2frame.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_2frame.dcm-data7]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small.dcm-data8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/emri_small.dcm-data9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_16bit.dcm-data10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_16bit_2frame.dcm-data11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose_1frame.dcm-data12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose.dcm-data13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_32bit.dcm-data14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_32bit_2frame.dcm-data15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_1bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_1bit_1sample_3frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_1frame_padded", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_10frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_1sample_15frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_float_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_float_15frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_64bit_float_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_64bit_float_15frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/liver_1frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/liver_expb_1frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/liver.dcm-/n/fs/guest/jy1682/.pydicom/data/liver_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A.dcm-/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A_2frame.dcm-/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A_expb_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_2frame.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/emri_small.dcm-/n/fs/guest/jy1682/.pydicom/data/emri_small_big_endian.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_16bit.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_16bit.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_16bit_2frame.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_16bit_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose_1frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose_expb_1frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_32bit.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_32bit.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_32bit_2frame.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_32bit_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_endianness_not_set", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_read_only", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_no_pixel_data_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_required_elem_pixel_data_color", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_required_elem_float_pixel_data_monochrome", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_unknown_pixel_representation_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_unsupported_syntaxes_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_bad_length_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_padding_warns", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_change_photometric_interpretation", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_array_read_only", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_array_read_only_bit_packed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_ybr422_excess_padding", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_ybr422_wrong_interpretation", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_float_pixel_data", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_double_float_pixel_data", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[-output0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00-output1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x01-output2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x02-output3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x04-output4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x08-output5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x10-output6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[@-output8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x80-output9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xaa-output10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xf0-output11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x0f-output12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xff-output13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x00-output14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x01-output15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x80-output16]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\xff-output17]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x01\\x80-output18]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x80\\x80-output19]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xff\\x80-output20]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[-input0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00-input1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x01-input2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x02-input3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x04-input4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x08-input5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x10-input6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[@-input8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x80-input9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xaa-input10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xf0-input11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x0f-input12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xff-input13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x00-input14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x01-input15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x80-input16]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\xff-input17]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x01\\x80-input18]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x80\\x80-input19]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xff\\x80-input20]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_non_binary_input", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_ndarray_input", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_padding", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00@-input0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x10-input2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x08-input3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x04-input4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x02-input5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x01-input6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x80-input7]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[@-input8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x10-input10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x08-input11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x04-input12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x02-input13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x01-input14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[-input15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_functional"], "environment_setup_commit": "0fa18d2a2179c92efc22200ed6b3689e66cecf92", "query": "Pixel Representation attribute should be optional for pixel data handler\n**Describe the bug**\r\nThe NumPy pixel data handler currently [requires the Pixel Representation attribute](https://github.com/pydicom/pydicom/blob/8da0b9b215ebfad5756051c891def88e426787e7/pydicom/pixel_data_handlers/numpy_handler.py#L46). This is problematic, because in case of Float Pixel Data or Double Float Pixel Data the attribute shall be absent. Compare [Floating Point Image Pixel Module Attributes](http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.24.html) versus [Image Pixel Description Macro Attributes](http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.3.html#table_C.7-11c)\r\n\r\n**Expected behavior**\r\nI would expect the `Dataset.pixel_array` property to be able to decode a Float Pixel Data or Double Float Pixel Data element without presence of the Pixel Representation element in the metadata.\r\n\r\n**Steps To Reproduce**\r\n```python\r\nimport numpy as np\r\nfrom pydicom.dataset import Dataset, FileMetaDataset\r\n\r\n\r\nds = Dataset()\r\nds.file_meta = FileMetaDataset()\r\nds.file_meta.TransferSyntaxUID = '1.2.840.10008.1.2.1'\r\n\r\nds.BitsAllocated = 32\r\nds.SamplesPerPixel = 1\r\nds.Rows = 5\r\nds.Columns = 5\r\nds.PhotometricInterpretation = 'MONOCHROME2'\r\n\r\npixel_array = np.zeros((ds.Rows, ds.Columns), dtype=np.float32)\r\nds.FloatPixelData = pixel_array.flatten().tobytes()\r\n\r\nnp.array_equal(ds.pixel_array, pixel_array)\r\n```\n", "task_id": "pydicom__pydicom-1458"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1268", "base_commit": "ce5cbce5ba11cdc2f8139ade66feea1e181a7944", "patch": "diff --git a/astroid/nodes/as_string.py b/astroid/nodes/as_string.py\n--- a/astroid/nodes/as_string.py\n+++ b/astroid/nodes/as_string.py\n@@ -36,6 +36,7 @@\n MatchSingleton,\n MatchStar,\n MatchValue,\n+ Unknown,\n )\n \n # pylint: disable=unused-argument\n@@ -643,6 +644,9 @@ def visit_property(self, node):\n def visit_evaluatedobject(self, node):\n return node.original.accept(self)\n \n+ def visit_unknown(self, node: \"Unknown\") -> str:\n+ return str(node)\n+\n \n def _import_string(names):\n \"\"\"return a list of (name, asname) formatted as a string\"\"\"\n", "test_patch": "diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py\n--- a/tests/unittest_nodes.py\n+++ b/tests/unittest_nodes.py\n@@ -306,6 +306,11 @@ def test_f_strings(self):\n ast = abuilder.string_build(code)\n self.assertEqual(ast.as_string().strip(), code.strip())\n \n+ @staticmethod\n+ def test_as_string_unknown() -> None:\n+ assert nodes.Unknown().as_string() == \"Unknown.Unknown()\"\n+ assert nodes.Unknown(lineno=1, col_offset=0).as_string() == \"Unknown.Unknown()\"\n+\n \n class _NodeTest(unittest.TestCase):\n \"\"\"test transformation of If Node\"\"\"\n", "problem_statement": "'AsStringVisitor' object has no attribute 'visit_unknown'\n```python\r\n>>> import astroid\r\n>>> astroid.nodes.Unknown().as_string()\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py\", line 609, in as_string\r\n return AsStringVisitor()(self)\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/as_string.py\", line 56, in __call__\r\n return node.accept(self).replace(DOC_NEWLINE, \"\\n\")\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py\", line 220, in accept\r\n func = getattr(visitor, \"visit_\" + self.__class__.__name__.lower())\r\nAttributeError: 'AsStringVisitor' object has no attribute 'visit_unknown'\r\n>>> \r\n```\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n\r\n2.8.6-dev0\n", "hints_text": "Thank you for opening the issue.\nI don't believe `Unknown().as_string()` is ever called regularly. AFAIK it's only used during inference. What should the string representation of an `Unknown` node be? So not sure this needs to be addressed.\nProbably just `'Unknown'`.\nIt's mostly only a problem when we do something like this:\n\n```python\ninferred = infer(node)\nif inferred is not Uninferable:\n if inferred.as_string().contains(some_value):\n ...\n```\nSo for the most part, as long as it doesn't crash we're good.", "created_at": "2021-11-21T16:15:23Z", "version": "2.9", "FAIL_TO_PASS": ["tests/unittest_nodes.py::AsStringTest::test_as_string_unknown"], "PASS_TO_PASS": ["tests/unittest_nodes.py::AsStringTest::test_3k_annotations_and_metaclass", "tests/unittest_nodes.py::AsStringTest::test_3k_as_string", "tests/unittest_nodes.py::AsStringTest::test_as_string", "tests/unittest_nodes.py::AsStringTest::test_as_string_for_list_containing_uninferable", "tests/unittest_nodes.py::AsStringTest::test_class_def", "tests/unittest_nodes.py::AsStringTest::test_ellipsis", "tests/unittest_nodes.py::AsStringTest::test_f_strings", "tests/unittest_nodes.py::AsStringTest::test_frozenset_as_string", "tests/unittest_nodes.py::AsStringTest::test_func_signature_issue_185", "tests/unittest_nodes.py::AsStringTest::test_int_attribute", "tests/unittest_nodes.py::AsStringTest::test_module2_as_string", "tests/unittest_nodes.py::AsStringTest::test_module_as_string", "tests/unittest_nodes.py::AsStringTest::test_operator_precedence", "tests/unittest_nodes.py::AsStringTest::test_slice_and_subscripts", "tests/unittest_nodes.py::AsStringTest::test_slices", "tests/unittest_nodes.py::AsStringTest::test_tuple_as_string", "tests/unittest_nodes.py::AsStringTest::test_varargs_kwargs_as_string", "tests/unittest_nodes.py::IfNodeTest::test_block_range", "tests/unittest_nodes.py::IfNodeTest::test_if_elif_else_node", "tests/unittest_nodes.py::IfNodeTest::test_if_sys_guard", "tests/unittest_nodes.py::IfNodeTest::test_if_typing_guard", "tests/unittest_nodes.py::TryExceptNodeTest::test_block_range", "tests/unittest_nodes.py::TryFinallyNodeTest::test_block_range", "tests/unittest_nodes.py::TryExceptFinallyNodeTest::test_block_range", "tests/unittest_nodes.py::ImportNodeTest::test_absolute_import", "tests/unittest_nodes.py::ImportNodeTest::test_as_string", "tests/unittest_nodes.py::ImportNodeTest::test_bad_import_inference", "tests/unittest_nodes.py::ImportNodeTest::test_conditional", "tests/unittest_nodes.py::ImportNodeTest::test_conditional_import", "tests/unittest_nodes.py::ImportNodeTest::test_from_self_resolve", "tests/unittest_nodes.py::ImportNodeTest::test_import_self_resolve", "tests/unittest_nodes.py::ImportNodeTest::test_more_absolute_import", "tests/unittest_nodes.py::ImportNodeTest::test_real_name", "tests/unittest_nodes.py::CmpNodeTest::test_as_string", "tests/unittest_nodes.py::ConstNodeTest::test_bool", "tests/unittest_nodes.py::ConstNodeTest::test_complex", "tests/unittest_nodes.py::ConstNodeTest::test_copy", "tests/unittest_nodes.py::ConstNodeTest::test_float", "tests/unittest_nodes.py::ConstNodeTest::test_int", "tests/unittest_nodes.py::ConstNodeTest::test_none", "tests/unittest_nodes.py::ConstNodeTest::test_str", "tests/unittest_nodes.py::ConstNodeTest::test_str_kind", "tests/unittest_nodes.py::ConstNodeTest::test_unicode", "tests/unittest_nodes.py::NameNodeTest::test_assign_to_true", "tests/unittest_nodes.py::TestNamedExprNode::test_frame", "tests/unittest_nodes.py::TestNamedExprNode::test_scope", "tests/unittest_nodes.py::AnnAssignNodeTest::test_as_string", "tests/unittest_nodes.py::AnnAssignNodeTest::test_complex", "tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive", "tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive_without_initial_value", "tests/unittest_nodes.py::ArgumentsNodeTC::test_kwoargs", "tests/unittest_nodes.py::ArgumentsNodeTC::test_positional_only", "tests/unittest_nodes.py::UnboundMethodNodeTest::test_no_super_getattr", "tests/unittest_nodes.py::BoundMethodNodeTest::test_is_property", "tests/unittest_nodes.py::AliasesTest::test_aliases", "tests/unittest_nodes.py::Python35AsyncTest::test_async_await_keywords", "tests/unittest_nodes.py::Python35AsyncTest::test_asyncfor_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_asyncwith_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_await_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_decorated_async_def_as_string", "tests/unittest_nodes.py::ContextTest::test_list_del", "tests/unittest_nodes.py::ContextTest::test_list_load", "tests/unittest_nodes.py::ContextTest::test_list_store", "tests/unittest_nodes.py::ContextTest::test_starred_load", "tests/unittest_nodes.py::ContextTest::test_starred_store", "tests/unittest_nodes.py::ContextTest::test_subscript_del", "tests/unittest_nodes.py::ContextTest::test_subscript_load", "tests/unittest_nodes.py::ContextTest::test_subscript_store", "tests/unittest_nodes.py::ContextTest::test_tuple_load", "tests/unittest_nodes.py::ContextTest::test_tuple_store", "tests/unittest_nodes.py::test_unknown", "tests/unittest_nodes.py::test_type_comments_with", "tests/unittest_nodes.py::test_type_comments_for", "tests/unittest_nodes.py::test_type_coments_assign", "tests/unittest_nodes.py::test_type_comments_invalid_expression", "tests/unittest_nodes.py::test_type_comments_invalid_function_comments", "tests/unittest_nodes.py::test_type_comments_function", "tests/unittest_nodes.py::test_type_comments_arguments", "tests/unittest_nodes.py::test_type_comments_posonly_arguments", "tests/unittest_nodes.py::test_correct_function_type_comment_parent", "tests/unittest_nodes.py::test_is_generator_for_yield_assignments", "tests/unittest_nodes.py::test_f_string_correct_line_numbering", "tests/unittest_nodes.py::test_assignment_expression", "tests/unittest_nodes.py::test_assignment_expression_in_functiondef", "tests/unittest_nodes.py::test_get_doc", "tests/unittest_nodes.py::test_parse_fstring_debug_mode", "tests/unittest_nodes.py::test_parse_type_comments_with_proper_parent", "tests/unittest_nodes.py::test_const_itered", "tests/unittest_nodes.py::test_is_generator_for_yield_in_while", "tests/unittest_nodes.py::test_is_generator_for_yield_in_if", "tests/unittest_nodes.py::test_is_generator_for_yield_in_aug_assign"], "environment_setup_commit": "0d1211558670cfefd95b39984b8d5f7f34837f32", "query": "'AsStringVisitor' object has no attribute 'visit_unknown'\n```python\r\n>>> import astroid\r\n>>> astroid.nodes.Unknown().as_string()\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py\", line 609, in as_string\r\n return AsStringVisitor()(self)\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/as_string.py\", line 56, in __call__\r\n return node.accept(self).replace(DOC_NEWLINE, \"\\n\")\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py\", line 220, in accept\r\n func = getattr(visitor, \"visit_\" + self.__class__.__name__.lower())\r\nAttributeError: 'AsStringVisitor' object has no attribute 'visit_unknown'\r\n>>> \r\n```\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n\r\n2.8.6-dev0\n", "task_id": "pylint-dev__astroid-1268"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1194", "base_commit": "5e70c1dfe09820023fec519dac4c51bebcb7f60d", "patch": "diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -87,6 +87,9 @@ def _correct_ambiguous_vr_element(elem, ds, is_little_endian):\n elem.VR = 'SS'\n byte_type = 'h'\n \n+ if elem.VM == 0:\n+ return elem\n+\n # Need to handle type check for elements with VM > 1\n elem_value = elem.value if elem.VM == 1 else elem.value[0]\n if not isinstance(elem_value, int):\n@@ -115,6 +118,9 @@ def _correct_ambiguous_vr_element(elem, ds, is_little_endian):\n # As per PS3.3 C.11.1.1.1\n if ds.LUTDescriptor[0] == 1:\n elem.VR = 'US'\n+ if elem.VM == 0:\n+ return elem\n+\n elem_value = elem.value if elem.VM == 1 else elem.value[0]\n if not isinstance(elem_value, int):\n elem.value = convert_numbers(elem.value, is_little_endian, 'H')\n", "test_patch": "diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -1054,7 +1054,7 @@ def test_not_ambiguous_raw_data_element(self):\n elem = RawDataElement(0x60003000, 'OB', 1, b'\\x00', 0, True, True)\n out = correct_ambiguous_vr_element(elem, Dataset(), True)\n assert out == elem\n- assert type(out) == RawDataElement\n+ assert isinstance(out, RawDataElement)\n \n def test_correct_ambiguous_data_element(self):\n \"\"\"Test correct ambiguous US/SS element\"\"\"\n@@ -1086,10 +1086,28 @@ def test_correct_ambiguous_raw_data_element(self):\n ds[0x00280120] = elem\n ds.PixelRepresentation = 0\n out = correct_ambiguous_vr_element(elem, ds, True)\n- assert type(out) == DataElement\n+ assert isinstance(out, DataElement)\n assert out.VR == 'US'\n assert out.value == 0xfffe\n \n+ def test_empty_value(self):\n+ \"\"\"Regression test for #1193: empty value raises exception.\"\"\"\n+ ds = Dataset()\n+ elem = RawDataElement(0x00280106, 'US or SS', 0, None, 0, True, True)\n+ ds[0x00280106] = elem\n+ out = correct_ambiguous_vr_element(elem, ds, True)\n+ assert isinstance(out, DataElement)\n+ assert out.VR == 'US'\n+\n+ ds.LUTDescriptor = [1, 1, 1]\n+ elem = RawDataElement(0x00283006, 'US or SS', 0, None, 0, True, True)\n+ assert out.value is None\n+ ds[0x00283006] = elem\n+ out = correct_ambiguous_vr_element(elem, ds, True)\n+ assert isinstance(out, DataElement)\n+ assert out.VR == 'US'\n+ assert out.value is None\n+\n \n class TestWriteAmbiguousVR:\n \"\"\"Attempt to write data elements with ambiguous VR.\"\"\"\n", "problem_statement": "Error decoding dataset with ambiguous VR element when the value is None\nHi all,\r\n I used the storescu in pynetdicom 1.5.3 to send the dicom ct files(both on mac and ubuntu): \r\n**python storescu.py 192.168.1.120 9002 ~/Downloads/test/**\r\n(I also tried https://pydicom.github.io/pynetdicom/stable/examples/storage.html#storage-scu)\r\nbut it throwed errors: \r\n\r\n_E: Failed to encode the supplied Dataset\r\nE: Store failed: /Users/me/Downloads/test/CT_S1_118.dcm\r\nE: Failed to encode the supplied Dataset\r\nTraceback (most recent call last):\r\n File \"storescu.py\", line 283, in main\r\n status = assoc.send_c_store(ds, ii)\r\n File \"/Users/me/.pyenv/versions/3.8.2/lib/python3.8/site-packages/pynetdicom/association.py\", line 1736, in send_c_store\r\n raise ValueError('Failed to encode the supplied Dataset')\r\nValueError: Failed to encode the supplied Dataset_\r\n\r\nBut I used to send same files with storescu in dcm4che successfully.\r\nFile attached.\r\n\r\n[test.zip](https://github.com/pydicom/pynetdicom/files/5258867/test.zip)\r\n\n", "hints_text": "```python\r\n>>> from pydicom import dcmread\r\n>>> dcmread(\"CT_S1_001.dcm\")\r\nTraceback (most recent call last):\r\n File \".../pydicom/tag.py\", line 30, in tag_in_exception\r\n yield\r\n File \".../pydicom/filewriter.py\", line 555, in write_dataset\r\n write_data_element(fp, dataset.get_item(tag), dataset_encoding)\r\n File \".../pydicom/dataset.py\", line 1060, in get_item\r\n return self[key]\r\n File \".../pydicom/dataset.py\", line 878, in __getitem__\r\n self[tag] = correct_ambiguous_vr_element(\r\n File \".../pydicom/filewriter.py\", line 160, in correct_ambiguous_vr_element\r\n _correct_ambiguous_vr_element(elem, ds, is_little_endian)\r\n File \".../pydicom/filewriter.py\", line 86, in _correct_ambiguous_vr_element\r\n elem_value = elem.value if elem.VM == 1 else elem.value[0]\r\nTypeError: 'NoneType' object is not subscriptable\r\n```\r\nIssue occurs because the dataset is Implicit VR and the *Smallest Image Pixel Value* is ambiguous but empty,", "created_at": "2020-09-22T03:16:19Z", "version": "2.0", "FAIL_TO_PASS": ["pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_empty_value"], "PASS_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestWriteFile::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_deflated_retains_elements", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_deflated_deflates_post_file_meta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_dataset_without_encoding", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_deflated_retains_elements", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_deflated_deflates_post_file_meta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_dataset_without_encoding", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestScratchWrite::testImpl_LE_deflen_write", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_filename", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of_dataset", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding"], "environment_setup_commit": "9d69811e539774f296c2f289839147e741251716", "query": "Error decoding dataset with ambiguous VR element when the value is None\nHi all,\r\n I used the storescu in pynetdicom 1.5.3 to send the dicom ct files(both on mac and ubuntu): \r\n**python storescu.py 192.168.1.120 9002 ~/Downloads/test/**\r\n(I also tried https://pydicom.github.io/pynetdicom/stable/examples/storage.html#storage-scu)\r\nbut it throwed errors: \r\n\r\n_E: Failed to encode the supplied Dataset\r\nE: Store failed: /Users/me/Downloads/test/CT_S1_118.dcm\r\nE: Failed to encode the supplied Dataset\r\nTraceback (most recent call last):\r\n File \"storescu.py\", line 283, in main\r\n status = assoc.send_c_store(ds, ii)\r\n File \"/Users/me/.pyenv/versions/3.8.2/lib/python3.8/site-packages/pynetdicom/association.py\", line 1736, in send_c_store\r\n raise ValueError('Failed to encode the supplied Dataset')\r\nValueError: Failed to encode the supplied Dataset_\r\n\r\nBut I used to send same files with storescu in dcm4che successfully.\r\nFile attached.\r\n\r\n[test.zip](https://github.com/pydicom/pynetdicom/files/5258867/test.zip)\r\n\n", "task_id": "pydicom__pydicom-1194"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1268", "base_commit": "ce5cbce5ba11cdc2f8139ade66feea1e181a7944", "patch": "diff --git a/astroid/nodes/as_string.py b/astroid/nodes/as_string.py\n--- a/astroid/nodes/as_string.py\n+++ b/astroid/nodes/as_string.py\n@@ -36,6 +36,7 @@\n MatchSingleton,\n MatchStar,\n MatchValue,\n+ Unknown,\n )\n \n # pylint: disable=unused-argument\n@@ -643,6 +644,9 @@ def visit_property(self, node):\n def visit_evaluatedobject(self, node):\n return node.original.accept(self)\n \n+ def visit_unknown(self, node: \"Unknown\") -> str:\n+ return str(node)\n+\n \n def _import_string(names):\n \"\"\"return a list of (name, asname) formatted as a string\"\"\"\n", "test_patch": "diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py\n--- a/tests/unittest_nodes.py\n+++ b/tests/unittest_nodes.py\n@@ -306,6 +306,11 @@ def test_f_strings(self):\n ast = abuilder.string_build(code)\n self.assertEqual(ast.as_string().strip(), code.strip())\n \n+ @staticmethod\n+ def test_as_string_unknown() -> None:\n+ assert nodes.Unknown().as_string() == \"Unknown.Unknown()\"\n+ assert nodes.Unknown(lineno=1, col_offset=0).as_string() == \"Unknown.Unknown()\"\n+\n \n class _NodeTest(unittest.TestCase):\n \"\"\"test transformation of If Node\"\"\"\n", "problem_statement": "'AsStringVisitor' object has no attribute 'visit_unknown'\n```python\r\n>>> import astroid\r\n>>> astroid.nodes.Unknown().as_string()\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py\", line 609, in as_string\r\n return AsStringVisitor()(self)\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/as_string.py\", line 56, in __call__\r\n return node.accept(self).replace(DOC_NEWLINE, \"\\n\")\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py\", line 220, in accept\r\n func = getattr(visitor, \"visit_\" + self.__class__.__name__.lower())\r\nAttributeError: 'AsStringVisitor' object has no attribute 'visit_unknown'\r\n>>> \r\n```\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n\r\n2.8.6-dev0\n", "hints_text": "Thank you for opening the issue.\nI don't believe `Unknown().as_string()` is ever called regularly. AFAIK it's only used during inference. What should the string representation of an `Unknown` node be? So not sure this needs to be addressed.\nProbably just `'Unknown'`.\nIt's mostly only a problem when we do something like this:\n\n```python\ninferred = infer(node)\nif inferred is not Uninferable:\n if inferred.as_string().contains(some_value):\n ...\n```\nSo for the most part, as long as it doesn't crash we're good.", "created_at": "2021-11-21T16:15:23Z", "version": "2.9", "FAIL_TO_PASS": ["tests/unittest_nodes.py::AsStringTest::test_as_string_unknown"], "PASS_TO_PASS": ["tests/unittest_nodes.py::AsStringTest::test_3k_annotations_and_metaclass", "tests/unittest_nodes.py::AsStringTest::test_3k_as_string", "tests/unittest_nodes.py::AsStringTest::test_as_string", "tests/unittest_nodes.py::AsStringTest::test_as_string_for_list_containing_uninferable", "tests/unittest_nodes.py::AsStringTest::test_class_def", "tests/unittest_nodes.py::AsStringTest::test_ellipsis", "tests/unittest_nodes.py::AsStringTest::test_f_strings", "tests/unittest_nodes.py::AsStringTest::test_frozenset_as_string", "tests/unittest_nodes.py::AsStringTest::test_func_signature_issue_185", "tests/unittest_nodes.py::AsStringTest::test_int_attribute", "tests/unittest_nodes.py::AsStringTest::test_module2_as_string", "tests/unittest_nodes.py::AsStringTest::test_module_as_string", "tests/unittest_nodes.py::AsStringTest::test_operator_precedence", "tests/unittest_nodes.py::AsStringTest::test_slice_and_subscripts", "tests/unittest_nodes.py::AsStringTest::test_slices", "tests/unittest_nodes.py::AsStringTest::test_tuple_as_string", "tests/unittest_nodes.py::AsStringTest::test_varargs_kwargs_as_string", "tests/unittest_nodes.py::IfNodeTest::test_block_range", "tests/unittest_nodes.py::IfNodeTest::test_if_elif_else_node", "tests/unittest_nodes.py::IfNodeTest::test_if_sys_guard", "tests/unittest_nodes.py::IfNodeTest::test_if_typing_guard", "tests/unittest_nodes.py::TryExceptNodeTest::test_block_range", "tests/unittest_nodes.py::TryFinallyNodeTest::test_block_range", "tests/unittest_nodes.py::TryExceptFinallyNodeTest::test_block_range", "tests/unittest_nodes.py::ImportNodeTest::test_absolute_import", "tests/unittest_nodes.py::ImportNodeTest::test_as_string", "tests/unittest_nodes.py::ImportNodeTest::test_bad_import_inference", "tests/unittest_nodes.py::ImportNodeTest::test_conditional", "tests/unittest_nodes.py::ImportNodeTest::test_conditional_import", "tests/unittest_nodes.py::ImportNodeTest::test_from_self_resolve", "tests/unittest_nodes.py::ImportNodeTest::test_import_self_resolve", "tests/unittest_nodes.py::ImportNodeTest::test_more_absolute_import", "tests/unittest_nodes.py::ImportNodeTest::test_real_name", "tests/unittest_nodes.py::CmpNodeTest::test_as_string", "tests/unittest_nodes.py::ConstNodeTest::test_bool", "tests/unittest_nodes.py::ConstNodeTest::test_complex", "tests/unittest_nodes.py::ConstNodeTest::test_copy", "tests/unittest_nodes.py::ConstNodeTest::test_float", "tests/unittest_nodes.py::ConstNodeTest::test_int", "tests/unittest_nodes.py::ConstNodeTest::test_none", "tests/unittest_nodes.py::ConstNodeTest::test_str", "tests/unittest_nodes.py::ConstNodeTest::test_str_kind", "tests/unittest_nodes.py::ConstNodeTest::test_unicode", "tests/unittest_nodes.py::NameNodeTest::test_assign_to_true", "tests/unittest_nodes.py::TestNamedExprNode::test_frame", "tests/unittest_nodes.py::TestNamedExprNode::test_scope", "tests/unittest_nodes.py::AnnAssignNodeTest::test_as_string", "tests/unittest_nodes.py::AnnAssignNodeTest::test_complex", "tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive", "tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive_without_initial_value", "tests/unittest_nodes.py::ArgumentsNodeTC::test_kwoargs", "tests/unittest_nodes.py::ArgumentsNodeTC::test_positional_only", "tests/unittest_nodes.py::UnboundMethodNodeTest::test_no_super_getattr", "tests/unittest_nodes.py::BoundMethodNodeTest::test_is_property", "tests/unittest_nodes.py::AliasesTest::test_aliases", "tests/unittest_nodes.py::Python35AsyncTest::test_async_await_keywords", "tests/unittest_nodes.py::Python35AsyncTest::test_asyncfor_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_asyncwith_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_await_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_decorated_async_def_as_string", "tests/unittest_nodes.py::ContextTest::test_list_del", "tests/unittest_nodes.py::ContextTest::test_list_load", "tests/unittest_nodes.py::ContextTest::test_list_store", "tests/unittest_nodes.py::ContextTest::test_starred_load", "tests/unittest_nodes.py::ContextTest::test_starred_store", "tests/unittest_nodes.py::ContextTest::test_subscript_del", "tests/unittest_nodes.py::ContextTest::test_subscript_load", "tests/unittest_nodes.py::ContextTest::test_subscript_store", "tests/unittest_nodes.py::ContextTest::test_tuple_load", "tests/unittest_nodes.py::ContextTest::test_tuple_store", "tests/unittest_nodes.py::test_unknown", "tests/unittest_nodes.py::test_type_comments_with", "tests/unittest_nodes.py::test_type_comments_for", "tests/unittest_nodes.py::test_type_coments_assign", "tests/unittest_nodes.py::test_type_comments_invalid_expression", "tests/unittest_nodes.py::test_type_comments_invalid_function_comments", "tests/unittest_nodes.py::test_type_comments_function", "tests/unittest_nodes.py::test_type_comments_arguments", "tests/unittest_nodes.py::test_type_comments_posonly_arguments", "tests/unittest_nodes.py::test_correct_function_type_comment_parent", "tests/unittest_nodes.py::test_is_generator_for_yield_assignments", "tests/unittest_nodes.py::test_f_string_correct_line_numbering", "tests/unittest_nodes.py::test_assignment_expression", "tests/unittest_nodes.py::test_assignment_expression_in_functiondef", "tests/unittest_nodes.py::test_get_doc", "tests/unittest_nodes.py::test_parse_fstring_debug_mode", "tests/unittest_nodes.py::test_parse_type_comments_with_proper_parent", "tests/unittest_nodes.py::test_const_itered", "tests/unittest_nodes.py::test_is_generator_for_yield_in_while", "tests/unittest_nodes.py::test_is_generator_for_yield_in_if", "tests/unittest_nodes.py::test_is_generator_for_yield_in_aug_assign"], "environment_setup_commit": "0d1211558670cfefd95b39984b8d5f7f34837f32", "query": "'AsStringVisitor' object has no attribute 'visit_unknown'\n```python\r\n>>> import astroid\r\n>>> astroid.nodes.Unknown().as_string()\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py\", line 609, in as_string\r\n return AsStringVisitor()(self)\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/as_string.py\", line 56, in __call__\r\n return node.accept(self).replace(DOC_NEWLINE, \"\\n\")\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py\", line 220, in accept\r\n func = getattr(visitor, \"visit_\" + self.__class__.__name__.lower())\r\nAttributeError: 'AsStringVisitor' object has no attribute 'visit_unknown'\r\n>>> \r\n```\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n\r\n2.8.6-dev0\n", "task_id": "pylint-dev__astroid-1268"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2386", "base_commit": "23d698607b45b8469c766b521d27e9a6e92e8739", "patch": "diff --git a/src/sqlfluff/core/rules/base.py b/src/sqlfluff/core/rules/base.py\n--- a/src/sqlfluff/core/rules/base.py\n+++ b/src/sqlfluff/core/rules/base.py\n@@ -875,7 +875,7 @@ def eval(self, **kwargs):\n \n plugin_name, code = rule_name_match.groups()\n # If the docstring is multiline, then we extract just summary.\n- description = cls.__doc__.split(\"\\n\")[0]\n+ description = cls.__doc__.replace(\"``\", \"'\").split(\"\\n\")[0]\n \n if plugin_name:\n code = f\"{plugin_name}_{code}\"\n", "test_patch": "diff --git a/test/core/rules/docstring_test.py b/test/core/rules/docstring_test.py\n--- a/test/core/rules/docstring_test.py\n+++ b/test/core/rules/docstring_test.py\n@@ -1,6 +1,7 @@\n \"\"\"Test rules docstring.\"\"\"\n import pytest\n \n+from sqlfluff import lint\n from sqlfluff.core.plugin.host import get_plugin_manager\n \n KEYWORD_ANTI = \"\\n | **Anti-pattern**\"\n@@ -34,3 +35,19 @@ def test_keyword_anti_before_best():\n assert rule.__doc__.index(KEYWORD_ANTI) < rule.__doc__.index(\n KEYWORD_BEST\n ), f\"{rule.__name__} keyword {KEYWORD_BEST} appears before {KEYWORD_ANTI}\"\n+\n+\n+def test_backtick_replace():\n+ \"\"\"Test replacing docstring double backticks for lint results.\"\"\"\n+ sql = \"\"\"\n+ SELECT\n+ foo.a,\n+ bar.b\n+ FROM foo\n+ JOIN bar;\n+ \"\"\"\n+ result = lint(sql, rules=[\"L051\"])\n+ # L051 docstring looks like:\n+ # ``INNER JOIN`` must be fully qualified.\n+ # Check the double bacticks (``) get replaced by a single quote (').\n+ assert result[0][\"description\"] == \"'INNER JOIN' must be fully qualified.\"\ndiff --git a/test/rules/std_L054_test.py b/test/rules/std_L054_test.py\n--- a/test/rules/std_L054_test.py\n+++ b/test/rules/std_L054_test.py\n@@ -29,7 +29,7 @@ def test__rules__std_L054_raised() -> None:\n assert len(results_l054) == 2\n assert (\n results_l054[0][\"description\"]\n- == \"Inconsistent column references in ``GROUP BY/ORDER BY`` clauses.\"\n+ == \"Inconsistent column references in 'GROUP BY/ORDER BY' clauses.\"\n )\n \n \n", "problem_statement": "Double backticks in Lint description\n![image](https://user-images.githubusercontent.com/80432516/150420352-57452c80-ad25-423b-8251-645e541579ad.png)\r\n(n.b. this affects a lot more rules than L051)\r\n\r\nThis was introduced in #2234 in which docstrings such as\r\n```\r\n`INNER JOIN` must be fully qualified.\r\n```\r\nwere replaced with \r\n```\r\n``INNER JOIN`` must be fully qualified.\r\n```\r\nso that they appear as code blocks in Sphinx for docs.\r\n![image](https://user-images.githubusercontent.com/80432516/150420294-eb9d3127-db1d-457c-a637-d614e0267277.png)\r\n\r\nHowever, our rules will use the first line of these docstrings in the event that no `description` is provided to the lint results.\r\n\r\nThis doesn't look great on the CLI so we should fix this. As far as I'm aware there are two approaches for this:\r\n1. Pass a `description` to all the `LintResult`s.\r\n2. Update the code that gets the default description from the docstring to do something like, replace the double backticks with a single one, or remove them, or do something clever like make them bold for the CLI and remove them for non-CLI.\r\n\r\nMy strong preference is number 2, but I'm open to discussion as to how exactly we do this \ud83d\ude04 \r\n\r\n@barrywhart @tunetheweb \n", "hints_text": "Number 2 sounds good to me!\n@barrywhart which variation?\nI would replace with single \"normal\" quotes: ' rather than \\`.\r\n\r\nThe clever approach could be cool for later, but I wouldn't try it now. I can't remember if we already handle detecting whether we're running in a terminal or not, because the techniques for doing bold or colored text don't work well when redirecting output to a file, etc.\n> The clever approach could be cool for later, but I wouldn't try it now. I can't remember if we already handle detecting whether we're running in a terminal or not, because the techniques for doing bold or colored text don't work well when redirecting output to a file, etc.\r\n\r\nYeah I think there's some `isatty` function we use in the formatter, but agree on the simple replace method for now \ud83d\ude04 ", "created_at": "2022-01-21T00:03:48Z", "version": "0.8", "FAIL_TO_PASS": ["test/core/rules/docstring_test.py::test_backtick_replace", "test/rules/std_L054_test.py::test__rules__std_L054_raised"], "PASS_TO_PASS": ["test/core/rules/docstring_test.py::test_content_count[\\n", "test/core/rules/docstring_test.py::test_keyword_anti_before_best", "test/rules/std_L054_test.py::test__rules__std_L054_unparsable", "test/rules/std_L054_test.py::test__rules__std_L054_noqa"], "environment_setup_commit": "a5c4eae4e3e419fe95460c9afd9cf39a35a470c4", "query": "Double backticks in Lint description\n![image](https://user-images.githubusercontent.com/80432516/150420352-57452c80-ad25-423b-8251-645e541579ad.png)\r\n(n.b. this affects a lot more rules than L051)\r\n\r\nThis was introduced in #2234 in which docstrings such as\r\n```\r\n`INNER JOIN` must be fully qualified.\r\n```\r\nwere replaced with \r\n```\r\n``INNER JOIN`` must be fully qualified.\r\n```\r\nso that they appear as code blocks in Sphinx for docs.\r\n![image](https://user-images.githubusercontent.com/80432516/150420294-eb9d3127-db1d-457c-a637-d614e0267277.png)\r\n\r\nHowever, our rules will use the first line of these docstrings in the event that no `description` is provided to the lint results.\r\n\r\nThis doesn't look great on the CLI so we should fix this. As far as I'm aware there are two approaches for this:\r\n1. Pass a `description` to all the `LintResult`s.\r\n2. Update the code that gets the default description from the docstring to do something like, replace the double backticks with a single one, or remove them, or do something clever like make them bold for the CLI and remove them for non-CLI.\r\n\r\nMy strong preference is number 2, but I'm open to discussion as to how exactly we do this \ud83d\ude04 \r\n\r\n@barrywhart @tunetheweb \n", "task_id": "sqlfluff__sqlfluff-2386"}]
diff --git a/tests/test_data/data_sources/swe-bench-lite-test.json b/tests/test_data/data_sources/swe-bench-lite-test.json
new file mode 100644
index 00000000..30259c07
--- /dev/null
+++ b/tests/test_data/data_sources/swe-bench-lite-test.json
@@ -0,0 +1 @@
+[{"repo": "django/django", "instance_id": "django__django-16255", "base_commit": "444b6da7cc229a58a2c476a52e45233001dc7073", "patch": "diff --git a/django/contrib/sitemaps/__init__.py b/django/contrib/sitemaps/__init__.py\n--- a/django/contrib/sitemaps/__init__.py\n+++ b/django/contrib/sitemaps/__init__.py\n@@ -167,7 +167,7 @@ def get_latest_lastmod(self):\n return None\n if callable(self.lastmod):\n try:\n- return max([self.lastmod(item) for item in self.items()])\n+ return max([self.lastmod(item) for item in self.items()], default=None)\n except TypeError:\n return None\n else:\n", "test_patch": "diff --git a/tests/sitemaps_tests/test_http.py b/tests/sitemaps_tests/test_http.py\n--- a/tests/sitemaps_tests/test_http.py\n+++ b/tests/sitemaps_tests/test_http.py\n@@ -507,6 +507,16 @@ def test_callable_sitemod_full(self):\n self.assertXMLEqual(index_response.content.decode(), expected_content_index)\n self.assertXMLEqual(sitemap_response.content.decode(), expected_content_sitemap)\n \n+ def test_callable_sitemod_no_items(self):\n+ index_response = self.client.get(\"/callable-lastmod-no-items/index.xml\")\n+ self.assertNotIn(\"Last-Modified\", index_response)\n+ expected_content_index = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n+ <sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n+ <sitemap><loc>http://example.com/simple/sitemap-callable-lastmod.xml</loc></sitemap>\n+ </sitemapindex>\n+ \"\"\"\n+ self.assertXMLEqual(index_response.content.decode(), expected_content_index)\n+\n \n # RemovedInDjango50Warning\n class DeprecatedTests(SitemapTestsBase):\ndiff --git a/tests/sitemaps_tests/urls/http.py b/tests/sitemaps_tests/urls/http.py\n--- a/tests/sitemaps_tests/urls/http.py\n+++ b/tests/sitemaps_tests/urls/http.py\n@@ -114,6 +114,16 @@ def lastmod(self, obj):\n return obj.lastmod\n \n \n+class CallableLastmodNoItemsSitemap(Sitemap):\n+ location = \"/location/\"\n+\n+ def items(self):\n+ return []\n+\n+ def lastmod(self, obj):\n+ return obj.lastmod\n+\n+\n class GetLatestLastmodNoneSiteMap(Sitemap):\n changefreq = \"never\"\n priority = 0.5\n@@ -233,6 +243,10 @@ def testmodelview(request, id):\n \"callable-lastmod\": CallableLastmodFullSitemap,\n }\n \n+callable_lastmod_no_items_sitemap = {\n+ \"callable-lastmod\": CallableLastmodNoItemsSitemap,\n+}\n+\n urlpatterns = [\n path(\"simple/index.xml\", views.index, {\"sitemaps\": simple_sitemaps}),\n path(\"simple-paged/index.xml\", views.index, {\"sitemaps\": simple_sitemaps_paged}),\n@@ -417,6 +431,11 @@ def testmodelview(request, id):\n views.sitemap,\n {\"sitemaps\": callable_lastmod_full_sitemap},\n ),\n+ path(\n+ \"callable-lastmod-no-items/index.xml\",\n+ views.index,\n+ {\"sitemaps\": callable_lastmod_no_items_sitemap},\n+ ),\n path(\n \"generic-lastmod/index.xml\",\n views.index,\n", "problem_statement": "Sitemaps without items raise ValueError on callable lastmod.\nDescription\n\t\nWhen sitemap contains not items, but supports returning lastmod for an item, it fails with a ValueError:\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py\", line 55, in inner\n\tresponse = get_response(request)\n File \"/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py\", line 197, in _get_response\n\tresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\n File \"/usr/local/lib/python3.10/site-packages/django/utils/decorators.py\", line 133, in _wrapped_view\n\tresponse = view_func(request, *args, **kwargs)\n File \"/usr/local/lib/python3.10/site-packages/django/contrib/sitemaps/views.py\", line 34, in inner\n\tresponse = func(request, *args, **kwargs)\n File \"/usr/local/lib/python3.10/site-packages/django/contrib/sitemaps/views.py\", line 76, in index\n\tsite_lastmod = site.get_latest_lastmod()\n File \"/usr/local/lib/python3.10/site-packages/django/contrib/sitemaps/__init__.py\", line 170, in get_latest_lastmod\n\treturn max([self.lastmod(item) for item in self.items()])\nException Type: ValueError at /sitemap.xml\nException Value: max() arg is an empty sequence\nSomething like this might be a solution:\n\t def get_latest_lastmod(self):\n\t\t if not hasattr(self, \"lastmod\"):\n\t\t\t return None\n\t\t if callable(self.lastmod):\n\t\t\t try:\n\t\t\t\t return max([self.lastmod(item) for item in self.items()])\n-\t\t\texcept TypeError:\n+\t\t\texcept (TypeError, ValueError):\n\t\t\t\t return None\n\t\t else:\n\t\t\t return self.lastmod\n", "hints_text": "Thanks for the report.\nThe default argument of max() can be used.", "created_at": "2022-11-04T13:49:40Z", "version": "4.2", "FAIL_TO_PASS": ["test_callable_sitemod_no_items (sitemaps_tests.test_http.HTTPSitemapTests)"], "PASS_TO_PASS": ["A cached sitemap index can be rendered (#2713).", "A i18n sitemap index with limited languages can be rendered.", "A i18n sitemap index with x-default can be rendered.", "A i18n sitemap with alternate/hreflang links can be rendered.", "A simple i18n sitemap index can be rendered, without logging variable", "A simple sitemap can be rendered", "A simple sitemap can be rendered with a custom template", "A simple sitemap index can be rendered", "A simple sitemap index can be rendered with a custom template", "A simple sitemap section can be rendered", "A sitemap may have multiple pages.", "A sitemap may not be callable.", "All items in the sitemap have `lastmod`. The `Last-Modified` header", "Check to make sure that the raw item is included with each", "Check we get ImproperlyConfigured if we don't pass a site object to", "Check we get ImproperlyConfigured when we don't pass a site object to", "Last-Modified header is missing when sitemap has no lastmod", "Last-Modified header is omitted when lastmod not on all items", "Last-Modified header is set correctly", "Not all items have `lastmod`. Therefore the `Last-Modified` header", "The Last-Modified header is omitted when lastmod isn't found in all", "The Last-Modified header is set to the most recent sitemap lastmod.", "The Last-Modified header should be converted from timezone aware dates", "The Last-Modified header should be support dates (without time).", "The priority value should not be localized.", "lastmod datestamp shows timezones if Sitemap.get_latest_lastmod", "sitemapindex.lastmod is included when Sitemap.lastmod is", "sitemapindex.lastmod is omitted when Sitemap.lastmod is", "test_empty_page (sitemaps_tests.test_http.HTTPSitemapTests)", "test_empty_sitemap (sitemaps_tests.test_http.HTTPSitemapTests)", "test_no_section (sitemaps_tests.test_http.HTTPSitemapTests)", "test_page_not_int (sitemaps_tests.test_http.HTTPSitemapTests)", "test_requestsite_sitemap (sitemaps_tests.test_http.HTTPSitemapTests)", "test_simple_sitemap_custom_index_warning (sitemaps_tests.test_http.DeprecatedTests)", "test_sitemap_without_entries (sitemaps_tests.test_http.HTTPSitemapTests)", "test_x_robots_sitemap (sitemaps_tests.test_http.HTTPSitemapTests)"], "environment_setup_commit": "0fbdb9784da915fce5dcc1fe82bac9b4785749e5"}, {"repo": "sympy/sympy", "instance_id": "sympy__sympy-13031", "base_commit": "2dfa7457f20ee187fbb09b5b6a1631da4458388c", "patch": "diff --git a/sympy/matrices/sparse.py b/sympy/matrices/sparse.py\n--- a/sympy/matrices/sparse.py\n+++ b/sympy/matrices/sparse.py\n@@ -985,8 +985,10 @@ def col_join(self, other):\n >>> C == A.row_insert(A.rows, Matrix(B))\n True\n \"\"\"\n- if not self:\n- return type(self)(other)\n+ # A null matrix can always be stacked (see #10770)\n+ if self.rows == 0 and self.cols != other.cols:\n+ return self._new(0, other.cols, []).col_join(other)\n+\n A, B = self, other\n if not A.cols == B.cols:\n raise ShapeError()\n@@ -1191,8 +1193,10 @@ def row_join(self, other):\n >>> C == A.col_insert(A.cols, B)\n True\n \"\"\"\n- if not self:\n- return type(self)(other)\n+ # A null matrix can always be stacked (see #10770)\n+ if self.cols == 0 and self.rows != other.rows:\n+ return self._new(other.rows, 0, []).row_join(other)\n+\n A, B = self, other\n if not A.rows == B.rows:\n raise ShapeError()\n", "test_patch": "diff --git a/sympy/matrices/tests/test_sparse.py b/sympy/matrices/tests/test_sparse.py\n--- a/sympy/matrices/tests/test_sparse.py\n+++ b/sympy/matrices/tests/test_sparse.py\n@@ -26,6 +26,12 @@ def sparse_zeros(n):\n assert type(a.row_join(b)) == type(a)\n assert type(a.col_join(b)) == type(a)\n \n+ # make sure 0 x n matrices get stacked correctly\n+ sparse_matrices = [SparseMatrix.zeros(0, n) for n in range(4)]\n+ assert SparseMatrix.hstack(*sparse_matrices) == Matrix(0, 6, [])\n+ sparse_matrices = [SparseMatrix.zeros(n, 0) for n in range(4)]\n+ assert SparseMatrix.vstack(*sparse_matrices) == Matrix(6, 0, [])\n+\n # test element assignment\n a = SparseMatrix((\n (1, 0),\n", "problem_statement": "Behavior of Matrix hstack and vstack changed in sympy 1.1\nIn sympy 1.0:\r\n```\r\nimport sympy as sy\r\nM1 = sy.Matrix.zeros(0, 0)\r\nM2 = sy.Matrix.zeros(0, 1)\r\nM3 = sy.Matrix.zeros(0, 2)\r\nM4 = sy.Matrix.zeros(0, 3)\r\nsy.Matrix.hstack(M1, M2, M3, M4).shape\r\n```\r\nreturns \r\n`(0, 6)`\r\n\r\nNow, same in sympy 1.1:\r\n```\r\nimport sympy as sy\r\nM1 = sy.Matrix.zeros(0, 0)\r\nM2 = sy.Matrix.zeros(0, 1)\r\nM3 = sy.Matrix.zeros(0, 2)\r\nM4 = sy.Matrix.zeros(0, 3)\r\nsy.Matrix.hstack(M1, M2, M3, M4).shape\r\n```\r\nreturns\r\n`(0, 3)\r\n`\r\nwhereas:\r\n```\r\nimport sympy as sy\r\nM1 = sy.Matrix.zeros(1, 0)\r\nM2 = sy.Matrix.zeros(1, 1)\r\nM3 = sy.Matrix.zeros(1, 2)\r\nM4 = sy.Matrix.zeros(1, 3)\r\nsy.Matrix.hstack(M1, M2, M3, M4).shape\r\n```\r\nreturns\r\n`(1, 6)\r\n`\n", "hints_text": "CC @siefkenj \nI update my comment in case someone already read it. We still have an issue with matrices shape in [pyphs](https://github.com/pyphs/pyphs/issues/49#issuecomment-316618994), but hstack and vstack seem ok in sympy 1.1.1rc1:\r\n\r\n```\r\n>>> import sympy as sy\r\n>>> sy.__version__\r\n'1.1.1rc1'\r\n>>> '1.1.1rc1'\r\n'1.1.1rc1'\r\n>>> matrices = [sy.Matrix.zeros(0, n) for n in range(4)]\r\n>>> sy.Matrix.hstack(*matrices).shape\r\n(0, 6)\r\n>>> matrices = [sy.Matrix.zeros(1, n) for n in range(4)]\r\n>>> sy.Matrix.hstack(*matrices).shape\r\n(1, 6)\r\n>>> matrices = [sy.Matrix.zeros(n, 0) for n in range(4)]\r\n>>> sy.Matrix.vstack(*matrices).shape\r\n(6, 0)\r\n>>> matrices = [sy.Matrix.zeros(1, n) for n in range(4)]\r\n>>> sy.Matrix.hstack(*matrices).shape\r\n(1, 6)\r\n>>> \r\n```\nThe problem is solved with Matrix but not SparseMatrix:\r\n```\r\n>>> import sympy as sy\r\n>>> sy.__version__\r\n'1.1.1rc1'\r\n>>> matrices = [Matrix.zeros(0, n) for n in range(4)]\r\n>>> Matrix.hstack(*matrices)\r\nMatrix(0, 6, [])\r\n>>> sparse_matrices = [SparseMatrix.zeros(0, n) for n in range(4)]\r\n>>> SparseMatrix.hstack(*sparse_matrices)\r\nMatrix(0, 3, [])\r\n>>> \r\n```\nBisected to 27e9ee425819fa09a4cbb8179fb38939cc693249. Should we revert that commit? CC @aravindkanna\nAny thoughts? This is the last fix to potentially go in the 1.1.1 release, but I want to cut a release candidate today or tomorrow, so speak now, or hold your peace (until the next major release).\nI am away at a conference. The change should be almost identical to the fix for dense matrices, if someone can manage to get a patch in. I *might* be able to do it tomorrow.\nOkay. I've looked this over and its convoluted...\r\n\r\n`SparseMatrix` should impliment `_eval_col_join`. `col_join` should not be implemented. It is, and that is what `hstack` is calling, which is why my previous patch didn't fix `SparseMatrix`s as well. However, the patch that @asmeurer referenced ensures that `SparseMatrix.row_join(DenseMatrix)` returns a `SparseMatrix` whereas `CommonMatrix.row_join(SparseMatrix, DenseMatrix)` returns a `classof(SparseMatrix, DenseMatrix)` which happens to be a `DenseMatrix`. I don't think that these should behave differently. This API needs to be better thought out.\nSo is there a simple fix that can be made for the release or should this be postponed?", "created_at": "2017-07-23T15:48:13Z", "version": "1.1", "FAIL_TO_PASS": ["test_sparse_matrix"], "PASS_TO_PASS": ["test_CL_RL", "test_add", "test_copyin", "test_errors", "test_len", "test_sparse_solve", "test_sparse_zeros_sparse_eye", "test_trace", "test_transpose"], "environment_setup_commit": "ec9e3c0436fbff934fa84e22bf07f1b3ef5bfac3"}, {"repo": "pytest-dev/pytest", "instance_id": "pytest-dev__pytest-11143", "base_commit": "6995257cf470d2143ad1683824962de4071c0eb7", "patch": "diff --git a/src/_pytest/assertion/rewrite.py b/src/_pytest/assertion/rewrite.py\n--- a/src/_pytest/assertion/rewrite.py\n+++ b/src/_pytest/assertion/rewrite.py\n@@ -676,6 +676,7 @@ def run(self, mod: ast.Module) -> None:\n expect_docstring\n and isinstance(item, ast.Expr)\n and isinstance(item.value, ast.Constant)\n+ and isinstance(item.value.value, str)\n ):\n doc = item.value.value\n if self.is_rewrite_disabled(doc):\n", "test_patch": "diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py\n--- a/testing/test_assertrewrite.py\n+++ b/testing/test_assertrewrite.py\n@@ -2042,3 +2042,17 @@ def test_max_increased_verbosity(self, pytester: Pytester) -> None:\n self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE * 10)\n result = pytester.runpytest(\"-vv\")\n result.stdout.no_fnmatch_line(\"*xxx...xxx*\")\n+\n+\n+class TestIssue11140:\n+ def test_constant_not_picked_as_module_docstring(self, pytester: Pytester) -> None:\n+ pytester.makepyfile(\n+ \"\"\"\\\n+ 0\n+\n+ def test_foo():\n+ pass\n+ \"\"\"\n+ )\n+ result = pytester.runpytest()\n+ assert result.ret == 0\n", "problem_statement": "Rewrite fails when first expression of file is a number and mistaken as docstring \n<!--\r\nThanks for submitting an issue!\r\n\r\nQuick check-list while reporting bugs:\r\n-->\r\n\r\n- [x] a detailed description of the bug or problem you are having\r\n- [x] output of `pip list` from the virtual environment you are using\r\n- [x] pytest and operating system versions\r\n- [x] minimal example if possible\r\n```\r\nInstalling collected packages: zipp, six, PyYAML, python-dateutil, MarkupSafe, importlib-metadata, watchdog, tomli, soupsieve, pyyaml-env-tag, pycparser, pluggy, packaging, mergedeep, Markdown, jinja2, iniconfig, ghp-import, exceptiongroup, click, websockets, urllib3, tqdm, smmap, pytest, pyee, mkdocs, lxml, importlib-resources, idna, cssselect, charset-normalizer, cffi, certifi, beautifulsoup4, attrs, appdirs, w3lib, typing-extensions, texttable, requests, pyzstd, pytest-metadata, pyquery, pyppmd, pyppeteer, pynacl, pymdown-extensions, pycryptodomex, pybcj, pyasn1, py, psutil, parse, multivolumefile, mkdocs-autorefs, inflate64, gitdb, fake-useragent, cryptography, comtypes, bs4, brotli, bcrypt, allure-python-commons, xlwt, xlrd, rsa, requests-html, pywinauto, python-i18n, python-dotenv, pytest-rerunfailures, pytest-html, pytest-check, PySocks, py7zr, paramiko, mkdocstrings, loguru, GitPython, ftputil, crcmod, chardet, brotlicffi, allure-pytest\r\nSuccessfully installed GitPython-3.1.31 Markdown-3.3.7 MarkupSafe-2.1.3 PySocks-1.7.1 PyYAML-6.0 allure-pytest-2.13.2 allure-python-commons-2.13.2 appdirs-1.4.4 attrs-23.1.0 bcrypt-4.0.1 beautifulsoup4-4.12.2 brotli-1.0.9 brotlicffi-1.0.9.2 bs4-0.0.1 certifi-2023.5.7 cffi-1.15.1 chardet-5.1.0 charset-normalizer-3.1.0 click-8.1.3 comtypes-1.2.0 crcmod-1.7 cryptography-41.0.1 cssselect-1.2.0 exceptiongroup-1.1.1 fake-useragent-1.1.3 ftputil-5.0.4 ghp-import-2.1.0 gitdb-4.0.10 idna-3.4 importlib-metadata-6.7.0 importlib-resources-5.12.0 inflate64-0.3.1 iniconfig-2.0.0 jinja2-3.1.2 loguru-0.7.0 lxml-4.9.2 mergedeep-1.3.4 mkdocs-1.4.3 mkdocs-autorefs-0.4.1 mkdocstrings-0.22.0 multivolumefile-0.2.3 packaging-23.1 paramiko-3.2.0 parse-1.19.1 pluggy-1.2.0 psutil-5.9.5 py-1.11.0 py7zr-0.20.5 pyasn1-0.5.0 pybcj-1.0.1 pycparser-2.21 pycryptodomex-3.18.0 pyee-8.2.2 pymdown-extensions-10.0.1 pynacl-1.5.0 pyppeteer-1.0.2 pyppmd-1.0.0 pyquery-2.0.0 pytest-7.4.0 pytest-check-2.1.5 pytest-html-3.2.0 pytest-metadata-3.0.0 pytest-rerunfailures-11.1.2 python-dateutil-2.8.2 python-dotenv-1.0.0 python-i18n-0.3.9 pywinauto-0.6.6 pyyaml-env-tag-0.1 pyzstd-0.15.9 requests-2.31.0 requests-html-0.10.0 rsa-4.9 six-1.16.0 smmap-5.0.0 soupsieve-2.4.1 texttable-1.6.7 tomli-2.0.1 tqdm-4.65.0 typing-extensions-4.6.3 urllib3-1.26.16 w3lib-2.1.1 watchdog-3.0.0 websockets-10.4 xlrd-2.0.1 xlwt-1.3.0 zipp-3.15.0\r\n```\r\nuse `pytest -k xxx`\uff0c report an error\uff1a`TypeError: argument of type 'int' is not iterable`\r\n\r\nit seems a error in collecting testcase\r\n```\r\n==================================== ERRORS ====================================\r\n_ ERROR collecting testcases/\u57fa\u7ebf/\u4ee3\u7406\u7b56\u7565/SOCKS\u4e8c\u7ea7\u4ee3\u7406\u8fed\u4ee3\u4e8c/\u5728\u7ebf\u7528\u6237/\u5728\u7ebf\u7528\u6237\u66f4\u65b0/\u4e0a\u7ebf\u7528\u6237/test_socks_user_011.py _\r\n/usr/local/lib/python3.8/site-packages/_pytest/runner.py:341: in from_call\r\n result: Optional[TResult] = func()\r\n/usr/local/lib/python3.8/site-packages/_pytest/runner.py:372: in <lambda>\r\n call = CallInfo.from_call(lambda: list(collector.collect()), \"collect\")\r\n/usr/local/lib/python3.8/site-packages/_pytest/python.py:531: in collect\r\n self._inject_setup_module_fixture()\r\n/usr/local/lib/python3.8/site-packages/_pytest/python.py:545: in _inject_setup_module_fixture\r\n self.obj, (\"setUpModule\", \"setup_module\")\r\n/usr/local/lib/python3.8/site-packages/_pytest/python.py:310: in obj\r\n self._obj = obj = self._getobj()\r\n/usr/local/lib/python3.8/site-packages/_pytest/python.py:528: in _getobj\r\n return self._importtestmodule()\r\n/usr/local/lib/python3.8/site-packages/_pytest/python.py:617: in _importtestmodule\r\n mod = import_path(self.path, mode=importmode, root=self.config.rootpath)\r\n/usr/local/lib/python3.8/site-packages/_pytest/pathlib.py:565: in import_path\r\n importlib.import_module(module_name)\r\n/usr/local/lib/python3.8/importlib/__init__.py:127: in import_module\r\n return _bootstrap._gcd_import(name[level:], package, level)\r\n<frozen importlib._bootstrap>:1014: in _gcd_import\r\n ???\r\n<frozen importlib._bootstrap>:991: in _find_and_load\r\n ???\r\n<frozen importlib._bootstrap>:975: in _find_and_load_unlocked\r\n ???\r\n<frozen importlib._bootstrap>:671: in _load_unlocked\r\n ???\r\n/usr/local/lib/python3.8/site-packages/_pytest/assertion/rewrite.py:169: in exec_module\r\n source_stat, co = _rewrite_test(fn, self.config)\r\n/usr/local/lib/python3.8/site-packages/_pytest/assertion/rewrite.py:352: in _rewrite_test\r\n rewrite_asserts(tree, source, strfn, config)\r\n/usr/local/lib/python3.8/site-packages/_pytest/assertion/rewrite.py:413: in rewrite_asserts\r\n AssertionRewriter(module_path, config, source).run(mod)\r\n/usr/local/lib/python3.8/site-packages/_pytest/assertion/rewrite.py:695: in run\r\n if self.is_rewrite_disabled(doc):\r\n/usr/local/lib/python3.8/site-packages/_pytest/assertion/rewrite.py:760: in is_rewrite_disabled\r\n return \"PYTEST_DONT_REWRITE\" in docstring\r\nE TypeError: argument of type 'int' is not iterable\r\n```\n", "hints_text": "more details are needed - based on the exception, the docstring is a integer, that seems completely wrong\nI run it pass lasttime in 2023-6-20 17:07:23. it run in docker and install newest pytest before run testcase everytime . maybe some commit cause it recently. \r\nI run it can pass in 7.2.0 a few minutes ago.\r\n\r\n`pytest ini`\r\n```\r\n[pytest]\r\nlog_cli = false\r\nlog_cli_level = debug\r\nlog_cli_format = %(asctime)s %(levelname)s %(message)s\r\nlog_cli_date_format = %Y-%m-%d %H:%M:%S\r\n\r\naddopts = -v -s\r\n\r\nfilterwarnings =\r\n ignore::UserWarning\r\n\r\nmarkers=\r\n case_id: mark test id to upload on tp\r\n case_level_bvt: testcase level bvt\r\n case_level_1: testcase level level 1\r\n case_level_2: testcase level level 2\r\n case_level_3: testcase level level 3\r\n case_status_pass: mark case as PASS\r\n case_status_fail: mark case as FAILED\r\n case_status_not_finish: mark case as CODEING\r\n case_status_not_run: mark case as FINISH\r\n case_not_run: mark case as DONT RUN\r\n run_env: mark run this case on which environment\r\n ```\r\n \r\n`testcase:`\r\n```\r\[email protected](autouse=True)\r\ndef default_setup_teardown():\r\n xxxx\r\n\r\[email protected](\"\u521d\u59cb\u72b6\u6001\")\r\nclass TestDefauleName:\r\n @allure.title(\"\u4e0a\u7ebf\u4e00\u4e2a\u57df\u7528\u6237\uff0c\u7528\u6237\u540d\u548c\u7ec4\u540d\u6b63\u786e\")\r\n @pytest.mark.case_level_1\r\n @pytest.mark.case_id(\"tc_proxyheard_insert_011\")\r\n def test_tc_proxyheard_insert_011(self):\r\n xxxx\r\n ```\nthanks for the update\r\n\r\ni took the liberty to edit your comments to use markdown code blocks for ease of reading\r\n\r\nfrom the given information the problem is still unclear\r\n\r\nplease try running with `--assert=plain` for verification\r\n\r\nthe error indicates that the python ast parser somehow ends up with a integer as the docstring for `test_socks_user_011.py` the reason is still unclear based on the redacted information\nI run with --assert=plain and it has passed\r\n\r\npython3 -m pytest -k helloworld --assert=plain\r\n```\r\ntestcases/smoke_testcase/test_helloworld.py::TestGuardProcess::test_hello_world 2023-06-25 08:54:17.659 | INFO | NAC_AIO.testcases.smoke_testcase.test_helloworld:test_hello_world:15 - Great! Frame Work is working\r\nPASSED\r\ntotal: 1648\r\npassed: 1\r\nfailed: 0\r\nerror: 0\r\npass_rate 100.00%\r\n\r\n================================================================================= 1 passed, 1647 deselected in 12.28s =================================================================================\r\n```\nIt seems to me that we have a potential bug in the ast transformer where's in case the first expression of a file is a integer, we mistake it as a docstring\n\nCan you verify the first expression in the file that fails?\nyou are right this file first expression is a 0 . It can pass after I delete it \r\nthank you!\nMinimal reproducer:\r\n\r\n```python\r\n0\r\n```\r\n\r\n(yes, just that, in a .py file)", "created_at": "2023-06-26T06:44:43Z", "version": "8.0", "FAIL_TO_PASS": ["testing/test_assertrewrite.py::TestIssue11140::test_constant_not_picked_as_module_docstring"], "PASS_TO_PASS": ["testing/test_assertrewrite.py::TestAssertionPass::test_hook_call", "testing/test_assertrewrite.py::TestAssertionPass::test_hook_call_with_parens", "testing/test_assertrewrite.py::TestAssertionPass::test_hook_not_called_without_cmd_option", "testing/test_assertrewrite.py::TestAssertionPass::test_hook_not_called_without_hookimpl", "testing/test_assertrewrite.py::TestAssertionPass::test_option_default", "testing/test_assertrewrite.py::TestAssertionRewrite::test_assert_already_has_message", "testing/test_assertrewrite.py::TestAssertionRewrite::test_assert_raising__bool__in_comparison", "testing/test_assertrewrite.py::TestAssertionRewrite::test_assertion_message", "testing/test_assertrewrite.py::TestAssertionRewrite::test_assertion_message_escape", "testing/test_assertrewrite.py::TestAssertionRewrite::test_assertion_message_expr", "testing/test_assertrewrite.py::TestAssertionRewrite::test_assertion_message_multiline", "testing/test_assertrewrite.py::TestAssertionRewrite::test_assertion_message_tuple", "testing/test_assertrewrite.py::TestAssertionRewrite::test_assertion_messages_bytes", "testing/test_assertrewrite.py::TestAssertionRewrite::test_assertrepr_compare_same_width", "testing/test_assertrewrite.py::TestAssertionRewrite::test_at_operator_issue1290", "testing/test_assertrewrite.py::TestAssertionRewrite::test_attribute", "testing/test_assertrewrite.py::TestAssertionRewrite::test_binary_op", "testing/test_assertrewrite.py::TestAssertionRewrite::test_boolop", "testing/test_assertrewrite.py::TestAssertionRewrite::test_boolop_percent", "testing/test_assertrewrite.py::TestAssertionRewrite::test_call", "testing/test_assertrewrite.py::TestAssertionRewrite::test_comparisons", "testing/test_assertrewrite.py::TestAssertionRewrite::test_custom_repr", "testing/test_assertrewrite.py::TestAssertionRewrite::test_custom_repr_non_ascii", "testing/test_assertrewrite.py::TestAssertionRewrite::test_custom_reprcompare", "testing/test_assertrewrite.py::TestAssertionRewrite::test_dont_rewrite", "testing/test_assertrewrite.py::TestAssertionRewrite::test_dont_rewrite_if_hasattr_fails", "testing/test_assertrewrite.py::TestAssertionRewrite::test_dont_rewrite_plugin", "testing/test_assertrewrite.py::TestAssertionRewrite::test_formatchar", "testing/test_assertrewrite.py::TestAssertionRewrite::test_honors_pep_235", "testing/test_assertrewrite.py::TestAssertionRewrite::test_len", "testing/test_assertrewrite.py::TestAssertionRewrite::test_location_is_set", "testing/test_assertrewrite.py::TestAssertionRewrite::test_name", "testing/test_assertrewrite.py::TestAssertionRewrite::test_place_initial_imports", "testing/test_assertrewrite.py::TestAssertionRewrite::test_rewrites_plugin_as_a_package", "testing/test_assertrewrite.py::TestAssertionRewrite::test_short_circuit_evaluation", "testing/test_assertrewrite.py::TestAssertionRewrite::test_starred_with_side_effect", "testing/test_assertrewrite.py::TestAssertionRewrite::test_unary_op", "testing/test_assertrewrite.py::TestAssertionRewriteHookDetails::test_get_data_support", "testing/test_assertrewrite.py::TestAssertionRewriteHookDetails::test_read_pyc", "testing/test_assertrewrite.py::TestAssertionRewriteHookDetails::test_read_pyc_more_invalid", "testing/test_assertrewrite.py::TestAssertionRewriteHookDetails::test_read_pyc_success", "testing/test_assertrewrite.py::TestAssertionRewriteHookDetails::test_reload_is_same_and_reloads", "testing/test_assertrewrite.py::TestAssertionRewriteHookDetails::test_resources_provider_for_loader", "testing/test_assertrewrite.py::TestAssertionRewriteHookDetails::test_sys_meta_path_munged", "testing/test_assertrewrite.py::TestAssertionRewriteHookDetails::test_write_pyc", "testing/test_assertrewrite.py::TestEarlyRewriteBailout::test_basic", "testing/test_assertrewrite.py::TestEarlyRewriteBailout::test_cwd_changed", "testing/test_assertrewrite.py::TestEarlyRewriteBailout::test_pattern_contains_subdirectories", "testing/test_assertrewrite.py::TestIssue10743::test_assertion_inline_walrus_operator", "testing/test_assertrewrite.py::TestIssue10743::test_assertion_inline_walrus_operator_reverse", "testing/test_assertrewrite.py::TestIssue10743::test_assertion_walrus_no_variable_name_conflict", "testing/test_assertrewrite.py::TestIssue10743::test_assertion_walrus_operator", "testing/test_assertrewrite.py::TestIssue10743::test_assertion_walrus_operator_boolean_composite", "testing/test_assertrewrite.py::TestIssue10743::test_assertion_walrus_operator_boolean_none_fails", "testing/test_assertrewrite.py::TestIssue10743::test_assertion_walrus_operator_compare_boolean_fails", "testing/test_assertrewrite.py::TestIssue10743::test_assertion_walrus_operator_dont_rewrite", "testing/test_assertrewrite.py::TestIssue10743::test_assertion_walrus_operator_fail_assertion", "testing/test_assertrewrite.py::TestIssue10743::test_assertion_walrus_operator_true_assertion_and_changes_variable_value", "testing/test_assertrewrite.py::TestIssue10743::test_assertion_walrus_operator_value_changes_cleared_after_each_test", "testing/test_assertrewrite.py::TestIssue11028::test_assertion_walrus_operator_equals_operand_function", "testing/test_assertrewrite.py::TestIssue11028::test_assertion_walrus_operator_equals_operand_function_arg_as_function", "testing/test_assertrewrite.py::TestIssue11028::test_assertion_walrus_operator_equals_operand_function_keyword_arg", "testing/test_assertrewrite.py::TestIssue11028::test_assertion_walrus_operator_gt_operand_function", "testing/test_assertrewrite.py::TestIssue11028::test_assertion_walrus_operator_in_operand", "testing/test_assertrewrite.py::TestIssue11028::test_assertion_walrus_operator_in_operand_json_dumps", "testing/test_assertrewrite.py::TestIssue2121::test_rewrite_python_files_contain_subdirs", "testing/test_assertrewrite.py::TestIssue925::test_long_case", "testing/test_assertrewrite.py::TestIssue925::test_many_brackets", "testing/test_assertrewrite.py::TestIssue925::test_simple_case", "testing/test_assertrewrite.py::TestPyCacheDir::test_get_cache_dir[/tmp/pycs-/home/projects/src/foo.py-/tmp/pycs/home/projects/src]", "testing/test_assertrewrite.py::TestPyCacheDir::test_get_cache_dir[None-/home/projects/src/foo.py-/home/projects/src/__pycache__]", "testing/test_assertrewrite.py::TestPyCacheDir::test_get_cache_dir[None-d:/projects/src/foo.py-d:/projects/src/__pycache__]", "testing/test_assertrewrite.py::TestPyCacheDir::test_get_cache_dir[c:/tmp/pycs-d:/projects/src/foo.py-c:/tmp/pycs/projects/src]", "testing/test_assertrewrite.py::TestPyCacheDir::test_sys_pycache_prefix_integration", "testing/test_assertrewrite.py::TestReprSizeVerbosity::test_default_verbosity", "testing/test_assertrewrite.py::TestReprSizeVerbosity::test_get_maxsize_for_saferepr[0-240]", "testing/test_assertrewrite.py::TestReprSizeVerbosity::test_get_maxsize_for_saferepr[1-2400]", "testing/test_assertrewrite.py::TestReprSizeVerbosity::test_get_maxsize_for_saferepr[2-None]", "testing/test_assertrewrite.py::TestReprSizeVerbosity::test_get_maxsize_for_saferepr[3-None]", "testing/test_assertrewrite.py::TestReprSizeVerbosity::test_increased_verbosity", "testing/test_assertrewrite.py::TestReprSizeVerbosity::test_max_increased_verbosity", "testing/test_assertrewrite.py::TestRewriteOnImport::test_cached_pyc_includes_pytest_version", "testing/test_assertrewrite.py::TestRewriteOnImport::test_dont_write_bytecode", "testing/test_assertrewrite.py::TestRewriteOnImport::test_load_resource_via_files_with_rewrite", "testing/test_assertrewrite.py::TestRewriteOnImport::test_orphaned_pyc_file", "testing/test_assertrewrite.py::TestRewriteOnImport::test_package", "testing/test_assertrewrite.py::TestRewriteOnImport::test_package_without__init__py", "testing/test_assertrewrite.py::TestRewriteOnImport::test_pyc_vs_pyo", "testing/test_assertrewrite.py::TestRewriteOnImport::test_pycache_is_a_file", "testing/test_assertrewrite.py::TestRewriteOnImport::test_pycache_is_readonly", "testing/test_assertrewrite.py::TestRewriteOnImport::test_readonly", "testing/test_assertrewrite.py::TestRewriteOnImport::test_remember_rewritten_modules", "testing/test_assertrewrite.py::TestRewriteOnImport::test_rewrite_module_imported_from_conftest", "testing/test_assertrewrite.py::TestRewriteOnImport::test_rewrite_warning", "testing/test_assertrewrite.py::TestRewriteOnImport::test_rewrite_warning_using_pytest_plugins", "testing/test_assertrewrite.py::TestRewriteOnImport::test_rewrite_warning_using_pytest_plugins_env_var", "testing/test_assertrewrite.py::TestRewriteOnImport::test_translate_newlines", "testing/test_assertrewrite.py::TestRewriteOnImport::test_zipfile", "testing/test_assertrewrite.py::test_get_assertion_exprs[assert", "testing/test_assertrewrite.py::test_get_assertion_exprs[assertion", "testing/test_assertrewrite.py::test_get_assertion_exprs[backslash", "testing/test_assertrewrite.py::test_get_assertion_exprs[escaped", "testing/test_assertrewrite.py::test_get_assertion_exprs[latin1", "testing/test_assertrewrite.py::test_get_assertion_exprs[multi", "testing/test_assertrewrite.py::test_get_assertion_exprs[multi-line", "testing/test_assertrewrite.py::test_get_assertion_exprs[multiple", "testing/test_assertrewrite.py::test_get_assertion_exprs[no", "testing/test_assertrewrite.py::test_get_assertion_exprs[trivial]", "testing/test_assertrewrite.py::test_get_assertion_exprs[utf-8", "testing/test_assertrewrite.py::test_issue731", "testing/test_assertrewrite.py::test_rewrite_infinite_recursion", "testing/test_assertrewrite.py::test_source_mtime_long_long[-1]", "testing/test_assertrewrite.py::test_source_mtime_long_long[1]", "testing/test_assertrewrite.py::test_try_makedirs"], "environment_setup_commit": "10056865d2a4784934ce043908a0e78d0578f677"}, {"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-13584", "base_commit": "0e3c1879b06d839171b7d0a607d71bbb19a966a9", "patch": "diff --git a/sklearn/utils/_pprint.py b/sklearn/utils/_pprint.py\n--- a/sklearn/utils/_pprint.py\n+++ b/sklearn/utils/_pprint.py\n@@ -95,7 +95,7 @@ def _changed_params(estimator):\n init_params = signature(init_func).parameters\n init_params = {name: param.default for name, param in init_params.items()}\n for k, v in params.items():\n- if (v != init_params[k] and\n+ if (repr(v) != repr(init_params[k]) and\n not (is_scalar_nan(init_params[k]) and is_scalar_nan(v))):\n filtered_params[k] = v\n return filtered_params\n", "test_patch": "diff --git a/sklearn/utils/tests/test_pprint.py b/sklearn/utils/tests/test_pprint.py\n--- a/sklearn/utils/tests/test_pprint.py\n+++ b/sklearn/utils/tests/test_pprint.py\n@@ -4,6 +4,7 @@\n import numpy as np\n \n from sklearn.utils._pprint import _EstimatorPrettyPrinter\n+from sklearn.linear_model import LogisticRegressionCV\n from sklearn.pipeline import make_pipeline\n from sklearn.base import BaseEstimator, TransformerMixin\n from sklearn.feature_selection import SelectKBest, chi2\n@@ -212,6 +213,9 @@ def test_changed_only():\n expected = \"\"\"SimpleImputer()\"\"\"\n assert imputer.__repr__() == expected\n \n+ # make sure array parameters don't throw error (see #13583)\n+ repr(LogisticRegressionCV(Cs=np.array([0.1, 1])))\n+\n set_config(print_changed_only=False)\n \n \n", "problem_statement": "bug in print_changed_only in new repr: vector values\n```python\r\nimport sklearn\r\nimport numpy as np\r\nfrom sklearn.linear_model import LogisticRegressionCV\r\nsklearn.set_config(print_changed_only=True)\r\nprint(LogisticRegressionCV(Cs=np.array([0.1, 1])))\r\n```\r\n> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\r\n\r\nping @NicolasHug \r\n\n", "hints_text": "", "created_at": "2019-04-05T23:09:48Z", "version": "0.21", "FAIL_TO_PASS": ["sklearn/utils/tests/test_pprint.py::test_changed_only", "sklearn/utils/tests/test_pprint.py::test_deeply_nested", "sklearn/utils/tests/test_pprint.py::test_gridsearch", "sklearn/utils/tests/test_pprint.py::test_gridsearch_pipeline", "sklearn/utils/tests/test_pprint.py::test_n_max_elements_to_show", "sklearn/utils/tests/test_pprint.py::test_pipeline"], "PASS_TO_PASS": ["sklearn/utils/tests/test_pprint.py::test_basic", "sklearn/utils/tests/test_pprint.py::test_builtin_prettyprinter", "sklearn/utils/tests/test_pprint.py::test_length_constraint"], "environment_setup_commit": "7813f7efb5b2012412888b69e73d76f2df2b50b6"}, {"repo": "django/django", "instance_id": "django__django-15781", "base_commit": "8d160f154f0240a423e83ffe0690e472f837373c", "patch": "diff --git a/django/core/management/base.py b/django/core/management/base.py\n--- a/django/core/management/base.py\n+++ b/django/core/management/base.py\n@@ -286,10 +286,10 @@ def create_parser(self, prog_name, subcommand, **kwargs):\n Create and return the ``ArgumentParser`` which will be used to\n parse the arguments to this command.\n \"\"\"\n+ kwargs.setdefault(\"formatter_class\", DjangoHelpFormatter)\n parser = CommandParser(\n prog=\"%s %s\" % (os.path.basename(prog_name), subcommand),\n description=self.help or None,\n- formatter_class=DjangoHelpFormatter,\n missing_args_message=getattr(self, \"missing_args_message\", None),\n called_from_command_line=getattr(self, \"_called_from_command_line\", None),\n **kwargs,\n", "test_patch": "diff --git a/tests/user_commands/tests.py b/tests/user_commands/tests.py\n--- a/tests/user_commands/tests.py\n+++ b/tests/user_commands/tests.py\n@@ -1,4 +1,5 @@\n import os\n+from argparse import ArgumentDefaultsHelpFormatter\n from io import StringIO\n from unittest import mock\n \n@@ -408,8 +409,14 @@ def test_subparser_invalid_option(self):\n def test_create_parser_kwargs(self):\n \"\"\"BaseCommand.create_parser() passes kwargs to CommandParser.\"\"\"\n epilog = \"some epilog text\"\n- parser = BaseCommand().create_parser(\"prog_name\", \"subcommand\", epilog=epilog)\n+ parser = BaseCommand().create_parser(\n+ \"prog_name\",\n+ \"subcommand\",\n+ epilog=epilog,\n+ formatter_class=ArgumentDefaultsHelpFormatter,\n+ )\n self.assertEqual(parser.epilog, epilog)\n+ self.assertEqual(parser.formatter_class, ArgumentDefaultsHelpFormatter)\n \n def test_outputwrapper_flush(self):\n out = StringIO()\n", "problem_statement": "Customizable management command formatters.\nDescription\n\t\nWith code like:\nclass Command(BaseCommand):\n\thelp = '''\n\tImport a contract from tzkt.\n\tExample usage:\n\t\t./manage.py tzkt_import 'Tezos Mainnet' KT1HTDtMBRCKoNHjfWEEvXneGQpCfPAt6BRe\n\t'''\nHelp output is:\n$ ./manage.py help tzkt_import\nusage: manage.py tzkt_import [-h] [--api API] [--version] [-v {0,1,2,3}] [--settings SETTINGS]\n\t\t\t\t\t\t\t [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]\n\t\t\t\t\t\t\t [--skip-checks]\n\t\t\t\t\t\t\t blockchain target\nImport a contract from tzkt Example usage: ./manage.py tzkt_import 'Tezos Mainnet'\nKT1HTDtMBRCKoNHjfWEEvXneGQpCfPAt6BRe\npositional arguments:\n blockchain\t\t\tName of the blockchain to import into\n target\t\t\t\tId of the contract to import\nWhen that was expected:\n$ ./manage.py help tzkt_import\nusage: manage.py tzkt_import [-h] [--api API] [--version] [-v {0,1,2,3}] [--settings SETTINGS]\n\t\t\t\t\t\t\t [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]\n\t\t\t\t\t\t\t [--skip-checks]\n\t\t\t\t\t\t\t blockchain target\nImport a contract from tzkt \nExample usage: \n\t./manage.py tzkt_import 'Tezos Mainnet' KT1HTDtMBRCKoNHjfWEEvXneGQpCfPAt6BRe\npositional arguments:\n blockchain\t\t\tName of the blockchain to import into\n target\t\t\t\tId of the contract to import\n", "hints_text": "This seems no fault of Django but is rather \u200bthe default behavior of ArgumentParser (\"By default, ArgumentParser objects line-wrap the description and epilog texts in command-line help messages\"). This can be changed by using a custom \u200bformatter_class, though Django already specifies a custom one (\u200bDjangoHelpFormatter).\nIt seems reasonable, to make it customizable by passing via kwargs to the \u200bBaseCommand.create_parser() (as documented): django/core/management/base.py diff --git a/django/core/management/base.py b/django/core/management/base.py index f0e711ac76..52407807d8 100644 a b class BaseCommand: 286286 Create and return the ``ArgumentParser`` which will be used to 287287 parse the arguments to this command. 288288 \"\"\" 289 kwargs.setdefault(\"formatter_class\", DjangoHelpFormatter) 289290 parser = CommandParser( 290291 prog=\"%s %s\" % (os.path.basename(prog_name), subcommand), 291292 description=self.help or None, 292 formatter_class=DjangoHelpFormatter, 293293 missing_args_message=getattr(self, \"missing_args_message\", None), 294294 called_from_command_line=getattr(self, \"_called_from_command_line\", None), 295295 **kwargs, What do you think?\nLooks good but I don't see a reason for keeping a default that swallows newlines because PEP257 forbids having a multiline sentence on the first line anyway: Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description. As such, the default formater which purpose is to unwrap the first sentence encourages breaking PEP 257. And users who are naturally complying with PEP257 will have to override the formatter, it should be the other way around.\nAlso, the not-unwraping formater will also look fine with existing docstrings, it will work for both use cases, while the current one only works for one use case and breaks the other. The default formater should work for both\nReplying to James Pic: Also, the not-unwraping formater will also look fine with existing docstrings, it will work for both use cases, while the current one only works for one use case and breaks the other. The default formater should work for both It seems you think that Python's (not Django's) default behavior should be changed according to PEP 257. I'd recommend to start a discussion in Python's bugtracker. As far as I'm aware the proposed solution will allow users to freely change a formatter, which should be enough from the Django point of view.\nNo, I think that Django's default behavior should match Python's PEP 257, and at the same time, have a default that works in all use cases. I think my report and comments are pretty clear, I fail to understand how you could get my comment completely backward, so, unless you have any specific question about this statement, I'm going to give up on this.\nSo as part of this issue, do we make changes to allow a user to override the formatter through kwargs and also keep DjangoHelpFormatter as the default?\nReplying to Subhankar Hotta: So as part of this issue, do we make changes to allow a user to override the formatter through kwargs and also keep DjangoHelpFormatter as the default? Yes, see comment.", "created_at": "2022-06-18T19:39:34Z", "version": "4.2", "FAIL_TO_PASS": ["BaseCommand.create_parser() passes kwargs to CommandParser."], "PASS_TO_PASS": ["An unknown command raises CommandError", "By default, call_command should not trigger the check framework, unless", "Exception raised in a command should raise CommandError with", "It should be possible to pass non-string arguments to call_command.", "Management commands can also be loaded from Python eggs.", "To avoid conflicts with custom options, commands don't allow", "When passing the long option name to call_command, the available option", "When the Command handle method is decorated with @no_translations,", "find_command should still work when the PATH environment variable", "test_call_command_unrecognized_option (user_commands.tests.CommandTests)", "test_call_command_with_required_parameters_in_mixed_options (user_commands.tests.CommandTests)", "test_call_command_with_required_parameters_in_options (user_commands.tests.CommandTests)", "test_calling_a_command_with_no_app_labels_and_parameters_raise_command_error (user_commands.tests.CommandTests)", "test_calling_a_command_with_only_empty_parameter_should_ends_gracefully (user_commands.tests.CommandTests)", "test_calling_command_with_app_labels_and_parameters_should_be_ok (user_commands.tests.CommandTests)", "test_calling_command_with_parameters_and_app_labels_at_the_end_should_be_ok (user_commands.tests.CommandTests)", "test_check_migrations (user_commands.tests.CommandTests)", "test_command (user_commands.tests.CommandTests)", "test_command_add_arguments_after_common_arguments (user_commands.tests.CommandTests)", "test_command_style (user_commands.tests.CommandTests)", "test_get_random_secret_key (user_commands.tests.UtilsTests)", "test_is_ignored_path_false (user_commands.tests.UtilsTests)", "test_is_ignored_path_true (user_commands.tests.UtilsTests)", "test_language_preserved (user_commands.tests.CommandTests)", "test_mutually_exclusive_group_required_const_options (user_commands.tests.CommandTests)", "test_mutually_exclusive_group_required_options (user_commands.tests.CommandTests)", "test_mutually_exclusive_group_required_with_same_dest_args (user_commands.tests.CommandTests)", "test_mutually_exclusive_group_required_with_same_dest_options (user_commands.tests.CommandTests)", "test_no_existent_external_program (user_commands.tests.UtilsTests)", "test_normalize_path_patterns_truncates_wildcard_base (user_commands.tests.UtilsTests)", "test_output_transaction (user_commands.tests.CommandTests)", "test_outputwrapper_flush (user_commands.tests.CommandTests)", "test_required_const_options (user_commands.tests.CommandTests)", "test_required_list_option (user_commands.tests.CommandTests)", "test_requires_system_checks_empty (user_commands.tests.CommandTests)", "test_requires_system_checks_invalid (user_commands.tests.CommandTests)", "test_requires_system_checks_specific (user_commands.tests.CommandTests)", "test_script_prefix_set_in_commands (user_commands.tests.CommandRunTests)", "test_skip_checks (user_commands.tests.CommandRunTests)", "test_subparser (user_commands.tests.CommandTests)", "test_subparser_dest_args (user_commands.tests.CommandTests)", "test_subparser_dest_required_args (user_commands.tests.CommandTests)", "test_subparser_invalid_option (user_commands.tests.CommandTests)"], "environment_setup_commit": "0fbdb9784da915fce5dcc1fe82bac9b4785749e5"}]
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 8b59880e..ff66be02 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,7 +1,9 @@
+import dataclasses
import hashlib
+import logging
import subprocess
import pytest
-from sweagent.environment.utils import InvalidGithubURL, format_trajectory_markdown, _MARKDOWN_TRAJECTORY_EMOJI_MAPPING, get_instances, is_github_repo_url, remove_triple_backticks, parse_gh_repo_url, parse_gh_issue_url, is_github_issue_url, get_associated_commit_urls
+from sweagent.environment.utils import Instance, InvalidGithubURL, format_trajectory_markdown, _MARKDOWN_TRAJECTORY_EMOJI_MAPPING, get_instances, is_github_repo_url, remove_triple_backticks, parse_gh_repo_url, parse_gh_issue_url, is_github_issue_url, get_associated_commit_urls
def test_format_trajectory_markdown(test_trajectory):
formatted = format_trajectory_markdown(test_trajectory["trajectory"])
@@ -76,10 +78,10 @@ def test_get_instance_gh_issue():
"repo_type": "github",
}
for key in compare_with:
- assert instance[key] == compare_with[key]
- assert "SyntaxError" in instance["problem_statement"]
- assert len(instance["base_commit"]) > 10
- assert instance["version"]
+ assert getattr(instance, key) == compare_with[key]
+ assert "SyntaxError" in instance.problem_statement
+ assert len(instance.base_commit) > 10
+ assert instance.version
def clone_repo(tmp_path, repo_url):
@@ -99,10 +101,10 @@ def test_get_instance_gh_issue_local_repo(tmp_path):
'instance_id': 'klieret__swe-agent-test-repo-i1'
}
for key in compare_with:
- assert instance[key] == compare_with[key]
- assert "SyntaxError" in instance["problem_statement"]
- assert len(instance["base_commit"]) > 10
- assert instance["version"]
+ assert getattr(instance, key) == compare_with[key]
+ assert "SyntaxError" in instance.problem_statement
+ assert len(instance.base_commit) > 10
+ assert instance.version
def test_get_instance_local_issue_local_repo(tmp_path):
@@ -120,12 +122,12 @@ def test_get_instance_local_issue_local_repo(tmp_path):
"problem_statement": "asdf",
}
for key in compare_with:
- assert instance[key] == compare_with[key]
- assert len(instance["base_commit"]) > 10
- assert instance["version"]
+ assert getattr(instance, key) == compare_with[key]
+ assert len(instance.base_commit) > 10
+ assert instance.version
-def test_get_instance_gh_issue_gh_repo(tmp_path):
+def test_get_instance_gh_issue_gh_repo():
instance = get_instances(
file_path="https://github.com/klieret/swe-agent-test-repo/issues/1",
repo_path="https://github.com/princeton-nlp/SWE-agent",
@@ -136,7 +138,29 @@ def test_get_instance_gh_issue_gh_repo(tmp_path):
'instance_id': "klieret__swe-agent-test-repo-i1",
}
for key in compare_with:
- assert instance[key] == compare_with[key]
- assert "SyntaxError" in instance["problem_statement"]
- assert len(instance["base_commit"]) > 10
- assert instance["version"]
+ assert getattr(instance, key) == compare_with[key]
+ assert "SyntaxError" in instance.problem_statement
+ assert len(instance.base_commit) > 10
+ assert instance.version
+
+
+def test_instance_added_field():
+ dct = {
+ 'repo': 'klieret/swe-agent-test-repo',
+ 'instance_id': 'klieret__swe-agent-test-repo-i1',
+ "repo_type": "github",
+ "base_commit": "asdf",
+ "version": "1.1",
+ "thisisnew": "new",
+ "problem_statement": "asdf",
+ }
+ assert "thisisnew" in dataclasses.asdict(Instance.from_dict(dct))
+
+
+def test_load_instances(test_data_path, caplog):
+ test_data_sources = test_data_path / "data_sources"
+ examples = list(test_data_sources.iterdir())
+ for example in examples:
+ with caplog.at_level(logging.DEBUG):
+ get_instances(file_path=str(example))
+ assert not "missing fields" in caplog.text.lower()