{"index": 0, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_pep_572_version_detection", "test_class_name": "BlackTestCase", "original_test_prefix": " def test_pep_572_version_detection(self) -> None:\n source, _ = read_data(\"cases\", \"pep_572\")\n root = black.lib2to3_parse(source)\n features = black.get_features_used(root)\n self.assertIn(black.Feature.ASSIGNMENT_EXPRESSIONS, features)\n versions = black.detect_target_versions(root)\n self.assertIn(black.TargetVersion.PY38, versions)", "test_prefix": " def test_pep_572_version_detection(self) -> None:\n source, _ = read_data(\"cases\", \"pep_572\")\n root = black.lib2to3_parse(source)\n features = black.get_features_used(root)\n self.assertIn(black.Feature.ASSIGNMENT_EXPRESSIONS, features)\n versions = black.detect_target_versions(root)\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 243, "test_prefix_end_lineno": 249, "test_target": "tests/test_black.py::BlackTestCase::test_pep_572_version_detection", "ground_truth_oracle": "self.assertIn(black.TargetVersion.PY38, versions)", "ground_truth_oracle_lineno": 249, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def detect_target_versions(\n node: Node, *, future_imports: Optional[set[str]] = None\n) -> set[TargetVersion]:\n \"\"\"Detect the version to target based on the nodes used.\"\"\"\n features = get_features_used(node, future_imports=future_imports)\n return {\n version for version in TargetVersion if features <= VERSION_TO_FEATURES[version]\n }", "focal_method_file_path": "src/black/__init__.py", "focal_method_start_lineno": 1510, "focal_method_end_lineno": 1517} {"index": 1, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_detect_pos_only_arguments", "test_class_name": "BlackTestCase", "original_test_prefix": " def test_detect_pos_only_arguments(self) -> None:\n source, _ = read_data(\"cases\", \"pep_570\")\n root = black.lib2to3_parse(source)\n features = black.get_features_used(root)\n self.assertIn(black.Feature.POS_ONLY_ARGUMENTS, features)\n versions = black.detect_target_versions(root)\n self.assertIn(black.TargetVersion.PY38, versions)", "test_prefix": " def test_detect_pos_only_arguments(self) -> None:\n source, _ = read_data(\"cases\", \"pep_570\")\n root = black.lib2to3_parse(source)\n features = black.get_features_used(root)\n self.assertIn(black.Feature.POS_ONLY_ARGUMENTS, features)\n versions = black.detect_target_versions(root)\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 334, "test_prefix_end_lineno": 340, "test_target": "tests/test_black.py::BlackTestCase::test_detect_pos_only_arguments", "ground_truth_oracle": "self.assertIn(black.TargetVersion.PY38, versions)", "ground_truth_oracle_lineno": 340, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def detect_target_versions(\n node: Node, *, future_imports: Optional[set[str]] = None\n) -> set[TargetVersion]:\n \"\"\"Detect the version to target based on the nodes used.\"\"\"\n features = get_features_used(node, future_imports=future_imports)\n return {\n version for version in TargetVersion if features <= VERSION_TO_FEATURES[version]\n }", "focal_method_file_path": "src/black/__init__.py", "focal_method_start_lineno": 1510, "focal_method_end_lineno": 1517} {"index": 2, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_detect_debug_f_strings", "test_class_name": "BlackTestCase", "original_test_prefix": " def test_detect_debug_f_strings(self) -> None:\n root = black.lib2to3_parse(\"\"\"f\"{x=}\" \"\"\")\n features = black.get_features_used(root)\n self.assertIn(black.Feature.DEBUG_F_STRINGS, features)\n versions = black.detect_target_versions(root)\n self.assertIn(black.TargetVersion.PY38, versions)\n\n root = black.lib2to3_parse(\n \"\"\"f\"{x}\"\\nf'{\"=\"}'\\nf'{(x:=5)}'\\nf'{f(a=\"3=\")}'\\nf'{x:=10}'\\n\"\"\"\n )\n features = black.get_features_used(root)\n self.assertNotIn(black.Feature.DEBUG_F_STRINGS, features)\n\n root = black.lib2to3_parse(\n \"\"\"f\"heard a rumour that { f'{1+1=}' } ... seems like it could be true\" \"\"\"\n )\n features = black.get_features_used(root)\n self.assertIn(black.Feature.DEBUG_F_STRINGS, features)", "test_prefix": " def test_detect_debug_f_strings(self) -> None:\n root = black.lib2to3_parse(\"\"\"f\"{x=}\" \"\"\")\n features = black.get_features_used(root)\n self.assertIn(black.Feature.DEBUG_F_STRINGS, features)\n versions = black.detect_target_versions(root)\n \n\n root = black.lib2to3_parse(\n \"\"\"f\"{x}\"\\nf'{\"=\"}'\\nf'{(x:=5)}'\\nf'{f(a=\"3=\")}'\\nf'{x:=10}'\\n\"\"\"\n )\n features = black.get_features_used(root)\n self.assertNotIn(black.Feature.DEBUG_F_STRINGS, features)\n\n root = black.lib2to3_parse(\n \"\"\"f\"heard a rumour that { f'{1+1=}' } ... seems like it could be true\" \"\"\"\n )\n features = black.get_features_used(root)\n self.assertIn(black.Feature.DEBUG_F_STRINGS, features)", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 342, "test_prefix_end_lineno": 359, "test_target": "tests/test_black.py::BlackTestCase::test_detect_debug_f_strings", "ground_truth_oracle": "self.assertIn(black.TargetVersion.PY38, versions)", "ground_truth_oracle_lineno": 347, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def detect_target_versions(\n node: Node, *, future_imports: Optional[set[str]] = None\n) -> set[TargetVersion]:\n \"\"\"Detect the version to target based on the nodes used.\"\"\"\n features = get_features_used(node, future_imports=future_imports)\n return {\n version for version in TargetVersion if features <= VERSION_TO_FEATURES[version]\n }", "focal_method_file_path": "src/black/__init__.py", "focal_method_start_lineno": 1510, "focal_method_end_lineno": 1517} {"index": 3, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_future_imports", "test_class_name": "BlackTestCase", "original_test_prefix": " def test_get_future_imports(self) -> None:\n node = black.lib2to3_parse(\"\\n\")\n self.assertEqual(set(), black.get_future_imports(node))\n node = black.lib2to3_parse(\"from __future__ import black\\n\")\n self.assertEqual({\"black\"}, black.get_future_imports(node))\n node = black.lib2to3_parse(\"from __future__ import multiple, imports\\n\")\n self.assertEqual({\"multiple\", \"imports\"}, black.get_future_imports(node))\n node = black.lib2to3_parse(\"from __future__ import (parenthesized, imports)\\n\")\n self.assertEqual({\"parenthesized\", \"imports\"}, black.get_future_imports(node))\n node = black.lib2to3_parse(\n \"from __future__ import multiple\\nfrom __future__ import imports\\n\"\n )\n self.assertEqual({\"multiple\", \"imports\"}, black.get_future_imports(node))\n node = black.lib2to3_parse(\"# comment\\nfrom __future__ import black\\n\")\n self.assertEqual({\"black\"}, black.get_future_imports(node))\n node = black.lib2to3_parse('\"\"\"docstring\"\"\"\\nfrom __future__ import black\\n')\n self.assertEqual({\"black\"}, black.get_future_imports(node))\n node = black.lib2to3_parse(\"some(other, code)\\nfrom __future__ import black\\n\")\n self.assertEqual(set(), black.get_future_imports(node))\n node = black.lib2to3_parse(\"from some.module import black\\n\")\n self.assertEqual(set(), black.get_future_imports(node))\n node = black.lib2to3_parse(\n \"from __future__ import unicode_literals as _unicode_literals\"\n )\n self.assertEqual({\"unicode_literals\"}, black.get_future_imports(node))\n node = black.lib2to3_parse(\n \"from __future__ import unicode_literals as _lol, print\"\n )\n self.assertEqual({\"unicode_literals\", \"print\"}, black.get_future_imports(node))", "test_prefix": " def test_get_future_imports(self) -> None:\n node = black.lib2to3_parse(\"\\n\")\n self.assertEqual(set(), black.get_future_imports(node))\n node = black.lib2to3_parse(\"from __future__ import black\\n\")\n self.assertEqual({\"black\"}, black.get_future_imports(node))\n node = black.lib2to3_parse(\"from __future__ import multiple, imports\\n\")\n \n node = black.lib2to3_parse(\"from __future__ import (parenthesized, imports)\\n\")\n self.assertEqual({\"parenthesized\", \"imports\"}, black.get_future_imports(node))\n node = black.lib2to3_parse(\n \"from __future__ import multiple\\nfrom __future__ import imports\\n\"\n )\n \n node = black.lib2to3_parse(\"# comment\\nfrom __future__ import black\\n\")\n self.assertEqual({\"black\"}, black.get_future_imports(node))\n node = black.lib2to3_parse('\"\"\"docstring\"\"\"\\nfrom __future__ import black\\n')\n self.assertEqual({\"black\"}, black.get_future_imports(node))\n node = black.lib2to3_parse(\"some(other, code)\\nfrom __future__ import black\\n\")\n self.assertEqual(set(), black.get_future_imports(node))\n node = black.lib2to3_parse(\"from some.module import black\\n\")\n self.assertEqual(set(), black.get_future_imports(node))\n node = black.lib2to3_parse(\n \"from __future__ import unicode_literals as _unicode_literals\"\n )\n self.assertEqual({\"unicode_literals\"}, black.get_future_imports(node))\n node = black.lib2to3_parse(\n \"from __future__ import unicode_literals as _lol, print\"\n )\n self.assertEqual({\"unicode_literals\", \"print\"}, black.get_future_imports(node))", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 930, "test_prefix_end_lineno": 958, "test_target": "tests/test_black.py::BlackTestCase::test_get_future_imports", "ground_truth_oracle": "self.assertEqual({\"multiple\", \"imports\"}, black.get_future_imports(node))", "ground_truth_oracle_lineno": 942, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_future_imports(node: Node) -> set[str]:\n \"\"\"Return a set of __future__ imports in the file.\"\"\"\n imports: set[str] = set()\n\n def get_imports_from_children(children: list[LN]) -> Generator[str, None, None]:\n for child in children:\n if isinstance(child, Leaf):\n if child.type == token.NAME:\n yield child.value\n\n elif child.type == syms.import_as_name:\n orig_name = child.children[0]\n assert isinstance(orig_name, Leaf), \"Invalid syntax parsing imports\"\n assert orig_name.type == token.NAME, \"Invalid syntax parsing imports\"\n yield orig_name.value\n\n elif child.type == syms.import_as_names:\n yield from get_imports_from_children(child.children)\n\n else:\n raise AssertionError(\"Invalid syntax parsing imports\")\n\n for child in node.children:\n if child.type != syms.simple_stmt:\n break\n\n first_child = child.children[0]\n if isinstance(first_child, Leaf):\n # Continue looking if we see a docstring; otherwise stop.\n if (\n len(child.children) == 2\n and first_child.type == token.STRING\n and child.children[1].type == token.NEWLINE\n ):\n continue\n\n break\n\n elif first_child.type == syms.import_from:\n module_name = first_child.children[1]\n if not isinstance(module_name, Leaf) or module_name.value != \"__future__\":\n break\n\n imports |= set(get_imports_from_children(first_child.children[3:]))\n else:\n break\n\n return imports", "focal_method_file_path": "src/black/__init__.py", "focal_method_start_lineno": 1520, "focal_method_end_lineno": 1567} {"index": 4, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_endmarker", "test_class_name": "BlackTestCase", "original_test_prefix": " def test_endmarker(self) -> None:\n n = black.lib2to3_parse(\"\\n\")\n self.assertEqual(n.type, black.syms.file_input)\n self.assertEqual(len(n.children), 1)\n self.assertEqual(n.children[0].type, black.token.ENDMARKER)", "test_prefix": " def test_endmarker(self) -> None:\n n = black.lib2to3_parse(\"\\n\")\n self.assertEqual(n.type, black.syms.file_input)\n \n self.assertEqual(n.children[0].type, black.token.ENDMARKER)", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 1015, "test_prefix_end_lineno": 1019, "test_target": "tests/test_black.py::BlackTestCase::test_endmarker", "ground_truth_oracle": "self.assertEqual(len(n.children), 1)", "ground_truth_oracle_lineno": 1018, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def lib2to3_parse(\n src_txt: str, target_versions: Collection[TargetVersion] = ()\n) -> Node:\n \"\"\"Given a string with source, return the lib2to3 Node.\"\"\"\n if not src_txt.endswith(\"\\n\"):\n src_txt += \"\\n\"\n\n grammars = get_grammars(set(target_versions))\n if target_versions:\n max_tv = max(target_versions, key=lambda tv: tv.value)\n tv_str = f\" for target version {max_tv.pretty()}\"\n else:\n tv_str = \"\"\n\n errors = {}\n for grammar in grammars:\n drv = driver.Driver(grammar)\n try:\n result = drv.parse_string(src_txt, False)\n break\n\n except ParseError as pe:\n lineno, column = pe.context[1]\n lines = src_txt.splitlines()\n try:\n faulty_line = lines[lineno - 1]\n except IndexError:\n faulty_line = \"\"\n errors[grammar.version] = InvalidInput(\n f\"Cannot parse{tv_str}: {lineno}:{column}: {faulty_line}\"\n )\n\n except TokenError as te:\n # In edge cases these are raised; and typically don't have a \"faulty_line\".\n lineno, column = te.args[1]\n errors[grammar.version] = InvalidInput(\n f\"Cannot parse{tv_str}: {lineno}:{column}: {te.args[0]}\"\n )\n\n else:\n # Choose the latest version when raising the actual parsing error.\n assert len(errors) >= 1\n exc = errors[max(errors)]\n raise exc from None\n\n if isinstance(result, Leaf):\n result = Node(syms.file_input, [result])\n return result", "focal_method_file_path": "src/black/parsing.py", "focal_method_start_lineno": 55, "focal_method_end_lineno": 102} {"index": 5, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_single_file_force_pyi", "test_class_name": "BlackTestCase", "original_test_prefix": " def test_single_file_force_pyi(self) -> None:\n pyi_mode = replace(DEFAULT_MODE, is_pyi=True)\n contents, expected = read_data(\"miscellaneous\", \"force_pyi\")\n with cache_dir() as workspace:\n path = (workspace / \"file.py\").resolve()\n path.write_text(contents, encoding=\"utf-8\")\n self.invokeBlack([str(path), \"--pyi\"])\n actual = path.read_text(encoding=\"utf-8\")\n # verify cache with --pyi is separate\n pyi_cache = black.Cache.read(pyi_mode)\n assert not pyi_cache.is_changed(path)\n normal_cache = black.Cache.read(DEFAULT_MODE)\n assert normal_cache.is_changed(path)\n self.assertFormatEqual(expected, actual)\n black.assert_equivalent(contents, actual)\n black.assert_stable(contents, actual, pyi_mode)", "test_prefix": " def test_single_file_force_pyi(self) -> None:\n pyi_mode = replace(DEFAULT_MODE, is_pyi=True)\n contents, expected = read_data(\"miscellaneous\", \"force_pyi\")\n with cache_dir() as workspace:\n path = (workspace / \"file.py\").resolve()\n path.write_text(contents, encoding=\"utf-8\")\n self.invokeBlack([str(path), \"--pyi\"])\n actual = path.read_text(encoding=\"utf-8\")\n # verify cache with --pyi is separate\n pyi_cache = black.Cache.read(pyi_mode)\n assert not pyi_cache.is_changed(path)\n normal_cache = black.Cache.read(DEFAULT_MODE)\n assert normal_cache.is_changed(path)\n \n black.assert_equivalent(contents, actual)\n black.assert_stable(contents, actual, pyi_mode)", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 1106, "test_prefix_end_lineno": 1121, "test_target": "tests/test_black.py::BlackTestCase::test_single_file_force_pyi", "ground_truth_oracle": "self.assertFormatEqual(expected, actual)", "ground_truth_oracle_lineno": 1119, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def read(cls, mode: Mode) -> Self:\n \"\"\"Read the cache if it exists and is well-formed.\n\n If it is not well-formed, the call to write later should\n resolve the issue.\n \"\"\"\n cache_file = get_cache_file(mode)\n try:\n exists = cache_file.exists()\n except OSError as e:\n # Likely file too long; see #4172 and #4174\n err(f\"Unable to read cache file {cache_file} due to {e}\")\n return cls(mode, cache_file)\n if not exists:\n return cls(mode, cache_file)\n\n with cache_file.open(\"rb\") as fobj:\n try:\n data: dict[str, tuple[float, int, str]] = pickle.load(fobj)\n file_data = {k: FileData(*v) for k, v in data.items()}\n except (pickle.UnpicklingError, ValueError, IndexError):\n return cls(mode, cache_file)\n\n return cls(mode, cache_file, file_data)", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 61, "focal_method_end_lineno": 85} {"index": 6, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_multi_file_force_pyi", "test_class_name": "BlackTestCase", "original_test_prefix": " @event_loop()\n def test_multi_file_force_pyi(self) -> None:\n reg_mode = DEFAULT_MODE\n pyi_mode = replace(DEFAULT_MODE, is_pyi=True)\n contents, expected = read_data(\"miscellaneous\", \"force_pyi\")\n with cache_dir() as workspace:\n paths = [\n (workspace / \"file1.py\").resolve(),\n (workspace / \"file2.py\").resolve(),\n ]\n for path in paths:\n path.write_text(contents, encoding=\"utf-8\")\n self.invokeBlack([str(p) for p in paths] + [\"--pyi\"])\n for path in paths:\n actual = path.read_text(encoding=\"utf-8\")\n self.assertEqual(actual, expected)\n # verify cache with --pyi is separate\n pyi_cache = black.Cache.read(pyi_mode)\n normal_cache = black.Cache.read(reg_mode)\n for path in paths:\n assert not pyi_cache.is_changed(path)\n assert normal_cache.is_changed(path)", "test_prefix": " @event_loop()\n def test_multi_file_force_pyi(self) -> None:\n reg_mode = DEFAULT_MODE\n pyi_mode = replace(DEFAULT_MODE, is_pyi=True)\n contents, expected = read_data(\"miscellaneous\", \"force_pyi\")\n with cache_dir() as workspace:\n paths = [\n (workspace / \"file1.py\").resolve(),\n (workspace / \"file2.py\").resolve(),\n ]\n for path in paths:\n path.write_text(contents, encoding=\"utf-8\")\n self.invokeBlack([str(p) for p in paths] + [\"--pyi\"])\n for path in paths:\n actual = path.read_text(encoding=\"utf-8\")\n self.assertEqual(actual, expected)\n # verify cache with --pyi is separate\n pyi_cache = black.Cache.read(pyi_mode)\n normal_cache = black.Cache.read(reg_mode)\n for path in paths:\n \n assert normal_cache.is_changed(path)", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 1123, "test_prefix_end_lineno": 1144, "test_target": "tests/test_black.py::BlackTestCase::test_multi_file_force_pyi", "ground_truth_oracle": "assert not pyi_cache.is_changed(path)", "ground_truth_oracle_lineno": 1143, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def is_changed(self, source: Path) -> bool:\n \"\"\"Check if source has changed compared to cached version.\"\"\"\n res_src = source.resolve()\n old = self.file_data.get(str(res_src))\n if old is None:\n return True\n\n st = res_src.stat()\n if st.st_size != old.st_size:\n return True\n if st.st_mtime != old.st_mtime:\n new_hash = Cache.hash_digest(res_src)\n if new_hash != old.hash:\n return True\n return False", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 102, "focal_method_end_lineno": 116} {"index": 7, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_single_file_force_py36", "test_class_name": "BlackTestCase", "original_test_prefix": " def test_single_file_force_py36(self) -> None:\n reg_mode = DEFAULT_MODE\n py36_mode = replace(DEFAULT_MODE, target_versions=PY36_VERSIONS)\n source, expected = read_data(\"miscellaneous\", \"force_py36\")\n with cache_dir() as workspace:\n path = (workspace / \"file.py\").resolve()\n path.write_text(source, encoding=\"utf-8\")\n self.invokeBlack([str(path), *PY36_ARGS])\n actual = path.read_text(encoding=\"utf-8\")\n # verify cache with --target-version is separate\n py36_cache = black.Cache.read(py36_mode)\n assert not py36_cache.is_changed(path)\n normal_cache = black.Cache.read(reg_mode)\n assert normal_cache.is_changed(path)\n self.assertEqual(actual, expected)", "test_prefix": " def test_single_file_force_py36(self) -> None:\n reg_mode = DEFAULT_MODE\n py36_mode = replace(DEFAULT_MODE, target_versions=PY36_VERSIONS)\n source, expected = read_data(\"miscellaneous\", \"force_py36\")\n with cache_dir() as workspace:\n path = (workspace / \"file.py\").resolve()\n path.write_text(source, encoding=\"utf-8\")\n self.invokeBlack([str(path), *PY36_ARGS])\n actual = path.read_text(encoding=\"utf-8\")\n # verify cache with --target-version is separate\n py36_cache = black.Cache.read(py36_mode)\n assert not py36_cache.is_changed(path)\n normal_cache = black.Cache.read(reg_mode)\n assert normal_cache.is_changed(path)\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 1155, "test_prefix_end_lineno": 1169, "test_target": "tests/test_black.py::BlackTestCase::test_single_file_force_py36", "ground_truth_oracle": "self.assertEqual(actual, expected)", "ground_truth_oracle_lineno": 1169, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def read(cls, mode: Mode) -> Self:\n \"\"\"Read the cache if it exists and is well-formed.\n\n If it is not well-formed, the call to write later should\n resolve the issue.\n \"\"\"\n cache_file = get_cache_file(mode)\n try:\n exists = cache_file.exists()\n except OSError as e:\n # Likely file too long; see #4172 and #4174\n err(f\"Unable to read cache file {cache_file} due to {e}\")\n return cls(mode, cache_file)\n if not exists:\n return cls(mode, cache_file)\n\n with cache_file.open(\"rb\") as fobj:\n try:\n data: dict[str, tuple[float, int, str]] = pickle.load(fobj)\n file_data = {k: FileData(*v) for k, v in data.items()}\n except (pickle.UnpicklingError, ValueError, IndexError):\n return cls(mode, cache_file)\n\n return cls(mode, cache_file, file_data)", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 61, "focal_method_end_lineno": 85} {"index": 8, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_parse_pyproject_toml", "test_class_name": "BlackTestCase", "original_test_prefix": " def test_parse_pyproject_toml(self) -> None:\n test_toml_file = THIS_DIR / \"test.toml\"\n config = black.parse_pyproject_toml(str(test_toml_file))\n self.assertEqual(config[\"verbose\"], 1)\n self.assertEqual(config[\"check\"], \"no\")\n self.assertEqual(config[\"diff\"], \"y\")\n self.assertEqual(config[\"color\"], True)\n self.assertEqual(config[\"line_length\"], 79)\n self.assertEqual(config[\"target_version\"], [\"py36\", \"py37\", \"py38\"])\n self.assertEqual(config[\"python_cell_magics\"], [\"custom1\", \"custom2\"])\n self.assertEqual(config[\"exclude\"], r\"\\.pyi?$\")\n self.assertEqual(config[\"include\"], r\"\\.py?$\")", "test_prefix": " def test_parse_pyproject_toml(self) -> None:\n test_toml_file = THIS_DIR / \"test.toml\"\n config = black.parse_pyproject_toml(str(test_toml_file))\n self.assertEqual(config[\"verbose\"], 1)\n self.assertEqual(config[\"check\"], \"no\")\n self.assertEqual(config[\"diff\"], \"y\")\n self.assertEqual(config[\"color\"], True)\n \n self.assertEqual(config[\"target_version\"], [\"py36\", \"py37\", \"py38\"])\n self.assertEqual(config[\"python_cell_magics\"], [\"custom1\", \"custom2\"])\n self.assertEqual(config[\"exclude\"], r\"\\.pyi?$\")\n self.assertEqual(config[\"include\"], r\"\\.py?$\")", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 1476, "test_prefix_end_lineno": 1487, "test_target": "tests/test_black.py::BlackTestCase::test_parse_pyproject_toml", "ground_truth_oracle": "self.assertEqual(config[\"line_length\"], 79)", "ground_truth_oracle_lineno": 1483, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "@mypyc_attr(patchable=True)\ndef parse_pyproject_toml(path_config: str) -> dict[str, Any]:\n \"\"\"Parse a pyproject toml file, pulling out relevant parts for Black.\n\n If parsing fails, will raise a tomllib.TOMLDecodeError.\n \"\"\"\n pyproject_toml = _load_toml(path_config)\n config: dict[str, Any] = pyproject_toml.get(\"tool\", {}).get(\"black\", {})\n config = {k.replace(\"--\", \"\").replace(\"-\", \"_\"): v for k, v in config.items()}\n\n if \"target_version\" not in config:\n inferred_target_version = infer_target_version(pyproject_toml)\n if inferred_target_version is not None:\n config[\"target_version\"] = [v.name.lower() for v in inferred_target_version]\n\n return config", "focal_method_file_path": "src/black/files.py", "focal_method_start_lineno": 120, "focal_method_end_lineno": 135} {"index": 9, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_find_pyproject_toml", "test_class_name": "BlackTestCase", "original_test_prefix": " @patch(\n \"black.files.find_user_pyproject_toml\",\n )\n def test_find_pyproject_toml(self, find_user_pyproject_toml: MagicMock) -> None:\n find_user_pyproject_toml.side_effect = RuntimeError()\n\n with redirect_stderr(io.StringIO()) as stderr:\n result = black.files.find_pyproject_toml(\n path_search_start=(str(Path.cwd().root),)\n )\n\n assert result is None\n err = stderr.getvalue()\n assert \"Ignoring user configuration\" in err", "test_prefix": " @patch(\n \"black.files.find_user_pyproject_toml\",\n )\n def test_find_pyproject_toml(self, find_user_pyproject_toml: MagicMock) -> None:\n find_user_pyproject_toml.side_effect = RuntimeError()\n\n with redirect_stderr(io.StringIO()) as stderr:\n result = black.files.find_pyproject_toml(\n path_search_start=(str(Path.cwd().root),)\n )\n\n \n err = stderr.getvalue()\n assert \"Ignoring user configuration\" in err", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 1708, "test_prefix_end_lineno": 1721, "test_target": "tests/test_black.py::BlackTestCase::test_find_pyproject_toml", "ground_truth_oracle": "assert result is None", "ground_truth_oracle_lineno": 1719, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def find_pyproject_toml(\n path_search_start: tuple[str, ...], stdin_filename: Optional[str] = None\n) -> Optional[str]:\n \"\"\"Find the absolute filepath to a pyproject.toml if it exists\"\"\"\n path_project_root, _ = find_project_root(path_search_start, stdin_filename)\n path_pyproject_toml = path_project_root / \"pyproject.toml\"\n if path_pyproject_toml.is_file():\n return str(path_pyproject_toml)\n\n try:\n path_user_pyproject_toml = find_user_pyproject_toml()\n return (\n str(path_user_pyproject_toml)\n if path_user_pyproject_toml.is_file()\n else None\n )\n except (PermissionError, RuntimeError) as e:\n # We do not have access to the user-level config directory, so ignore it.\n err(f\"Ignoring user configuration directory due to {e!r}\")\n return None", "focal_method_file_path": "src/black/files.py", "focal_method_start_lineno": 98, "focal_method_end_lineno": 117} {"index": 10, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_bpo_33660_workaround", "test_class_name": "BlackTestCase", "original_test_prefix": " def test_bpo_33660_workaround(self) -> None:\n if system() == \"Windows\":\n return\n\n # https://bugs.python.org/issue33660\n # Can be removed when we drop support for Python 3.8.5\n root = Path(\"/\")\n with change_directory(root):\n path = Path(\"workspace\") / \"project\"\n report = black.Report(verbose=True)\n resolves_outside = black.resolves_outside_root_or_cannot_stat(\n path, root, report\n )\n self.assertIs(resolves_outside, False)", "test_prefix": " def test_bpo_33660_workaround(self) -> None:\n if system() == \"Windows\":\n return\n\n # https://bugs.python.org/issue33660\n # Can be removed when we drop support for Python 3.8.5\n root = Path(\"/\")\n with change_directory(root):\n path = Path(\"workspace\") / \"project\"\n report = black.Report(verbose=True)\n resolves_outside = black.resolves_outside_root_or_cannot_stat(\n path, root, report\n )\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 1756, "test_prefix_end_lineno": 1769, "test_target": "tests/test_black.py::BlackTestCase::test_bpo_33660_workaround", "ground_truth_oracle": "self.assertIs(resolves_outside, False)", "ground_truth_oracle_lineno": 1769, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def resolves_outside_root_or_cannot_stat(\n path: Path,\n root: Path,\n report: Optional[Report] = None,\n) -> bool:\n \"\"\"\n Returns whether the path is a symbolic link that points outside the\n root directory. Also returns True if we failed to resolve the path.\n \"\"\"\n try:\n resolved_path = _cached_resolve(path)\n except OSError as e:\n if report:\n report.path_ignored(path, f\"cannot be read because {e}\")\n return True\n try:\n resolved_path.relative_to(root)\n except ValueError:\n if report:\n report.path_ignored(path, f\"is a symbolic link that points outside {root}\")\n return True\n return False", "focal_method_file_path": "src/black/files.py", "focal_method_start_lineno": 255, "focal_method_end_lineno": 276} {"index": 11, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_lines_with_leading_tabs_expanded", "test_class_name": "BlackTestCase", "original_test_prefix": " def test_lines_with_leading_tabs_expanded(self) -> None:\n # See CVE-2024-21503. Mostly test that this completes in a reasonable\n # time.\n payload = \"\\t\" * 10_000\n assert lines_with_leading_tabs_expanded(payload) == [payload]\n\n tab = \" \" * 8\n assert lines_with_leading_tabs_expanded(\"\\tx\") == [f\"{tab}x\"]\n assert lines_with_leading_tabs_expanded(\"\\t\\tx\") == [f\"{tab}{tab}x\"]\n assert lines_with_leading_tabs_expanded(\"\\tx\\n y\") == [f\"{tab}x\", \" y\"]", "test_prefix": " def test_lines_with_leading_tabs_expanded(self) -> None:\n # See CVE-2024-21503. Mostly test that this completes in a reasonable\n # time.\n payload = \"\\t\" * 10_000\n assert lines_with_leading_tabs_expanded(payload) == [payload]\n\n tab = \" \" * 8\n assert lines_with_leading_tabs_expanded(\"\\tx\") == [f\"{tab}x\"]\n assert lines_with_leading_tabs_expanded(\"\\t\\tx\") == [f\"{tab}{tab}x\"]\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2046, "test_prefix_end_lineno": 2055, "test_target": "tests/test_black.py::BlackTestCase::test_lines_with_leading_tabs_expanded", "ground_truth_oracle": "assert lines_with_leading_tabs_expanded(\"\\tx\\n y\") == [f\"{tab}x\", \" y\"]", "ground_truth_oracle_lineno": 2055, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def lines_with_leading_tabs_expanded(s: str) -> list[str]:\n \"\"\"\n Splits string into lines and expands only leading tabs (following the normal\n Python rules)\n \"\"\"\n lines = []\n for line in s.splitlines():\n stripped_line = line.lstrip()\n if not stripped_line or stripped_line == line:\n lines.append(line)\n else:\n prefix_length = len(line) - len(stripped_line)\n prefix = line[:prefix_length].expandtabs()\n lines.append(prefix + stripped_line)\n if s.endswith(\"\\n\"):\n lines.append(\"\")\n return lines", "focal_method_file_path": "src/black/strings.py", "focal_method_start_lineno": 47, "focal_method_end_lineno": 63} {"index": 12, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_preview_newline_type_detection", "test_class_name": "BlackTestCase", "original_test_prefix": " def test_preview_newline_type_detection(self) -> None:\n mode = Mode(enabled_features={Preview.normalize_cr_newlines})\n newline_types = [\"A\\n\", \"A\\r\\n\", \"A\\r\"]\n for test_case in itertools.permutations(newline_types):\n assert black.format_str(\"\".join(test_case), mode=mode) == test_case[0] * 3", "test_prefix": " def test_preview_newline_type_detection(self) -> None:\n mode = Mode(enabled_features={Preview.normalize_cr_newlines})\n newline_types = [\"A\\n\", \"A\\r\\n\", \"A\\r\"]\n for test_case in itertools.permutations(newline_types):\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2087, "test_prefix_end_lineno": 2091, "test_target": "tests/test_black.py::BlackTestCase::test_preview_newline_type_detection", "ground_truth_oracle": "assert black.format_str(\"\".join(test_case), mode=mode) == test_case[0] * 3", "ground_truth_oracle_lineno": 2091, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def format_str(\n src_contents: str, *, mode: Mode, lines: Collection[tuple[int, int]] = ()\n) -> str:\n \"\"\"Reformat a string and return new contents.\n\n `mode` determines formatting options, such as how many characters per line are\n allowed. Example:\n\n >>> import black\n >>> print(black.format_str(\"def f(arg:str='')->None:...\", mode=black.Mode()))\n def f(arg: str = \"\") -> None:\n ...\n\n A more complex example:\n\n >>> print(\n ... black.format_str(\n ... \"def f(arg:str='')->None: hey\",\n ... mode=black.Mode(\n ... target_versions={black.TargetVersion.PY36},\n ... line_length=10,\n ... string_normalization=False,\n ... is_pyi=False,\n ... ),\n ... ),\n ... )\n def f(\n arg: str = '',\n ) -> None:\n hey\n\n \"\"\"\n if lines:\n lines = sanitized_lines(lines, src_contents)\n if not lines:\n return src_contents # Nothing to format\n dst_contents = _format_str_once(src_contents, mode=mode, lines=lines)\n # Forced second pass to work around optional trailing commas (becoming\n # forced trailing commas on pass 2) interacting differently with optional\n # parentheses. Admittedly ugly.\n if src_contents != dst_contents:\n if lines:\n lines = adjusted_lines(lines, src_contents, dst_contents)\n return _format_str_once(dst_contents, mode=mode, lines=lines)\n return dst_contents", "focal_method_file_path": "src/black/__init__.py", "focal_method_start_lineno": 1176, "focal_method_end_lineno": 1220} {"index": 13, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_cache_dir", "test_class_name": "TestCaching", "original_test_prefix": " def test_get_cache_dir(\n self,\n tmp_path: Path,\n monkeypatch: pytest.MonkeyPatch,\n ) -> None:\n # Create multiple cache directories\n workspace1 = tmp_path / \"ws1\"\n workspace1.mkdir()\n workspace2 = tmp_path / \"ws2\"\n workspace2.mkdir()\n\n # Force user_cache_dir to use the temporary directory for easier assertions\n patch_user_cache_dir = patch(\n target=\"black.cache.user_cache_dir\",\n autospec=True,\n return_value=str(workspace1),\n )\n\n # If BLACK_CACHE_DIR is not set, use user_cache_dir\n monkeypatch.delenv(\"BLACK_CACHE_DIR\", raising=False)\n with patch_user_cache_dir:\n assert get_cache_dir().parent == workspace1\n\n # If it is set, use the path provided in the env var.\n monkeypatch.setenv(\"BLACK_CACHE_DIR\", str(workspace2))\n assert get_cache_dir().parent == workspace2", "test_prefix": " def test_get_cache_dir(\n self,\n tmp_path: Path,\n monkeypatch: pytest.MonkeyPatch,\n ) -> None:\n # Create multiple cache directories\n workspace1 = tmp_path / \"ws1\"\n workspace1.mkdir()\n workspace2 = tmp_path / \"ws2\"\n workspace2.mkdir()\n\n # Force user_cache_dir to use the temporary directory for easier assertions\n patch_user_cache_dir = patch(\n target=\"black.cache.user_cache_dir\",\n autospec=True,\n return_value=str(workspace1),\n )\n\n # If BLACK_CACHE_DIR is not set, use user_cache_dir\n monkeypatch.delenv(\"BLACK_CACHE_DIR\", raising=False)\n with patch_user_cache_dir:\n assert get_cache_dir().parent == workspace1\n\n # If it is set, use the path provided in the env var.\n monkeypatch.setenv(\"BLACK_CACHE_DIR\", str(workspace2))\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2095, "test_prefix_end_lineno": 2120, "test_target": "tests/test_black.py::TestCaching::test_get_cache_dir", "ground_truth_oracle": "assert get_cache_dir().parent == workspace2", "ground_truth_oracle_lineno": 2120, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_cache_dir() -> Path:\n \"\"\"Get the cache directory used by black.\n\n Users can customize this directory on all systems using `BLACK_CACHE_DIR`\n environment variable. By default, the cache directory is the user cache directory\n under the black application.\n\n This result is immediately set to a constant `black.cache.CACHE_DIR` as to avoid\n repeated calls.\n \"\"\"\n # NOTE: Function mostly exists as a clean way to test getting the cache directory.\n default_cache_dir = user_cache_dir(\"black\")\n cache_dir = Path(os.environ.get(\"BLACK_CACHE_DIR\", default_cache_dir))\n cache_dir = cache_dir / __version__\n return cache_dir", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 31, "focal_method_end_lineno": 45} {"index": 14, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_cache_file_length", "test_class_name": "TestCaching", "original_test_prefix": " def test_cache_file_length(self) -> None:\n cases = [\n DEFAULT_MODE,\n # all of the target versions\n Mode(target_versions=set(TargetVersion)),\n # all of the features\n Mode(enabled_features=set(Preview)),\n # all of the magics\n Mode(python_cell_magics={f\"magic{i}\" for i in range(500)}),\n # all of the things\n Mode(\n target_versions=set(TargetVersion),\n enabled_features=set(Preview),\n python_cell_magics={f\"magic{i}\" for i in range(500)},\n ),\n ]\n for case in cases:\n cache_file = get_cache_file(case)\n # Some common file systems enforce a maximum path length\n # of 143 (issue #4174). We can't do anything if the directory\n # path is too long, but ensure the name of the cache file itself\n # doesn't get too crazy.\n assert len(cache_file.name) <= 96", "test_prefix": " def test_cache_file_length(self) -> None:\n cases = [\n DEFAULT_MODE,\n # all of the target versions\n Mode(target_versions=set(TargetVersion)),\n # all of the features\n Mode(enabled_features=set(Preview)),\n # all of the magics\n Mode(python_cell_magics={f\"magic{i}\" for i in range(500)}),\n # all of the things\n Mode(\n target_versions=set(TargetVersion),\n enabled_features=set(Preview),\n python_cell_magics={f\"magic{i}\" for i in range(500)},\n ),\n ]\n for case in cases:\n cache_file = get_cache_file(case)\n # Some common file systems enforce a maximum path length\n # of 143 (issue #4174). We can't do anything if the directory\n # path is too long, but ensure the name of the cache file itself\n # doesn't get too crazy.\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2122, "test_prefix_end_lineno": 2144, "test_target": "tests/test_black.py::TestCaching::test_cache_file_length", "ground_truth_oracle": "assert len(cache_file.name) <= 96", "ground_truth_oracle_lineno": 2144, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_cache_file(mode: Mode) -> Path:\n return CACHE_DIR / f\"cache.{mode.get_cache_key()}.pickle\"", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 51, "focal_method_end_lineno": 52} {"index": 15, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_cache_broken_file", "test_class_name": "TestCaching", "original_test_prefix": " def test_cache_broken_file(self) -> None:\n mode = DEFAULT_MODE\n with cache_dir() as workspace:\n cache_file = get_cache_file(mode)\n cache_file.write_text(\"this is not a pickle\", encoding=\"utf-8\")\n assert black.Cache.read(mode).file_data == {}\n src = (workspace / \"test.py\").resolve()\n src.write_text(\"print('hello')\", encoding=\"utf-8\")\n invokeBlack([str(src)])\n cache = black.Cache.read(mode)\n assert not cache.is_changed(src)", "test_prefix": " def test_cache_broken_file(self) -> None:\n mode = DEFAULT_MODE\n with cache_dir() as workspace:\n cache_file = get_cache_file(mode)\n cache_file.write_text(\"this is not a pickle\", encoding=\"utf-8\")\n assert black.Cache.read(mode).file_data == {}\n src = (workspace / \"test.py\").resolve()\n src.write_text(\"print('hello')\", encoding=\"utf-8\")\n invokeBlack([str(src)])\n cache = black.Cache.read(mode)\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2146, "test_prefix_end_lineno": 2156, "test_target": "tests/test_black.py::TestCaching::test_cache_broken_file", "ground_truth_oracle": "assert not cache.is_changed(src)", "ground_truth_oracle_lineno": 2156, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def is_changed(self, source: Path) -> bool:\n \"\"\"Check if source has changed compared to cached version.\"\"\"\n res_src = source.resolve()\n old = self.file_data.get(str(res_src))\n if old is None:\n return True\n\n st = res_src.stat()\n if st.st_size != old.st_size:\n return True\n if st.st_mtime != old.st_mtime:\n new_hash = Cache.hash_digest(res_src)\n if new_hash != old.hash:\n return True\n return False", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 102, "focal_method_end_lineno": 116} {"index": 16, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_read_cache_no_cachefile", "test_class_name": "TestCaching", "original_test_prefix": " def test_read_cache_no_cachefile(self) -> None:\n mode = DEFAULT_MODE\n with cache_dir():\n assert black.Cache.read(mode).file_data == {}", "test_prefix": " def test_read_cache_no_cachefile(self) -> None:\n mode = DEFAULT_MODE\n with cache_dir():\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2236, "test_prefix_end_lineno": 2239, "test_target": "tests/test_black.py::TestCaching::test_read_cache_no_cachefile", "ground_truth_oracle": "assert black.Cache.read(mode).file_data == {}", "ground_truth_oracle_lineno": 2239, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def read(cls, mode: Mode) -> Self:\n \"\"\"Read the cache if it exists and is well-formed.\n\n If it is not well-formed, the call to write later should\n resolve the issue.\n \"\"\"\n cache_file = get_cache_file(mode)\n try:\n exists = cache_file.exists()\n except OSError as e:\n # Likely file too long; see #4172 and #4174\n err(f\"Unable to read cache file {cache_file} due to {e}\")\n return cls(mode, cache_file)\n if not exists:\n return cls(mode, cache_file)\n\n with cache_file.open(\"rb\") as fobj:\n try:\n data: dict[str, tuple[float, int, str]] = pickle.load(fobj)\n file_data = {k: FileData(*v) for k, v in data.items()}\n except (pickle.UnpicklingError, ValueError, IndexError):\n return cls(mode, cache_file)\n\n return cls(mode, cache_file, file_data)", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 61, "focal_method_end_lineno": 85} {"index": 17, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_write_cache_read_cache", "test_class_name": "TestCaching", "original_test_prefix": " def test_write_cache_read_cache(self) -> None:\n mode = DEFAULT_MODE\n with cache_dir() as workspace:\n src = (workspace / \"test.py\").resolve()\n src.touch()\n write_cache = black.Cache.read(mode)\n write_cache.write([src])\n read_cache = black.Cache.read(mode)\n assert not read_cache.is_changed(src)", "test_prefix": " def test_write_cache_read_cache(self) -> None:\n mode = DEFAULT_MODE\n with cache_dir() as workspace:\n src = (workspace / \"test.py\").resolve()\n src.touch()\n write_cache = black.Cache.read(mode)\n write_cache.write([src])\n read_cache = black.Cache.read(mode)\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2241, "test_prefix_end_lineno": 2249, "test_target": "tests/test_black.py::TestCaching::test_write_cache_read_cache", "ground_truth_oracle": "assert not read_cache.is_changed(src)", "ground_truth_oracle_lineno": 2249, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def is_changed(self, source: Path) -> bool:\n \"\"\"Check if source has changed compared to cached version.\"\"\"\n res_src = source.resolve()\n old = self.file_data.get(str(res_src))\n if old is None:\n return True\n\n st = res_src.stat()\n if st.st_size != old.st_size:\n return True\n if st.st_mtime != old.st_mtime:\n new_hash = Cache.hash_digest(res_src)\n if new_hash != old.hash:\n return True\n return False", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 102, "focal_method_end_lineno": 116} {"index": 18, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_filter_cached", "test_class_name": "TestCaching", "original_test_prefix": " @pytest.mark.incompatible_with_mypyc\n def test_filter_cached(self) -> None:\n with TemporaryDirectory() as workspace:\n path = Path(workspace)\n uncached = (path / \"uncached\").resolve()\n cached = (path / \"cached\").resolve()\n cached_but_changed = (path / \"changed\").resolve()\n uncached.touch()\n cached.touch()\n cached_but_changed.touch()\n cache = black.Cache.read(DEFAULT_MODE)\n\n orig_func = black.Cache.get_file_data\n\n def wrapped_func(path: Path) -> FileData:\n if path == cached:\n return orig_func(path)\n if path == cached_but_changed:\n return FileData(0.0, 0, \"\")\n raise AssertionError\n\n with patch.object(black.Cache, \"get_file_data\", side_effect=wrapped_func):\n cache.write([cached, cached_but_changed])\n todo, done = cache.filtered_cached({uncached, cached, cached_but_changed})\n assert todo == {uncached, cached_but_changed}\n assert done == {cached}", "test_prefix": " @pytest.mark.incompatible_with_mypyc\n def test_filter_cached(self) -> None:\n with TemporaryDirectory() as workspace:\n path = Path(workspace)\n uncached = (path / \"uncached\").resolve()\n cached = (path / \"cached\").resolve()\n cached_but_changed = (path / \"changed\").resolve()\n uncached.touch()\n cached.touch()\n cached_but_changed.touch()\n cache = black.Cache.read(DEFAULT_MODE)\n\n orig_func = black.Cache.get_file_data\n\n def wrapped_func(path: Path) -> FileData:\n if path == cached:\n return orig_func(path)\n if path == cached_but_changed:\n return FileData(0.0, 0, \"\")\n raise AssertionError\n\n with patch.object(black.Cache, \"get_file_data\", side_effect=wrapped_func):\n cache.write([cached, cached_but_changed])\n todo, done = cache.filtered_cached({uncached, cached, cached_but_changed})\n \n assert done == {cached}", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2251, "test_prefix_end_lineno": 2276, "test_target": "tests/test_black.py::TestCaching::test_filter_cached", "ground_truth_oracle": "assert todo == {uncached, cached_but_changed}", "ground_truth_oracle_lineno": 2275, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def filtered_cached(self, sources: Iterable[Path]) -> tuple[set[Path], set[Path]]:\n \"\"\"Split an iterable of paths in `sources` into two sets.\n\n The first contains paths of files that modified on disk or are not in the\n cache. The other contains paths to non-modified files.\n \"\"\"\n changed: set[Path] = set()\n done: set[Path] = set()\n for src in sources:\n if self.is_changed(src):\n changed.add(src)\n else:\n done.add(src)\n return changed, done", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 118, "focal_method_end_lineno": 131} {"index": 19, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_filter_cached_hash", "test_class_name": "TestCaching", "original_test_prefix": " def test_filter_cached_hash(self) -> None:\n with TemporaryDirectory() as workspace:\n path = Path(workspace)\n src = (path / \"test.py\").resolve()\n src.write_text(\"print('hello')\", encoding=\"utf-8\")\n st = src.stat()\n cache = black.Cache.read(DEFAULT_MODE)\n cache.write([src])\n cached_file_data = cache.file_data[str(src)]\n\n todo, done = cache.filtered_cached([src])\n assert todo == set()\n assert done == {src}\n assert cached_file_data.st_mtime == st.st_mtime\n\n # Modify st_mtime\n cached_file_data = cache.file_data[str(src)] = FileData(\n cached_file_data.st_mtime - 1,\n cached_file_data.st_size,\n cached_file_data.hash,\n )\n todo, done = cache.filtered_cached([src])\n assert todo == set()\n assert done == {src}\n assert cached_file_data.st_mtime < st.st_mtime\n assert cached_file_data.st_size == st.st_size\n assert cached_file_data.hash == black.Cache.hash_digest(src)\n\n # Modify contents\n src.write_text(\"print('hello world')\", encoding=\"utf-8\")\n new_st = src.stat()\n todo, done = cache.filtered_cached([src])\n assert todo == {src}\n assert done == set()\n assert cached_file_data.st_mtime < new_st.st_mtime\n assert cached_file_data.st_size != new_st.st_size\n assert cached_file_data.hash != black.Cache.hash_digest(src)", "test_prefix": " def test_filter_cached_hash(self) -> None:\n with TemporaryDirectory() as workspace:\n path = Path(workspace)\n src = (path / \"test.py\").resolve()\n src.write_text(\"print('hello')\", encoding=\"utf-8\")\n st = src.stat()\n cache = black.Cache.read(DEFAULT_MODE)\n cache.write([src])\n cached_file_data = cache.file_data[str(src)]\n\n todo, done = cache.filtered_cached([src])\n assert todo == set()\n assert done == {src}\n \n\n # Modify st_mtime\n cached_file_data = cache.file_data[str(src)] = FileData(\n cached_file_data.st_mtime - 1,\n cached_file_data.st_size,\n cached_file_data.hash,\n )\n todo, done = cache.filtered_cached([src])\n assert todo == set()\n assert done == {src}\n assert cached_file_data.st_mtime < st.st_mtime\n assert cached_file_data.st_size == st.st_size\n assert cached_file_data.hash == black.Cache.hash_digest(src)\n\n # Modify contents\n src.write_text(\"print('hello world')\", encoding=\"utf-8\")\n new_st = src.stat()\n todo, done = cache.filtered_cached([src])\n assert todo == {src}\n assert done == set()\n assert cached_file_data.st_mtime < new_st.st_mtime\n assert cached_file_data.st_size != new_st.st_size\n assert cached_file_data.hash != black.Cache.hash_digest(src)", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2278, "test_prefix_end_lineno": 2314, "test_target": "tests/test_black.py::TestCaching::test_filter_cached_hash", "ground_truth_oracle": "assert cached_file_data.st_mtime == st.st_mtime", "ground_truth_oracle_lineno": 2291, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def filtered_cached(self, sources: Iterable[Path]) -> tuple[set[Path], set[Path]]:\n \"\"\"Split an iterable of paths in `sources` into two sets.\n\n The first contains paths of files that modified on disk or are not in the\n cache. The other contains paths to non-modified files.\n \"\"\"\n changed: set[Path] = set()\n done: set[Path] = set()\n for src in sources:\n if self.is_changed(src):\n changed.add(src)\n else:\n done.add(src)\n return changed, done", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 118, "focal_method_end_lineno": 131} {"index": 20, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_write_cache_creates_directory_if_needed", "test_class_name": "TestCaching", "original_test_prefix": " def test_write_cache_creates_directory_if_needed(self) -> None:\n mode = DEFAULT_MODE\n with cache_dir(exists=False) as workspace:\n assert not workspace.exists()\n cache = black.Cache.read(mode)\n cache.write([])\n assert workspace.exists()", "test_prefix": " def test_write_cache_creates_directory_if_needed(self) -> None:\n mode = DEFAULT_MODE\n with cache_dir(exists=False) as workspace:\n assert not workspace.exists()\n cache = black.Cache.read(mode)\n cache.write([])\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2316, "test_prefix_end_lineno": 2322, "test_target": "tests/test_black.py::TestCaching::test_write_cache_creates_directory_if_needed", "ground_truth_oracle": "assert workspace.exists()", "ground_truth_oracle_lineno": 2322, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def read(cls, mode: Mode) -> Self:\n \"\"\"Read the cache if it exists and is well-formed.\n\n If it is not well-formed, the call to write later should\n resolve the issue.\n \"\"\"\n cache_file = get_cache_file(mode)\n try:\n exists = cache_file.exists()\n except OSError as e:\n # Likely file too long; see #4172 and #4174\n err(f\"Unable to read cache file {cache_file} due to {e}\")\n return cls(mode, cache_file)\n if not exists:\n return cls(mode, cache_file)\n\n with cache_file.open(\"rb\") as fobj:\n try:\n data: dict[str, tuple[float, int, str]] = pickle.load(fobj)\n file_data = {k: FileData(*v) for k, v in data.items()}\n except (pickle.UnpicklingError, ValueError, IndexError):\n return cls(mode, cache_file)\n\n return cls(mode, cache_file, file_data)", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 61, "focal_method_end_lineno": 85} {"index": 21, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_failed_formatting_does_not_get_cached", "test_class_name": "TestCaching", "original_test_prefix": " @event_loop()\n def test_failed_formatting_does_not_get_cached(self) -> None:\n mode = DEFAULT_MODE\n with (\n cache_dir() as workspace,\n patch(\"concurrent.futures.ProcessPoolExecutor\", new=ThreadPoolExecutor),\n ):\n failing = (workspace / \"failing.py\").resolve()\n failing.write_text(\"not actually python\", encoding=\"utf-8\")\n clean = (workspace / \"clean.py\").resolve()\n clean.write_text('print(\"hello\")\\n', encoding=\"utf-8\")\n invokeBlack([str(workspace)], exit_code=123)\n cache = black.Cache.read(mode)\n assert cache.is_changed(failing)\n assert not cache.is_changed(clean)", "test_prefix": " @event_loop()\n def test_failed_formatting_does_not_get_cached(self) -> None:\n mode = DEFAULT_MODE\n with (\n cache_dir() as workspace,\n patch(\"concurrent.futures.ProcessPoolExecutor\", new=ThreadPoolExecutor),\n ):\n failing = (workspace / \"failing.py\").resolve()\n failing.write_text(\"not actually python\", encoding=\"utf-8\")\n clean = (workspace / \"clean.py\").resolve()\n clean.write_text('print(\"hello\")\\n', encoding=\"utf-8\")\n invokeBlack([str(workspace)], exit_code=123)\n cache = black.Cache.read(mode)\n assert cache.is_changed(failing)\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2324, "test_prefix_end_lineno": 2338, "test_target": "tests/test_black.py::TestCaching::test_failed_formatting_does_not_get_cached", "ground_truth_oracle": "assert not cache.is_changed(clean)", "ground_truth_oracle_lineno": 2338, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def is_changed(self, source: Path) -> bool:\n \"\"\"Check if source has changed compared to cached version.\"\"\"\n res_src = source.resolve()\n old = self.file_data.get(str(res_src))\n if old is None:\n return True\n\n st = res_src.stat()\n if st.st_size != old.st_size:\n return True\n if st.st_mtime != old.st_mtime:\n new_hash = Cache.hash_digest(res_src)\n if new_hash != old.hash:\n return True\n return False", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 102, "focal_method_end_lineno": 116} {"index": 22, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_read_cache_line_lengths", "test_class_name": "TestCaching", "original_test_prefix": " def test_read_cache_line_lengths(self) -> None:\n mode = DEFAULT_MODE\n short_mode = replace(DEFAULT_MODE, line_length=1)\n with cache_dir() as workspace:\n path = (workspace / \"file.py\").resolve()\n path.touch()\n cache = black.Cache.read(mode)\n cache.write([path])\n one = black.Cache.read(mode)\n assert not one.is_changed(path)\n two = black.Cache.read(short_mode)\n assert two.is_changed(path)", "test_prefix": " def test_read_cache_line_lengths(self) -> None:\n mode = DEFAULT_MODE\n short_mode = replace(DEFAULT_MODE, line_length=1)\n with cache_dir() as workspace:\n path = (workspace / \"file.py\").resolve()\n path.touch()\n cache = black.Cache.read(mode)\n cache.write([path])\n one = black.Cache.read(mode)\n \n two = black.Cache.read(short_mode)\n assert two.is_changed(path)", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2348, "test_prefix_end_lineno": 2359, "test_target": "tests/test_black.py::TestCaching::test_read_cache_line_lengths", "ground_truth_oracle": "assert not one.is_changed(path)", "ground_truth_oracle_lineno": 2357, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def is_changed(self, source: Path) -> bool:\n \"\"\"Check if source has changed compared to cached version.\"\"\"\n res_src = source.resolve()\n old = self.file_data.get(str(res_src))\n if old is None:\n return True\n\n st = res_src.stat()\n if st.st_size != old.st_size:\n return True\n if st.st_mtime != old.st_mtime:\n new_hash = Cache.hash_digest(res_src)\n if new_hash != old.hash:\n return True\n return False", "focal_method_file_path": "src/black/cache.py", "focal_method_start_lineno": 102, "focal_method_end_lineno": 116} {"index": 23, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_cache_key", "test_class_name": "TestCaching", "original_test_prefix": " def test_cache_key(self) -> None:\n # Test that all members of the mode enum affect the cache key.\n for field in fields(Mode):\n values: list[Any]\n if field.name == \"target_versions\":\n values = [\n {TargetVersion.PY312},\n {TargetVersion.PY313},\n ]\n elif field.name == \"python_cell_magics\":\n values = [{\"magic1\"}, {\"magic2\"}]\n elif field.name == \"enabled_features\":\n # If you are looking to remove one of these features, just\n # replace it with any other feature.\n values = [\n {Preview.multiline_string_handling},\n {Preview.string_processing},\n ]\n elif field.type is bool:\n values = [True, False]\n elif field.type is int:\n values = [1, 2]\n else:\n raise AssertionError(\n f\"Unhandled field type: {field.type} for field {field.name}\"\n )\n modes = [replace(DEFAULT_MODE, **{field.name: value}) for value in values]\n keys = [mode.get_cache_key() for mode in modes]\n assert len(set(keys)) == len(modes)", "test_prefix": " def test_cache_key(self) -> None:\n # Test that all members of the mode enum affect the cache key.\n for field in fields(Mode):\n values: list[Any]\n if field.name == \"target_versions\":\n values = [\n {TargetVersion.PY312},\n {TargetVersion.PY313},\n ]\n elif field.name == \"python_cell_magics\":\n values = [{\"magic1\"}, {\"magic2\"}]\n elif field.name == \"enabled_features\":\n # If you are looking to remove one of these features, just\n # replace it with any other feature.\n values = [\n {Preview.multiline_string_handling},\n {Preview.string_processing},\n ]\n elif field.type is bool:\n values = [True, False]\n elif field.type is int:\n values = [1, 2]\n else:\n raise AssertionError(\n f\"Unhandled field type: {field.type} for field {field.name}\"\n )\n modes = [replace(DEFAULT_MODE, **{field.name: value}) for value in values]\n keys = [mode.get_cache_key() for mode in modes]\n ", "test_prefix_file_path": "tests/test_black.py", "test_prefix_start_lineno": 2361, "test_prefix_end_lineno": 2389, "test_target": "tests/test_black.py::TestCaching::test_cache_key", "ground_truth_oracle": "assert len(set(keys)) == len(modes)", "ground_truth_oracle_lineno": 2389, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_cache_key(self) -> str:\n if self.target_versions:\n version_str = \",\".join(\n str(version.value)\n for version in sorted(self.target_versions, key=attrgetter(\"value\"))\n )\n else:\n version_str = \"-\"\n if len(version_str) > _MAX_CACHE_KEY_PART_LENGTH:\n version_str = sha256(version_str.encode()).hexdigest()[\n :_MAX_CACHE_KEY_PART_LENGTH\n ]\n features_and_magics = (\n \",\".join(sorted(f.name for f in self.enabled_features))\n + \"@\"\n + \",\".join(sorted(self.python_cell_magics))\n )\n if len(features_and_magics) > _MAX_CACHE_KEY_PART_LENGTH:\n features_and_magics = sha256(features_and_magics.encode()).hexdigest()[\n :_MAX_CACHE_KEY_PART_LENGTH\n ]\n parts = [\n version_str,\n str(self.line_length),\n str(int(self.string_normalization)),\n str(int(self.is_pyi)),\n str(int(self.is_ipynb)),\n str(int(self.skip_source_first_line)),\n str(int(self.magic_trailing_comma)),\n str(int(self.preview)),\n str(int(self.unstable)),\n features_and_magics,\n ]\n return \".\".join(parts)", "focal_method_file_path": "src/black/mode.py", "focal_method_start_lineno": 286, "focal_method_end_lineno": 319} {"index": 24, "repo_name": "black", "github": "https://github.com/psf/black.git", "version": "25.9.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r test_requirements.txt\npip install -e .\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_fexpr_spans", "test_class_name": "", "original_test_prefix": "def test_fexpr_spans() -> None:\n def check(\n string: str, expected_spans: list[tuple[int, int]], expected_slices: list[str]\n ) -> None:\n spans = list(iter_fexpr_spans(string))\n\n # Checking slices isn't strictly necessary, but it's easier to verify at\n # a glance than only spans\n assert len(spans) == len(expected_slices)\n for (i, j), slice in zip(spans, expected_slices):\n assert 0 <= i <= j <= len(string)\n assert string[i:j] == slice\n\n assert spans == expected_spans\n\n # Most of these test cases omit the leading 'f' and leading / closing quotes\n # for convenience\n # Some additional property-based tests can be found in\n # https://github.com/psf/black/pull/2654#issuecomment-981411748\n check(\"\"\"{var}\"\"\", [(0, 5)], [\"{var}\"])\n check(\"\"\"f'{var}'\"\"\", [(2, 7)], [\"{var}\"])\n check(\"\"\"f'{1 + f() + 2 + \"asdf\"}'\"\"\", [(2, 24)], [\"\"\"{1 + f() + 2 + \"asdf\"}\"\"\"])\n check(\"\"\"text {var} text\"\"\", [(5, 10)], [\"{var}\"])\n check(\"\"\"text {{ {var} }} text\"\"\", [(8, 13)], [\"{var}\"])\n check(\"\"\"{a} {b} {c}\"\"\", [(0, 3), (4, 7), (8, 11)], [\"{a}\", \"{b}\", \"{c}\"])\n check(\"\"\"f'{a} {b} {c}'\"\"\", [(2, 5), (6, 9), (10, 13)], [\"{a}\", \"{b}\", \"{c}\"])\n check(\"\"\"{ {} }\"\"\", [(0, 6)], [\"{ {} }\"])\n check(\"\"\"{ {{}} }\"\"\", [(0, 8)], [\"{ {{}} }\"])\n check(\"\"\"{ {{{}}} }\"\"\", [(0, 10)], [\"{ {{{}}} }\"])\n check(\"\"\"{{ {{{}}} }}\"\"\", [(5, 7)], [\"{}\"])\n check(\"\"\"{{ {{{var}}} }}\"\"\", [(5, 10)], [\"{var}\"])\n check(\"\"\"{f\"{0}\"}\"\"\", [(0, 8)], [\"\"\"{f\"{0}\"}\"\"\"])\n check(\"\"\"{\"'\"}\"\"\", [(0, 5)], [\"\"\"{\"'\"}\"\"\"])\n check(\"\"\"{\"{\"}\"\"\", [(0, 5)], [\"\"\"{\"{\"}\"\"\"])\n check(\"\"\"{\"}\"}\"\"\", [(0, 5)], [\"\"\"{\"}\"}\"\"\"])\n check(\"\"\"{\"{{\"}\"\"\", [(0, 6)], [\"\"\"{\"{{\"}\"\"\"])\n check(\"\"\"{''' '''}\"\"\", [(0, 9)], [\"\"\"{''' '''}\"\"\"])\n check(\"\"\"{'''{'''}\"\"\", [(0, 9)], [\"\"\"{'''{'''}\"\"\"])\n check(\"\"\"{''' {'{ '''}\"\"\", [(0, 13)], [\"\"\"{''' {'{ '''}\"\"\"])\n check(\n '''f\\'\\'\\'-{f\"\"\"*{f\"+{f'.{x}.'}+\"}*\"\"\"}-'y\\\\'\\'\\'\\'''',\n [(5, 33)],\n ['''{f\"\"\"*{f\"+{f'.{x}.'}+\"}*\"\"\"}'''],\n )\n check(r\"\"\"{}{\"\"\", [(0, 2)], [\"{}\"])\n check(\"\"\"f\"{'{'''''''''}\\\"\"\"\", [(2, 15)], [\"{'{'''''''''}\"])", "test_prefix": "def test_fexpr_spans() -> None:\n def check(\n string: str, expected_spans: list[tuple[int, int]], expected_slices: list[str]\n ) -> None:\n spans = list(iter_fexpr_spans(string))\n\n # Checking slices isn't strictly necessary, but it's easier to verify at\n # a glance than only spans\n \n for (i, j), slice in zip(spans, expected_slices):\n assert 0 <= i <= j <= len(string)\n assert string[i:j] == slice\n\n assert spans == expected_spans\n\n # Most of these test cases omit the leading 'f' and leading / closing quotes\n # for convenience\n # Some additional property-based tests can be found in\n # https://github.com/psf/black/pull/2654#issuecomment-981411748\n check(\"\"\"{var}\"\"\", [(0, 5)], [\"{var}\"])\n check(\"\"\"f'{var}'\"\"\", [(2, 7)], [\"{var}\"])\n check(\"\"\"f'{1 + f() + 2 + \"asdf\"}'\"\"\", [(2, 24)], [\"\"\"{1 + f() + 2 + \"asdf\"}\"\"\"])\n check(\"\"\"text {var} text\"\"\", [(5, 10)], [\"{var}\"])\n check(\"\"\"text {{ {var} }} text\"\"\", [(8, 13)], [\"{var}\"])\n check(\"\"\"{a} {b} {c}\"\"\", [(0, 3), (4, 7), (8, 11)], [\"{a}\", \"{b}\", \"{c}\"])\n check(\"\"\"f'{a} {b} {c}'\"\"\", [(2, 5), (6, 9), (10, 13)], [\"{a}\", \"{b}\", \"{c}\"])\n check(\"\"\"{ {} }\"\"\", [(0, 6)], [\"{ {} }\"])\n check(\"\"\"{ {{}} }\"\"\", [(0, 8)], [\"{ {{}} }\"])\n check(\"\"\"{ {{{}}} }\"\"\", [(0, 10)], [\"{ {{{}}} }\"])\n check(\"\"\"{{ {{{}}} }}\"\"\", [(5, 7)], [\"{}\"])\n check(\"\"\"{{ {{{var}}} }}\"\"\", [(5, 10)], [\"{var}\"])\n check(\"\"\"{f\"{0}\"}\"\"\", [(0, 8)], [\"\"\"{f\"{0}\"}\"\"\"])\n check(\"\"\"{\"'\"}\"\"\", [(0, 5)], [\"\"\"{\"'\"}\"\"\"])\n check(\"\"\"{\"{\"}\"\"\", [(0, 5)], [\"\"\"{\"{\"}\"\"\"])\n check(\"\"\"{\"}\"}\"\"\", [(0, 5)], [\"\"\"{\"}\"}\"\"\"])\n check(\"\"\"{\"{{\"}\"\"\", [(0, 6)], [\"\"\"{\"{{\"}\"\"\"])\n check(\"\"\"{''' '''}\"\"\", [(0, 9)], [\"\"\"{''' '''}\"\"\"])\n check(\"\"\"{'''{'''}\"\"\", [(0, 9)], [\"\"\"{'''{'''}\"\"\"])\n check(\"\"\"{''' {'{ '''}\"\"\", [(0, 13)], [\"\"\"{''' {'{ '''}\"\"\"])\n check(\n '''f\\'\\'\\'-{f\"\"\"*{f\"+{f'.{x}.'}+\"}*\"\"\"}-'y\\\\'\\'\\'\\'''',\n [(5, 33)],\n ['''{f\"\"\"*{f\"+{f'.{x}.'}+\"}*\"\"\"}'''],\n )\n check(r\"\"\"{}{\"\"\", [(0, 2)], [\"{}\"])\n check(\"\"\"f\"{'{'''''''''}\\\"\"\"\", [(2, 15)], [\"{'{'''''''''}\"])", "test_prefix_file_path": "tests/test_trans.py", "test_prefix_start_lineno": 4, "test_prefix_end_lineno": 49, "test_target": "tests/test_trans.py::test_fexpr_spans", "ground_truth_oracle": "assert len(spans) == len(expected_slices)", "ground_truth_oracle_lineno": 12, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def iter_fexpr_spans(s: str) -> Iterator[tuple[int, int]]:\n \"\"\"\n Yields spans corresponding to expressions in a given f-string.\n Spans are half-open ranges (left inclusive, right exclusive).\n Assumes the input string is a valid f-string, but will not crash if the input\n string is invalid.\n \"\"\"\n stack: list[int] = [] # our curly paren stack\n i = 0\n while i < len(s):\n if s[i] == \"{\":\n # if we're in a string part of the f-string, ignore escaped curly braces\n if not stack and i + 1 < len(s) and s[i + 1] == \"{\":\n i += 2\n continue\n stack.append(i)\n i += 1\n continue\n\n if s[i] == \"}\":\n if not stack:\n i += 1\n continue\n j = stack.pop()\n # we've made it back out of the expression! yield the span\n if not stack:\n yield (j, i + 1)\n i += 1\n continue\n\n # if we're in an expression part of the f-string, fast-forward through strings\n # note that backslashes are not legal in the expression portion of f-strings\n if stack:\n delim = None\n if s[i : i + 3] in (\"'''\", '\"\"\"'):\n delim = s[i : i + 3]\n elif s[i] in (\"'\", '\"'):\n delim = s[i]\n if delim:\n i += len(delim)\n while i < len(s) and s[i : i + len(delim)] != delim:\n i += 1\n i += len(delim)\n continue\n i += 1", "focal_method_file_path": "src/black/trans.py", "focal_method_start_lineno": 1309, "focal_method_end_lineno": 1353} {"index": 25, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_buffer_protocol", "test_class_name": "TestConcatKDFHash", "original_test_prefix": " def test_buffer_protocol(self, backend):\n prk = binascii.unhexlify(\n b\"52169af5c485dcc2321eb8d26d5efa21fb9b93c98e38412ee2484cf14f0d0d23\"\n )\n\n okm = binascii.unhexlify(b\"1c3bc9e7c4547c5191c0d478cccaed55\")\n\n oinfo = binascii.unhexlify(\n b\"a1b2c3d4e53728157e634612c12d6d5223e204aeea4341565369647bd184bcd2\"\n b\"46f72971f292badaa2fe4124612cba\"\n )\n\n ckdf = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend)\n\n assert ckdf.derive(bytearray(prk)) == okm", "test_prefix": " def test_buffer_protocol(self, backend):\n prk = binascii.unhexlify(\n b\"52169af5c485dcc2321eb8d26d5efa21fb9b93c98e38412ee2484cf14f0d0d23\"\n )\n\n okm = binascii.unhexlify(b\"1c3bc9e7c4547c5191c0d478cccaed55\")\n\n oinfo = binascii.unhexlify(\n b\"a1b2c3d4e53728157e634612c12d6d5223e204aeea4341565369647bd184bcd2\"\n b\"46f72971f292badaa2fe4124612cba\"\n )\n\n ckdf = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend)\n\n ", "test_prefix_file_path": "tests/hazmat/primitives/test_concatkdf.py", "test_prefix_start_lineno": 49, "test_prefix_end_lineno": 63, "test_target": "tests/hazmat/primitives/test_concatkdf.py::TestConcatKDFHash::test_buffer_protocol", "ground_truth_oracle": "assert ckdf.derive(bytearray(prk)) == okm", "ground_truth_oracle_lineno": 63, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def derive(self, key_material: utils.Buffer) -> bytes:\n if self._used:\n raise AlreadyFinalized\n self._used = True\n return _concatkdf_derive(\n key_material, self._length, self._hash, self._otherinfo\n )", "focal_method_file_path": "src/cryptography/hazmat/primitives/kdf/concatkdf.py", "focal_method_start_lineno": 73, "focal_method_end_lineno": 79} {"index": 26, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_eq", "test_class_name": "TestUserNotice", "original_test_prefix": " def test_eq(self):\n nr = x509.NoticeReference(\"org\", [1, 2])\n nr2 = x509.NoticeReference(\"org\", [1, 2])\n un = x509.UserNotice(nr, \"text\")\n un2 = x509.UserNotice(nr2, \"text\")\n assert un == un2", "test_prefix": " def test_eq(self):\n nr = x509.NoticeReference(\"org\", [1, 2])\n nr2 = x509.NoticeReference(\"org\", [1, 2])\n un = x509.UserNotice(nr, \"text\")\n un2 = x509.UserNotice(nr2, \"text\")\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 530, "test_prefix_end_lineno": 535, "test_target": "tests/x509/test_x509_ext.py::TestUserNotice::test_eq", "ground_truth_oracle": "assert un == un2", "ground_truth_oracle_lineno": 535, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class UserNotice:\n def __init__(\n self,\n notice_reference: NoticeReference | None,\n explicit_text: str | None,\n ) -> None:\n if notice_reference and not isinstance(\n notice_reference, NoticeReference\n ):\n raise TypeError(\n \"notice_reference must be None or a NoticeReference\"\n )\n\n self._notice_reference = notice_reference\n self._explicit_text = explicit_text\n\n def __repr__(self) -> str:\n return (\n f\"\"\n )\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, UserNotice):\n return NotImplemented\n\n return (\n self.notice_reference == other.notice_reference\n and self.explicit_text == other.explicit_text\n )\n\n def __hash__(self) -> int:\n return hash((self.notice_reference, self.explicit_text))\n\n @property\n def notice_reference(self) -> NoticeReference | None:\n return self._notice_reference\n\n @property\n def explicit_text(self) -> str | None:\n return self._explicit_text", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 905, "focal_method_end_lineno": 945} {"index": 27, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_add_multiple_extensions", "test_class_name": "TestRevokedCertificateBuilder", "original_test_prefix": " def test_add_multiple_extensions(self, backend):\n serial_number = 333\n revocation_date = datetime.datetime(2002, 1, 1, 12, 1)\n invalidity_date = x509.InvalidityDate(\n datetime.datetime(2015, 1, 1, 0, 0)\n )\n certificate_issuer = x509.CertificateIssuer(\n [x509.DNSName(\"cryptography.io\")]\n )\n crl_reason = x509.CRLReason(x509.ReasonFlags.aa_compromise)\n builder = (\n x509.RevokedCertificateBuilder()\n .serial_number(serial_number)\n .revocation_date(revocation_date)\n .add_extension(invalidity_date, True)\n .add_extension(crl_reason, True)\n .add_extension(certificate_issuer, True)\n )\n\n revoked_certificate = builder.build(backend)\n assert len(revoked_certificate.extensions) == 3\n for ext_data in [invalidity_date, certificate_issuer, crl_reason]:\n ext = revoked_certificate.extensions.get_extension_for_class(\n type(ext_data)\n )\n assert ext.critical is True\n assert ext.value == ext_data", "test_prefix": " def test_add_multiple_extensions(self, backend):\n serial_number = 333\n revocation_date = datetime.datetime(2002, 1, 1, 12, 1)\n invalidity_date = x509.InvalidityDate(\n datetime.datetime(2015, 1, 1, 0, 0)\n )\n certificate_issuer = x509.CertificateIssuer(\n [x509.DNSName(\"cryptography.io\")]\n )\n crl_reason = x509.CRLReason(x509.ReasonFlags.aa_compromise)\n builder = (\n x509.RevokedCertificateBuilder()\n .serial_number(serial_number)\n .revocation_date(revocation_date)\n .add_extension(invalidity_date, True)\n .add_extension(crl_reason, True)\n .add_extension(certificate_issuer, True)\n )\n\n revoked_certificate = builder.build(backend)\n assert len(revoked_certificate.extensions) == 3\n for ext_data in [invalidity_date, certificate_issuer, crl_reason]:\n ext = revoked_certificate.extensions.get_extension_for_class(\n type(ext_data)\n )\n \n assert ext.value == ext_data", "test_prefix_file_path": "tests/x509/test_x509_revokedcertbuilder.py", "test_prefix_start_lineno": 179, "test_prefix_end_lineno": 205, "test_target": "tests/x509/test_x509_revokedcertbuilder.py::TestRevokedCertificateBuilder::test_add_multiple_extensions", "ground_truth_oracle": "assert ext.critical is True", "ground_truth_oracle_lineno": 204, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_extension_for_class(\n self, extclass: type[ExtensionTypeVar]\n ) -> Extension[ExtensionTypeVar]:\n if extclass is UnrecognizedExtension:\n raise TypeError(\n \"UnrecognizedExtension can't be used with \"\n \"get_extension_for_class because more than one instance of the\"\n \" class may be present.\"\n )\n\n for ext in self:\n if isinstance(ext.value, extclass):\n return ext\n\n raise ExtensionNotFound(\n f\"No {extclass} extension was found\", extclass.oid\n )", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 125, "focal_method_end_lineno": 141} {"index": 28, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ipaddress", "test_class_name": "TestRSASubjectAlternativeNameExtension", "original_test_prefix": " def test_ipaddress(self, backend):\n cert = _load_cert(\n os.path.join(\"x509\", \"custom\", \"san_ipaddr.pem\"),\n x509.load_pem_x509_certificate,\n )\n ext = cert.extensions.get_extension_for_class(\n x509.SubjectAlternativeName\n )\n assert ext is not None\n assert ext.critical is False\n\n san = ext.value\n\n ip = san.get_values_for_type(x509.IPAddress)\n assert [\n ipaddress.ip_address(\"127.0.0.1\"),\n ipaddress.ip_address(\"ff::\"),\n ] == ip", "test_prefix": " def test_ipaddress(self, backend):\n cert = _load_cert(\n os.path.join(\"x509\", \"custom\", \"san_ipaddr.pem\"),\n x509.load_pem_x509_certificate,\n )\n ext = cert.extensions.get_extension_for_class(\n x509.SubjectAlternativeName\n )\n assert ext is not None\n \n\n san = ext.value\n\n ip = san.get_values_for_type(x509.IPAddress)\n assert [\n ipaddress.ip_address(\"127.0.0.1\"),\n ipaddress.ip_address(\"ff::\"),\n ] == ip", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 2751, "test_prefix_end_lineno": 2768, "test_target": "tests/x509/test_x509_ext.py::TestRSASubjectAlternativeNameExtension::test_ipaddress", "ground_truth_oracle": "assert ext.critical is False", "ground_truth_oracle_lineno": 2760, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_extension_for_class(\n self, extclass: type[ExtensionTypeVar]\n ) -> Extension[ExtensionTypeVar]:\n if extclass is UnrecognizedExtension:\n raise TypeError(\n \"UnrecognizedExtension can't be used with \"\n \"get_extension_for_class because more than one instance of the\"\n \" class may be present.\"\n )\n\n for ext in self:\n if isinstance(ext.value, extclass):\n return ext\n\n raise ExtensionNotFound(\n f\"No {extclass} extension was found\", extclass.oid\n )", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 125, "focal_method_end_lineno": 141} {"index": 29, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_hash", "test_class_name": "TestOtherName", "original_test_prefix": " def test_hash(self):\n gn = x509.OtherName(x509.ObjectIdentifier(\"1.2.3.4\"), b\"derdata\")\n gn2 = x509.OtherName(x509.ObjectIdentifier(\"1.2.3.4\"), b\"derdata\")\n gn3 = x509.OtherName(x509.ObjectIdentifier(\"1.2.3.5\"), b\"derdata\")\n assert hash(gn) == hash(gn2)\n assert hash(gn) != hash(gn3)", "test_prefix": " def test_hash(self):\n gn = x509.OtherName(x509.ObjectIdentifier(\"1.2.3.4\"), b\"derdata\")\n gn2 = x509.OtherName(x509.ObjectIdentifier(\"1.2.3.4\"), b\"derdata\")\n gn3 = x509.OtherName(x509.ObjectIdentifier(\"1.2.3.5\"), b\"derdata\")\n \n assert hash(gn) != hash(gn3)", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 2379, "test_prefix_end_lineno": 2384, "test_target": "tests/x509/test_x509_ext.py::TestOtherName::test_hash", "ground_truth_oracle": "assert hash(gn) == hash(gn2)", "ground_truth_oracle_lineno": 2383, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class OtherName(GeneralName):\n def __init__(self, type_id: ObjectIdentifier, value: bytes) -> None:\n if not isinstance(type_id, ObjectIdentifier):\n raise TypeError(\"type_id must be an ObjectIdentifier\")\n if not isinstance(value, bytes):\n raise TypeError(\"value must be a binary string\")\n\n self._type_id = type_id\n self._value = value\n\n @property\n def type_id(self) -> ObjectIdentifier:\n return self._type_id\n\n @property\n def value(self) -> bytes:\n return self._value\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, OtherName):\n return NotImplemented\n\n return self.type_id == other.type_id and self.value == other.value\n\n def __hash__(self) -> int:\n return hash((self.type_id, self.value))", "focal_method_file_path": "src/cryptography/x509/general_name.py", "focal_method_start_lineno": 253, "focal_method_end_lineno": 281} {"index": 30, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_hash", "test_class_name": "TestUniformResourceIdentifier", "original_test_prefix": " def test_hash(self):\n g1 = x509.UniformResourceIdentifier(\"http://host.com\")\n g2 = x509.UniformResourceIdentifier(\"http://host.com\")\n g3 = x509.UniformResourceIdentifier(\"http://other.com\")\n\n assert hash(g1) == hash(g2)\n assert hash(g1) != hash(g3)", "test_prefix": " def test_hash(self):\n g1 = x509.UniformResourceIdentifier(\"http://host.com\")\n g2 = x509.UniformResourceIdentifier(\"http://host.com\")\n g3 = x509.UniformResourceIdentifier(\"http://other.com\")\n\n \n assert hash(g1) != hash(g3)", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 2250, "test_prefix_end_lineno": 2256, "test_target": "tests/x509/test_x509_ext.py::TestUniformResourceIdentifier::test_hash", "ground_truth_oracle": "assert hash(g1) == hash(g2)", "ground_truth_oracle_lineno": 2255, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class UniformResourceIdentifier(GeneralName):\n def __init__(self, value: str) -> None:\n if isinstance(value, str):\n try:\n value.encode(\"ascii\")\n except UnicodeEncodeError:\n raise ValueError(\n \"URI values should be passed as an A-label string. \"\n \"This means unicode characters should be encoded via \"\n \"a library like idna.\"\n )\n else:\n raise TypeError(\"value must be string\")\n\n self._value = value\n\n @property\n def value(self) -> str:\n return self._value\n\n @classmethod\n def _init_without_validation(cls, value: str) -> UniformResourceIdentifier:\n instance = cls.__new__(cls)\n instance._value = value\n return instance\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, UniformResourceIdentifier):\n return NotImplemented\n\n return self.value == other.value\n\n def __hash__(self) -> int:\n return hash(self.value)", "focal_method_file_path": "src/cryptography/x509/general_name.py", "focal_method_start_lineno": 120, "focal_method_end_lineno": 156} {"index": 31, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_eq", "test_class_name": "TestSubjectKeyIdentifier", "original_test_prefix": " def test_eq(self):\n ski = x509.SubjectKeyIdentifier(\n binascii.unhexlify(b\"092384932230498bc980aa8098456f6ff7ff3ac9\")\n )\n ski2 = x509.SubjectKeyIdentifier(\n binascii.unhexlify(b\"092384932230498bc980aa8098456f6ff7ff3ac9\")\n )\n assert ski == ski2", "test_prefix": " def test_eq(self):\n ski = x509.SubjectKeyIdentifier(\n binascii.unhexlify(b\"092384932230498bc980aa8098456f6ff7ff3ac9\")\n )\n ski2 = x509.SubjectKeyIdentifier(\n binascii.unhexlify(b\"092384932230498bc980aa8098456f6ff7ff3ac9\")\n )\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 1200, "test_prefix_end_lineno": 1207, "test_target": "tests/x509/test_x509_ext.py::TestSubjectKeyIdentifier::test_eq", "ground_truth_oracle": "assert ski == ski2", "ground_truth_oracle_lineno": 1207, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class SubjectKeyIdentifier(ExtensionType):\n oid = ExtensionOID.SUBJECT_KEY_IDENTIFIER\n\n def __init__(self, digest: bytes) -> None:\n self._digest = digest\n\n @classmethod\n def from_public_key(\n cls, public_key: CertificatePublicKeyTypes\n ) -> SubjectKeyIdentifier:\n return cls(_key_identifier_from_public_key(public_key))\n\n @property\n def digest(self) -> bytes:\n return self._digest\n\n @property\n def key_identifier(self) -> bytes:\n return self._digest\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, SubjectKeyIdentifier):\n return NotImplemented\n\n return constant_time.bytes_eq(self.digest, other.digest)\n\n def __hash__(self) -> int:\n return hash(self.digest)\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 286, "focal_method_end_lineno": 319} {"index": 32, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_iter_input", "test_class_name": "TestNoticeReference", "original_test_prefix": " def test_iter_input(self):\n numbers = [1, 3, 4]\n nr = x509.NoticeReference(\"org\", iter(numbers))\n assert list(nr.notice_numbers) == numbers", "test_prefix": " def test_iter_input(self):\n numbers = [1, 3, 4]\n nr = x509.NoticeReference(\"org\", iter(numbers))\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 480, "test_prefix_end_lineno": 483, "test_target": "tests/x509/test_x509_ext.py::TestNoticeReference::test_iter_input", "ground_truth_oracle": "assert list(nr.notice_numbers) == numbers", "ground_truth_oracle_lineno": 483, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class NoticeReference:\n def __init__(\n self,\n organization: str | None,\n notice_numbers: Iterable[int],\n ) -> None:\n self._organization = organization\n notice_numbers = list(notice_numbers)\n if not all(isinstance(x, int) for x in notice_numbers):\n raise TypeError(\"notice_numbers must be a list of integers\")\n\n self._notice_numbers = notice_numbers\n\n def __repr__(self) -> str:\n return (\n f\"\"\n )\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, NoticeReference):\n return NotImplemented\n\n return (\n self.organization == other.organization\n and self.notice_numbers == other.notice_numbers\n )\n\n def __hash__(self) -> int:\n return hash((self.organization, tuple(self.notice_numbers)))\n\n @property\n def organization(self) -> str | None:\n return self._organization\n\n @property\n def notice_numbers(self) -> list[int]:\n return self._notice_numbers", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 948, "focal_method_end_lineno": 985} {"index": 33, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_key_equality", "test_class_name": "", "original_test_prefix": "@pytest.mark.supported(\n only_if=lambda backend: backend.x25519_supported(),\n skip_message=\"Requires OpenSSL with X25519 support\",\n)\ndef test_public_key_equality(backend):\n key_bytes = load_vectors_from_file(\n os.path.join(\"asymmetric\", \"X25519\", \"x25519-pkcs8.der\"),\n lambda derfile: derfile.read(),\n mode=\"rb\",\n )\n key1 = serialization.load_der_private_key(key_bytes, None).public_key()\n key2 = serialization.load_der_private_key(key_bytes, None).public_key()\n key3 = X25519PrivateKey.generate().public_key()\n assert key1 == key2\n assert key1 != key3\n assert key1 != object()\n with pytest.raises(TypeError):\n key1 < key2 # type: ignore[operator]", "test_prefix": "@pytest.mark.supported(\n only_if=lambda backend: backend.x25519_supported(),\n skip_message=\"Requires OpenSSL with X25519 support\",\n)\ndef test_public_key_equality(backend):\n key_bytes = load_vectors_from_file(\n os.path.join(\"asymmetric\", \"X25519\", \"x25519-pkcs8.der\"),\n lambda derfile: derfile.read(),\n mode=\"rb\",\n )\n key1 = serialization.load_der_private_key(key_bytes, None).public_key()\n key2 = serialization.load_der_private_key(key_bytes, None).public_key()\n key3 = X25519PrivateKey.generate().public_key()\n assert key1 == key2\n \n assert key1 != object()\n with pytest.raises(TypeError):\n key1 < key2 # type: ignore[operator]", "test_prefix_file_path": "tests/hazmat/primitives/test_x25519.py", "test_prefix_start_lineno": 346, "test_prefix_end_lineno": 363, "test_target": "tests/hazmat/primitives/test_x25519.py::test_public_key_equality", "ground_truth_oracle": "assert key1 != key3", "ground_truth_oracle_lineno": 360, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @abc.abstractmethod\n def public_key(self) -> X25519PublicKey:\n \"\"\"\n Returns the public key associated with this private key\n \"\"\"", "focal_method_file_path": "src/cryptography/hazmat/primitives/asymmetric/x25519.py", "focal_method_start_lineno": 85, "focal_method_end_lineno": 89} {"index": 34, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ne", "test_class_name": "TestDeltaCRLIndicator", "original_test_prefix": " def test_ne(self):\n delta1 = x509.DeltaCRLIndicator(1)\n delta2 = x509.DeltaCRLIndicator(2)\n assert delta1 != delta2\n assert delta1 != object()", "test_prefix": " def test_ne(self):\n delta1 = x509.DeltaCRLIndicator(1)\n delta2 = x509.DeltaCRLIndicator(2)\n \n assert delta1 != object()", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 392, "test_prefix_end_lineno": 396, "test_target": "tests/x509/test_x509_ext.py::TestDeltaCRLIndicator::test_ne", "ground_truth_oracle": "assert delta1 != delta2", "ground_truth_oracle_lineno": 395, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class DeltaCRLIndicator(ExtensionType):\n oid = ExtensionOID.DELTA_CRL_INDICATOR\n\n def __init__(self, crl_number: int) -> None:\n if not isinstance(crl_number, int):\n raise TypeError(\"crl_number must be an integer\")\n\n self._crl_number = crl_number\n\n @property\n def crl_number(self) -> int:\n return self._crl_number\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, DeltaCRLIndicator):\n return NotImplemented\n\n return self.crl_number == other.crl_number\n\n def __hash__(self) -> int:\n return hash(self.crl_number)\n\n def __repr__(self) -> str:\n return f\"\"\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 470, "focal_method_end_lineno": 496} {"index": 35, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_zany_py2_bytes_subclass", "test_class_name": "TestPKCS7", "original_test_prefix": " def test_zany_py2_bytes_subclass(self):\n class mybytes(bytes): # noqa: N801\n def __str__(self):\n return \"broken\"\n\n str(mybytes())\n padder = padding.PKCS7(128).padder()\n data = padder.update(mybytes(b\"abc\")) + padder.finalize()\n unpadder = padding.PKCS7(128).unpadder()\n unpadder.update(mybytes(data))\n assert unpadder.finalize() == b\"abc\"", "test_prefix": " def test_zany_py2_bytes_subclass(self):\n class mybytes(bytes): # noqa: N801\n def __str__(self):\n return \"broken\"\n\n str(mybytes())\n padder = padding.PKCS7(128).padder()\n data = padder.update(mybytes(b\"abc\")) + padder.finalize()\n unpadder = padding.PKCS7(128).unpadder()\n unpadder.update(mybytes(data))\n ", "test_prefix_file_path": "tests/hazmat/primitives/test_padding.py", "test_prefix_start_lineno": 43, "test_prefix_end_lineno": 53, "test_target": "tests/hazmat/primitives/test_padding.py::TestPKCS7::test_zany_py2_bytes_subclass", "ground_truth_oracle": "assert unpadder.finalize() == b\"abc\"", "ground_truth_oracle_lineno": 53, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @abc.abstractmethod\n def finalize(self) -> bytes:\n \"\"\"\n Finalize the padding, returns bytes.\n \"\"\"", "focal_method_file_path": "src/cryptography/hazmat/primitives/padding.py", "focal_method_start_lineno": 25, "focal_method_end_lineno": 29} {"index": 36, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_revoked_certificate_doesnt_reorder", "test_class_name": "TestRevokedCertificate", "original_test_prefix": " def test_get_revoked_certificate_doesnt_reorder(\n self, rsa_key_2048: rsa.RSAPrivateKey, backend\n ):\n private_key = rsa_key_2048\n last_update = datetime.datetime(2002, 1, 1, 12, 1)\n next_update = datetime.datetime(2030, 1, 1, 12, 1)\n builder = (\n x509.CertificateRevocationListBuilder()\n .issuer_name(\n x509.Name(\n [\n x509.NameAttribute(\n NameOID.COMMON_NAME, \"cryptography.io CA\"\n )\n ]\n )\n )\n .last_update(last_update)\n .next_update(next_update)\n )\n for i in [2, 500, 3, 49, 7, 1]:\n revoked_cert = (\n x509.RevokedCertificateBuilder()\n .serial_number(i)\n .revocation_date(datetime.datetime(2012, 1, 1, 1, 1))\n .build(backend)\n )\n builder = builder.add_revoked_certificate(revoked_cert)\n crl = builder.sign(private_key, hashes.SHA256(), backend)\n assert crl[0].serial_number == 2\n assert crl[2].serial_number == 3\n # make sure get_revoked_certificate_by_serial_number doesn't affect\n # ordering after being invoked\n crl.get_revoked_certificate_by_serial_number(500)\n assert crl[0].serial_number == 2\n assert crl[2].serial_number == 3", "test_prefix": " def test_get_revoked_certificate_doesnt_reorder(\n self, rsa_key_2048: rsa.RSAPrivateKey, backend\n ):\n private_key = rsa_key_2048\n last_update = datetime.datetime(2002, 1, 1, 12, 1)\n next_update = datetime.datetime(2030, 1, 1, 12, 1)\n builder = (\n x509.CertificateRevocationListBuilder()\n .issuer_name(\n x509.Name(\n [\n x509.NameAttribute(\n NameOID.COMMON_NAME, \"cryptography.io CA\"\n )\n ]\n )\n )\n .last_update(last_update)\n .next_update(next_update)\n )\n for i in [2, 500, 3, 49, 7, 1]:\n revoked_cert = (\n x509.RevokedCertificateBuilder()\n .serial_number(i)\n .revocation_date(datetime.datetime(2012, 1, 1, 1, 1))\n .build(backend)\n )\n builder = builder.add_revoked_certificate(revoked_cert)\n crl = builder.sign(private_key, hashes.SHA256(), backend)\n \n assert crl[2].serial_number == 3\n # make sure get_revoked_certificate_by_serial_number doesn't affect\n # ordering after being invoked\n crl.get_revoked_certificate_by_serial_number(500)\n \n assert crl[2].serial_number == 3", "test_prefix_file_path": "tests/x509/test_x509.py", "test_prefix_start_lineno": 772, "test_prefix_end_lineno": 807, "test_target": "tests/x509/test_x509.py::TestRevokedCertificate::test_get_revoked_certificate_doesnt_reorder", "ground_truth_oracle": "assert crl[0].serial_number == 2", "ground_truth_oracle_lineno": 801, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def sign(\n self,\n private_key: CertificateIssuerPrivateKeyTypes,\n algorithm: _AllowedHashTypes | None,\n backend: typing.Any = None,\n *,\n rsa_padding: padding.PSS | padding.PKCS1v15 | None = None,\n ecdsa_deterministic: bool | None = None,\n ) -> CertificateRevocationList:\n if self._issuer_name is None:\n raise ValueError(\"A CRL must have an issuer name\")\n\n if self._last_update is None:\n raise ValueError(\"A CRL must have a last update time\")\n\n if self._next_update is None:\n raise ValueError(\"A CRL must have a next update time\")\n\n if rsa_padding is not None:\n if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)):\n raise TypeError(\"Padding must be PSS or PKCS1v15\")\n if not isinstance(private_key, rsa.RSAPrivateKey):\n raise TypeError(\"Padding is only supported for RSA keys\")\n\n if ecdsa_deterministic is not None:\n if not isinstance(private_key, ec.EllipticCurvePrivateKey):\n raise TypeError(\n \"Deterministic ECDSA is only supported for EC keys\"\n )\n\n return rust_x509.create_x509_crl(\n self,\n private_key,\n algorithm,\n rsa_padding,\n ecdsa_deterministic,\n )", "focal_method_file_path": "src/cryptography/x509/base.py", "focal_method_start_lineno": 735, "focal_method_end_lineno": 771} {"index": 37, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_hash", "test_class_name": "TestSignedCertificateTimestampsExtension", "original_test_prefix": " def test_hash(self, backend):\n sct1 = (\n _load_data(\n os.path.join(\"x509\", \"ocsp\", \"resp-sct-extension.der\"),\n ocsp.load_der_ocsp_response,\n )\n .single_extensions.get_extension_for_class(\n x509.SignedCertificateTimestamps\n )\n .value\n )\n sct2 = (\n _load_data(\n os.path.join(\"x509\", \"ocsp\", \"resp-sct-extension.der\"),\n ocsp.load_der_ocsp_response,\n )\n .single_extensions.get_extension_for_class(\n x509.SignedCertificateTimestamps\n )\n .value\n )\n sct3 = x509.SignedCertificateTimestamps([])\n assert hash(sct1) == hash(sct2)\n assert hash(sct1) != hash(sct3)", "test_prefix": " def test_hash(self, backend):\n sct1 = (\n _load_data(\n os.path.join(\"x509\", \"ocsp\", \"resp-sct-extension.der\"),\n ocsp.load_der_ocsp_response,\n )\n .single_extensions.get_extension_for_class(\n x509.SignedCertificateTimestamps\n )\n .value\n )\n sct2 = (\n _load_data(\n os.path.join(\"x509\", \"ocsp\", \"resp-sct-extension.der\"),\n ocsp.load_der_ocsp_response,\n )\n .single_extensions.get_extension_for_class(\n x509.SignedCertificateTimestamps\n )\n .value\n )\n sct3 = x509.SignedCertificateTimestamps([])\n assert hash(sct1) == hash(sct2)\n ", "test_prefix_file_path": "tests/x509/test_ocsp.py", "test_prefix_start_lineno": 1234, "test_prefix_end_lineno": 1257, "test_target": "tests/x509/test_ocsp.py::TestSignedCertificateTimestampsExtension::test_hash", "ground_truth_oracle": "assert hash(sct1) != hash(sct3)", "ground_truth_oracle_lineno": 1257, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class SignedCertificateTimestamps(ExtensionType):\n oid = ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS\n\n def __init__(\n self,\n signed_certificate_timestamps: Iterable[SignedCertificateTimestamp],\n ) -> None:\n signed_certificate_timestamps = list(signed_certificate_timestamps)\n if not all(\n isinstance(sct, SignedCertificateTimestamp)\n for sct in signed_certificate_timestamps\n ):\n raise TypeError(\n \"Every item in the signed_certificate_timestamps list must be \"\n \"a SignedCertificateTimestamp\"\n )\n self._signed_certificate_timestamps = signed_certificate_timestamps\n\n __len__, __iter__, __getitem__ = _make_sequence_methods(\n \"_signed_certificate_timestamps\"\n )\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __hash__(self) -> int:\n return hash(tuple(self._signed_certificate_timestamps))\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, SignedCertificateTimestamps):\n return NotImplemented\n\n return (\n self._signed_certificate_timestamps\n == other._signed_certificate_timestamps\n )\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1899, "focal_method_end_lineno": 1937} {"index": 38, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ne", "test_class_name": "TestSignedCertificateTimestampsExtension", "original_test_prefix": " def test_ne(self, backend):\n sct1 = (\n _load_data(\n os.path.join(\"x509\", \"ocsp\", \"resp-sct-extension.der\"),\n ocsp.load_der_ocsp_response,\n )\n .single_extensions.get_extension_for_class(\n x509.SignedCertificateTimestamps\n )\n .value\n )\n sct2 = x509.SignedCertificateTimestamps([])\n assert sct1 != sct2\n assert sct1 != object()", "test_prefix": " def test_ne(self, backend):\n sct1 = (\n _load_data(\n os.path.join(\"x509\", \"ocsp\", \"resp-sct-extension.der\"),\n ocsp.load_der_ocsp_response,\n )\n .single_extensions.get_extension_for_class(\n x509.SignedCertificateTimestamps\n )\n .value\n )\n sct2 = x509.SignedCertificateTimestamps([])\n \n assert sct1 != object()", "test_prefix_file_path": "tests/x509/test_ocsp.py", "test_prefix_start_lineno": 1219, "test_prefix_end_lineno": 1232, "test_target": "tests/x509/test_ocsp.py::TestSignedCertificateTimestampsExtension::test_ne", "ground_truth_oracle": "assert sct1 != sct2", "ground_truth_oracle_lineno": 1231, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class SignedCertificateTimestamps(ExtensionType):\n oid = ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS\n\n def __init__(\n self,\n signed_certificate_timestamps: Iterable[SignedCertificateTimestamp],\n ) -> None:\n signed_certificate_timestamps = list(signed_certificate_timestamps)\n if not all(\n isinstance(sct, SignedCertificateTimestamp)\n for sct in signed_certificate_timestamps\n ):\n raise TypeError(\n \"Every item in the signed_certificate_timestamps list must be \"\n \"a SignedCertificateTimestamp\"\n )\n self._signed_certificate_timestamps = signed_certificate_timestamps\n\n __len__, __iter__, __getitem__ = _make_sequence_methods(\n \"_signed_certificate_timestamps\"\n )\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __hash__(self) -> int:\n return hash(tuple(self._signed_certificate_timestamps))\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, SignedCertificateTimestamps):\n return NotImplemented\n\n return (\n self._signed_certificate_timestamps\n == other._signed_certificate_timestamps\n )\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1899, "focal_method_end_lineno": 1937} {"index": 39, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_bytes", "test_class_name": "TestDeltaCRLIndicator", "original_test_prefix": " def test_public_bytes(self):\n ext = x509.DeltaCRLIndicator(2)\n assert ext.public_bytes() == b\"\\x02\\x01\\x02\"", "test_prefix": " def test_public_bytes(self):\n ext = x509.DeltaCRLIndicator(2)\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 409, "test_prefix_end_lineno": 411, "test_target": "tests/x509/test_x509_ext.py::TestDeltaCRLIndicator::test_public_bytes", "ground_truth_oracle": "assert ext.public_bytes() == b\"\\x02\\x01\\x02\"", "ground_truth_oracle_lineno": 411, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 495, "focal_method_end_lineno": 496} {"index": 40, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_no_parsed_hostname", "test_class_name": "TestUniformResourceIdentifier", "original_test_prefix": " def test_no_parsed_hostname(self):\n gn = x509.UniformResourceIdentifier(\"singlelabel\")\n assert gn.value == \"singlelabel\"", "test_prefix": " def test_no_parsed_hostname(self):\n gn = x509.UniformResourceIdentifier(\"singlelabel\")\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 2232, "test_prefix_end_lineno": 2234, "test_target": "tests/x509/test_x509_ext.py::TestUniformResourceIdentifier::test_no_parsed_hostname", "ground_truth_oracle": "assert gn.value == \"singlelabel\"", "ground_truth_oracle_lineno": 2234, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class UniformResourceIdentifier(GeneralName):\n def __init__(self, value: str) -> None:\n if isinstance(value, str):\n try:\n value.encode(\"ascii\")\n except UnicodeEncodeError:\n raise ValueError(\n \"URI values should be passed as an A-label string. \"\n \"This means unicode characters should be encoded via \"\n \"a library like idna.\"\n )\n else:\n raise TypeError(\"value must be string\")\n\n self._value = value\n\n @property\n def value(self) -> str:\n return self._value\n\n @classmethod\n def _init_without_validation(cls, value: str) -> UniformResourceIdentifier:\n instance = cls.__new__(cls)\n instance._value = value\n return instance\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, UniformResourceIdentifier):\n return NotImplemented\n\n return self.value == other.value\n\n def __hash__(self) -> int:\n return hash(self.value)", "focal_method_file_path": "src/cryptography/x509/general_name.py", "focal_method_start_lineno": 120, "focal_method_end_lineno": 156} {"index": 41, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_repr", "test_class_name": "TestIPAddress", "original_test_prefix": " def test_repr(self):\n gn = x509.IPAddress(ipaddress.IPv4Address(\"127.0.0.1\"))\n assert repr(gn) == \"\"\n\n gn2 = x509.IPAddress(ipaddress.IPv6Address(\"ff::\"))\n assert repr(gn2) == \"\"\n\n gn3 = x509.IPAddress(ipaddress.IPv4Network(\"192.168.0.0/24\"))\n assert repr(gn3) == \"\"\n\n gn4 = x509.IPAddress(ipaddress.IPv6Network(\"ff::/96\"))\n assert repr(gn4) == \"\"", "test_prefix": " def test_repr(self):\n gn = x509.IPAddress(ipaddress.IPv4Address(\"127.0.0.1\"))\n assert repr(gn) == \"\"\n\n gn2 = x509.IPAddress(ipaddress.IPv6Address(\"ff::\"))\n assert repr(gn2) == \"\"\n\n gn3 = x509.IPAddress(ipaddress.IPv4Network(\"192.168.0.0/24\"))\n \n\n gn4 = x509.IPAddress(ipaddress.IPv6Network(\"ff::/96\"))\n assert repr(gn4) == \"\"", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 2305, "test_prefix_end_lineno": 2316, "test_target": "tests/x509/test_x509_ext.py::TestIPAddress::test_repr", "ground_truth_oracle": "assert repr(gn3) == \"\"", "ground_truth_oracle_lineno": 2313, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class IPAddress(GeneralName):\n def __init__(self, value: _IPAddressTypes) -> None:\n if not isinstance(\n value,\n (\n ipaddress.IPv4Address,\n ipaddress.IPv6Address,\n ipaddress.IPv4Network,\n ipaddress.IPv6Network,\n ),\n ):\n raise TypeError(\n \"value must be an instance of ipaddress.IPv4Address, \"\n \"ipaddress.IPv6Address, ipaddress.IPv4Network, or \"\n \"ipaddress.IPv6Network\"\n )\n\n self._value = value\n\n @property\n def value(self) -> _IPAddressTypes:\n return self._value\n\n def _packed(self) -> bytes:\n if isinstance(\n self.value, (ipaddress.IPv4Address, ipaddress.IPv6Address)\n ):\n return self.value.packed\n else:\n return (\n self.value.network_address.packed + self.value.netmask.packed\n )\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, IPAddress):\n return NotImplemented\n\n return self.value == other.value\n\n def __hash__(self) -> int:\n return hash(self.value)", "focal_method_file_path": "src/cryptography/x509/general_name.py", "focal_method_start_lineno": 207, "focal_method_end_lineno": 250} {"index": 42, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_rsa_padding_supported_pkcs1v15", "test_class_name": "TestOpenSSLRSA", "original_test_prefix": " def test_rsa_padding_supported_pkcs1v15(self):\n assert backend.rsa_padding_supported(padding.PKCS1v15()) is True", "test_prefix": " def test_rsa_padding_supported_pkcs1v15(self):\n ", "test_prefix_file_path": "tests/hazmat/backends/test_openssl.py", "test_prefix_start_lineno": 126, "test_prefix_end_lineno": 127, "test_target": "tests/hazmat/backends/test_openssl.py::TestOpenSSLRSA::test_rsa_padding_supported_pkcs1v15", "ground_truth_oracle": "assert backend.rsa_padding_supported(padding.PKCS1v15()) is True", "ground_truth_oracle_lineno": 127, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def rsa_padding_supported(self, padding: AsymmetricPadding) -> bool:\n if isinstance(padding, PKCS1v15):\n return True\n elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1):\n # FIPS 186-4 only allows salt length == digest length for PSS\n # It is technically acceptable to set an explicit salt length\n # equal to the digest length and this will incorrectly fail, but\n # since we don't do that in the tests and this method is\n # private, we'll ignore that until we need to do otherwise.\n if (\n self._fips_enabled\n and padding._salt_length != PSS.DIGEST_LENGTH\n ):\n return False\n return self.hash_supported(padding._mgf._algorithm)\n elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1):\n return self._oaep_hash_supported(\n padding._mgf._algorithm\n ) and self._oaep_hash_supported(padding._algorithm)\n else:\n return False", "focal_method_file_path": "src/cryptography/hazmat/backends/openssl/backend.py", "focal_method_start_lineno": 180, "focal_method_end_lineno": 200} {"index": 43, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_block_size_padding", "test_class_name": "TestANSIX923", "original_test_prefix": " def test_block_size_padding(self):\n padder = padding.ANSIX923(64).padder()\n data = padder.update(b\"a\" * 8) + padder.finalize()\n assert data == b\"a\" * 8 + b\"\\x00\" * 7 + b\"\\x08\"", "test_prefix": " def test_block_size_padding(self):\n padder = padding.ANSIX923(64).padder()\n data = padder.update(b\"a\" * 8) + padder.finalize()\n ", "test_prefix_file_path": "tests/hazmat/primitives/test_padding.py", "test_prefix_start_lineno": 249, "test_prefix_end_lineno": 252, "test_target": "tests/hazmat/primitives/test_padding.py::TestANSIX923::test_block_size_padding", "ground_truth_oracle": "assert data == b\"a\" * 8 + b\"\\x00\" * 7 + b\"\\x08\"", "ground_truth_oracle_lineno": 252, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @abc.abstractmethod\n def finalize(self) -> bytes:\n \"\"\"\n Finalize the padding, returns bytes.\n \"\"\"", "focal_method_file_path": "src/cryptography/hazmat/primitives/padding.py", "focal_method_start_lineno": 25, "focal_method_end_lineno": 29} {"index": 44, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_sign_with_appended_certs", "test_class_name": "TestOCSPResponseBuilder", "original_test_prefix": " def test_sign_with_appended_certs(self):\n builder = ocsp.OCSPResponseBuilder()\n cert, issuer = _cert_and_issuer()\n root_cert, private_key = _generate_root()\n current_time = (\n datetime.datetime.now(datetime.timezone.utc)\n .replace(tzinfo=None)\n .replace(microsecond=0)\n )\n this_update = current_time - datetime.timedelta(days=1)\n next_update = this_update + datetime.timedelta(days=7)\n builder = (\n builder.responder_id(ocsp.OCSPResponderEncoding.NAME, root_cert)\n .add_response(\n cert,\n issuer,\n hashes.SHA1(),\n ocsp.OCSPCertStatus.GOOD,\n this_update,\n next_update,\n None,\n None,\n )\n .certificates([root_cert])\n )\n resp = builder.sign(private_key, hashes.SHA256())\n assert resp.certificates == [root_cert]", "test_prefix": " def test_sign_with_appended_certs(self):\n builder = ocsp.OCSPResponseBuilder()\n cert, issuer = _cert_and_issuer()\n root_cert, private_key = _generate_root()\n current_time = (\n datetime.datetime.now(datetime.timezone.utc)\n .replace(tzinfo=None)\n .replace(microsecond=0)\n )\n this_update = current_time - datetime.timedelta(days=1)\n next_update = this_update + datetime.timedelta(days=7)\n builder = (\n builder.responder_id(ocsp.OCSPResponderEncoding.NAME, root_cert)\n .add_response(\n cert,\n issuer,\n hashes.SHA1(),\n ocsp.OCSPCertStatus.GOOD,\n this_update,\n next_update,\n None,\n None,\n )\n .certificates([root_cert])\n )\n resp = builder.sign(private_key, hashes.SHA256())\n ", "test_prefix_file_path": "tests/x509/test_ocsp.py", "test_prefix_start_lineno": 752, "test_prefix_end_lineno": 778, "test_target": "tests/x509/test_ocsp.py::TestOCSPResponseBuilder::test_sign_with_appended_certs", "ground_truth_oracle": "assert resp.certificates == [root_cert]", "ground_truth_oracle_lineno": 778, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def sign(\n self,\n private_key: CertificateIssuerPrivateKeyTypes,\n algorithm: hashes.HashAlgorithm | None,\n ) -> OCSPResponse:\n if self._response is None:\n raise ValueError(\"You must add a response before signing\")\n if self._responder_id is None:\n raise ValueError(\"You must add a responder_id before signing\")\n\n return ocsp.create_ocsp_response(\n OCSPResponseStatus.SUCCESSFUL, self, private_key, algorithm\n )", "focal_method_file_path": "src/cryptography/x509/ocsp.py", "focal_method_start_lineno": 350, "focal_method_end_lineno": 362} {"index": 45, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_recover_prime_factors", "test_class_name": "TestRSAPrimeFactorRecovery", "original_test_prefix": " def test_recover_prime_factors(self, subtests):\n for key in [\n RSA_KEY_1024,\n RSA_KEY_1025,\n RSA_KEY_1026,\n RSA_KEY_1027,\n RSA_KEY_1028,\n RSA_KEY_1029,\n RSA_KEY_1030,\n RSA_KEY_1031,\n RSA_KEY_1536,\n RSA_KEY_2048,\n ]:\n with subtests.test():\n p, q = rsa.rsa_recover_prime_factors(\n key.public_numbers.n,\n key.public_numbers.e,\n key.d,\n )\n # Unfortunately there is no convention on which prime should be\n # p and which one q. The function we use always makes p > q,\n # but the NIST vectors are not so consistent. Accordingly, we\n # verify we've recovered the proper (p, q) by sorting them and\n # asserting on that.\n assert sorted([p, q]) == sorted([key.p, key.q])\n assert p > q", "test_prefix": " def test_recover_prime_factors(self, subtests):\n for key in [\n RSA_KEY_1024,\n RSA_KEY_1025,\n RSA_KEY_1026,\n RSA_KEY_1027,\n RSA_KEY_1028,\n RSA_KEY_1029,\n RSA_KEY_1030,\n RSA_KEY_1031,\n RSA_KEY_1536,\n RSA_KEY_2048,\n ]:\n with subtests.test():\n p, q = rsa.rsa_recover_prime_factors(\n key.public_numbers.n,\n key.public_numbers.e,\n key.d,\n )\n # Unfortunately there is no convention on which prime should be\n # p and which one q. The function we use always makes p > q,\n # but the NIST vectors are not so consistent. Accordingly, we\n # verify we've recovered the proper (p, q) by sorting them and\n # asserting on that.\n \n assert p > q", "test_prefix_file_path": "tests/hazmat/primitives/test_rsa.py", "test_prefix_start_lineno": 2353, "test_prefix_end_lineno": 2378, "test_target": "tests/hazmat/primitives/test_rsa.py::TestRSAPrimeFactorRecovery::test_recover_prime_factors", "ground_truth_oracle": "assert sorted([p, q]) == sorted([key.p, key.q])", "ground_truth_oracle_lineno": 2377, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def rsa_recover_prime_factors(n: int, e: int, d: int) -> tuple[int, int]:\n \"\"\"\n Compute factors p and q from the private exponent d. We assume that n has\n no more than two factors. This function is adapted from code in PyCrypto.\n \"\"\"\n # reject invalid values early\n if d <= 1 or e <= 1:\n raise ValueError(\"d, e can't be <= 1\")\n if 17 != pow(17, e * d, n):\n raise ValueError(\"n, d, e don't match\")\n # See 8.2.2(i) in Handbook of Applied Cryptography.\n ktot = d * e - 1\n # The quantity d*e-1 is a multiple of phi(n), even,\n # and can be represented as t*2^s.\n t = ktot\n while t % 2 == 0:\n t = t // 2\n # Cycle through all multiplicative inverses in Zn.\n # The algorithm is non-deterministic, but there is a 50% chance\n # any candidate a leads to successful factoring.\n # See \"Digitalized Signatures and Public Key Functions as Intractable\n # as Factorization\", M. Rabin, 1979\n spotted = False\n tries = 0\n while not spotted and tries < _MAX_RECOVERY_ATTEMPTS:\n a = random.randint(2, n - 1)\n tries += 1\n k = t\n # Cycle through all values a^{t*2^i}=a^k\n while k < ktot:\n cand = pow(a, k, n)\n # Check if a^k is a non-trivial root of unity (mod n)\n if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:\n # We have found a number such that (cand-1)(cand+1)=0 (mod n).\n # Either of the terms divides n.\n p = gcd(cand + 1, n)\n spotted = True\n break\n k *= 2\n if not spotted:\n raise ValueError(\"Unable to compute factors p and q from exponent d.\")\n # Found !\n q, r = divmod(n, p)\n assert r == 0\n p, q = sorted((p, q), reverse=True)\n return (p, q)", "focal_method_file_path": "src/cryptography/hazmat/primitives/asymmetric/rsa.py", "focal_method_start_lineno": 240, "focal_method_end_lineno": 285} {"index": 46, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_hash", "test_class_name": "TestDNSName", "original_test_prefix": " def test_hash(self):\n n1 = x509.DNSName(\"test1\")\n n2 = x509.DNSName(\"test2\")\n n3 = x509.DNSName(\"test2\")\n assert hash(n1) != hash(n2)\n assert hash(n2) == hash(n3)", "test_prefix": " def test_hash(self):\n n1 = x509.DNSName(\"test1\")\n n2 = x509.DNSName(\"test2\")\n n3 = x509.DNSName(\"test2\")\n \n assert hash(n2) == hash(n3)", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 2117, "test_prefix_end_lineno": 2122, "test_target": "tests/x509/test_x509_ext.py::TestDNSName::test_hash", "ground_truth_oracle": "assert hash(n1) != hash(n2)", "ground_truth_oracle_lineno": 2121, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class DNSName(GeneralName):\n def __init__(self, value: str) -> None:\n if isinstance(value, str):\n try:\n value.encode(\"ascii\")\n except UnicodeEncodeError:\n raise ValueError(\n \"DNSName values should be passed as an A-label string. \"\n \"This means unicode characters should be encoded via \"\n \"a library like idna.\"\n )\n else:\n raise TypeError(\"value must be string\")\n\n self._value = value\n\n @property\n def value(self) -> str:\n return self._value\n\n @classmethod\n def _init_without_validation(cls, value: str) -> DNSName:\n instance = cls.__new__(cls)\n instance._value = value\n return instance\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, DNSName):\n return NotImplemented\n\n return self.value == other.value\n\n def __hash__(self) -> int:\n return hash(self.value)", "focal_method_file_path": "src/cryptography/x509/general_name.py", "focal_method_start_lineno": 81, "focal_method_end_lineno": 117} {"index": 47, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_generate", "test_class_name": "TestX448Exchange", "original_test_prefix": " def test_generate(self, backend):\n key = X448PrivateKey.generate()\n assert key\n assert key.public_key()", "test_prefix": " def test_generate(self, backend):\n key = X448PrivateKey.generate()\n assert key\n ", "test_prefix_file_path": "tests/hazmat/primitives/test_x448.py", "test_prefix_start_lineno": 180, "test_prefix_end_lineno": 183, "test_target": "tests/hazmat/primitives/test_x448.py::TestX448Exchange::test_generate", "ground_truth_oracle": "assert key.public_key()", "ground_truth_oracle_lineno": 183, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def generate(cls) -> X448PrivateKey:\n from cryptography.hazmat.backends.openssl.backend import backend\n\n if not backend.x448_supported():\n raise UnsupportedAlgorithm(\n \"X448 is not supported by this version of OpenSSL.\",\n _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM,\n )\n\n return rust_openssl.x448.generate_key()", "focal_method_file_path": "src/cryptography/hazmat/primitives/asymmetric/x448.py", "focal_method_start_lineno": 63, "focal_method_end_lineno": 73} {"index": 48, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_delta_crl_indicator", "test_class_name": "TestCertificateRevocationList", "original_test_prefix": " def test_delta_crl_indicator(self, backend):\n crl = _load_cert(\n os.path.join(\"x509\", \"custom\", \"crl_delta_crl_indicator.pem\"),\n x509.load_pem_x509_crl,\n )\n\n dci = crl.extensions.get_extension_for_oid(\n ExtensionOID.DELTA_CRL_INDICATOR\n )\n assert dci.value == x509.DeltaCRLIndicator(12345678901234567890)\n assert dci.critical is True", "test_prefix": " def test_delta_crl_indicator(self, backend):\n crl = _load_cert(\n os.path.join(\"x509\", \"custom\", \"crl_delta_crl_indicator.pem\"),\n x509.load_pem_x509_crl,\n )\n\n dci = crl.extensions.get_extension_for_oid(\n ExtensionOID.DELTA_CRL_INDICATOR\n )\n assert dci.value == x509.DeltaCRLIndicator(12345678901234567890)\n ", "test_prefix_file_path": "tests/x509/test_x509.py", "test_prefix_start_lineno": 437, "test_prefix_end_lineno": 447, "test_target": "tests/x509/test_x509.py::TestCertificateRevocationList::test_delta_crl_indicator", "ground_truth_oracle": "assert dci.critical is True", "ground_truth_oracle_lineno": 447, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_extension_for_oid(\n self, oid: ObjectIdentifier\n ) -> Extension[ExtensionType]:\n for ext in self:\n if ext.oid == oid:\n return ext\n\n raise ExtensionNotFound(f\"No {oid} extension was found\", oid)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 116, "focal_method_end_lineno": 123} {"index": 49, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_with_port", "test_class_name": "TestUniformResourceIdentifier", "original_test_prefix": " def test_with_port(self):\n gn = x509.UniformResourceIdentifier(\"singlelabel:443/test\")\n assert gn.value == \"singlelabel:443/test\"", "test_prefix": " def test_with_port(self):\n gn = x509.UniformResourceIdentifier(\"singlelabel:443/test\")\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 2236, "test_prefix_end_lineno": 2238, "test_target": "tests/x509/test_x509_ext.py::TestUniformResourceIdentifier::test_with_port", "ground_truth_oracle": "assert gn.value == \"singlelabel:443/test\"", "ground_truth_oracle_lineno": 2238, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class UniformResourceIdentifier(GeneralName):\n def __init__(self, value: str) -> None:\n if isinstance(value, str):\n try:\n value.encode(\"ascii\")\n except UnicodeEncodeError:\n raise ValueError(\n \"URI values should be passed as an A-label string. \"\n \"This means unicode characters should be encoded via \"\n \"a library like idna.\"\n )\n else:\n raise TypeError(\"value must be string\")\n\n self._value = value\n\n @property\n def value(self) -> str:\n return self._value\n\n @classmethod\n def _init_without_validation(cls, value: str) -> UniformResourceIdentifier:\n instance = cls.__new__(cls)\n instance._value = value\n return instance\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, UniformResourceIdentifier):\n return NotImplemented\n\n return self.value == other.value\n\n def __hash__(self) -> int:\n return hash(self.value)", "focal_method_file_path": "src/cryptography/x509/general_name.py", "focal_method_start_lineno": 120, "focal_method_end_lineno": 156} {"index": 50, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_build_ca_request_with_ed448", "test_class_name": "TestCertificateSigningRequestBuilder", "original_test_prefix": " @pytest.mark.supported(\n only_if=lambda backend: backend.ed448_supported(),\n skip_message=\"Requires OpenSSL with Ed448 support\",\n )\n def test_build_ca_request_with_ed448(self, backend):\n private_key = ed448.Ed448PrivateKey.generate()\n\n request = (\n x509.CertificateSigningRequestBuilder()\n .subject_name(\n x509.Name(\n [\n x509.NameAttribute(\n NameOID.STATE_OR_PROVINCE_NAME, \"Texas\"\n ),\n ]\n )\n )\n .add_extension(\n x509.BasicConstraints(ca=True, path_length=2), critical=True\n )\n .sign(private_key, None, backend)\n )\n\n assert request.signature_hash_algorithm is None\n public_key = request.public_key()\n assert isinstance(public_key, ed448.Ed448PublicKey)\n subject = request.subject\n assert isinstance(subject, x509.Name)\n assert list(subject) == [\n x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, \"Texas\"),\n ]\n basic_constraints = request.extensions.get_extension_for_class(\n x509.BasicConstraints\n )\n assert basic_constraints.value.ca is True\n assert basic_constraints.value.path_length == 2", "test_prefix": " @pytest.mark.supported(\n only_if=lambda backend: backend.ed448_supported(),\n skip_message=\"Requires OpenSSL with Ed448 support\",\n )\n def test_build_ca_request_with_ed448(self, backend):\n private_key = ed448.Ed448PrivateKey.generate()\n\n request = (\n x509.CertificateSigningRequestBuilder()\n .subject_name(\n x509.Name(\n [\n x509.NameAttribute(\n NameOID.STATE_OR_PROVINCE_NAME, \"Texas\"\n ),\n ]\n )\n )\n .add_extension(\n x509.BasicConstraints(ca=True, path_length=2), critical=True\n )\n .sign(private_key, None, backend)\n )\n\n assert request.signature_hash_algorithm is None\n public_key = request.public_key()\n assert isinstance(public_key, ed448.Ed448PublicKey)\n subject = request.subject\n assert isinstance(subject, x509.Name)\n assert list(subject) == [\n x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, \"Texas\"),\n ]\n basic_constraints = request.extensions.get_extension_for_class(\n x509.BasicConstraints\n )\n \n assert basic_constraints.value.path_length == 2", "test_prefix_file_path": "tests/x509/test_x509.py", "test_prefix_start_lineno": 4951, "test_prefix_end_lineno": 4987, "test_target": "tests/x509/test_x509.py::TestCertificateSigningRequestBuilder::test_build_ca_request_with_ed448", "ground_truth_oracle": "assert basic_constraints.value.ca is True", "ground_truth_oracle_lineno": 4986, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_extension_for_class(\n self, extclass: type[ExtensionTypeVar]\n ) -> Extension[ExtensionTypeVar]:\n if extclass is UnrecognizedExtension:\n raise TypeError(\n \"UnrecognizedExtension can't be used with \"\n \"get_extension_for_class because more than one instance of the\"\n \" class may be present.\"\n )\n\n for ext in self:\n if isinstance(ext.value, extclass):\n return ext\n\n raise ExtensionNotFound(\n f\"No {extclass} extension was found\", extclass.oid\n )", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 125, "focal_method_end_lineno": 141} {"index": 51, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_key_equality", "test_class_name": "", "original_test_prefix": "@pytest.mark.supported(\n only_if=lambda backend: backend.ed25519_supported(),\n skip_message=\"Requires OpenSSL with Ed25519 support\",\n)\ndef test_public_key_equality(backend):\n key_bytes = load_vectors_from_file(\n os.path.join(\"asymmetric\", \"Ed25519\", \"ed25519-pkcs8.der\"),\n lambda derfile: derfile.read(),\n mode=\"rb\",\n )\n key1 = serialization.load_der_private_key(key_bytes, None).public_key()\n key2 = serialization.load_der_private_key(key_bytes, None).public_key()\n key3 = Ed25519PrivateKey.generate().public_key()\n assert key1 == key2\n assert key1 != key3\n assert key1 != object()\n\n with pytest.raises(TypeError):\n key1 < key2 # type: ignore[operator]", "test_prefix": "@pytest.mark.supported(\n only_if=lambda backend: backend.ed25519_supported(),\n skip_message=\"Requires OpenSSL with Ed25519 support\",\n)\ndef test_public_key_equality(backend):\n key_bytes = load_vectors_from_file(\n os.path.join(\"asymmetric\", \"Ed25519\", \"ed25519-pkcs8.der\"),\n lambda derfile: derfile.read(),\n mode=\"rb\",\n )\n key1 = serialization.load_der_private_key(key_bytes, None).public_key()\n key2 = serialization.load_der_private_key(key_bytes, None).public_key()\n key3 = Ed25519PrivateKey.generate().public_key()\n assert key1 == key2\n \n assert key1 != object()\n\n with pytest.raises(TypeError):\n key1 < key2 # type: ignore[operator]", "test_prefix_file_path": "tests/hazmat/primitives/test_ed25519.py", "test_prefix_start_lineno": 295, "test_prefix_end_lineno": 313, "test_target": "tests/hazmat/primitives/test_ed25519.py::test_public_key_equality", "ground_truth_oracle": "assert key1 != key3", "ground_truth_oracle_lineno": 309, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @abc.abstractmethod\n def public_key(self) -> Ed25519PublicKey:\n \"\"\"\n The Ed25519PublicKey derived from the private key.\n \"\"\"", "focal_method_file_path": "src/cryptography/hazmat/primitives/asymmetric/ed25519.py", "focal_method_start_lineno": 92, "focal_method_end_lineno": 96} {"index": 52, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_idna2003_invalid", "test_class_name": "TestRSASubjectAlternativeNameExtension", "original_test_prefix": " def test_idna2003_invalid(self, backend):\n cert = _load_cert(\n os.path.join(\"x509\", \"custom\", \"san_idna2003_dnsname.pem\"),\n x509.load_pem_x509_certificate,\n )\n san = cert.extensions.get_extension_for_class(\n x509.SubjectAlternativeName\n ).value\n\n assert len(san) == 1\n [name] = san\n assert name.value == \"xn--k4h.ws\"", "test_prefix": " def test_idna2003_invalid(self, backend):\n cert = _load_cert(\n os.path.join(\"x509\", \"custom\", \"san_idna2003_dnsname.pem\"),\n x509.load_pem_x509_certificate,\n )\n san = cert.extensions.get_extension_for_class(\n x509.SubjectAlternativeName\n ).value\n\n assert len(san) == 1\n [name] = san\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 2812, "test_prefix_end_lineno": 2823, "test_target": "tests/x509/test_x509_ext.py::TestRSASubjectAlternativeNameExtension::test_idna2003_invalid", "ground_truth_oracle": "assert name.value == \"xn--k4h.ws\"", "ground_truth_oracle_lineno": 2823, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_extension_for_class(\n self, extclass: type[ExtensionTypeVar]\n ) -> Extension[ExtensionTypeVar]:\n if extclass is UnrecognizedExtension:\n raise TypeError(\n \"UnrecognizedExtension can't be used with \"\n \"get_extension_for_class because more than one instance of the\"\n \" class may be present.\"\n )\n\n for ext in self:\n if isinstance(ext.value, extclass):\n return ext\n\n raise ExtensionNotFound(\n f\"No {extclass} extension was found\", extclass.oid\n )", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 125, "focal_method_end_lineno": 141} {"index": 53, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_encrypt", "test_class_name": "TestMultiFernet", "original_test_prefix": " def test_encrypt(self, backend):\n f1 = Fernet(base64.urlsafe_b64encode(b\"\\x00\" * 32), backend=backend)\n f2 = Fernet(base64.urlsafe_b64encode(b\"\\x01\" * 32), backend=backend)\n f = MultiFernet([f1, f2])\n\n assert f1.decrypt(f.encrypt(b\"abc\")) == b\"abc\"", "test_prefix": " def test_encrypt(self, backend):\n f1 = Fernet(base64.urlsafe_b64encode(b\"\\x00\" * 32), backend=backend)\n f2 = Fernet(base64.urlsafe_b64encode(b\"\\x01\" * 32), backend=backend)\n f = MultiFernet([f1, f2])\n\n ", "test_prefix_file_path": "tests/test_fernet.py", "test_prefix_start_lineno": 168, "test_prefix_end_lineno": 173, "test_target": "tests/test_fernet.py::TestMultiFernet::test_encrypt", "ground_truth_oracle": "assert f1.decrypt(f.encrypt(b\"abc\")) == b\"abc\"", "ground_truth_oracle_lineno": 173, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes:\n timestamp, data = Fernet._get_unverified_token_data(token)\n if ttl is None:\n time_info = None\n else:\n time_info = (ttl, int(time.time()))\n return self._decrypt_data(data, timestamp, time_info)", "focal_method_file_path": "src/cryptography/fernet.py", "focal_method_start_lineno": 84, "focal_method_end_lineno": 90} {"index": 54, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ne", "test_class_name": "TestExtendedKeyUsage", "original_test_prefix": " def test_ne(self):\n eku = x509.ExtendedKeyUsage([x509.ObjectIdentifier(\"1.3.6\")])\n eku2 = x509.ExtendedKeyUsage([x509.ObjectIdentifier(\"1.3.6.1\")])\n assert eku != eku2\n assert eku != object()", "test_prefix": " def test_ne(self):\n eku = x509.ExtendedKeyUsage([x509.ObjectIdentifier(\"1.3.6\")])\n eku2 = x509.ExtendedKeyUsage([x509.ObjectIdentifier(\"1.3.6.1\")])\n \n assert eku != object()", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 1484, "test_prefix_end_lineno": 1488, "test_target": "tests/x509/test_x509_ext.py::TestExtendedKeyUsage::test_ne", "ground_truth_oracle": "assert eku != eku2", "ground_truth_oracle_lineno": 1487, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class ExtendedKeyUsage(ExtensionType):\n oid = ExtensionOID.EXTENDED_KEY_USAGE\n\n def __init__(self, usages: Iterable[ObjectIdentifier]) -> None:\n usages = list(usages)\n if not all(isinstance(x, ObjectIdentifier) for x in usages):\n raise TypeError(\n \"Every item in the usages list must be an ObjectIdentifier\"\n )\n\n self._usages = usages\n\n __len__, __iter__, __getitem__ = _make_sequence_methods(\"_usages\")\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, ExtendedKeyUsage):\n return NotImplemented\n\n return self._usages == other._usages\n\n def __hash__(self) -> int:\n return hash(tuple(self._usages))\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 988, "focal_method_end_lineno": 1015} {"index": 55, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_hash", "test_class_name": "TestCRLDistributionPoints", "original_test_prefix": " def test_hash(self):\n cdp = x509.CRLDistributionPoints(\n [\n x509.DistributionPoint(\n [x509.UniformResourceIdentifier(\"ftp://domain\")],\n None,\n frozenset(\n [\n x509.ReasonFlags.key_compromise,\n x509.ReasonFlags.ca_compromise,\n ]\n ),\n [x509.UniformResourceIdentifier(\"uri://thing\")],\n ),\n ]\n )\n cdp2 = x509.CRLDistributionPoints(\n [\n x509.DistributionPoint(\n [x509.UniformResourceIdentifier(\"ftp://domain\")],\n None,\n frozenset(\n [\n x509.ReasonFlags.key_compromise,\n x509.ReasonFlags.ca_compromise,\n ]\n ),\n [x509.UniformResourceIdentifier(\"uri://thing\")],\n ),\n ]\n )\n cdp3 = x509.CRLDistributionPoints(\n [\n x509.DistributionPoint(\n [x509.UniformResourceIdentifier(\"ftp://domain\")],\n None,\n frozenset([x509.ReasonFlags.key_compromise]),\n [x509.UniformResourceIdentifier(\"uri://thing\")],\n ),\n ]\n )\n assert hash(cdp) == hash(cdp2)\n assert hash(cdp) != hash(cdp3)", "test_prefix": " def test_hash(self):\n cdp = x509.CRLDistributionPoints(\n [\n x509.DistributionPoint(\n [x509.UniformResourceIdentifier(\"ftp://domain\")],\n None,\n frozenset(\n [\n x509.ReasonFlags.key_compromise,\n x509.ReasonFlags.ca_compromise,\n ]\n ),\n [x509.UniformResourceIdentifier(\"uri://thing\")],\n ),\n ]\n )\n cdp2 = x509.CRLDistributionPoints(\n [\n x509.DistributionPoint(\n [x509.UniformResourceIdentifier(\"ftp://domain\")],\n None,\n frozenset(\n [\n x509.ReasonFlags.key_compromise,\n x509.ReasonFlags.ca_compromise,\n ]\n ),\n [x509.UniformResourceIdentifier(\"uri://thing\")],\n ),\n ]\n )\n cdp3 = x509.CRLDistributionPoints(\n [\n x509.DistributionPoint(\n [x509.UniformResourceIdentifier(\"ftp://domain\")],\n None,\n frozenset([x509.ReasonFlags.key_compromise]),\n [x509.UniformResourceIdentifier(\"uri://thing\")],\n ),\n ]\n )\n assert hash(cdp) == hash(cdp2)\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 4816, "test_prefix_end_lineno": 4858, "test_target": "tests/x509/test_x509_ext.py::TestCRLDistributionPoints::test_hash", "ground_truth_oracle": "assert hash(cdp) != hash(cdp3)", "ground_truth_oracle_lineno": 4858, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class CRLDistributionPoints(ExtensionType):\n oid = ExtensionOID.CRL_DISTRIBUTION_POINTS\n\n def __init__(\n self, distribution_points: Iterable[DistributionPoint]\n ) -> None:\n distribution_points = list(distribution_points)\n if not all(\n isinstance(x, DistributionPoint) for x in distribution_points\n ):\n raise TypeError(\n \"distribution_points must be a list of DistributionPoint \"\n \"objects\"\n )\n\n self._distribution_points = distribution_points\n\n __len__, __iter__, __getitem__ = _make_sequence_methods(\n \"_distribution_points\"\n )\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, CRLDistributionPoints):\n return NotImplemented\n\n return self._distribution_points == other._distribution_points\n\n def __hash__(self) -> int:\n return hash(tuple(self._distribution_points))\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 499, "focal_method_end_lineno": 533} {"index": 56, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_iter_input", "test_class_name": "TestExtendedKeyUsage", "original_test_prefix": " def test_iter_input(self):\n usages = [\n x509.ObjectIdentifier(\"1.3.6.1.5.5.7.3.1\"),\n x509.ObjectIdentifier(\"1.3.6.1.5.5.7.3.2\"),\n ]\n aia = x509.ExtendedKeyUsage(iter(usages))\n assert list(aia) == usages", "test_prefix": " def test_iter_input(self):\n usages = [\n x509.ObjectIdentifier(\"1.3.6.1.5.5.7.3.1\"),\n x509.ObjectIdentifier(\"1.3.6.1.5.5.7.3.2\"),\n ]\n aia = x509.ExtendedKeyUsage(iter(usages))\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 1454, "test_prefix_end_lineno": 1460, "test_target": "tests/x509/test_x509_ext.py::TestExtendedKeyUsage::test_iter_input", "ground_truth_oracle": "assert list(aia) == usages", "ground_truth_oracle_lineno": 1460, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class ExtendedKeyUsage(ExtensionType):\n oid = ExtensionOID.EXTENDED_KEY_USAGE\n\n def __init__(self, usages: Iterable[ObjectIdentifier]) -> None:\n usages = list(usages)\n if not all(isinstance(x, ObjectIdentifier) for x in usages):\n raise TypeError(\n \"Every item in the usages list must be an ObjectIdentifier\"\n )\n\n self._usages = usages\n\n __len__, __iter__, __getitem__ = _make_sequence_methods(\"_usages\")\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, ExtendedKeyUsage):\n return NotImplemented\n\n return self._usages == other._usages\n\n def __hash__(self) -> int:\n return hash(tuple(self._usages))\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 988, "focal_method_end_lineno": 1015} {"index": 57, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_equality", "test_class_name": "TestUniformResourceIdentifier", "original_test_prefix": " def test_equality(self):\n gn = x509.UniformResourceIdentifier(\"string\")\n gn2 = x509.UniformResourceIdentifier(\"string2\")\n gn3 = x509.UniformResourceIdentifier(\"string\")\n assert gn != gn2\n assert gn != object()\n assert gn == gn3", "test_prefix": " def test_equality(self):\n gn = x509.UniformResourceIdentifier(\"string\")\n gn2 = x509.UniformResourceIdentifier(\"string2\")\n gn3 = x509.UniformResourceIdentifier(\"string\")\n assert gn != gn2\n assert gn != object()\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 2220, "test_prefix_end_lineno": 2226, "test_target": "tests/x509/test_x509_ext.py::TestUniformResourceIdentifier::test_equality", "ground_truth_oracle": "assert gn == gn3", "ground_truth_oracle_lineno": 2226, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class UniformResourceIdentifier(GeneralName):\n def __init__(self, value: str) -> None:\n if isinstance(value, str):\n try:\n value.encode(\"ascii\")\n except UnicodeEncodeError:\n raise ValueError(\n \"URI values should be passed as an A-label string. \"\n \"This means unicode characters should be encoded via \"\n \"a library like idna.\"\n )\n else:\n raise TypeError(\"value must be string\")\n\n self._value = value\n\n @property\n def value(self) -> str:\n return self._value\n\n @classmethod\n def _init_without_validation(cls, value: str) -> UniformResourceIdentifier:\n instance = cls.__new__(cls)\n instance._value = value\n return instance\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, UniformResourceIdentifier):\n return NotImplemented\n\n return self.value == other.value\n\n def __hash__(self) -> int:\n return hash(self.value)", "focal_method_file_path": "src/cryptography/x509/general_name.py", "focal_method_start_lineno": 120, "focal_method_end_lineno": 156} {"index": 58, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_eq", "test_class_name": "TestCRLDistributionPoints", "original_test_prefix": " def test_eq(self):\n cdp = x509.CRLDistributionPoints(\n [\n x509.DistributionPoint(\n [x509.UniformResourceIdentifier(\"ftp://domain\")],\n None,\n frozenset(\n [\n x509.ReasonFlags.key_compromise,\n x509.ReasonFlags.ca_compromise,\n ]\n ),\n [x509.UniformResourceIdentifier(\"uri://thing\")],\n ),\n ]\n )\n cdp2 = x509.CRLDistributionPoints(\n [\n x509.DistributionPoint(\n [x509.UniformResourceIdentifier(\"ftp://domain\")],\n None,\n frozenset(\n [\n x509.ReasonFlags.key_compromise,\n x509.ReasonFlags.ca_compromise,\n ]\n ),\n [x509.UniformResourceIdentifier(\"uri://thing\")],\n ),\n ]\n )\n assert cdp == cdp2", "test_prefix": " def test_eq(self):\n cdp = x509.CRLDistributionPoints(\n [\n x509.DistributionPoint(\n [x509.UniformResourceIdentifier(\"ftp://domain\")],\n None,\n frozenset(\n [\n x509.ReasonFlags.key_compromise,\n x509.ReasonFlags.ca_compromise,\n ]\n ),\n [x509.UniformResourceIdentifier(\"uri://thing\")],\n ),\n ]\n )\n cdp2 = x509.CRLDistributionPoints(\n [\n x509.DistributionPoint(\n [x509.UniformResourceIdentifier(\"ftp://domain\")],\n None,\n frozenset(\n [\n x509.ReasonFlags.key_compromise,\n x509.ReasonFlags.ca_compromise,\n ]\n ),\n [x509.UniformResourceIdentifier(\"uri://thing\")],\n ),\n ]\n )\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 4722, "test_prefix_end_lineno": 4753, "test_target": "tests/x509/test_x509_ext.py::TestCRLDistributionPoints::test_eq", "ground_truth_oracle": "assert cdp == cdp2", "ground_truth_oracle_lineno": 4753, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class CRLDistributionPoints(ExtensionType):\n oid = ExtensionOID.CRL_DISTRIBUTION_POINTS\n\n def __init__(\n self, distribution_points: Iterable[DistributionPoint]\n ) -> None:\n distribution_points = list(distribution_points)\n if not all(\n isinstance(x, DistributionPoint) for x in distribution_points\n ):\n raise TypeError(\n \"distribution_points must be a list of DistributionPoint \"\n \"objects\"\n )\n\n self._distribution_points = distribution_points\n\n __len__, __iter__, __getitem__ = _make_sequence_methods(\n \"_distribution_points\"\n )\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, CRLDistributionPoints):\n return NotImplemented\n\n return self._distribution_points == other._distribution_points\n\n def __hash__(self) -> int:\n return hash(tuple(self._distribution_points))\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 499, "focal_method_end_lineno": 533} {"index": 59, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_bytes", "test_class_name": "TestPrecertPoisonExtension", "original_test_prefix": " def test_public_bytes(self):\n ext = x509.PrecertPoison()\n assert ext.public_bytes() == b\"\\x05\\x00\"", "test_prefix": " def test_public_bytes(self):\n ext = x509.PrecertPoison()\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 5974, "test_prefix_end_lineno": 5976, "test_target": "tests/x509/test_x509_ext.py::TestPrecertPoisonExtension::test_public_bytes", "ground_truth_oracle": "assert ext.public_bytes() == b\"\\x05\\x00\"", "ground_truth_oracle_lineno": 5976, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1052, "focal_method_end_lineno": 1053} {"index": 60, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ne", "test_class_name": "TestInvalidityDate", "original_test_prefix": " def test_ne(self):\n invalid1 = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 1))\n invalid2 = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 2))\n assert invalid1 != invalid2\n assert invalid1 != object()", "test_prefix": " def test_ne(self):\n invalid1 = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 1))\n invalid2 = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 2))\n \n assert invalid1 != object()", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 424, "test_prefix_end_lineno": 428, "test_target": "tests/x509/test_x509_ext.py::TestInvalidityDate::test_ne", "ground_truth_oracle": "assert invalid1 != invalid2", "ground_truth_oracle_lineno": 427, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class InvalidityDate(ExtensionType):\n oid = CRLEntryExtensionOID.INVALIDITY_DATE\n\n def __init__(self, invalidity_date: datetime.datetime) -> None:\n if not isinstance(invalidity_date, datetime.datetime):\n raise TypeError(\"invalidity_date must be a datetime.datetime\")\n\n self._invalidity_date = invalidity_date\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, InvalidityDate):\n return NotImplemented\n\n return self.invalidity_date == other.invalidity_date\n\n def __hash__(self) -> int:\n return hash(self.invalidity_date)\n\n @property\n def invalidity_date(self) -> datetime.datetime:\n return self._invalidity_date\n\n @property\n def invalidity_date_utc(self) -> datetime.datetime:\n if self._invalidity_date.tzinfo is None:\n return self._invalidity_date.replace(tzinfo=datetime.timezone.utc)\n else:\n return self._invalidity_date.astimezone(tz=datetime.timezone.utc)\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1822, "focal_method_end_lineno": 1855} {"index": 61, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_eq", "test_class_name": "TestInhibitAnyPolicy", "original_test_prefix": " def test_eq(self):\n iap = x509.InhibitAnyPolicy(1)\n iap2 = x509.InhibitAnyPolicy(1)\n assert iap == iap2", "test_prefix": " def test_eq(self):\n iap = x509.InhibitAnyPolicy(1)\n iap2 = x509.InhibitAnyPolicy(1)\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 5361, "test_prefix_end_lineno": 5364, "test_target": "tests/x509/test_x509_ext.py::TestInhibitAnyPolicy::test_eq", "ground_truth_oracle": "assert iap == iap2", "ground_truth_oracle_lineno": 5364, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class InhibitAnyPolicy(ExtensionType):\n oid = ExtensionOID.INHIBIT_ANY_POLICY\n\n def __init__(self, skip_certs: int) -> None:\n if not isinstance(skip_certs, int):\n raise TypeError(\"skip_certs must be an integer\")\n\n if skip_certs < 0:\n raise ValueError(\"skip_certs must be a non-negative integer\")\n\n self._skip_certs = skip_certs\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, InhibitAnyPolicy):\n return NotImplemented\n\n return self.skip_certs == other.skip_certs\n\n def __hash__(self) -> int:\n return hash(self.skip_certs)\n\n @property\n def skip_certs(self) -> int:\n return self._skip_certs\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1104, "focal_method_end_lineno": 1133} {"index": 62, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_nocheck", "test_class_name": "TestOCSPNoCheckExtension", "original_test_prefix": " def test_nocheck(self, backend):\n cert = _load_cert(\n os.path.join(\"x509\", \"custom\", \"ocsp_nocheck.pem\"),\n x509.load_pem_x509_certificate,\n )\n ext = cert.extensions.get_extension_for_oid(ExtensionOID.OCSP_NO_CHECK)\n assert isinstance(ext.value, x509.OCSPNoCheck)", "test_prefix": " def test_nocheck(self, backend):\n cert = _load_cert(\n os.path.join(\"x509\", \"custom\", \"ocsp_nocheck.pem\"),\n x509.load_pem_x509_certificate,\n )\n ext = cert.extensions.get_extension_for_oid(ExtensionOID.OCSP_NO_CHECK)\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 5310, "test_prefix_end_lineno": 5316, "test_target": "tests/x509/test_x509_ext.py::TestOCSPNoCheckExtension::test_nocheck", "ground_truth_oracle": "assert isinstance(ext.value, x509.OCSPNoCheck)", "ground_truth_oracle_lineno": 5316, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_extension_for_oid(\n self, oid: ObjectIdentifier\n ) -> Extension[ExtensionType]:\n for ext in self:\n if ext.oid == oid:\n return ext\n\n raise ExtensionNotFound(f\"No {oid} extension was found\", oid)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 116, "focal_method_end_lineno": 123} {"index": 63, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_gcm_tag_with_only_aad", "test_class_name": "TestAESModeGCM", "original_test_prefix": " def test_gcm_tag_with_only_aad(self, backend):\n key = binascii.unhexlify(b\"5211242698bed4774a090620a6ca56f3\")\n iv = binascii.unhexlify(b\"b1e1349120b6e832ef976f5d\")\n aad = binascii.unhexlify(b\"b6d729aab8e6416d7002b9faa794c410d8d2f193\")\n tag = binascii.unhexlify(b\"0f247e7f9c2505de374006738018493b\")\n\n cipher = base.Cipher(\n algorithms.AES(key), modes.GCM(iv), backend=backend\n )\n encryptor = cipher.encryptor()\n encryptor.authenticate_additional_data(aad)\n encryptor.finalize()\n assert encryptor.tag == tag", "test_prefix": " def test_gcm_tag_with_only_aad(self, backend):\n key = binascii.unhexlify(b\"5211242698bed4774a090620a6ca56f3\")\n iv = binascii.unhexlify(b\"b1e1349120b6e832ef976f5d\")\n aad = binascii.unhexlify(b\"b6d729aab8e6416d7002b9faa794c410d8d2f193\")\n tag = binascii.unhexlify(b\"0f247e7f9c2505de374006738018493b\")\n\n cipher = base.Cipher(\n algorithms.AES(key), modes.GCM(iv), backend=backend\n )\n encryptor = cipher.encryptor()\n encryptor.authenticate_additional_data(aad)\n encryptor.finalize()\n ", "test_prefix_file_path": "tests/hazmat/primitives/test_aes_gcm.py", "test_prefix_start_lineno": 41, "test_prefix_end_lineno": 53, "test_target": "tests/hazmat/primitives/test_aes_gcm.py::TestAESModeGCM::test_gcm_tag_with_only_aad", "ground_truth_oracle": "assert encryptor.tag == tag", "ground_truth_oracle_lineno": 53, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @typing.overload\n def encryptor(\n self: Cipher[modes.ModeWithAuthenticationTag],\n ) -> AEADEncryptionContext: ...", "focal_method_file_path": "src/cryptography/hazmat/primitives/ciphers/base.py", "focal_method_start_lineno": 97, "focal_method_end_lineno": 100} {"index": 64, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_bytes", "test_class_name": "TestSubjectAlternativeName", "original_test_prefix": " def test_public_bytes(self):\n ext = x509.SubjectAlternativeName([x509.DNSName(\"cryptography.io\")])\n assert ext.public_bytes() == b\"0\\x11\\x82\\x0fcryptography.io\"", "test_prefix": " def test_public_bytes(self):\n ext = x509.SubjectAlternativeName([x509.DNSName(\"cryptography.io\")])\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 2649, "test_prefix_end_lineno": 2651, "test_target": "tests/x509/test_x509_ext.py::TestSubjectAlternativeName::test_public_bytes", "ground_truth_oracle": "assert ext.public_bytes() == b\"0\\x11\\x82\\x0fcryptography.io\"", "ground_truth_oracle_lineno": 2651, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1645, "focal_method_end_lineno": 1646} {"index": 65, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_sign_ed448_key", "test_class_name": "TestCertificateRevocationListBuilder", "original_test_prefix": " @pytest.mark.supported(\n only_if=lambda backend: backend.ed448_supported(),\n skip_message=\"Requires OpenSSL with Ed448 support\",\n )\n def test_sign_ed448_key(self, backend):\n private_key = ed448.Ed448PrivateKey.generate()\n invalidity_date = x509.InvalidityDate(\n datetime.datetime(2002, 1, 1, 0, 0)\n )\n ian = x509.IssuerAlternativeName(\n [x509.UniformResourceIdentifier(\"https://cryptography.io\")]\n )\n revoked_cert0 = (\n x509.RevokedCertificateBuilder()\n .serial_number(2)\n .revocation_date(datetime.datetime(2012, 1, 1, 1, 1))\n .add_extension(invalidity_date, False)\n .build(backend)\n )\n last_update = datetime.datetime(2002, 1, 1, 12, 1)\n next_update = datetime.datetime(2030, 1, 1, 12, 1)\n builder = (\n x509.CertificateRevocationListBuilder()\n .issuer_name(\n x509.Name(\n [\n x509.NameAttribute(\n NameOID.COMMON_NAME, \"cryptography.io CA\"\n )\n ]\n )\n )\n .last_update(last_update)\n .next_update(next_update)\n .add_revoked_certificate(revoked_cert0)\n .add_extension(ian, False)\n )\n\n crl = builder.sign(private_key, None, backend)\n assert crl.signature_hash_algorithm is None\n assert crl.signature_algorithm_oid == SignatureAlgorithmOID.ED448\n assert (\n crl.extensions.get_extension_for_class(\n x509.IssuerAlternativeName\n ).value\n == ian\n )\n assert crl[0].serial_number == revoked_cert0.serial_number\n with pytest.warns(utils.DeprecatedIn42):\n assert crl[0].revocation_date == revoked_cert0.revocation_date\n assert crl[0].revocation_date_utc == revoked_cert0.revocation_date_utc\n assert len(crl[0].extensions) == 1\n ext = crl[0].extensions.get_extension_for_class(x509.InvalidityDate)\n assert ext.critical is False\n assert ext.value == invalidity_date", "test_prefix": " @pytest.mark.supported(\n only_if=lambda backend: backend.ed448_supported(),\n skip_message=\"Requires OpenSSL with Ed448 support\",\n )\n def test_sign_ed448_key(self, backend):\n private_key = ed448.Ed448PrivateKey.generate()\n invalidity_date = x509.InvalidityDate(\n datetime.datetime(2002, 1, 1, 0, 0)\n )\n ian = x509.IssuerAlternativeName(\n [x509.UniformResourceIdentifier(\"https://cryptography.io\")]\n )\n revoked_cert0 = (\n x509.RevokedCertificateBuilder()\n .serial_number(2)\n .revocation_date(datetime.datetime(2012, 1, 1, 1, 1))\n .add_extension(invalidity_date, False)\n .build(backend)\n )\n last_update = datetime.datetime(2002, 1, 1, 12, 1)\n next_update = datetime.datetime(2030, 1, 1, 12, 1)\n builder = (\n x509.CertificateRevocationListBuilder()\n .issuer_name(\n x509.Name(\n [\n x509.NameAttribute(\n NameOID.COMMON_NAME, \"cryptography.io CA\"\n )\n ]\n )\n )\n .last_update(last_update)\n .next_update(next_update)\n .add_revoked_certificate(revoked_cert0)\n .add_extension(ian, False)\n )\n\n crl = builder.sign(private_key, None, backend)\n \n assert crl.signature_algorithm_oid == SignatureAlgorithmOID.ED448\n assert (\n crl.extensions.get_extension_for_class(\n x509.IssuerAlternativeName\n ).value\n == ian\n )\n assert crl[0].serial_number == revoked_cert0.serial_number\n with pytest.warns(utils.DeprecatedIn42):\n assert crl[0].revocation_date == revoked_cert0.revocation_date\n assert crl[0].revocation_date_utc == revoked_cert0.revocation_date_utc\n assert len(crl[0].extensions) == 1\n ext = crl[0].extensions.get_extension_for_class(x509.InvalidityDate)\n assert ext.critical is False\n assert ext.value == invalidity_date", "test_prefix_file_path": "tests/x509/test_x509_crlbuilder.py", "test_prefix_start_lineno": 785, "test_prefix_end_lineno": 839, "test_target": "tests/x509/test_x509_crlbuilder.py::TestCertificateRevocationListBuilder::test_sign_ed448_key", "ground_truth_oracle": "assert crl.signature_hash_algorithm is None", "ground_truth_oracle_lineno": 824, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def sign(\n self,\n private_key: CertificateIssuerPrivateKeyTypes,\n algorithm: _AllowedHashTypes | None,\n backend: typing.Any = None,\n *,\n rsa_padding: padding.PSS | padding.PKCS1v15 | None = None,\n ecdsa_deterministic: bool | None = None,\n ) -> CertificateRevocationList:\n if self._issuer_name is None:\n raise ValueError(\"A CRL must have an issuer name\")\n\n if self._last_update is None:\n raise ValueError(\"A CRL must have a last update time\")\n\n if self._next_update is None:\n raise ValueError(\"A CRL must have a next update time\")\n\n if rsa_padding is not None:\n if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)):\n raise TypeError(\"Padding must be PSS or PKCS1v15\")\n if not isinstance(private_key, rsa.RSAPrivateKey):\n raise TypeError(\"Padding is only supported for RSA keys\")\n\n if ecdsa_deterministic is not None:\n if not isinstance(private_key, ec.EllipticCurvePrivateKey):\n raise TypeError(\n \"Deterministic ECDSA is only supported for EC keys\"\n )\n\n return rust_x509.create_x509_crl(\n self,\n private_key,\n algorithm,\n rsa_padding,\n ecdsa_deterministic,\n )", "focal_method_file_path": "src/cryptography/x509/base.py", "focal_method_start_lineno": 735, "focal_method_end_lineno": 771} {"index": 66, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_hash", "test_class_name": "TestRelativeDistinguishedName", "original_test_prefix": " def test_hash(self):\n rdn1 = x509.RelativeDistinguishedName(\n [\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.1\"), \"value1\"),\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.2\"), \"value2\"),\n ]\n )\n rdn2 = x509.RelativeDistinguishedName(\n [\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.2\"), \"value2\"),\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.1\"), \"value1\"),\n ]\n )\n rdn3 = x509.RelativeDistinguishedName(\n [\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.1\"), \"value1\"),\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.2\"), \"value3\"),\n ]\n )\n assert hash(rdn1) == hash(rdn2)\n assert hash(rdn1) != hash(rdn3)", "test_prefix": " def test_hash(self):\n rdn1 = x509.RelativeDistinguishedName(\n [\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.1\"), \"value1\"),\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.2\"), \"value2\"),\n ]\n )\n rdn2 = x509.RelativeDistinguishedName(\n [\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.2\"), \"value2\"),\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.1\"), \"value1\"),\n ]\n )\n rdn3 = x509.RelativeDistinguishedName(\n [\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.1\"), \"value1\"),\n x509.NameAttribute(x509.ObjectIdentifier(\"2.999.2\"), \"value3\"),\n ]\n )\n \n assert hash(rdn1) != hash(rdn3)", "test_prefix_file_path": "tests/x509/test_x509.py", "test_prefix_start_lineno": 6214, "test_prefix_end_lineno": 6234, "test_target": "tests/x509/test_x509.py::TestRelativeDistinguishedName::test_hash", "ground_truth_oracle": "assert hash(rdn1) == hash(rdn2)", "ground_truth_oracle_lineno": 6233, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class RelativeDistinguishedName:\n def __init__(self, attributes: Iterable[NameAttribute]):\n attributes = list(attributes)\n if not attributes:\n raise ValueError(\"a relative distinguished name cannot be empty\")\n if not all(isinstance(x, NameAttribute) for x in attributes):\n raise TypeError(\"attributes must be an iterable of NameAttribute\")\n\n # Keep list and frozenset to preserve attribute order where it matters\n self._attributes = attributes\n self._attribute_set = frozenset(attributes)\n\n if len(self._attribute_set) != len(attributes):\n raise ValueError(\"duplicate attributes are not allowed\")\n\n def get_attributes_for_oid(\n self,\n oid: ObjectIdentifier,\n ) -> list[NameAttribute[str | bytes]]:\n return [i for i in self if i.oid == oid]\n\n def rfc4514_string(\n self, attr_name_overrides: _OidNameMap | None = None\n ) -> str:\n \"\"\"\n Format as RFC4514 Distinguished Name string.\n\n Within each RDN, attributes are joined by '+', although that is rarely\n used in certificates.\n \"\"\"\n return \"+\".join(\n attr.rfc4514_string(attr_name_overrides)\n for attr in self._attributes\n )\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, RelativeDistinguishedName):\n return NotImplemented\n\n return self._attribute_set == other._attribute_set\n\n def __hash__(self) -> int:\n return hash(self._attribute_set)\n\n def __iter__(self) -> Iterator[NameAttribute]:\n return iter(self._attributes)\n\n def __len__(self) -> int:\n return len(self._attributes)\n\n def __repr__(self) -> str:\n return f\"\"", "focal_method_file_path": "src/cryptography/x509/name.py", "focal_method_start_lineno": 227, "focal_method_end_lineno": 278} {"index": 67, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_load_key_and_certificates_key_only", "test_class_name": "TestPKCS12Loading", "original_test_prefix": " def test_load_key_and_certificates_key_only(self, backend):\n _, key = _load_ca(backend)\n assert isinstance(key, ec.EllipticCurvePrivateKey)\n parsed_key, parsed_cert, parsed_more_certs = load_vectors_from_file(\n os.path.join(\"pkcs12\", \"no-cert-key-aes256cbc.p12\"),\n lambda data: load_key_and_certificates(\n data.read(), b\"cryptography\", backend\n ),\n mode=\"rb\",\n )\n assert isinstance(parsed_key, ec.EllipticCurvePrivateKey)\n assert parsed_key.private_numbers() == key.private_numbers()\n assert parsed_cert is None\n assert parsed_more_certs == []", "test_prefix": " def test_load_key_and_certificates_key_only(self, backend):\n _, key = _load_ca(backend)\n assert isinstance(key, ec.EllipticCurvePrivateKey)\n parsed_key, parsed_cert, parsed_more_certs = load_vectors_from_file(\n os.path.join(\"pkcs12\", \"no-cert-key-aes256cbc.p12\"),\n lambda data: load_key_and_certificates(\n data.read(), b\"cryptography\", backend\n ),\n mode=\"rb\",\n )\n assert isinstance(parsed_key, ec.EllipticCurvePrivateKey)\n \n assert parsed_cert is None\n assert parsed_more_certs == []", "test_prefix_file_path": "tests/hazmat/primitives/test_pkcs12.py", "test_prefix_start_lineno": 114, "test_prefix_end_lineno": 127, "test_target": "tests/hazmat/primitives/test_pkcs12.py::TestPKCS12Loading::test_load_key_and_certificates_key_only", "ground_truth_oracle": "assert parsed_key.private_numbers() == key.private_numbers()", "ground_truth_oracle_lineno": 125, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @abc.abstractmethod\n def private_numbers(self) -> EllipticCurvePrivateNumbers:\n \"\"\"\n Returns an EllipticCurvePrivateNumbers.\n \"\"\"", "focal_method_file_path": "src/cryptography/hazmat/primitives/asymmetric/ec.py", "focal_method_start_lineno": 114, "focal_method_end_lineno": 118} {"index": 68, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_hash", "test_class_name": "TestPolicyInformation", "original_test_prefix": " def test_hash(self):\n pi = x509.PolicyInformation(\n x509.ObjectIdentifier(\"1.2.3\"),\n [\"string\", x509.UserNotice(None, \"hi\")],\n )\n pi2 = x509.PolicyInformation(\n x509.ObjectIdentifier(\"1.2.3\"),\n [\"string\", x509.UserNotice(None, \"hi\")],\n )\n pi3 = x509.PolicyInformation(x509.ObjectIdentifier(\"1.2.3\"), None)\n assert hash(pi) == hash(pi2)\n assert hash(pi) != hash(pi3)", "test_prefix": " def test_hash(self):\n pi = x509.PolicyInformation(\n x509.ObjectIdentifier(\"1.2.3\"),\n [\"string\", x509.UserNotice(None, \"hi\")],\n )\n pi2 = x509.PolicyInformation(\n x509.ObjectIdentifier(\"1.2.3\"),\n [\"string\", x509.UserNotice(None, \"hi\")],\n )\n pi3 = x509.PolicyInformation(x509.ObjectIdentifier(\"1.2.3\"), None)\n assert hash(pi) == hash(pi2)\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 621, "test_prefix_end_lineno": 632, "test_target": "tests/x509/test_x509_ext.py::TestPolicyInformation::test_hash", "ground_truth_oracle": "assert hash(pi) != hash(pi3)", "ground_truth_oracle_lineno": 632, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class PolicyInformation:\n def __init__(\n self,\n policy_identifier: ObjectIdentifier,\n policy_qualifiers: Iterable[str | UserNotice] | None,\n ) -> None:\n if not isinstance(policy_identifier, ObjectIdentifier):\n raise TypeError(\"policy_identifier must be an ObjectIdentifier\")\n\n self._policy_identifier = policy_identifier\n\n if policy_qualifiers is not None:\n policy_qualifiers = list(policy_qualifiers)\n if not all(\n isinstance(x, (str, UserNotice)) for x in policy_qualifiers\n ):\n raise TypeError(\n \"policy_qualifiers must be a list of strings and/or \"\n \"UserNotice objects or None\"\n )\n\n self._policy_qualifiers = policy_qualifiers\n\n def __repr__(self) -> str:\n return (\n f\"\"\n )\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, PolicyInformation):\n return NotImplemented\n\n return (\n self.policy_identifier == other.policy_identifier\n and self.policy_qualifiers == other.policy_qualifiers\n )\n\n def __hash__(self) -> int:\n if self.policy_qualifiers is not None:\n pq = tuple(self.policy_qualifiers)\n else:\n pq = None\n\n return hash((self.policy_identifier, pq))\n\n @property\n def policy_identifier(self) -> ObjectIdentifier:\n return self._policy_identifier\n\n @property\n def policy_qualifiers(\n self,\n ) -> list[str | UserNotice] | None:\n return self._policy_qualifiers", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 848, "focal_method_end_lineno": 902} {"index": 69, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_repr", "test_class_name": "TestPrecertPoisonExtension", "original_test_prefix": " def test_repr(self):\n pcp = x509.PrecertPoison()\n\n assert repr(pcp) == \"\"", "test_prefix": " def test_repr(self):\n pcp = x509.PrecertPoison()\n\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 5969, "test_prefix_end_lineno": 5972, "test_target": "tests/x509/test_x509_ext.py::TestPrecertPoisonExtension::test_repr", "ground_truth_oracle": "assert repr(pcp) == \"\"", "ground_truth_oracle_lineno": 5972, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class PrecertPoison(ExtensionType):\n oid = ExtensionOID.PRECERT_POISON\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, PrecertPoison):\n return NotImplemented\n\n return True\n\n def __hash__(self) -> int:\n return hash(PrecertPoison)\n\n def __repr__(self) -> str:\n return \"\"\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1037, "focal_method_end_lineno": 1053} {"index": 70, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_hash", "test_class_name": "TestCRLReason", "original_test_prefix": " def test_hash(self):\n reason1 = x509.CRLReason(x509.ReasonFlags.unspecified)\n reason2 = x509.CRLReason(x509.ReasonFlags.unspecified)\n reason3 = x509.CRLReason(x509.ReasonFlags.ca_compromise)\n\n assert hash(reason1) == hash(reason2)\n assert hash(reason1) != hash(reason3)", "test_prefix": " def test_hash(self):\n reason1 = x509.CRLReason(x509.ReasonFlags.unspecified)\n reason2 = x509.CRLReason(x509.ReasonFlags.unspecified)\n reason3 = x509.CRLReason(x509.ReasonFlags.ca_compromise)\n\n \n assert hash(reason1) != hash(reason3)", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 365, "test_prefix_end_lineno": 371, "test_target": "tests/x509/test_x509_ext.py::TestCRLReason::test_hash", "ground_truth_oracle": "assert hash(reason1) == hash(reason2)", "ground_truth_oracle_lineno": 370, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class CRLReason(ExtensionType):\n oid = CRLEntryExtensionOID.CRL_REASON\n\n def __init__(self, reason: ReasonFlags) -> None:\n if not isinstance(reason, ReasonFlags):\n raise TypeError(\"reason must be an element from ReasonFlags\")\n\n self._reason = reason\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, CRLReason):\n return NotImplemented\n\n return self.reason == other.reason\n\n def __hash__(self) -> int:\n return hash(self.reason)\n\n @property\n def reason(self) -> ReasonFlags:\n return self._reason\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1793, "focal_method_end_lineno": 1819} {"index": 71, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_valid_pss_parameters_maximum", "test_class_name": "TestPSS", "original_test_prefix": " def test_valid_pss_parameters_maximum(self):\n algorithm = hashes.SHA256()\n mgf = padding.MGF1(algorithm)\n pss = padding.PSS(mgf=mgf, salt_length=padding.PSS.MAX_LENGTH)\n assert pss._mgf == mgf\n assert pss._salt_length == padding.PSS.MAX_LENGTH", "test_prefix": " def test_valid_pss_parameters_maximum(self):\n algorithm = hashes.SHA256()\n mgf = padding.MGF1(algorithm)\n pss = padding.PSS(mgf=mgf, salt_length=padding.PSS.MAX_LENGTH)\n \n assert pss._salt_length == padding.PSS.MAX_LENGTH", "test_prefix_file_path": "tests/hazmat/primitives/test_rsa.py", "test_prefix_start_lineno": 1633, "test_prefix_end_lineno": 1638, "test_target": "tests/hazmat/primitives/test_rsa.py::TestPSS::test_valid_pss_parameters_maximum", "ground_truth_oracle": "assert pss._mgf == mgf", "ground_truth_oracle_lineno": 1637, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class PSS(AsymmetricPadding):\n MAX_LENGTH = _MaxLength()\n AUTO = _Auto()\n DIGEST_LENGTH = _DigestLength()\n name = \"EMSA-PSS\"\n _salt_length: int | _MaxLength | _Auto | _DigestLength\n\n def __init__(\n self,\n mgf: MGF,\n salt_length: int | _MaxLength | _Auto | _DigestLength,\n ) -> None:\n self._mgf = mgf\n\n if not isinstance(\n salt_length, (int, _MaxLength, _Auto, _DigestLength)\n ):\n raise TypeError(\n \"salt_length must be an integer, MAX_LENGTH, \"\n \"DIGEST_LENGTH, or AUTO\"\n )\n\n if isinstance(salt_length, int) and salt_length < 0:\n raise ValueError(\"salt_length must be zero or greater.\")\n\n self._salt_length = salt_length\n\n @property\n def mgf(self) -> MGF:\n return self._mgf", "focal_method_file_path": "src/cryptography/hazmat/primitives/asymmetric/padding.py", "focal_method_start_lineno": 32, "focal_method_end_lineno": 61} {"index": 72, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_bytes", "test_class_name": "TestPolicyConstraints", "original_test_prefix": " def test_public_bytes(self):\n ext = x509.PolicyConstraints(2, 1)\n assert ext.public_bytes() == b\"0\\x06\\x80\\x01\\x02\\x81\\x01\\x01\"", "test_prefix": " def test_public_bytes(self):\n ext = x509.PolicyConstraints(2, 1)\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 3086, "test_prefix_end_lineno": 3088, "test_target": "tests/x509/test_x509_ext.py::TestPolicyConstraints::test_public_bytes", "ground_truth_oracle": "assert ext.public_bytes() == b\"0\\x06\\x80\\x01\\x02\\x81\\x01\\x01\"", "ground_truth_oracle_lineno": 3088, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 814, "focal_method_end_lineno": 815} {"index": 73, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_key_equality", "test_class_name": "", "original_test_prefix": "@pytest.mark.supported(\n only_if=lambda backend: backend.ed448_supported(),\n skip_message=\"Requires OpenSSL with Ed448 support\",\n)\ndef test_public_key_equality(backend):\n key_bytes = load_vectors_from_file(\n os.path.join(\"asymmetric\", \"Ed448\", \"ed448-pkcs8.der\"),\n lambda derfile: derfile.read(),\n mode=\"rb\",\n )\n key1 = serialization.load_der_private_key(key_bytes, None).public_key()\n key2 = serialization.load_der_private_key(key_bytes, None).public_key()\n key3 = Ed448PrivateKey.generate().public_key()\n assert key1 == key2\n assert key1 != key3\n assert key1 != object()\n\n with pytest.raises(TypeError):\n key1 < key2 # type: ignore[operator]", "test_prefix": "@pytest.mark.supported(\n only_if=lambda backend: backend.ed448_supported(),\n skip_message=\"Requires OpenSSL with Ed448 support\",\n)\ndef test_public_key_equality(backend):\n key_bytes = load_vectors_from_file(\n os.path.join(\"asymmetric\", \"Ed448\", \"ed448-pkcs8.der\"),\n lambda derfile: derfile.read(),\n mode=\"rb\",\n )\n key1 = serialization.load_der_private_key(key_bytes, None).public_key()\n key2 = serialization.load_der_private_key(key_bytes, None).public_key()\n key3 = Ed448PrivateKey.generate().public_key()\n assert key1 == key2\n \n assert key1 != object()\n\n with pytest.raises(TypeError):\n key1 < key2 # type: ignore[operator]", "test_prefix_file_path": "tests/hazmat/primitives/test_ed448.py", "test_prefix_start_lineno": 289, "test_prefix_end_lineno": 307, "test_target": "tests/hazmat/primitives/test_ed448.py::test_public_key_equality", "ground_truth_oracle": "assert key1 != key3", "ground_truth_oracle_lineno": 303, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @abc.abstractmethod\n def public_key(self) -> Ed448PublicKey:\n \"\"\"\n The Ed448PublicKey derived from the private key.\n \"\"\"", "focal_method_file_path": "src/cryptography/hazmat/primitives/asymmetric/ed448.py", "focal_method_start_lineno": 93, "focal_method_end_lineno": 97} {"index": 74, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_exchange", "test_class_name": "TestDH", "original_test_prefix": " def test_exchange(self, backend):\n parameters = FFDH3072_P.parameters(backend)\n assert isinstance(parameters, dh.DHParameters)\n\n key1 = parameters.generate_private_key()\n key2 = parameters.generate_private_key()\n\n symkey1 = key1.exchange(key2.public_key())\n assert symkey1\n assert len(symkey1) == 3072 // 8\n\n symkey2 = key2.exchange(key1.public_key())\n assert symkey1 == symkey2", "test_prefix": " def test_exchange(self, backend):\n parameters = FFDH3072_P.parameters(backend)\n assert isinstance(parameters, dh.DHParameters)\n\n key1 = parameters.generate_private_key()\n key2 = parameters.generate_private_key()\n\n symkey1 = key1.exchange(key2.public_key())\n assert symkey1\n \n\n symkey2 = key2.exchange(key1.public_key())\n assert symkey1 == symkey2", "test_prefix_file_path": "tests/hazmat/primitives/test_dh.py", "test_prefix_start_lineno": 291, "test_prefix_end_lineno": 303, "test_target": "tests/hazmat/primitives/test_dh.py::TestDH::test_exchange", "ground_truth_oracle": "assert len(symkey1) == 3072 // 8", "ground_truth_oracle_lineno": 300, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @abc.abstractmethod\n def exchange(self, peer_public_key: DHPublicKey) -> bytes:\n \"\"\"\n Given peer's DHPublicKey, carry out the key exchange and\n return shared key as bytes.\n \"\"\"", "focal_method_file_path": "src/cryptography/hazmat/primitives/asymmetric/dh.py", "focal_method_start_lineno": 115, "focal_method_end_lineno": 120} {"index": 75, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_hash", "test_class_name": "TestInhibitAnyPolicy", "original_test_prefix": " def test_hash(self):\n iap = x509.InhibitAnyPolicy(1)\n iap2 = x509.InhibitAnyPolicy(1)\n iap3 = x509.InhibitAnyPolicy(4)\n assert hash(iap) == hash(iap2)\n assert hash(iap) != hash(iap3)", "test_prefix": " def test_hash(self):\n iap = x509.InhibitAnyPolicy(1)\n iap2 = x509.InhibitAnyPolicy(1)\n iap3 = x509.InhibitAnyPolicy(4)\n assert hash(iap) == hash(iap2)\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 5372, "test_prefix_end_lineno": 5377, "test_target": "tests/x509/test_x509_ext.py::TestInhibitAnyPolicy::test_hash", "ground_truth_oracle": "assert hash(iap) != hash(iap3)", "ground_truth_oracle_lineno": 5377, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class InhibitAnyPolicy(ExtensionType):\n oid = ExtensionOID.INHIBIT_ANY_POLICY\n\n def __init__(self, skip_certs: int) -> None:\n if not isinstance(skip_certs, int):\n raise TypeError(\"skip_certs must be an integer\")\n\n if skip_certs < 0:\n raise ValueError(\"skip_certs must be a non-negative integer\")\n\n self._skip_certs = skip_certs\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, InhibitAnyPolicy):\n return NotImplemented\n\n return self.skip_certs == other.skip_certs\n\n def __hash__(self) -> int:\n return hash(self.skip_certs)\n\n @property\n def skip_certs(self) -> int:\n return self._skip_certs\n\n def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1104, "focal_method_end_lineno": 1133} {"index": 76, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_unaligned_block_encryption", "test_class_name": "TestCipherContext", "original_test_prefix": " def test_unaligned_block_encryption(self, backend):\n cipher = Cipher(\n algorithms.AES(binascii.unhexlify(b\"0\" * 32)), modes.ECB(), backend\n )\n encryptor = cipher.encryptor()\n ct = encryptor.update(b\"a\" * 15)\n assert ct == b\"\"\n ct += encryptor.update(b\"a\" * 65)\n assert len(ct) == 80\n ct += encryptor.finalize()\n decryptor = cipher.decryptor()\n pt = decryptor.update(ct[:3])\n assert pt == b\"\"\n pt += decryptor.update(ct[3:])\n assert len(pt) == 80\n assert pt == b\"a\" * 80\n decryptor.finalize()", "test_prefix": " def test_unaligned_block_encryption(self, backend):\n cipher = Cipher(\n algorithms.AES(binascii.unhexlify(b\"0\" * 32)), modes.ECB(), backend\n )\n encryptor = cipher.encryptor()\n ct = encryptor.update(b\"a\" * 15)\n assert ct == b\"\"\n ct += encryptor.update(b\"a\" * 65)\n assert len(ct) == 80\n ct += encryptor.finalize()\n decryptor = cipher.decryptor()\n pt = decryptor.update(ct[:3])\n \n pt += decryptor.update(ct[3:])\n assert len(pt) == 80\n assert pt == b\"a\" * 80\n decryptor.finalize()", "test_prefix_file_path": "tests/hazmat/primitives/test_block.py", "test_prefix_start_lineno": 88, "test_prefix_end_lineno": 104, "test_target": "tests/hazmat/primitives/test_block.py::TestCipherContext::test_unaligned_block_encryption", "ground_truth_oracle": "assert pt == b\"\"", "ground_truth_oracle_lineno": 100, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @abc.abstractmethod\n def update(self, data: Buffer) -> bytes:\n \"\"\"\n Processes the provided bytes through the cipher and returns the results\n as bytes.\n \"\"\"", "focal_method_file_path": "src/cryptography/hazmat/primitives/ciphers/base.py", "focal_method_start_lineno": 17, "focal_method_end_lineno": 22} {"index": 77, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_key_cert_sign_crl_sign", "test_class_name": "TestKeyUsageExtension", "original_test_prefix": " def test_key_cert_sign_crl_sign(self, backend):\n cert = _load_cert(\n os.path.join(\n \"x509\", \"PKITS_data\", \"certs\", \"pathLenConstraint6CACert.crt\"\n ),\n x509.load_der_x509_certificate,\n )\n ext = cert.extensions.get_extension_for_class(x509.KeyUsage)\n assert ext is not None\n assert ext.critical is True\n\n ku = ext.value\n assert ku.digital_signature is False\n assert ku.content_commitment is False\n assert ku.key_encipherment is False\n assert ku.data_encipherment is False\n assert ku.key_agreement is False\n assert ku.key_cert_sign is True\n assert ku.crl_sign is True", "test_prefix": " def test_key_cert_sign_crl_sign(self, backend):\n cert = _load_cert(\n os.path.join(\n \"x509\", \"PKITS_data\", \"certs\", \"pathLenConstraint6CACert.crt\"\n ),\n x509.load_der_x509_certificate,\n )\n ext = cert.extensions.get_extension_for_class(x509.KeyUsage)\n assert ext is not None\n assert ext.critical is True\n\n ku = ext.value\n assert ku.digital_signature is False\n assert ku.content_commitment is False\n assert ku.key_encipherment is False\n \n assert ku.key_agreement is False\n assert ku.key_cert_sign is True\n assert ku.crl_sign is True", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 1857, "test_prefix_end_lineno": 1875, "test_target": "tests/x509/test_x509_ext.py::TestKeyUsageExtension::test_key_cert_sign_crl_sign", "ground_truth_oracle": "assert ku.data_encipherment is False", "ground_truth_oracle_lineno": 1872, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_extension_for_class(\n self, extclass: type[ExtensionTypeVar]\n ) -> Extension[ExtensionTypeVar]:\n if extclass is UnrecognizedExtension:\n raise TypeError(\n \"UnrecognizedExtension can't be used with \"\n \"get_extension_for_class because more than one instance of the\"\n \" class may be present.\"\n )\n\n for ext in self:\n if isinstance(ext.value, extclass):\n return ext\n\n raise ExtensionNotFound(\n f\"No {extclass} extension was found\", extclass.oid\n )", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 125, "focal_method_end_lineno": 141} {"index": 78, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_bytes", "test_class_name": "TestUnrecognizedExtension", "original_test_prefix": " def test_public_bytes(self):\n ext1 = x509.UnrecognizedExtension(\n x509.ObjectIdentifier(\"1.2.3.5\"), b\"\\x03\\x02\\x01\"\n )\n assert ext1.public_bytes() == b\"\\x03\\x02\\x01\"\n\n # The following creates a BasicConstraints extension with an invalid\n # value. The serialization code should still handle it correctly by\n # special-casing UnrecognizedExtension.\n ext2 = x509.UnrecognizedExtension(\n x509.oid.ExtensionOID.BASIC_CONSTRAINTS, b\"\\x03\\x02\\x01\"\n )\n assert ext2.public_bytes() == b\"\\x03\\x02\\x01\"", "test_prefix": " def test_public_bytes(self):\n ext1 = x509.UnrecognizedExtension(\n x509.ObjectIdentifier(\"1.2.3.5\"), b\"\\x03\\x02\\x01\"\n )\n \n\n # The following creates a BasicConstraints extension with an invalid\n # value. The serialization code should still handle it correctly by\n # special-casing UnrecognizedExtension.\n ext2 = x509.UnrecognizedExtension(\n x509.oid.ExtensionOID.BASIC_CONSTRAINTS, b\"\\x03\\x02\\x01\"\n )\n assert ext2.public_bytes() == b\"\\x03\\x02\\x01\"", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 273, "test_prefix_end_lineno": 285, "test_target": "tests/x509/test_x509_ext.py::TestUnrecognizedExtension::test_public_bytes", "ground_truth_oracle": "assert ext1.public_bytes() == b\"\\x03\\x02\\x01\"", "ground_truth_oracle_lineno": 277, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def public_bytes(self) -> bytes:\n return self.value", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 2527, "focal_method_end_lineno": 2528} {"index": 79, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_eq", "test_class_name": "TestExtension", "original_test_prefix": " def test_eq(self):\n ext1 = x509.Extension(\n x509.ObjectIdentifier(\"1.2.3.4\"),\n False,\n x509.BasicConstraints(ca=False, path_length=None),\n )\n ext2 = x509.Extension(\n x509.ObjectIdentifier(\"1.2.3.4\"),\n False,\n x509.BasicConstraints(ca=False, path_length=None),\n )\n assert ext1 == ext2", "test_prefix": " def test_eq(self):\n ext1 = x509.Extension(\n x509.ObjectIdentifier(\"1.2.3.4\"),\n False,\n x509.BasicConstraints(ca=False, path_length=None),\n )\n ext2 = x509.Extension(\n x509.ObjectIdentifier(\"1.2.3.4\"),\n False,\n x509.BasicConstraints(ca=False, path_length=None),\n )\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 86, "test_prefix_end_lineno": 97, "test_target": "tests/x509/test_x509_ext.py::TestExtension::test_eq", "ground_truth_oracle": "assert ext1 == ext2", "ground_truth_oracle_lineno": 97, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class Extension(typing.Generic[ExtensionTypeVar]):\n def __init__(\n self, oid: ObjectIdentifier, critical: bool, value: ExtensionTypeVar\n ) -> None:\n if not isinstance(oid, ObjectIdentifier):\n raise TypeError(\n \"oid argument must be an ObjectIdentifier instance.\"\n )\n\n if not isinstance(critical, bool):\n raise TypeError(\"critical must be a boolean value\")\n\n self._oid = oid\n self._critical = critical\n self._value = value\n\n @property\n def oid(self) -> ObjectIdentifier:\n return self._oid\n\n @property\n def critical(self) -> bool:\n return self._critical\n\n @property\n def value(self) -> ExtensionTypeVar:\n return self._value\n\n def __repr__(self) -> str:\n return (\n f\"\"\n )\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, Extension):\n return NotImplemented\n\n return (\n self.oid == other.oid\n and self.critical == other.critical\n and self.value == other.value\n )\n\n def __hash__(self) -> int:\n return hash((self.oid, self.critical, self.value))", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1449, "focal_method_end_lineno": 1494} {"index": 80, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_buffer_protocol", "test_class_name": "TestHOTP", "original_test_prefix": " def test_buffer_protocol(self, backend):\n key = bytearray(b\"a long key with lots of entropy goes here\")\n hotp = HOTP(key, 6, SHA1(), backend)\n assert hotp.generate(10) == b\"559978\"", "test_prefix": " def test_buffer_protocol(self, backend):\n key = bytearray(b\"a long key with lots of entropy goes here\")\n hotp = HOTP(key, 6, SHA1(), backend)\n ", "test_prefix_file_path": "tests/hazmat/primitives/twofactor/test_hotp.py", "test_prefix_start_lineno": 106, "test_prefix_end_lineno": 109, "test_target": "tests/hazmat/primitives/twofactor/test_hotp.py::TestHOTP::test_buffer_protocol", "ground_truth_oracle": "assert hotp.generate(10) == b\"559978\"", "ground_truth_oracle_lineno": 109, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def generate(self, counter: int) -> bytes:\n if not isinstance(counter, int):\n raise TypeError(\"Counter parameter must be an integer type.\")\n\n truncated_value = self._dynamic_truncate(counter)\n hotp = truncated_value % (10**self._length)\n return \"{0:0{1}}\".format(hotp, self._length).encode()", "focal_method_file_path": "src/cryptography/hazmat/primitives/twofactor/hotp.py", "focal_method_start_lineno": 70, "focal_method_end_lineno": 76} {"index": 81, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_eq", "test_class_name": "TestRegisteredID", "original_test_prefix": " def test_eq(self):\n gn = x509.RegisteredID(NameOID.COMMON_NAME)\n gn2 = x509.RegisteredID(NameOID.COMMON_NAME)\n assert gn == gn2", "test_prefix": " def test_eq(self):\n gn = x509.RegisteredID(NameOID.COMMON_NAME)\n gn2 = x509.RegisteredID(NameOID.COMMON_NAME)\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 2278, "test_prefix_end_lineno": 2281, "test_target": "tests/x509/test_x509_ext.py::TestRegisteredID::test_eq", "ground_truth_oracle": "assert gn == gn2", "ground_truth_oracle_lineno": 2281, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class RegisteredID(GeneralName):\n def __init__(self, value: ObjectIdentifier) -> None:\n if not isinstance(value, ObjectIdentifier):\n raise TypeError(\"value must be an ObjectIdentifier\")\n\n self._value = value\n\n @property\n def value(self) -> ObjectIdentifier:\n return self._value\n\n def __repr__(self) -> str:\n return f\"\"\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, RegisteredID):\n return NotImplemented\n\n return self.value == other.value\n\n def __hash__(self) -> int:\n return hash(self.value)", "focal_method_file_path": "src/cryptography/x509/general_name.py", "focal_method_start_lineno": 183, "focal_method_end_lineno": 204} {"index": 82, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ne", "test_class_name": "TestAccessDescription", "original_test_prefix": " def test_ne(self):\n ad = x509.AccessDescription(\n AuthorityInformationAccessOID.OCSP,\n x509.UniformResourceIdentifier(\"http://ocsp.domain.com\"),\n )\n ad2 = x509.AccessDescription(\n AuthorityInformationAccessOID.CA_ISSUERS,\n x509.UniformResourceIdentifier(\"http://ocsp.domain.com\"),\n )\n ad3 = x509.AccessDescription(\n AuthorityInformationAccessOID.OCSP,\n x509.UniformResourceIdentifier(\"http://notthesame\"),\n )\n assert ad != ad2\n assert ad != ad3\n assert ad != object()", "test_prefix": " def test_ne(self):\n ad = x509.AccessDescription(\n AuthorityInformationAccessOID.OCSP,\n x509.UniformResourceIdentifier(\"http://ocsp.domain.com\"),\n )\n ad2 = x509.AccessDescription(\n AuthorityInformationAccessOID.CA_ISSUERS,\n x509.UniformResourceIdentifier(\"http://ocsp.domain.com\"),\n )\n ad3 = x509.AccessDescription(\n AuthorityInformationAccessOID.OCSP,\n x509.UniformResourceIdentifier(\"http://notthesame\"),\n )\n assert ad != ad2\n assert ad != ad3\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 3011, "test_prefix_end_lineno": 3026, "test_target": "tests/x509/test_x509_ext.py::TestAccessDescription::test_ne", "ground_truth_oracle": "assert ad != object()", "ground_truth_oracle_lineno": 3026, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class AccessDescription:\n def __init__(\n self, access_method: ObjectIdentifier, access_location: GeneralName\n ) -> None:\n if not isinstance(access_method, ObjectIdentifier):\n raise TypeError(\"access_method must be an ObjectIdentifier\")\n\n if not isinstance(access_location, GeneralName):\n raise TypeError(\"access_location must be a GeneralName\")\n\n self._access_method = access_method\n self._access_location = access_location\n\n def __repr__(self) -> str:\n return (\n f\"\"\n )\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, AccessDescription):\n return NotImplemented\n\n return (\n self.access_method == other.access_method\n and self.access_location == other.access_location\n )\n\n def __hash__(self) -> int:\n return hash((self.access_method, self.access_location))\n\n @property\n def access_method(self) -> ObjectIdentifier:\n return self._access_method\n\n @property\n def access_location(self) -> GeneralName:\n return self._access_location", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 384, "focal_method_end_lineno": 421} {"index": 83, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_bytes", "test_class_name": "TestInvalidityDate", "original_test_prefix": " def test_public_bytes(self):\n ext = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 1))\n assert ext.public_bytes() == b\"\\x18\\x0f20150101010100Z\"", "test_prefix": " def test_public_bytes(self):\n ext = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 1))\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 443, "test_prefix_end_lineno": 445, "test_target": "tests/x509/test_x509_ext.py::TestInvalidityDate::test_public_bytes", "ground_truth_oracle": "assert ext.public_bytes() == b\"\\x18\\x0f20150101010100Z\"", "ground_truth_oracle_lineno": 445, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1854, "focal_method_end_lineno": 1855} {"index": 84, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_distinguished_name", "test_class_name": "TestNameAttribute", "original_test_prefix": " def test_distinguished_name(self):\n # Escaping\n na = x509.NameAttribute(NameOID.COMMON_NAME, 'James \"Jim\" Smith, III')\n assert na.rfc4514_string() == r\"CN=James \\\"Jim\\\" Smith\\, III\"\n na = x509.NameAttribute(NameOID.USER_ID, \"# escape+,;\\0this \")\n assert na.rfc4514_string() == r\"UID=\\# escape\\+\\,\\;\\00this\\ \"\n\n # Nonstandard attribute OID\n na = x509.NameAttribute(NameOID.BUSINESS_CATEGORY, \"banking\")\n assert na.rfc4514_string() == \"2.5.4.15=banking\"\n\n # non-utf8 attribute (bitstring with raw bytes)\n na_bytes = x509.NameAttribute(\n x509.ObjectIdentifier(\"2.5.4.45\"),\n b\"\\x01\\x02\\x03\\x04\",\n _ASN1Type.BitString,\n )\n assert na_bytes.rfc4514_string() == \"2.5.4.45=#01020304\"", "test_prefix": " def test_distinguished_name(self):\n # Escaping\n na = x509.NameAttribute(NameOID.COMMON_NAME, 'James \"Jim\" Smith, III')\n \n na = x509.NameAttribute(NameOID.USER_ID, \"# escape+,;\\0this \")\n assert na.rfc4514_string() == r\"UID=\\# escape\\+\\,\\;\\00this\\ \"\n\n # Nonstandard attribute OID\n na = x509.NameAttribute(NameOID.BUSINESS_CATEGORY, \"banking\")\n assert na.rfc4514_string() == \"2.5.4.15=banking\"\n\n # non-utf8 attribute (bitstring with raw bytes)\n na_bytes = x509.NameAttribute(\n x509.ObjectIdentifier(\"2.5.4.45\"),\n b\"\\x01\\x02\\x03\\x04\",\n _ASN1Type.BitString,\n )\n assert na_bytes.rfc4514_string() == \"2.5.4.45=#01020304\"", "test_prefix_file_path": "tests/x509/test_x509.py", "test_prefix_start_lineno": 6146, "test_prefix_end_lineno": 6163, "test_target": "tests/x509/test_x509.py::TestNameAttribute::test_distinguished_name", "ground_truth_oracle": "assert na.rfc4514_string() == r\"CN=James \\\"Jim\\\" Smith\\, III\"", "ground_truth_oracle_lineno": 6149, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def rfc4514_string(\n self, attr_name_overrides: _OidNameMap | None = None\n ) -> str:\n \"\"\"\n Format as RFC4514 Distinguished Name string.\n\n Use short attribute name if available, otherwise fall back to OID\n dotted string.\n \"\"\"\n attr_name = (\n attr_name_overrides.get(self.oid) if attr_name_overrides else None\n )\n if attr_name is None:\n attr_name = self.rfc4514_attribute_name\n\n return f\"{attr_name}={_escape_dn_value(self.value)}\"", "focal_method_file_path": "src/cryptography/x509/name.py", "focal_method_start_lineno": 197, "focal_method_end_lineno": 212} {"index": 85, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_key_equality", "test_class_name": "TestECEquality", "original_test_prefix": " def test_public_key_equality(self, backend):\n _skip_curve_unsupported(backend, ec.SECP256R1())\n key_bytes = load_vectors_from_file(\n os.path.join(\"asymmetric\", \"PKCS8\", \"ec_private_key.pem\"),\n lambda pemfile: pemfile.read().encode(),\n )\n key1 = serialization.load_pem_private_key(key_bytes, None).public_key()\n key2 = serialization.load_pem_private_key(key_bytes, None).public_key()\n key3 = ec.generate_private_key(ec.SECP256R1()).public_key()\n assert key1 == key2\n assert key1 != key3\n assert key1 != object()\n with pytest.raises(TypeError):\n key1 < key2 # type: ignore[operator]", "test_prefix": " def test_public_key_equality(self, backend):\n _skip_curve_unsupported(backend, ec.SECP256R1())\n key_bytes = load_vectors_from_file(\n os.path.join(\"asymmetric\", \"PKCS8\", \"ec_private_key.pem\"),\n lambda pemfile: pemfile.read().encode(),\n )\n key1 = serialization.load_pem_private_key(key_bytes, None).public_key()\n key2 = serialization.load_pem_private_key(key_bytes, None).public_key()\n key3 = ec.generate_private_key(ec.SECP256R1()).public_key()\n assert key1 == key2\n assert key1 != key3\n \n with pytest.raises(TypeError):\n key1 < key2 # type: ignore[operator]", "test_prefix_file_path": "tests/hazmat/primitives/test_ec.py", "test_prefix_start_lineno": 746, "test_prefix_end_lineno": 759, "test_target": "tests/hazmat/primitives/test_ec.py::TestECEquality::test_public_key_equality", "ground_truth_oracle": "assert key1 != object()", "ground_truth_oracle_lineno": 757, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @abc.abstractmethod\n def public_key(self) -> EllipticCurvePublicKey:\n \"\"\"\n The EllipticCurvePublicKey for this private key.\n \"\"\"", "focal_method_file_path": "src/cryptography/hazmat/primitives/asymmetric/ec.py", "focal_method_start_lineno": 84, "focal_method_end_lineno": 88} {"index": 86, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_bytes", "test_class_name": "TestInhibitAnyPolicy", "original_test_prefix": " def test_public_bytes(self):\n ext = x509.InhibitAnyPolicy(1)\n assert ext.public_bytes() == b\"\\x02\\x01\\x01\"", "test_prefix": " def test_public_bytes(self):\n ext = x509.InhibitAnyPolicy(1)\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 5379, "test_prefix_end_lineno": 5381, "test_target": "tests/x509/test_x509_ext.py::TestInhibitAnyPolicy::test_public_bytes", "ground_truth_oracle": "assert ext.public_bytes() == b\"\\x02\\x01\\x01\"", "ground_truth_oracle_lineno": 5381, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1132, "focal_method_end_lineno": 1133} {"index": 87, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_bytes", "test_class_name": "TestExtendedKeyUsage", "original_test_prefix": " def test_public_bytes(self):\n ext = x509.ExtendedKeyUsage(\n [x509.ObjectIdentifier(\"1.3.6\"), x509.ObjectIdentifier(\"1.3.7\")]\n )\n assert ext.public_bytes() == b\"0\\x08\\x06\\x02+\\x06\\x06\\x02+\\x07\"", "test_prefix": " def test_public_bytes(self):\n ext = x509.ExtendedKeyUsage(\n [x509.ObjectIdentifier(\"1.3.6\"), x509.ObjectIdentifier(\"1.3.7\")]\n )\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 1501, "test_prefix_end_lineno": 1505, "test_target": "tests/x509/test_x509_ext.py::TestExtendedKeyUsage::test_public_bytes", "ground_truth_oracle": "assert ext.public_bytes() == b\"0\\x08\\x06\\x02+\\x06\\x06\\x02+\\x07\"", "ground_truth_oracle_lineno": 1505, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1014, "focal_method_end_lineno": 1015} {"index": 88, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_generate", "test_class_name": "TestPrecertPoisonExtension", "original_test_prefix": " def test_generate(self, rsa_key_2048: rsa.RSAPrivateKey, backend):\n private_key = rsa_key_2048\n cert = (\n _make_certbuilder(private_key)\n .add_extension(x509.PrecertPoison(), critical=True)\n .sign(private_key, hashes.SHA256(), backend)\n )\n poison = cert.extensions.get_extension_for_oid(\n ExtensionOID.PRECERT_POISON\n ).value\n assert isinstance(poison, x509.PrecertPoison)", "test_prefix": " def test_generate(self, rsa_key_2048: rsa.RSAPrivateKey, backend):\n private_key = rsa_key_2048\n cert = (\n _make_certbuilder(private_key)\n .add_extension(x509.PrecertPoison(), critical=True)\n .sign(private_key, hashes.SHA256(), backend)\n )\n poison = cert.extensions.get_extension_for_oid(\n ExtensionOID.PRECERT_POISON\n ).value\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 5937, "test_prefix_end_lineno": 5947, "test_target": "tests/x509/test_x509_ext.py::TestPrecertPoisonExtension::test_generate", "ground_truth_oracle": "assert isinstance(poison, x509.PrecertPoison)", "ground_truth_oracle_lineno": 5947, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_extension_for_oid(\n self, oid: ObjectIdentifier\n ) -> Extension[ExtensionType]:\n for ext in self:\n if ext.oid == oid:\n return ext\n\n raise ExtensionNotFound(f\"No {oid} extension was found\", oid)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 116, "focal_method_end_lineno": 123} {"index": 89, "repo_name": "cryptography", "github": "https://github.com/pyca/cryptography.git", "version": "46.0.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e \".[test]\"\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_public_bytes", "test_class_name": "TestOCSPNoCheckExtension", "original_test_prefix": " def test_public_bytes(self):\n ext = x509.OCSPNoCheck()\n assert ext.public_bytes() == b\"\\x05\\x00\"", "test_prefix": " def test_public_bytes(self):\n ext = x509.OCSPNoCheck()\n ", "test_prefix_file_path": "tests/x509/test_x509_ext.py", "test_prefix_start_lineno": 5343, "test_prefix_end_lineno": 5345, "test_target": "tests/x509/test_x509_ext.py::TestOCSPNoCheckExtension::test_public_bytes", "ground_truth_oracle": "assert ext.public_bytes() == b\"\\x05\\x00\"", "ground_truth_oracle_lineno": 5345, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def public_bytes(self) -> bytes:\n return rust_x509.encode_extension_value(self)", "focal_method_file_path": "src/cryptography/x509/extensions.py", "focal_method_start_lineno": 1033, "focal_method_end_lineno": 1034} {"index": 90, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_unsafe_value", "test_class_name": "TestSanitizeForCSV", "original_test_prefix": " def test_unsafe_value(self):\n assert sanitize_value_for_csv(\"=OPEN()\") == \"'=OPEN()\"\n assert sanitize_value_for_csv(\"=1+2\") == \"'=1+2\"\n assert sanitize_value_for_csv('=1+2\";=1+2') == \"'=1+2\\\";=1+2\"", "test_prefix": " def test_unsafe_value(self):\n assert sanitize_value_for_csv(\"=OPEN()\") == \"'=OPEN()\"\n \n assert sanitize_value_for_csv('=1+2\";=1+2') == \"'=1+2\\\";=1+2\"", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 176, "test_prefix_end_lineno": 179, "test_target": "test/test_utils.py::TestSanitizeForCSV::test_unsafe_value", "ground_truth_oracle": "assert sanitize_value_for_csv(\"=1+2\") == \"'=1+2\"", "ground_truth_oracle_lineno": 178, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def sanitize_value_for_csv(value: str | float) -> str | float:\n \"\"\"\n Sanitizes a value that is being written to a CSV file to prevent CSV injection attacks.\n Reference: https://owasp.org/www-community/attacks/CSV_Injection\n \"\"\"\n if isinstance(value, (float, int)):\n return value\n unsafe_prefixes = [\"=\", \"+\", \"-\", \"@\", \"\\t\", \"\\n\"]\n unsafe_sequences = [\",=\", \",+\", \",-\", \",@\", \",\\t\", \",\\n\"]\n if any(value.startswith(prefix) for prefix in unsafe_prefixes) or any(\n sequence in value for sequence in unsafe_sequences\n ):\n value = f\"'{value}\"\n return value", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 783, "focal_method_end_lineno": 796} {"index": 91, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_safe_deepcopy_custom_object", "test_class_name": "TestSafeDeepCopy", "original_test_prefix": " def test_safe_deepcopy_custom_object(self):\n class CustomClass:\n def __init__(self, value):\n self.value = value\n\n original = CustomClass(10)\n copied = safe_deepcopy(original)\n\n assert copied.value == original.value\n assert copied is not original", "test_prefix": " def test_safe_deepcopy_custom_object(self):\n class CustomClass:\n def __init__(self, value):\n self.value = value\n\n original = CustomClass(10)\n copied = safe_deepcopy(original)\n\n assert copied.value == original.value\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 719, "test_prefix_end_lineno": 728, "test_target": "test/test_utils.py::TestSafeDeepCopy::test_safe_deepcopy_custom_object", "ground_truth_oracle": "assert copied is not original", "ground_truth_oracle_lineno": 728, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def safe_deepcopy(obj: Any) -> Any:\n try:\n return copy.deepcopy(obj)\n except Exception:\n if isinstance(obj, dict):\n return {\n safe_deepcopy(key): safe_deepcopy(value) for key, value in obj.items()\n }\n elif isinstance(obj, list):\n return [safe_deepcopy(item) for item in obj]\n elif isinstance(obj, tuple):\n return tuple(safe_deepcopy(item) for item in obj)\n elif isinstance(obj, set):\n return {safe_deepcopy(item) for item in obj}\n else:\n return copy.copy(obj)", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 521, "focal_method_end_lineno": 536} {"index": 92, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_no_suffix", "test_class_name": "TestAppendUniqueSuffix", "original_test_prefix": " def test_no_suffix(self):\n name = \"test\"\n list_of_names = [\"test_1\", \"test_2\"]\n assert append_unique_suffix(name, list_of_names) == name", "test_prefix": " def test_no_suffix(self):\n name = \"test\"\n list_of_names = [\"test_1\", \"test_2\"]\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 214, "test_prefix_end_lineno": 217, "test_target": "test/test_utils.py::TestAppendUniqueSuffix::test_no_suffix", "ground_truth_oracle": "assert append_unique_suffix(name, list_of_names) == name", "ground_truth_oracle_lineno": 217, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def append_unique_suffix(name: str, list_of_names: list[str]):\n \"\"\"Appends a numerical suffix to `name` so that it does not appear in `list_of_names`.\"\"\"\n set_of_names: set[str] = set(list_of_names) # for O(1) lookup\n if name not in set_of_names:\n return name\n else:\n suffix_counter = 1\n new_name = f\"{name}_{suffix_counter}\"\n while new_name in set_of_names:\n suffix_counter += 1\n new_name = f\"{name}_{suffix_counter}\"\n return new_name", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 815, "focal_method_end_lineno": 826} {"index": 93, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_resolve_schema_ref_direct", "test_class_name": "", "original_test_prefix": "def test_resolve_schema_ref_direct():\n schema = {\"type\": \"string\"}\n spec = {}\n assert resolve_schema_ref(schema, spec) == schema", "test_prefix": "def test_resolve_schema_ref_direct():\n schema = {\"type\": \"string\"}\n spec = {}\n ", "test_prefix_file_path": "test/test_external_utils.py", "test_prefix_start_lineno": 28, "test_prefix_end_lineno": 31, "test_target": "test/test_external_utils.py::test_resolve_schema_ref_direct", "ground_truth_oracle": "assert resolve_schema_ref(schema, spec) == schema", "ground_truth_oracle_lineno": 31, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def resolve_schema_ref(schema: dict, spec: dict) -> dict:\n \"\"\"Resolve schema references in OpenAPI spec.\"\"\"\n if \"$ref\" in schema:\n ref_path = schema[\"$ref\"]\n if ref_path.startswith(\"#/components/schemas/\"):\n schema_name = ref_path.split(\"/\")[-1]\n return spec.get(\"components\", {}).get(\"schemas\", {}).get(schema_name, {})\n elif ref_path.startswith(\"#/\"):\n path_parts = ref_path.split(\"/\")[1:]\n current = spec\n for part in path_parts:\n current = current.get(part, {})\n return current\n return schema", "focal_method_file_path": "gradio/external_utils.py", "focal_method_start_lineno": 515, "focal_method_end_lineno": 528} {"index": 94, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_safe_deepcopy_handles_undeepcopyable", "test_class_name": "TestSafeDeepCopy", "original_test_prefix": " def test_safe_deepcopy_handles_undeepcopyable(self):\n class Uncopyable:\n def __deepcopy__(self, memo):\n raise TypeError(\"Can't deepcopy\")\n\n original = Uncopyable()\n result = safe_deepcopy(original)\n assert result is not original\n assert type(result) is type(original)", "test_prefix": " def test_safe_deepcopy_handles_undeepcopyable(self):\n class Uncopyable:\n def __deepcopy__(self, memo):\n raise TypeError(\"Can't deepcopy\")\n\n original = Uncopyable()\n result = safe_deepcopy(original)\n assert result is not original\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 730, "test_prefix_end_lineno": 738, "test_target": "test/test_utils.py::TestSafeDeepCopy::test_safe_deepcopy_handles_undeepcopyable", "ground_truth_oracle": "assert type(result) is type(original)", "ground_truth_oracle_lineno": 738, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def safe_deepcopy(obj: Any) -> Any:\n try:\n return copy.deepcopy(obj)\n except Exception:\n if isinstance(obj, dict):\n return {\n safe_deepcopy(key): safe_deepcopy(value) for key, value in obj.items()\n }\n elif isinstance(obj, list):\n return [safe_deepcopy(item) for item in obj]\n elif isinstance(obj, tuple):\n return tuple(safe_deepcopy(item) for item in obj)\n elif isinstance(obj, set):\n return {safe_deepcopy(item) for item in obj}\n else:\n return copy.copy(obj)", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 521, "focal_method_end_lineno": 536} {"index": 95, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_safe_deepcopy_list", "test_class_name": "TestSafeDeepCopy", "original_test_prefix": " def test_safe_deepcopy_list(self):\n original = [1, 2, [3, 4, {\"key\": \"value\"}]]\n copied = safe_deepcopy(original)\n\n assert copied == original\n assert copied is not original\n assert copied[2] is not original[2]\n assert copied[2][2] is not original[2][2]", "test_prefix": " def test_safe_deepcopy_list(self):\n original = [1, 2, [3, 4, {\"key\": \"value\"}]]\n copied = safe_deepcopy(original)\n\n assert copied == original\n \n assert copied[2] is not original[2]\n assert copied[2][2] is not original[2][2]", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 710, "test_prefix_end_lineno": 717, "test_target": "test/test_utils.py::TestSafeDeepCopy::test_safe_deepcopy_list", "ground_truth_oracle": "assert copied is not original", "ground_truth_oracle_lineno": 715, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def safe_deepcopy(obj: Any) -> Any:\n try:\n return copy.deepcopy(obj)\n except Exception:\n if isinstance(obj, dict):\n return {\n safe_deepcopy(key): safe_deepcopy(value) for key, value in obj.items()\n }\n elif isinstance(obj, list):\n return [safe_deepcopy(item) for item in obj]\n elif isinstance(obj, tuple):\n return tuple(safe_deepcopy(item) for item in obj)\n elif isinstance(obj, set):\n return {safe_deepcopy(item) for item in obj}\n else:\n return copy.copy(obj)", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 521, "focal_method_end_lineno": 536} {"index": 96, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_colab_check_no_ipython", "test_class_name": "TestUtils", "original_test_prefix": " @patch(\"IPython.get_ipython\")\n def test_colab_check_no_ipython(self, mock_get_ipython):\n mock_get_ipython.return_value = None\n assert colab_check() is False", "test_prefix": " @patch(\"IPython.get_ipython\")\n def test_colab_check_no_ipython(self, mock_get_ipython):\n mock_get_ipython.return_value = None\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 55, "test_prefix_end_lineno": 58, "test_target": "test/test_utils.py::TestUtils::test_colab_check_no_ipython", "ground_truth_oracle": "assert colab_check() is False", "ground_truth_oracle_lineno": 58, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def colab_check() -> bool:\n \"\"\"\n Check if interface is launching from Google Colab\n :return is_colab (bool): True or False\n \"\"\"\n is_colab = False\n try: # Check if running interactively using ipython.\n from IPython.core.getipython import get_ipython\n\n from_ipynb = get_ipython()\n if \"google.colab\" in str(from_ipynb):\n is_colab = True\n except (ImportError, NameError):\n pass\n return is_colab", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 422, "focal_method_end_lineno": 436} {"index": 97, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_len", "test_class_name": "TestUnhashableKeyDict", "original_test_prefix": " def test_len(self):\n d = UnhashableKeyDict()\n assert len(d) == 0\n d[\"a\"] = 1\n d[\"b\"] = 2\n assert len(d) == 2", "test_prefix": " def test_len(self):\n d = UnhashableKeyDict()\n \n d[\"a\"] = 1\n d[\"b\"] = 2\n assert len(d) == 2", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 681, "test_prefix_end_lineno": 686, "test_target": "test/test_utils.py::TestUnhashableKeyDict::test_len", "ground_truth_oracle": "assert len(d) == 0", "ground_truth_oracle_lineno": 683, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class UnhashableKeyDict(MutableMapping):\n \"\"\"\n Essentially a list of key-value tuples that allows for keys that are not hashable,\n but acts like a dictionary for convenience.\n \"\"\"\n\n def __init__(self):\n self.data = []\n\n def __getitem__(self, key):\n for k, v in self.data:\n if deep_equal(k, key):\n return v\n raise KeyError(key)\n\n def __setitem__(self, key, value):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n self.data[i] = (key, value)\n return\n self.data.append((key, value))\n\n def __delitem__(self, key):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n del self.data[i]\n return\n raise KeyError(key)\n\n def __iter__(self):\n return (k for k, _ in self.data)\n\n def __len__(self):\n return len(self.data)\n\n def as_list(self):\n return [v for _, v in self.data]", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1520, "focal_method_end_lineno": 1556} {"index": 98, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_safe_deepcopy_dict", "test_class_name": "TestSafeDeepCopy", "original_test_prefix": " def test_safe_deepcopy_dict(self):\n original = {\"key1\": [1, 2, {\"nested_key\": \"value\"}], \"key2\": \"simple_string\"}\n copied = safe_deepcopy(original)\n\n assert copied == original\n assert copied is not original\n assert copied[\"key1\"] is not original[\"key1\"]\n assert copied[\"key1\"][2] is not original[\"key1\"][2]", "test_prefix": " def test_safe_deepcopy_dict(self):\n original = {\"key1\": [1, 2, {\"nested_key\": \"value\"}], \"key2\": \"simple_string\"}\n copied = safe_deepcopy(original)\n\n \n assert copied is not original\n assert copied[\"key1\"] is not original[\"key1\"]\n assert copied[\"key1\"][2] is not original[\"key1\"][2]", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 701, "test_prefix_end_lineno": 708, "test_target": "test/test_utils.py::TestSafeDeepCopy::test_safe_deepcopy_dict", "ground_truth_oracle": "assert copied == original", "ground_truth_oracle_lineno": 705, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def safe_deepcopy(obj: Any) -> Any:\n try:\n return copy.deepcopy(obj)\n except Exception:\n if isinstance(obj, dict):\n return {\n safe_deepcopy(key): safe_deepcopy(value) for key, value in obj.items()\n }\n elif isinstance(obj, list):\n return [safe_deepcopy(item) for item in obj]\n elif isinstance(obj, tuple):\n return tuple(safe_deepcopy(item) for item in obj)\n elif isinstance(obj, set):\n return {safe_deepcopy(item) for item in obj}\n else:\n return copy.copy(obj)", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 521, "focal_method_end_lineno": 536} {"index": 99, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_format_ner_list_standard", "test_class_name": "TestFormatNERList", "original_test_prefix": " def test_format_ner_list_standard(self):\n string = \"Wolfgang lives in Berlin\"\n groups = [\n {\"entity_group\": \"PER\", \"start\": 0, \"end\": 8},\n {\"entity_group\": \"LOC\", \"start\": 18, \"end\": 24},\n ]\n result = [\n (\"\", None),\n (\"Wolfgang\", \"PER\"),\n (\" lives in \", None),\n (\"Berlin\", \"LOC\"),\n (\"\", None),\n ]\n assert format_ner_list(string, groups) == result", "test_prefix": " def test_format_ner_list_standard(self):\n string = \"Wolfgang lives in Berlin\"\n groups = [\n {\"entity_group\": \"PER\", \"start\": 0, \"end\": 8},\n {\"entity_group\": \"LOC\", \"start\": 18, \"end\": 24},\n ]\n result = [\n (\"\", None),\n (\"Wolfgang\", \"PER\"),\n (\" lives in \", None),\n (\"Berlin\", \"LOC\"),\n (\"\", None),\n ]\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 125, "test_prefix_end_lineno": 138, "test_target": "test/test_utils.py::TestFormatNERList::test_format_ner_list_standard", "ground_truth_oracle": "assert format_ner_list(string, groups) == result", "ground_truth_oracle_lineno": 138, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def format_ner_list(input_string: str, ner_groups: list[dict[str, str | int]]):\n if len(ner_groups) == 0:\n return [(input_string, None)]\n\n output = []\n end = 0\n prev_end = 0\n\n for group in ner_groups:\n entity, start, end = group[\"entity_group\"], group[\"start\"], group[\"end\"]\n output.append((input_string[prev_end:start], None))\n output.append((input_string[start:end], entity))\n prev_end = end\n\n output.append((input_string[end:], None))\n return output", "focal_method_file_path": "gradio/external_utils.py", "focal_method_start_lineno": 177, "focal_method_end_lineno": 192} {"index": 100, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_set_get_simple", "test_class_name": "TestUnhashableKeyDict", "original_test_prefix": " def test_set_get_simple(self):\n d = UnhashableKeyDict()\n d[\"a\"] = 1\n assert d[\"a\"] == 1", "test_prefix": " def test_set_get_simple(self):\n d = UnhashableKeyDict()\n d[\"a\"] = 1\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 642, "test_prefix_end_lineno": 645, "test_target": "test/test_utils.py::TestUnhashableKeyDict::test_set_get_simple", "ground_truth_oracle": "assert d[\"a\"] == 1", "ground_truth_oracle_lineno": 645, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class UnhashableKeyDict(MutableMapping):\n \"\"\"\n Essentially a list of key-value tuples that allows for keys that are not hashable,\n but acts like a dictionary for convenience.\n \"\"\"\n\n def __init__(self):\n self.data = []\n\n def __getitem__(self, key):\n for k, v in self.data:\n if deep_equal(k, key):\n return v\n raise KeyError(key)\n\n def __setitem__(self, key, value):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n self.data[i] = (key, value)\n return\n self.data.append((key, value))\n\n def __delitem__(self, key):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n del self.data[i]\n return\n raise KeyError(key)\n\n def __iter__(self):\n return (k for k, _ in self.data)\n\n def __len__(self):\n return len(self.data)\n\n def as_list(self):\n return [v for _, v in self.data]", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1520, "focal_method_end_lineno": 1556} {"index": 101, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_tabular_examples_replaces_nan_with_str_nan", "test_class_name": "", "original_test_prefix": "def test_get_tabular_examples_replaces_nan_with_str_nan():\n readme = \"\"\"\n ---\n tags:\n - sklearn\n - skops\n - tabular-classification\n widget:\n structuredData:\n attribute_0:\n - material_7\n - material_7\n - material_7\n measurement_2:\n - 14.206\n - 15.094\n - .nan\n ---\n \"\"\"\n mock_response = MagicMock()\n mock_response.status_code = 200\n mock_response.text = textwrap.dedent(readme)\n\n with patch(\"gradio.external.httpx.get\", return_value=mock_response):\n examples = get_tabular_examples(\"foo-model\")\n assert examples[\"measurement_2\"] == [14.206, 15.094, \"NaN\"]", "test_prefix": "def test_get_tabular_examples_replaces_nan_with_str_nan():\n readme = \"\"\"\n ---\n tags:\n - sklearn\n - skops\n - tabular-classification\n widget:\n structuredData:\n attribute_0:\n - material_7\n - material_7\n - material_7\n measurement_2:\n - 14.206\n - 15.094\n - .nan\n ---\n \"\"\"\n mock_response = MagicMock()\n mock_response.status_code = 200\n mock_response.text = textwrap.dedent(readme)\n\n with patch(\"gradio.external.httpx.get\", return_value=mock_response):\n examples = get_tabular_examples(\"foo-model\")\n ", "test_prefix_file_path": "test/test_external.py", "test_prefix_start_lineno": 252, "test_prefix_end_lineno": 277, "test_target": "test/test_external.py::test_get_tabular_examples_replaces_nan_with_str_nan", "ground_truth_oracle": "assert examples[\"measurement_2\"] == [14.206, 15.094, \"NaN\"]", "ground_truth_oracle_lineno": 277, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "##################\n# Helper functions for processing tabular data\n##################\n\n\ndef get_tabular_examples(model_name: str) -> dict[str, list[float]]:\n readme = httpx.get(f\"https://huggingface.co/{model_name}/resolve/main/README.md\")\n if readme.status_code != 200:\n warnings.warn(f\"Cannot load examples from README for {model_name}\", UserWarning)\n example_data = {}\n else:\n yaml_regex = re.search(\n \"(?:^|[\\r\\n])---[\\n\\r]+([\\\\S\\\\s]*?)[\\n\\r]+---([\\n\\r]|$)\", readme.text\n )\n if yaml_regex is None:\n example_data = {}\n else:\n example_yaml = next(\n yaml.safe_load_all(readme.text[: yaml_regex.span()[-1]])\n )\n example_data = example_yaml.get(\"widget\", {}).get(\"structuredData\", {})\n if not example_data:\n raise ValueError(\n f\"No example data found in README.md of {model_name} - Cannot build gradio demo. \"\n \"See the README.md here: https://huggingface.co/scikit-learn/tabular-playground/blob/main/README.md \"\n \"for a reference on how to provide example data to your model.\"\n )\n # replace nan with string NaN for inference Endpoints\n for data in example_data.values():\n for i, val in enumerate(data):\n if isinstance(val, float) and math.isnan(val):\n data[i] = \"NaN\"\n return example_data", "focal_method_file_path": "gradio/external_utils.py", "focal_method_start_lineno": 31, "focal_method_end_lineno": 63} {"index": 102, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_list", "test_class_name": "TestSanitizeForCSV", "original_test_prefix": " def test_list(self):\n assert sanitize_list_for_csv([4, \"def=\", \"=gh+ij\"]) == [4, \"def=\", \"'=gh+ij\"]\n assert sanitize_list_for_csv(\n [[\"=abc\", \"def\", \"gh,+ij\"], [\"abc\", \"=def\", \"+ghij\"]]\n ) == [[\"'=abc\", \"def\", \"'gh,+ij\"], [\"abc\", \"'=def\", \"'+ghij\"]]\n assert sanitize_list_for_csv([1, [\"ab\", \"=de\"]]) == [1, [\"ab\", \"'=de\"]]", "test_prefix": " def test_list(self):\n assert sanitize_list_for_csv([4, \"def=\", \"=gh+ij\"]) == [4, \"def=\", \"'=gh+ij\"]\n assert sanitize_list_for_csv(\n [[\"=abc\", \"def\", \"gh,+ij\"], [\"abc\", \"=def\", \"+ghij\"]]\n ) == [[\"'=abc\", \"def\", \"'gh,+ij\"], [\"abc\", \"'=def\", \"'+ghij\"]]\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 187, "test_prefix_end_lineno": 192, "test_target": "test/test_utils.py::TestSanitizeForCSV::test_list", "ground_truth_oracle": "assert sanitize_list_for_csv([1, [\"ab\", \"=de\"]]) == [1, [\"ab\", \"'=de\"]]", "ground_truth_oracle_lineno": 192, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def sanitize_list_for_csv(values: list[Any]) -> list[Any]:\n \"\"\"\n Sanitizes a list of values (or a list of list of values) that is being written to a\n CSV file to prevent CSV injection attacks.\n \"\"\"\n sanitized_values = []\n for value in values:\n if isinstance(value, list):\n sanitized_value = [sanitize_value_for_csv(v) for v in value]\n sanitized_values.append(sanitized_value)\n else:\n sanitized_value = sanitize_value_for_csv(value)\n sanitized_values.append(sanitized_value)\n return sanitized_values", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 799, "focal_method_end_lineno": 812} {"index": 103, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_convert_to_16_bit_wav", "test_class_name": "TestAudioPreprocessing", "original_test_prefix": " def test_convert_to_16_bit_wav(self):\n # Generate a random audio sample and set the amplitude\n audio = np.random.randint(-100, 100, size=(100), dtype=\"int16\")\n audio[0] = -32767\n audio[1] = 32766\n\n audio_ = audio.astype(\"float64\")\n audio_ = processing_utils.convert_to_16_bit_wav(audio_)\n assert np.allclose(audio, audio_)\n assert audio_.dtype == \"int16\"\n\n audio_ = audio.astype(\"float32\")\n audio_ = processing_utils.convert_to_16_bit_wav(audio_)\n assert np.allclose(audio, audio_)\n assert audio_.dtype == \"int16\"\n\n audio_ = processing_utils.convert_to_16_bit_wav(audio)\n assert np.allclose(audio, audio_)\n assert audio_.dtype == \"int16\"", "test_prefix": " def test_convert_to_16_bit_wav(self):\n # Generate a random audio sample and set the amplitude\n audio = np.random.randint(-100, 100, size=(100), dtype=\"int16\")\n audio[0] = -32767\n audio[1] = 32766\n\n audio_ = audio.astype(\"float64\")\n audio_ = processing_utils.convert_to_16_bit_wav(audio_)\n \n assert audio_.dtype == \"int16\"\n\n audio_ = audio.astype(\"float32\")\n audio_ = processing_utils.convert_to_16_bit_wav(audio_)\n \n assert audio_.dtype == \"int16\"\n\n audio_ = processing_utils.convert_to_16_bit_wav(audio)\n \n assert audio_.dtype == \"int16\"", "test_prefix_file_path": "test/test_processing_utils.py", "test_prefix_start_lineno": 203, "test_prefix_end_lineno": 221, "test_target": "test/test_processing_utils.py::TestAudioPreprocessing::test_convert_to_16_bit_wav", "ground_truth_oracle": "assert np.allclose(audio, audio_)", "ground_truth_oracle_lineno": 220, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def convert_to_16_bit_wav(data):\n # Based on: https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.wavfile.write.html\n warning = \"Trying to convert audio automatically from {} to 16-bit int format.\"\n if data.dtype in [np.float64, np.float32, np.float16]:\n warnings.warn(warning.format(data.dtype))\n data = data / np.abs(data).max()\n data = data * 32767\n data = data.astype(np.int16)\n elif data.dtype == np.int32:\n warnings.warn(warning.format(data.dtype))\n data = data / 65536\n data = data.astype(np.int16)\n elif data.dtype == np.int16:\n pass\n elif data.dtype == np.uint16:\n warnings.warn(warning.format(data.dtype))\n data = data - 32768\n data = data.astype(np.int16)\n elif data.dtype == np.uint8:\n warnings.warn(warning.format(data.dtype))\n data = data * 257 - 32768\n data = data.astype(np.int16)\n elif data.dtype == np.int8:\n warnings.warn(warning.format(data.dtype))\n data = data * 256\n data = data.astype(np.int16)\n else:\n raise ValueError(\n \"Audio data cannot be converted automatically from \"\n f\"{data.dtype} to 16-bit int format.\"\n )\n return data", "focal_method_file_path": "gradio/processing_utils.py", "focal_method_start_lineno": 684, "focal_method_end_lineno": 715} {"index": 104, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_function_with_kwargs", "test_class_name": "TestFunctionParams", "original_test_prefix": " def test_function_with_kwargs(self):\n def func(a, **kwargs):\n pass\n\n assert get_function_params(func) == [(\"a\", False, None, None)]", "test_prefix": " def test_function_with_kwargs(self):\n def func(a, **kwargs):\n pass\n\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 577, "test_prefix_end_lineno": 581, "test_target": "test/test_utils.py::TestFunctionParams::test_function_with_kwargs", "ground_truth_oracle": "assert get_function_params(func) == [(\"a\", False, None, None)]", "ground_truth_oracle_lineno": 581, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_function_params(func: Callable) -> list[tuple[str, bool, Any, Any]]:\n \"\"\"\n Gets the parameters of a function as a list of tuples of the form (name, has_default, default_value, type_hint).\n Excludes *args and **kwargs, as well as args that are Gradio-specific, such as gr.Request, gr.EventData, gr.OAuthProfile, and gr.OAuthToken.\n \"\"\"\n params_info = []\n try:\n signature = inspect.signature(func)\n except ValueError:\n signature = inspect.Signature()\n type_hints = get_type_hints(func)\n for name, parameter in signature.parameters.items():\n if parameter.kind in (\n inspect.Parameter.VAR_POSITIONAL,\n inspect.Parameter.VAR_KEYWORD,\n ):\n break\n if is_special_typed_parameter(name, type_hints):\n continue\n if parameter.default is inspect.Parameter.empty:\n params_info.append((name, False, None, type_hints.get(name, None)))\n else:\n params_info.append(\n (name, True, parameter.default, type_hints.get(name, None))\n )\n return params_info", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1346, "focal_method_end_lineno": 1371} {"index": 105, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_is_special_typed_parameter", "test_class_name": "TestGetTypeHints", "original_test_prefix": " def test_is_special_typed_parameter(self):\n def func(a: list[str], b: Literal[\"a\", \"b\"], c, d: Request, e: Request | None):\n pass\n\n hints = get_type_hints(func)\n assert not is_special_typed_parameter(\"a\", hints)\n assert not is_special_typed_parameter(\"b\", hints)\n assert not is_special_typed_parameter(\"c\", hints)\n assert is_special_typed_parameter(\"d\", hints)\n assert is_special_typed_parameter(\"e\", hints)", "test_prefix": " def test_is_special_typed_parameter(self):\n def func(a: list[str], b: Literal[\"a\", \"b\"], c, d: Request, e: Request | None):\n pass\n\n hints = get_type_hints(func)\n assert not is_special_typed_parameter(\"a\", hints)\n assert not is_special_typed_parameter(\"b\", hints)\n \n assert is_special_typed_parameter(\"d\", hints)\n assert is_special_typed_parameter(\"e\", hints)", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 283, "test_prefix_end_lineno": 292, "test_target": "test/test_utils.py::TestGetTypeHints::test_is_special_typed_parameter", "ground_truth_oracle": "assert not is_special_typed_parameter(\"c\", hints)", "ground_truth_oracle_lineno": 290, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def is_special_typed_parameter(name, parameter_types):\n from gradio.helpers import EventData\n from gradio.oauth import OAuthProfile, OAuthToken\n from gradio.route_utils import Header\n from gradio.routes import Request\n\n \"\"\"Checks if parameter has a type hint designating it as a gr.Request, gr.EventData, gr.OAuthProfile or gr.OAuthToken.\"\"\"\n hint = parameter_types.get(name)\n if not hint:\n return False\n is_request = hint in (Request, Optional[Request])\n is_oauth_arg = hint in (\n OAuthProfile,\n Optional[OAuthProfile],\n OAuthToken,\n Optional[OAuthToken],\n Header,\n Optional[Header],\n )\n is_event_data = inspect.isclass(hint) and issubclass(hint, EventData)\n return is_request or is_event_data or is_oauth_arg", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1002, "focal_method_end_lineno": 1022} {"index": 106, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_url_ok", "test_class_name": "TestURLs", "original_test_prefix": " def test_url_ok(self):\n res = networking.url_ok(\"https://www.gradio.app\")\n assert res", "test_prefix": " def test_url_ok(self):\n res = networking.url_ok(\"https://www.gradio.app\")\n ", "test_prefix_file_path": "test/test_networking.py", "test_prefix_start_lineno": 46, "test_prefix_end_lineno": 48, "test_target": "test/test_networking.py::TestURLs::test_url_ok", "ground_truth_oracle": "assert res", "ground_truth_oracle_lineno": 48, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def url_ok(url: str) -> bool:\n try:\n for _ in range(5):\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\")\n r = httpx.head(url, timeout=3, verify=False)\n if (\n r.status_code in (200, 401, 302, 303, 307)\n ): # 401 or 302 if auth is set; 303 or 307 are alternatives to 302 for temporary redirects\n return True\n time.sleep(0.500)\n except (ConnectionError, httpx.ConnectError, httpx.TimeoutException):\n return False\n return False", "focal_method_file_path": "gradio/networking.py", "focal_method_start_lineno": 63, "focal_method_end_lineno": 76} {"index": 107, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_empty_expression_returns_latest", "test_class_name": "TestSemverMatch", "original_test_prefix": " def test_empty_expression_returns_latest(self):\n assert get_matching_version(assets, None) == ThemeAsset(\"theme_schema@3.20.1\")", "test_prefix": " def test_empty_expression_returns_latest(self):\n ", "test_prefix_file_path": "test/test_theme_sharing.py", "test_prefix_start_lineno": 187, "test_prefix_end_lineno": 188, "test_target": "test/test_theme_sharing.py::TestSemverMatch::test_empty_expression_returns_latest", "ground_truth_oracle": "assert get_matching_version(assets, None) == ThemeAsset(\"theme_schema@3.20.1\")", "ground_truth_oracle_lineno": 188, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "@dataclass\nclass ThemeAsset:\n filename: str\n version: semver.Version = field(init=False)\n\n def __post_init__(self):\n self.version = semver.Version(self.filename.split(\"@\")[1].replace(\".json\", \"\"))", "focal_method_file_path": "gradio/themes/utils/semver_match.py", "focal_method_start_lineno": 10, "focal_method_end_lineno": 16} {"index": 108, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_set_get_unhashable", "test_class_name": "TestUnhashableKeyDict", "original_test_prefix": " def test_set_get_unhashable(self):\n d = UnhashableKeyDict()\n key = [1, 2, 3]\n key2 = [1, 2, 3]\n d[key] = \"value\"\n assert d[key] == \"value\"\n assert d[key2] == \"value\"", "test_prefix": " def test_set_get_unhashable(self):\n d = UnhashableKeyDict()\n key = [1, 2, 3]\n key2 = [1, 2, 3]\n d[key] = \"value\"\n \n assert d[key2] == \"value\"", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 647, "test_prefix_end_lineno": 653, "test_target": "test/test_utils.py::TestUnhashableKeyDict::test_set_get_unhashable", "ground_truth_oracle": "assert d[key] == \"value\"", "ground_truth_oracle_lineno": 652, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class UnhashableKeyDict(MutableMapping):\n \"\"\"\n Essentially a list of key-value tuples that allows for keys that are not hashable,\n but acts like a dictionary for convenience.\n \"\"\"\n\n def __init__(self):\n self.data = []\n\n def __getitem__(self, key):\n for k, v in self.data:\n if deep_equal(k, key):\n return v\n raise KeyError(key)\n\n def __setitem__(self, key, value):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n self.data[i] = (key, value)\n return\n self.data.append((key, value))\n\n def __delitem__(self, key):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n del self.data[i]\n return\n raise KeyError(key)\n\n def __iter__(self):\n return (k for k, _ in self.data)\n\n def __len__(self):\n return len(self.data)\n\n def as_list(self):\n return [v for _, v in self.data]", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1520, "focal_method_end_lineno": 1556} {"index": 109, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_safe_value", "test_class_name": "TestSanitizeForCSV", "original_test_prefix": " def test_safe_value(self):\n assert sanitize_value_for_csv(4) == 4\n assert sanitize_value_for_csv(-44.44) == -44.44\n assert sanitize_value_for_csv(\"1+1=2\") == \"1+1=2\"\n assert sanitize_value_for_csv(\"1aaa2\") == \"1aaa2\"", "test_prefix": " def test_safe_value(self):\n assert sanitize_value_for_csv(4) == 4\n assert sanitize_value_for_csv(-44.44) == -44.44\n assert sanitize_value_for_csv(\"1+1=2\") == \"1+1=2\"\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 181, "test_prefix_end_lineno": 185, "test_target": "test/test_utils.py::TestSanitizeForCSV::test_safe_value", "ground_truth_oracle": "assert sanitize_value_for_csv(\"1aaa2\") == \"1aaa2\"", "ground_truth_oracle_lineno": 185, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def sanitize_value_for_csv(value: str | float) -> str | float:\n \"\"\"\n Sanitizes a value that is being written to a CSV file to prevent CSV injection attacks.\n Reference: https://owasp.org/www-community/attacks/CSV_Injection\n \"\"\"\n if isinstance(value, (float, int)):\n return value\n unsafe_prefixes = [\"=\", \"+\", \"-\", \"@\", \"\\t\", \"\\n\"]\n unsafe_sequences = [\",=\", \",+\", \",-\", \",@\", \",\\t\", \",\\n\"]\n if any(value.startswith(prefix) for prefix in unsafe_prefixes) or any(\n sequence in value for sequence in unsafe_sequences\n ):\n value = f\"'{value}\"\n return value", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 783, "focal_method_end_lineno": 796} {"index": 110, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_abspath_no_symlink", "test_class_name": "TestAbspath", "original_test_prefix": " def test_abspath_no_symlink(self):\n resolved_path = str(abspath(\"../gradio/gradio/test_data/lion.jpg\"))\n assert \"..\" not in resolved_path", "test_prefix": " def test_abspath_no_symlink(self):\n resolved_path = str(abspath(\"../gradio/gradio/test_data/lion.jpg\"))\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 231, "test_prefix_end_lineno": 233, "test_target": "test/test_utils.py::TestAbspath::test_abspath_no_symlink", "ground_truth_oracle": "assert \"..\" not in resolved_path", "ground_truth_oracle_lineno": 233, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def abspath(path: str | Path) -> Path:\n return Path(os.path.abspath(str(path)))", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1129, "focal_method_end_lineno": 1130} {"index": 111, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_navbar_config", "test_class_name": "", "original_test_prefix": "def test_navbar_config():\n \"\"\"\n Test that navbar component produces the correct config\n \"\"\"\n with gr.Blocks() as demo:\n gr.Navbar([(\"About2\", \"/about2\")], visible=True, main_page_name=\"My Custom App\")\n gr.Textbox(label=\"Main page content\")\n\n with demo.route(\"About\"):\n gr.Markdown(\"About page\")\n\n config = demo.get_config_file()\n navbar_component = None\n for component in config[\"components\"]:\n if component[\"type\"] == \"navbar\":\n navbar_component = component\n break\n\n assert navbar_component is not None\n assert navbar_component[\"props\"][\"value\"] == [[\"About2\", \"/about2\"]]\n assert navbar_component[\"props\"][\"visible\"]\n assert navbar_component[\"props\"][\"main_page_name\"] == \"My Custom App\"", "test_prefix": "def test_navbar_config():\n \"\"\"\n Test that navbar component produces the correct config\n \"\"\"\n with gr.Blocks() as demo:\n gr.Navbar([(\"About2\", \"/about2\")], visible=True, main_page_name=\"My Custom App\")\n gr.Textbox(label=\"Main page content\")\n\n with demo.route(\"About\"):\n gr.Markdown(\"About page\")\n\n config = demo.get_config_file()\n navbar_component = None\n for component in config[\"components\"]:\n if component[\"type\"] == \"navbar\":\n navbar_component = component\n break\n\n assert navbar_component is not None\n assert navbar_component[\"props\"][\"value\"] == [[\"About2\", \"/about2\"]]\n \n assert navbar_component[\"props\"][\"main_page_name\"] == \"My Custom App\"", "test_prefix_file_path": "test/test_blocks.py", "test_prefix_start_lineno": 1971, "test_prefix_end_lineno": 1992, "test_target": "test/test_blocks.py::test_navbar_config", "ground_truth_oracle": "assert navbar_component[\"props\"][\"visible\"]", "ground_truth_oracle_lineno": 1991, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_config_file(self) -> BlocksConfigDict:\n config: BlocksConfigDict = {\n \"version\": VERSION,\n \"api_prefix\": API_PREFIX,\n \"mode\": self.mode,\n \"app_id\": self.app_id,\n \"dev_mode\": self.dev_mode,\n \"vibe_mode\": self.vibe_mode,\n \"analytics_enabled\": self.analytics_enabled,\n \"components\": [],\n \"css\": self.css,\n \"connect_heartbeat\": False,\n \"js\": cast(str | Literal[True] | None, self.js),\n \"head\": self.head,\n \"title\": self.title or \"Gradio\",\n \"space_id\": self.space_id,\n \"enable_queue\": True, # launch attributes\n \"show_error\": getattr(self, \"show_error\", False),\n \"show_api\": getattr(self, \"show_api\", True),\n \"is_colab\": utils.colab_check(),\n \"max_file_size\": getattr(self, \"max_file_size\", None),\n \"stylesheets\": self.stylesheets,\n \"theme\": self.theme.name,\n \"protocol\": \"sse_v3\",\n \"body_css\": {\n \"body_background_fill\": self.theme._get_computed_value(\n \"body_background_fill\"\n ),\n \"body_text_color\": self.theme._get_computed_value(\"body_text_color\"),\n \"body_background_fill_dark\": self.theme._get_computed_value(\n \"body_background_fill_dark\"\n ),\n \"body_text_color_dark\": self.theme._get_computed_value(\n \"body_text_color_dark\"\n ),\n },\n \"fill_height\": self.fill_height,\n \"fill_width\": self.fill_width,\n \"theme_hash\": self.theme_hash,\n \"pwa\": self.pwa,\n \"pages\": self.pages,\n \"page\": {},\n \"mcp_server\": self.mcp_server,\n \"i18n_translations\": (\n getattr(self.i18n_instance, \"translations_dict\", None)\n if getattr(self, \"i18n_instance\", None) is not None\n else None\n ),\n }\n config.update(self.default_config.get_config()) # type: ignore\n config[\"connect_heartbeat\"] = utils.connect_heartbeat(\n config, self.blocks.values()\n )\n return config", "focal_method_file_path": "gradio/blocks.py", "focal_method_start_lineno": 2209, "focal_method_end_lineno": 2262} {"index": 112, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_extract_svg_content_from_url", "test_class_name": "", "original_test_prefix": "def test_extract_svg_content_from_url(monkeypatch):\n class MockResponse:\n def __init__(self):\n self.text = \"mock svg content\"\n\n def raise_for_status(self):\n pass\n\n def mock_get(*args, **kwargs):\n return MockResponse()\n\n monkeypatch.setattr(\"httpx.get\", mock_get)\n svg_content = extract_svg_content(\"https://example.com/test.svg\")\n assert svg_content == \"mock svg content\"", "test_prefix": "def test_extract_svg_content_from_url(monkeypatch):\n class MockResponse:\n def __init__(self):\n self.text = \"mock svg content\"\n\n def raise_for_status(self):\n pass\n\n def mock_get(*args, **kwargs):\n return MockResponse()\n\n monkeypatch.setattr(\"httpx.get\", mock_get)\n svg_content = extract_svg_content(\"https://example.com/test.svg\")\n ", "test_prefix_file_path": "test/test_image_utils.py", "test_prefix_start_lineno": 13, "test_prefix_end_lineno": 26, "test_target": "test/test_image_utils.py::test_extract_svg_content_from_url", "ground_truth_oracle": "assert svg_content == \"mock svg content\"", "ground_truth_oracle_lineno": 26, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def extract_svg_content(image_file: str | Path) -> str:\n \"\"\"\n Provided a path or URL to an SVG file, return the SVG content as a string.\n Parameters:\n image_file: Local file path or URL to an SVG file\n Returns:\n str: The SVG content as a string\n \"\"\"\n image_file = str(image_file)\n if is_http_url_like(image_file):\n response = httpx.get(image_file)\n response.raise_for_status() # Raise an error for bad status codes\n return response.text\n else:\n with open(image_file) as file:\n svg_content = file.read()\n return svg_content", "focal_method_file_path": "gradio/image_utils.py", "focal_method_start_lineno": 242, "focal_method_end_lineno": 258} {"index": 113, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_recover_kwargs", "test_class_name": "", "original_test_prefix": "def test_recover_kwargs():\n audio = gr.Audio(format=\"wav\", autoplay=True)\n props = audio.recover_kwargs(\n {\"format\": \"wav\", \"value\": \"foo.wav\", \"autoplay\": False, \"foo\": \"bar\"}\n )\n assert props == {\"format\": \"wav\", \"value\": \"foo.wav\", \"autoplay\": False}\n props = audio.recover_kwargs(\n {\"format\": \"wav\", \"value\": \"foo.wav\", \"autoplay\": False, \"foo\": \"bar\"},\n [\"value\"],\n )\n assert props == {\"format\": \"wav\", \"autoplay\": False}", "test_prefix": "def test_recover_kwargs():\n audio = gr.Audio(format=\"wav\", autoplay=True)\n props = audio.recover_kwargs(\n {\"format\": \"wav\", \"value\": \"foo.wav\", \"autoplay\": False, \"foo\": \"bar\"}\n )\n \n props = audio.recover_kwargs(\n {\"format\": \"wav\", \"value\": \"foo.wav\", \"autoplay\": False, \"foo\": \"bar\"},\n [\"value\"],\n )\n assert props == {\"format\": \"wav\", \"autoplay\": False}", "test_prefix_file_path": "test/test_blocks.py", "test_prefix_start_lineno": 1688, "test_prefix_end_lineno": 1698, "test_target": "test/test_blocks.py::test_recover_kwargs", "ground_truth_oracle": "assert props == {\"format\": \"wav\", \"value\": \"foo.wav\", \"autoplay\": False}", "ground_truth_oracle_lineno": 1693, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def recover_kwargs(\n cls, props: dict[str, Any], additional_keys: list[str] | None = None\n ):\n \"\"\"\n Recovers kwargs from a dict of props.\n \"\"\"\n additional_keys = additional_keys or []\n signature = inspect.signature(cls.__init__)\n kwargs = {}\n for parameter in signature.parameters.values():\n if parameter.name in props and parameter.name not in additional_keys:\n kwargs[parameter.name] = props[parameter.name]\n return kwargs", "focal_method_file_path": "gradio/blocks.py", "focal_method_start_lineno": 309, "focal_method_end_lineno": 322} {"index": 114, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_theme_assets", "test_class_name": "TestGetThemeAssets", "original_test_prefix": " def test_get_theme_assets(self):\n space_info = huggingface_hub.hf_api.SpaceInfo(\n id=\"freddyaboulton/dracula\",\n siblings=[\n {\n \"blob_id\": None,\n \"lfs\": None,\n \"rfilename\": \"themes/theme_schema@0.1.0.json\",\n \"size\": None,\n },\n {\n \"blob_id\": None,\n \"lfs\": None,\n \"rfilename\": \"themes/theme_schema@0.1.1.json\",\n \"size\": None,\n },\n {\n \"blob_id\": None,\n \"lfs\": None,\n \"rfilename\": \"themes/theme_schema@0.2.5.json\",\n \"size\": None,\n },\n {\n \"blob_id\": None,\n \"lfs\": None,\n \"rfilename\": \"themes/theme_schema@1.5.9.json\",\n \"size\": None,\n },\n ],\n tags=[\"gradio-theme\", \"gradio\"],\n private=False,\n likes=0,\n )\n\n assert get_theme_assets(space_info) == [\n ThemeAsset(\"themes/theme_schema@0.1.0.json\"),\n ThemeAsset(\"themes/theme_schema@0.1.1.json\"),\n ThemeAsset(\"themes/theme_schema@0.2.5.json\"),\n ThemeAsset(\"themes/theme_schema@1.5.9.json\"),\n ]\n\n assert gr.Theme._theme_version_exists(space_info, \"0.1.1\")\n assert not gr.Theme._theme_version_exists(space_info, \"2.0.0\")", "test_prefix": " def test_get_theme_assets(self):\n space_info = huggingface_hub.hf_api.SpaceInfo(\n id=\"freddyaboulton/dracula\",\n siblings=[\n {\n \"blob_id\": None,\n \"lfs\": None,\n \"rfilename\": \"themes/theme_schema@0.1.0.json\",\n \"size\": None,\n },\n {\n \"blob_id\": None,\n \"lfs\": None,\n \"rfilename\": \"themes/theme_schema@0.1.1.json\",\n \"size\": None,\n },\n {\n \"blob_id\": None,\n \"lfs\": None,\n \"rfilename\": \"themes/theme_schema@0.2.5.json\",\n \"size\": None,\n },\n {\n \"blob_id\": None,\n \"lfs\": None,\n \"rfilename\": \"themes/theme_schema@1.5.9.json\",\n \"size\": None,\n },\n ],\n tags=[\"gradio-theme\", \"gradio\"],\n private=False,\n likes=0,\n )\n\n assert get_theme_assets(space_info) == [\n ThemeAsset(\"themes/theme_schema@0.1.0.json\"),\n ThemeAsset(\"themes/theme_schema@0.1.1.json\"),\n ThemeAsset(\"themes/theme_schema@0.2.5.json\"),\n ThemeAsset(\"themes/theme_schema@1.5.9.json\"),\n ]\n\n assert gr.Theme._theme_version_exists(space_info, \"0.1.1\")\n ", "test_prefix_file_path": "test/test_theme_sharing.py", "test_prefix_start_lineno": 213, "test_prefix_end_lineno": 255, "test_target": "test/test_theme_sharing.py::TestGetThemeAssets::test_get_theme_assets", "ground_truth_oracle": "assert not gr.Theme._theme_version_exists(space_info, \"2.0.0\")", "ground_truth_oracle_lineno": 255, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @staticmethod\n def _theme_version_exists(\n space_info: huggingface_hub.hf_api.SpaceInfo, version: str\n ) -> bool:\n assets = get_theme_assets(space_info)\n return any(a.version == semver.Version(version) for a in assets)", "focal_method_file_path": "gradio/themes/base.py", "focal_method_start_lineno": 217, "focal_method_end_lineno": 222} {"index": 115, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_is_special_typed_parameter_with_pipe", "test_class_name": "TestGetTypeHints", "original_test_prefix": " def test_is_special_typed_parameter_with_pipe(self):\n def func(a: Request, b: str | int, c: list[str]):\n pass\n\n hints = get_type_hints(func)\n assert is_special_typed_parameter(\"a\", hints)\n assert not is_special_typed_parameter(\"b\", hints)\n assert not is_special_typed_parameter(\"c\", hints)", "test_prefix": " def test_is_special_typed_parameter_with_pipe(self):\n def func(a: Request, b: str | int, c: list[str]):\n pass\n\n hints = get_type_hints(func)\n \n assert not is_special_typed_parameter(\"b\", hints)\n assert not is_special_typed_parameter(\"c\", hints)", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 294, "test_prefix_end_lineno": 301, "test_target": "test/test_utils.py::TestGetTypeHints::test_is_special_typed_parameter_with_pipe", "ground_truth_oracle": "assert is_special_typed_parameter(\"a\", hints)", "ground_truth_oracle_lineno": 299, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_type_hints(fn):\n if inspect.isfunction(fn) or inspect.ismethod(fn):\n pass\n elif callable(fn):\n fn = fn.__call__\n else:\n return {}\n return typing.get_type_hints(fn)", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 992, "focal_method_end_lineno": 999} {"index": 116, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_resolve_schema_ref_ref", "test_class_name": "", "original_test_prefix": "def test_resolve_schema_ref_ref():\n schema = {\"$ref\": \"#/components/schemas/Pet\"}\n spec = {\n \"components\": {\n \"schemas\": {\n \"Pet\": {\"type\": \"object\", \"properties\": {\"id\": {\"type\": \"integer\"}}}\n }\n }\n }\n resolved = resolve_schema_ref(schema, spec)\n assert resolved[\"type\"] == \"object\"\n assert \"id\" in resolved[\"properties\"]", "test_prefix": "def test_resolve_schema_ref_ref():\n schema = {\"$ref\": \"#/components/schemas/Pet\"}\n spec = {\n \"components\": {\n \"schemas\": {\n \"Pet\": {\"type\": \"object\", \"properties\": {\"id\": {\"type\": \"integer\"}}}\n }\n }\n }\n resolved = resolve_schema_ref(schema, spec)\n \n assert \"id\" in resolved[\"properties\"]", "test_prefix_file_path": "test/test_external_utils.py", "test_prefix_start_lineno": 34, "test_prefix_end_lineno": 45, "test_target": "test/test_external_utils.py::test_resolve_schema_ref_ref", "ground_truth_oracle": "assert resolved[\"type\"] == \"object\"", "ground_truth_oracle_lineno": 44, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def resolve_schema_ref(schema: dict, spec: dict) -> dict:\n \"\"\"Resolve schema references in OpenAPI spec.\"\"\"\n if \"$ref\" in schema:\n ref_path = schema[\"$ref\"]\n if ref_path.startswith(\"#/components/schemas/\"):\n schema_name = ref_path.split(\"/\")[-1]\n return spec.get(\"components\", {}).get(\"schemas\", {}).get(schema_name, {})\n elif ref_path.startswith(\"#/\"):\n path_parts = ref_path.split(\"/\")[1:]\n current = spec\n for part in path_parts:\n current = current.get(part, {})\n return current\n return schema", "focal_method_file_path": "gradio/external_utils.py", "focal_method_start_lineno": 515, "focal_method_end_lineno": 528} {"index": 117, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_compatible_release_specifier", "test_class_name": "TestSemverMatch", "original_test_prefix": " def test_compatible_release_specifier(self):\n assert get_matching_version(assets, \"~=0.0\") == ThemeAsset(\"theme_schema@0.9.8\")", "test_prefix": " def test_compatible_release_specifier(self):\n ", "test_prefix_file_path": "test/test_theme_sharing.py", "test_prefix_start_lineno": 203, "test_prefix_end_lineno": 204, "test_target": "test/test_theme_sharing.py::TestSemverMatch::test_compatible_release_specifier", "ground_truth_oracle": "assert get_matching_version(assets, \"~=0.0\") == ThemeAsset(\"theme_schema@0.9.8\")", "ground_truth_oracle_lineno": 204, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "@dataclass\nclass ThemeAsset:\n filename: str\n version: semver.Version = field(init=False)\n\n def __post_init__(self):\n self.version = semver.Version(self.filename.split(\"@\")[1].replace(\".json\", \"\"))", "focal_method_file_path": "gradio/themes/utils/semver_match.py", "focal_method_start_lineno": 10, "focal_method_end_lineno": 16} {"index": 118, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_slugify", "test_class_name": "", "original_test_prefix": "def test_slugify():\n items = (\n (\"Hello, World!\", \"hello-world\"),\n (\"spam & eggs\", \"spam-eggs\"),\n (\" multiple---dash and space \", \"multiple-dash-and-space\"),\n (\"\\t whitespace-in-value \\n\", \"whitespace-in-value\"),\n (\"underscore_in-value\", \"underscore_in-value\"),\n (\"__strip__underscore-value___\", \"strip__underscore-value\"),\n (\"--strip-dash-value---\", \"strip-dash-value\"),\n (\"__strip-mixed-value---\", \"strip-mixed-value\"),\n (\"_ -strip-mixed-value _-\", \"strip-mixed-value\"),\n )\n for value, expected_output in items:\n assert slugify(value) == expected_output", "test_prefix": "def test_slugify():\n items = (\n (\"Hello, World!\", \"hello-world\"),\n (\"spam & eggs\", \"spam-eggs\"),\n (\" multiple---dash and space \", \"multiple-dash-and-space\"),\n (\"\\t whitespace-in-value \\n\", \"whitespace-in-value\"),\n (\"underscore_in-value\", \"underscore_in-value\"),\n (\"__strip__underscore-value___\", \"strip__underscore-value\"),\n (\"--strip-dash-value---\", \"strip-dash-value\"),\n (\"__strip-mixed-value---\", \"strip-mixed-value\"),\n (\"_ -strip-mixed-value _-\", \"strip-mixed-value\"),\n )\n for value, expected_output in items:\n ", "test_prefix_file_path": "test/test_routes.py", "test_prefix_start_lineno": 1984, "test_prefix_end_lineno": 1997, "test_target": "test/test_routes.py::test_slugify", "ground_truth_oracle": "assert slugify(value) == expected_output", "ground_truth_oracle_lineno": 1997, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def slugify(value):\n \"\"\"\n Convert to ASCII. Convert spaces or repeated dashes to single dashes.\n Remove characters that aren't alphanumerics, underscores, or hyphens.\n Convert to lowercase. Also strip leading and trailing whitespace,\n dashes, and underscores.\n \"\"\"\n value = str(value)\n value = (\n unicodedata.normalize(\"NFKD\", value).encode(\"ascii\", \"ignore\").decode(\"ascii\")\n )\n value = re.sub(r\"[^\\w\\s-]\", \"\", value.lower())\n return re.sub(r\"[-\\s]+\", \"-\", value).strip(\"-_\")", "focal_method_file_path": "gradio/route_utils.py", "focal_method_start_lineno": 1047, "focal_method_end_lineno": 1059} {"index": 119, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_delete", "test_class_name": "TestUnhashableKeyDict", "original_test_prefix": " def test_delete(self):\n d = UnhashableKeyDict()\n d[\"key\"] = \"value\"\n del d[\"key\"]\n assert len(d) == 0\n with pytest.raises(KeyError):\n d[\"key\"]", "test_prefix": " def test_delete(self):\n d = UnhashableKeyDict()\n d[\"key\"] = \"value\"\n del d[\"key\"]\n \n with pytest.raises(KeyError):\n d[\"key\"]", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 668, "test_prefix_end_lineno": 674, "test_target": "test/test_utils.py::TestUnhashableKeyDict::test_delete", "ground_truth_oracle": "assert len(d) == 0", "ground_truth_oracle_lineno": 672, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class UnhashableKeyDict(MutableMapping):\n \"\"\"\n Essentially a list of key-value tuples that allows for keys that are not hashable,\n but acts like a dictionary for convenience.\n \"\"\"\n\n def __init__(self):\n self.data = []\n\n def __getitem__(self, key):\n for k, v in self.data:\n if deep_equal(k, key):\n return v\n raise KeyError(key)\n\n def __setitem__(self, key, value):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n self.data[i] = (key, value)\n return\n self.data.append((key, value))\n\n def __delitem__(self, key):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n del self.data[i]\n return\n raise KeyError(key)\n\n def __iter__(self):\n return (k for k, _ in self.data)\n\n def __len__(self):\n return len(self.data)\n\n def as_list(self):\n return [v for _, v in self.data]", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1520, "focal_method_end_lineno": 1556} {"index": 120, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_parse_file_size", "test_class_name": "", "original_test_prefix": "def test_parse_file_size():\n assert _parse_file_size(\"1kb\") == 1 * FileSize.KB\n assert _parse_file_size(\"1mb\") == 1 * FileSize.MB\n assert _parse_file_size(\"505 Mb\") == 505 * FileSize.MB", "test_prefix": "def test_parse_file_size():\n \n assert _parse_file_size(\"1mb\") == 1 * FileSize.MB\n assert _parse_file_size(\"505 Mb\") == 505 * FileSize.MB", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 635, "test_prefix_end_lineno": 638, "test_target": "test/test_utils.py::test_parse_file_size", "ground_truth_oracle": "assert _parse_file_size(\"1kb\") == 1 * FileSize.KB", "ground_truth_oracle_lineno": 636, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _parse_file_size(size: str | int | None) -> int | None:\n if isinstance(size, int) or size is None:\n return size\n\n size = size.replace(\" \", \"\")\n\n last_digit_index = next(\n (i for i, c in enumerate(size) if not c.isdigit()), len(size)\n )\n size_int, unit = int(size[:last_digit_index]), size[last_digit_index:].upper()\n multiple = getattr(FileSize, unit, None)\n if not multiple:\n raise ValueError(f\"Invalid file size unit: {unit}\")\n return multiple * size_int", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1436, "focal_method_end_lineno": 1449} {"index": 121, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_lambda_with_kwargs", "test_class_name": "TestFunctionParams", "original_test_prefix": " def test_lambda_with_kwargs(self):\n assert get_function_params(lambda x, **kwargs: x) == [(\"x\", False, None, None)]", "test_prefix": " def test_lambda_with_kwargs(self):\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 631, "test_prefix_end_lineno": 632, "test_target": "test/test_utils.py::TestFunctionParams::test_lambda_with_kwargs", "ground_truth_oracle": "assert get_function_params(lambda x, **kwargs: x) == [(\"x\", False, None, None)]", "ground_truth_oracle_lineno": 632, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_function_params(func: Callable) -> list[tuple[str, bool, Any, Any]]:\n \"\"\"\n Gets the parameters of a function as a list of tuples of the form (name, has_default, default_value, type_hint).\n Excludes *args and **kwargs, as well as args that are Gradio-specific, such as gr.Request, gr.EventData, gr.OAuthProfile, and gr.OAuthToken.\n \"\"\"\n params_info = []\n try:\n signature = inspect.signature(func)\n except ValueError:\n signature = inspect.Signature()\n type_hints = get_type_hints(func)\n for name, parameter in signature.parameters.items():\n if parameter.kind in (\n inspect.Parameter.VAR_POSITIONAL,\n inspect.Parameter.VAR_KEYWORD,\n ):\n break\n if is_special_typed_parameter(name, type_hints):\n continue\n if parameter.default is inspect.Parameter.empty:\n params_info.append((name, False, None, type_hints.get(name, None)))\n else:\n params_info.append(\n (name, True, parameter.default, type_hints.get(name, None))\n )\n return params_info", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1346, "focal_method_end_lineno": 1371} {"index": 122, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_encode_pil_to_temp_file_metadata_color_profile", "test_class_name": "TestImagePreprocessing", "original_test_prefix": " def test_encode_pil_to_temp_file_metadata_color_profile(self, gradio_temp_dir):\n # Read image\n img = Image.open(\"gradio/test_data/test_image.png\")\n img_metadata = Image.open(\"gradio/test_data/test_image.png\")\n img_metadata.info = {\"key1\": \"value1\", \"key2\": \"value2\"}\n\n # Creating sRGB profile\n profile = ImageCms.createProfile(\"sRGB\")\n profile2 = ImageCms.ImageCmsProfile(profile)\n img.save(\n gradio_temp_dir / \"img_color_profile.png\", icc_profile=profile2.tobytes()\n )\n img_cp1 = Image.open(str(gradio_temp_dir / \"img_color_profile.png\"))\n\n # Creating XYZ profile\n profile = ImageCms.createProfile(\"XYZ\")\n profile2 = ImageCms.ImageCmsProfile(profile)\n img.save(\n gradio_temp_dir / \"img_color_profile_2.png\", icc_profile=profile2.tobytes()\n )\n img_cp2 = Image.open(str(gradio_temp_dir / \"img_color_profile_2.png\"))\n\n img_path = processing_utils.save_pil_to_cache(\n img, cache_dir=gradio_temp_dir, format=\"png\"\n )\n img_metadata_path = processing_utils.save_pil_to_cache(\n img_metadata, cache_dir=gradio_temp_dir, format=\"png\"\n )\n img_cp1_path = processing_utils.save_pil_to_cache(\n img_cp1, cache_dir=gradio_temp_dir, format=\"png\"\n )\n img_cp2_path = processing_utils.save_pil_to_cache(\n img_cp2, cache_dir=gradio_temp_dir, format=\"png\"\n )\n\n assert len({img_path, img_metadata_path, img_cp1_path, img_cp2_path}) == 4", "test_prefix": " def test_encode_pil_to_temp_file_metadata_color_profile(self, gradio_temp_dir):\n # Read image\n img = Image.open(\"gradio/test_data/test_image.png\")\n img_metadata = Image.open(\"gradio/test_data/test_image.png\")\n img_metadata.info = {\"key1\": \"value1\", \"key2\": \"value2\"}\n\n # Creating sRGB profile\n profile = ImageCms.createProfile(\"sRGB\")\n profile2 = ImageCms.ImageCmsProfile(profile)\n img.save(\n gradio_temp_dir / \"img_color_profile.png\", icc_profile=profile2.tobytes()\n )\n img_cp1 = Image.open(str(gradio_temp_dir / \"img_color_profile.png\"))\n\n # Creating XYZ profile\n profile = ImageCms.createProfile(\"XYZ\")\n profile2 = ImageCms.ImageCmsProfile(profile)\n img.save(\n gradio_temp_dir / \"img_color_profile_2.png\", icc_profile=profile2.tobytes()\n )\n img_cp2 = Image.open(str(gradio_temp_dir / \"img_color_profile_2.png\"))\n\n img_path = processing_utils.save_pil_to_cache(\n img, cache_dir=gradio_temp_dir, format=\"png\"\n )\n img_metadata_path = processing_utils.save_pil_to_cache(\n img_metadata, cache_dir=gradio_temp_dir, format=\"png\"\n )\n img_cp1_path = processing_utils.save_pil_to_cache(\n img_cp1, cache_dir=gradio_temp_dir, format=\"png\"\n )\n img_cp2_path = processing_utils.save_pil_to_cache(\n img_cp2, cache_dir=gradio_temp_dir, format=\"png\"\n )\n\n ", "test_prefix_file_path": "test/test_processing_utils.py", "test_prefix_start_lineno": 144, "test_prefix_end_lineno": 179, "test_target": "test/test_processing_utils.py::TestImagePreprocessing::test_encode_pil_to_temp_file_metadata_color_profile", "ground_truth_oracle": "assert len({img_path, img_metadata_path, img_cp1_path, img_cp2_path}) == 4", "ground_truth_oracle_lineno": 179, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def save_pil_to_cache(\n img: Image.Image,\n cache_dir: str,\n name: str = \"image\",\n format: str = \"webp\",\n) -> str:\n bytes_data = encode_pil_to_bytes(img, format)\n temp_dir = Path(cache_dir) / hash_bytes(bytes_data)\n temp_dir.mkdir(exist_ok=True, parents=True)\n filename = str((temp_dir / f\"{name}.{format}\").resolve())\n (temp_dir / f\"{name}.{format}\").resolve().write_bytes(bytes_data)\n return filename", "focal_method_file_path": "gradio/processing_utils.py", "focal_method_start_lineno": 158, "focal_method_end_lineno": 169} {"index": 123, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_delete_none", "test_class_name": "TestDeleteNone", "original_test_prefix": " def test_delete_none(self):\n input = {\n \"a\": 12,\n \"b\": 34,\n \"c\": None,\n \"k\": {\n \"d\": 34,\n \"t\": None,\n \"m\": [{\"k\": 23, \"t\": None}, [None, 1, 2, 3], {1, 2, None}],\n None: 123,\n },\n }\n truth = {\n \"a\": 12,\n \"b\": 34,\n \"k\": {\n \"d\": 34,\n \"t\": None,\n \"m\": [{\"k\": 23, \"t\": None}, [None, 1, 2, 3], {1, 2, None}],\n None: 123,\n },\n }\n assert delete_none(input) == truth", "test_prefix": " def test_delete_none(self):\n input = {\n \"a\": 12,\n \"b\": 34,\n \"c\": None,\n \"k\": {\n \"d\": 34,\n \"t\": None,\n \"m\": [{\"k\": 23, \"t\": None}, [None, 1, 2, 3], {1, 2, None}],\n None: 123,\n },\n }\n truth = {\n \"a\": 12,\n \"b\": 34,\n \"k\": {\n \"d\": 34,\n \"t\": None,\n \"m\": [{\"k\": 23, \"t\": None}, [None, 1, 2, 3], {1, 2, None}],\n None: 123,\n },\n }\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 150, "test_prefix_end_lineno": 172, "test_target": "test/test_utils.py::TestDeleteNone::test_delete_none", "ground_truth_oracle": "assert delete_none(input) == truth", "ground_truth_oracle_lineno": 172, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def delete_none(\n _dict: dict, skip_value: bool = False, skip_props: list[str] | None = None\n) -> dict:\n \"\"\"\n Delete keys whose values are None from a dictionary\n \"\"\"\n skip_props = [] if skip_props is None else skip_props\n for key, value in list(_dict.items()):\n if key in skip_props:\n continue\n if skip_value and key == \"value\":\n continue\n elif value is None:\n del _dict[key]\n return _dict", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 614, "focal_method_end_lineno": 628} {"index": 124, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_class_method_with_args", "test_class_name": "TestFunctionParams", "original_test_prefix": " def test_class_method_with_args(self):\n class MyClass:\n def method(self, a, *args, b=42):\n pass\n\n assert get_function_params(MyClass().method) == [(\"a\", False, None, None)]", "test_prefix": " def test_class_method_with_args(self):\n class MyClass:\n def method(self, a, *args, b=42):\n pass\n\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 621, "test_prefix_end_lineno": 626, "test_target": "test/test_utils.py::TestFunctionParams::test_class_method_with_args", "ground_truth_oracle": "assert get_function_params(MyClass().method) == [(\"a\", False, None, None)]", "ground_truth_oracle_lineno": 626, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_function_params(func: Callable) -> list[tuple[str, bool, Any, Any]]:\n \"\"\"\n Gets the parameters of a function as a list of tuples of the form (name, has_default, default_value, type_hint).\n Excludes *args and **kwargs, as well as args that are Gradio-specific, such as gr.Request, gr.EventData, gr.OAuthProfile, and gr.OAuthToken.\n \"\"\"\n params_info = []\n try:\n signature = inspect.signature(func)\n except ValueError:\n signature = inspect.Signature()\n type_hints = get_type_hints(func)\n for name, parameter in signature.parameters.items():\n if parameter.kind in (\n inspect.Parameter.VAR_POSITIONAL,\n inspect.Parameter.VAR_KEYWORD,\n ):\n break\n if is_special_typed_parameter(name, type_hints):\n continue\n if parameter.default is inspect.Parameter.empty:\n params_info.append((name, False, None, type_hints.get(name, None)))\n else:\n params_info.append(\n (name, True, parameter.default, type_hints.get(name, None))\n )\n return params_info", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1346, "focal_method_end_lineno": 1371} {"index": 125, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_contains", "test_class_name": "TestUnhashableKeyDict", "original_test_prefix": " def test_contains(self):\n d = UnhashableKeyDict()\n d[\"key\"] = \"value\"\n assert \"key\" in d\n assert \"nonexistent\" not in d", "test_prefix": " def test_contains(self):\n d = UnhashableKeyDict()\n d[\"key\"] = \"value\"\n \n assert \"nonexistent\" not in d", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 688, "test_prefix_end_lineno": 692, "test_target": "test/test_utils.py::TestUnhashableKeyDict::test_contains", "ground_truth_oracle": "assert \"key\" in d", "ground_truth_oracle_lineno": 691, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class UnhashableKeyDict(MutableMapping):\n \"\"\"\n Essentially a list of key-value tuples that allows for keys that are not hashable,\n but acts like a dictionary for convenience.\n \"\"\"\n\n def __init__(self):\n self.data = []\n\n def __getitem__(self, key):\n for k, v in self.data:\n if deep_equal(k, key):\n return v\n raise KeyError(key)\n\n def __setitem__(self, key, value):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n self.data[i] = (key, value)\n return\n self.data.append((key, value))\n\n def __delitem__(self, key):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n del self.data[i]\n return\n raise KeyError(key)\n\n def __iter__(self):\n return (k for k, _ in self.data)\n\n def __len__(self):\n return len(self.data)\n\n def as_list(self):\n return [v for _, v in self.data]", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1520, "focal_method_end_lineno": 1556} {"index": 126, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_audio_to_file", "test_class_name": "TestAudioPreprocessing", "original_test_prefix": " def test_audio_to_file(self):\n audio = processing_utils.audio_from_file(\"gradio/test_data/test_audio.wav\")\n processing_utils.audio_to_file(audio[0], audio[1], \"test_audio_to_file\")\n assert os.path.exists(\"test_audio_to_file\")\n os.remove(\"test_audio_to_file\")", "test_prefix": " def test_audio_to_file(self):\n audio = processing_utils.audio_from_file(\"gradio/test_data/test_audio.wav\")\n processing_utils.audio_to_file(audio[0], audio[1], \"test_audio_to_file\")\n \n os.remove(\"test_audio_to_file\")", "test_prefix_file_path": "test/test_processing_utils.py", "test_prefix_start_lineno": 197, "test_prefix_end_lineno": 201, "test_target": "test/test_processing_utils.py::TestAudioPreprocessing::test_audio_to_file", "ground_truth_oracle": "assert os.path.exists(\"test_audio_to_file\")", "ground_truth_oracle_lineno": 200, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "##################\n# Audio\n##################\n\n\ndef audio_from_file(\n filename: str, crop_min: float = 0, crop_max: float = 100\n) -> tuple[int, np.ndarray]:\n try:\n audio = AudioSegment.from_file(filename)\n except FileNotFoundError as e:\n isfile = Path(filename).is_file()\n msg = (\n f\"Cannot load audio from file: `{'ffprobe' if isfile else filename}` not found.\"\n + \" Please install `ffmpeg` in your system to use non-WAV audio file formats\"\n \" and make sure `ffprobe` is in your PATH.\"\n if isfile\n else \"\"\n )\n raise RuntimeError(msg) from e\n except OSError as e:\n raise e\n if crop_min != 0 or crop_max != 100:\n audio_start = len(audio) * crop_min / 100\n audio_end = len(audio) * crop_max / 100\n audio = audio[audio_start:audio_end]\n data = np.array(audio.get_array_of_samples())\n if audio.channels > 1:\n data = data.reshape(-1, audio.channels)\n return audio.frame_rate, data", "focal_method_file_path": "gradio/processing_utils.py", "focal_method_start_lineno": 638, "focal_method_end_lineno": 667} {"index": 127, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_overwrite", "test_class_name": "TestUnhashableKeyDict", "original_test_prefix": " def test_overwrite(self):\n d = UnhashableKeyDict()\n d[\"key\"] = \"old\"\n d[\"key\"] = \"new\"\n assert d[\"key\"] == \"new\"", "test_prefix": " def test_overwrite(self):\n d = UnhashableKeyDict()\n d[\"key\"] = \"old\"\n d[\"key\"] = \"new\"\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 662, "test_prefix_end_lineno": 666, "test_target": "test/test_utils.py::TestUnhashableKeyDict::test_overwrite", "ground_truth_oracle": "assert d[\"key\"] == \"new\"", "ground_truth_oracle_lineno": 666, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class UnhashableKeyDict(MutableMapping):\n \"\"\"\n Essentially a list of key-value tuples that allows for keys that are not hashable,\n but acts like a dictionary for convenience.\n \"\"\"\n\n def __init__(self):\n self.data = []\n\n def __getitem__(self, key):\n for k, v in self.data:\n if deep_equal(k, key):\n return v\n raise KeyError(key)\n\n def __setitem__(self, key, value):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n self.data[i] = (key, value)\n return\n self.data.append((key, value))\n\n def __delitem__(self, key):\n for i, (k, _) in enumerate(self.data):\n if deep_equal(k, key):\n del self.data[i]\n return\n raise KeyError(key)\n\n def __iter__(self):\n return (k for k, _ in self.data)\n\n def __len__(self):\n return len(self.data)\n\n def as_list(self):\n return [v for _, v in self.data]", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1520, "focal_method_end_lineno": 1556} {"index": 128, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_download_if_url_doesnt_crash_on_connection_error", "test_class_name": "TestUtils", "original_test_prefix": " def test_download_if_url_doesnt_crash_on_connection_error(self):\n in_article = \"placeholder\"\n out_article = download_if_url(in_article)\n assert out_article == in_article\n\n # non-printable characters are not allowed in URL address\n in_article = \"text\\twith\\rnon-printable\\nASCII\\x00characters\"\n out_article = download_if_url(in_article)\n assert out_article == in_article\n\n # only files with HTTP(S) URL can be downloaded\n in_article = \"ftp://localhost/tmp/index.html\"\n out_article = download_if_url(in_article)\n assert out_article == in_article\n\n in_article = \"file:///C:/tmp/index.html\"\n out_article = download_if_url(in_article)\n assert out_article == in_article\n\n # this address will raise ValueError during parsing\n in_article = \"https://[unmatched_bracket#?:@/index.html\"\n out_article = download_if_url(in_article)\n assert out_article == in_article", "test_prefix": " def test_download_if_url_doesnt_crash_on_connection_error(self):\n in_article = \"placeholder\"\n out_article = download_if_url(in_article)\n \n\n # non-printable characters are not allowed in URL address\n in_article = \"text\\twith\\rnon-printable\\nASCII\\x00characters\"\n out_article = download_if_url(in_article)\n \n\n # only files with HTTP(S) URL can be downloaded\n in_article = \"ftp://localhost/tmp/index.html\"\n out_article = download_if_url(in_article)\n \n\n in_article = \"file:///C:/tmp/index.html\"\n out_article = download_if_url(in_article)\n \n\n # this address will raise ValueError during parsing\n in_article = \"https://[unmatched_bracket#?:@/index.html\"\n out_article = download_if_url(in_article)\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 70, "test_prefix_end_lineno": 92, "test_target": "test/test_utils.py::TestUtils::test_download_if_url_doesnt_crash_on_connection_error", "ground_truth_oracle": "assert out_article == in_article", "ground_truth_oracle_lineno": 73, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def download_if_url(article: str) -> str:\n try:\n result = urllib.parse.urlparse(article)\n is_url = all([result.scheme, result.netloc, result.path])\n is_url = is_url and result.scheme in [\"http\", \"https\"]\n except ValueError:\n is_url = False\n\n if not is_url:\n return article\n\n try:\n response = httpx.get(article, timeout=3)\n if response.status_code == httpx.codes.OK: # pylint: disable=no-member\n article = response.text\n except (httpx.InvalidURL, httpx.RequestError, httpx.TimeoutException):\n pass\n\n return article", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 475, "focal_method_end_lineno": 493} {"index": 129, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_next_version", "test_class_name": "TestThemeUploadDownload", "original_test_prefix": " @patch(\"gradio.themes.base.get_theme_assets\", return_value=assets)\n def test_get_next_version(self, mock):\n next_version = gr.themes.Base._get_next_version(\n SpaceInfo(id=\"gradio/dracula_test\", private=False, likes=0, tags=[])\n )\n assert next_version == \"3.20.2\"", "test_prefix": " @patch(\"gradio.themes.base.get_theme_assets\", return_value=assets)\n def test_get_next_version(self, mock):\n next_version = gr.themes.Base._get_next_version(\n SpaceInfo(id=\"gradio/dracula_test\", private=False, likes=0, tags=[])\n )\n ", "test_prefix_file_path": "test/test_theme_sharing.py", "test_prefix_start_lineno": 279, "test_prefix_end_lineno": 284, "test_target": "test/test_theme_sharing.py::TestThemeUploadDownload::test_get_next_version", "ground_truth_oracle": "assert next_version == \"3.20.2\"", "ground_truth_oracle_lineno": 284, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @staticmethod\n def _get_next_version(space_info: huggingface_hub.hf_api.SpaceInfo) -> str:\n assets = get_theme_assets(space_info)\n latest_version = max(assets, key=lambda asset: asset.version).version\n return str(latest_version.next_patch())", "focal_method_file_path": "gradio/themes/base.py", "focal_method_start_lineno": 211, "focal_method_end_lineno": 215} {"index": 130, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_abspath_symlink_path", "test_class_name": "TestAbspath", "original_test_prefix": " @pytest.mark.skipif(\n sys.platform.startswith(\"win\"),\n reason=\"Windows doesn't allow creation of sym links without administrative privileges\",\n )\n def test_abspath_symlink_path(self):\n os.symlink(\"gradio/test_data\", \"gradio/test_link\", True)\n resolved_path = str(abspath(\"../gradio/gradio/test_link/lion.jpg\"))\n os.unlink(\"gradio/test_link\")\n assert \"test_link\" in resolved_path", "test_prefix": " @pytest.mark.skipif(\n sys.platform.startswith(\"win\"),\n reason=\"Windows doesn't allow creation of sym links without administrative privileges\",\n )\n def test_abspath_symlink_path(self):\n os.symlink(\"gradio/test_data\", \"gradio/test_link\", True)\n resolved_path = str(abspath(\"../gradio/gradio/test_link/lion.jpg\"))\n os.unlink(\"gradio/test_link\")\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 235, "test_prefix_end_lineno": 243, "test_target": "test/test_utils.py::TestAbspath::test_abspath_symlink_path", "ground_truth_oracle": "assert \"test_link\" in resolved_path", "ground_truth_oracle_lineno": 243, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def abspath(path: str | Path) -> Path:\n return Path(os.path.abspath(str(path)))", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1129, "focal_method_end_lineno": 1130} {"index": 131, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_audio_from_file", "test_class_name": "TestAudioPreprocessing", "original_test_prefix": " def test_audio_from_file(self):\n audio = processing_utils.audio_from_file(\"gradio/test_data/test_audio.wav\")\n assert audio[0] == 22050\n assert isinstance(audio[1], np.ndarray)", "test_prefix": " def test_audio_from_file(self):\n audio = processing_utils.audio_from_file(\"gradio/test_data/test_audio.wav\")\n \n assert isinstance(audio[1], np.ndarray)", "test_prefix_file_path": "test/test_processing_utils.py", "test_prefix_start_lineno": 192, "test_prefix_end_lineno": 195, "test_target": "test/test_processing_utils.py::TestAudioPreprocessing::test_audio_from_file", "ground_truth_oracle": "assert audio[0] == 22050", "ground_truth_oracle_lineno": 194, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "##################\n# Audio\n##################\n\n\ndef audio_from_file(\n filename: str, crop_min: float = 0, crop_max: float = 100\n) -> tuple[int, np.ndarray]:\n try:\n audio = AudioSegment.from_file(filename)\n except FileNotFoundError as e:\n isfile = Path(filename).is_file()\n msg = (\n f\"Cannot load audio from file: `{'ffprobe' if isfile else filename}` not found.\"\n + \" Please install `ffmpeg` in your system to use non-WAV audio file formats\"\n \" and make sure `ffprobe` is in your PATH.\"\n if isfile\n else \"\"\n )\n raise RuntimeError(msg) from e\n except OSError as e:\n raise e\n if crop_min != 0 or crop_max != 100:\n audio_start = len(audio) * crop_min / 100\n audio_end = len(audio) * crop_max / 100\n audio = audio[audio_start:audio_end]\n data = np.array(audio.get_array_of_samples())\n if audio.channels > 1:\n data = data.reshape(-1, audio.channels)\n return audio.frame_rate, data", "focal_method_file_path": "gradio/processing_utils.py", "focal_method_start_lineno": 638, "focal_method_end_lineno": 667} {"index": 132, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_first_suffix", "test_class_name": "TestAppendUniqueSuffix", "original_test_prefix": " def test_first_suffix(self):\n name = \"test\"\n list_of_names = [\"test\", \"test_-1\"]\n assert append_unique_suffix(name, list_of_names) == \"test_1\"", "test_prefix": " def test_first_suffix(self):\n name = \"test\"\n list_of_names = [\"test\", \"test_-1\"]\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 219, "test_prefix_end_lineno": 222, "test_target": "test/test_utils.py::TestAppendUniqueSuffix::test_first_suffix", "ground_truth_oracle": "assert append_unique_suffix(name, list_of_names) == \"test_1\"", "ground_truth_oracle_lineno": 222, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def append_unique_suffix(name: str, list_of_names: list[str]):\n \"\"\"Appends a numerical suffix to `name` so that it does not appear in `list_of_names`.\"\"\"\n set_of_names: set[str] = set(list_of_names) # for O(1) lookup\n if name not in set_of_names:\n return name\n else:\n suffix_counter = 1\n new_name = f\"{name}_{suffix_counter}\"\n while new_name in set_of_names:\n suffix_counter += 1\n new_name = f\"{name}_{suffix_counter}\"\n return new_name", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 815, "focal_method_end_lineno": 826} {"index": 133, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_lambda_with_args", "test_class_name": "TestFunctionParams", "original_test_prefix": " def test_lambda_with_args(self):\n assert get_function_params(lambda x, *args: x) == [(\"x\", False, None, None)]", "test_prefix": " def test_lambda_with_args(self):\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 628, "test_prefix_end_lineno": 629, "test_target": "test/test_utils.py::TestFunctionParams::test_lambda_with_args", "ground_truth_oracle": "assert get_function_params(lambda x, *args: x) == [(\"x\", False, None, None)]", "ground_truth_oracle_lineno": 629, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_function_params(func: Callable) -> list[tuple[str, bool, Any, Any]]:\n \"\"\"\n Gets the parameters of a function as a list of tuples of the form (name, has_default, default_value, type_hint).\n Excludes *args and **kwargs, as well as args that are Gradio-specific, such as gr.Request, gr.EventData, gr.OAuthProfile, and gr.OAuthToken.\n \"\"\"\n params_info = []\n try:\n signature = inspect.signature(func)\n except ValueError:\n signature = inspect.Signature()\n type_hints = get_type_hints(func)\n for name, parameter in signature.parameters.items():\n if parameter.kind in (\n inspect.Parameter.VAR_POSITIONAL,\n inspect.Parameter.VAR_KEYWORD,\n ):\n break\n if is_special_typed_parameter(name, type_hints):\n continue\n if parameter.default is inspect.Parameter.empty:\n params_info.append((name, False, None, type_hints.get(name, None)))\n else:\n params_info.append(\n (name, True, parameter.default, type_hints.get(name, None))\n )\n return params_info", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1346, "focal_method_end_lineno": 1371} {"index": 134, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_function_with_args", "test_class_name": "TestFunctionParams", "original_test_prefix": " def test_function_with_args(self):\n def func(a, *args):\n pass\n\n assert get_function_params(func) == [(\"a\", False, None, None)]", "test_prefix": " def test_function_with_args(self):\n def func(a, *args):\n pass\n\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 571, "test_prefix_end_lineno": 575, "test_target": "test/test_utils.py::TestFunctionParams::test_function_with_args", "ground_truth_oracle": "assert get_function_params(func) == [(\"a\", False, None, None)]", "ground_truth_oracle_lineno": 575, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_function_params(func: Callable) -> list[tuple[str, bool, Any, Any]]:\n \"\"\"\n Gets the parameters of a function as a list of tuples of the form (name, has_default, default_value, type_hint).\n Excludes *args and **kwargs, as well as args that are Gradio-specific, such as gr.Request, gr.EventData, gr.OAuthProfile, and gr.OAuthToken.\n \"\"\"\n params_info = []\n try:\n signature = inspect.signature(func)\n except ValueError:\n signature = inspect.Signature()\n type_hints = get_type_hints(func)\n for name, parameter in signature.parameters.items():\n if parameter.kind in (\n inspect.Parameter.VAR_POSITIONAL,\n inspect.Parameter.VAR_KEYWORD,\n ):\n break\n if is_special_typed_parameter(name, type_hints):\n continue\n if parameter.default is inspect.Parameter.empty:\n params_info.append((name, False, None, type_hints.get(name, None)))\n else:\n params_info.append(\n (name, True, parameter.default, type_hints.get(name, None))\n )\n return params_info", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1346, "focal_method_end_lineno": 1371} {"index": 135, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_format_ner_list_empty", "test_class_name": "TestFormatNERList", "original_test_prefix": " def test_format_ner_list_empty(self):\n string = \"I live in a city\"\n groups = []\n result = [(\"I live in a city\", None)]\n assert format_ner_list(string, groups) == result", "test_prefix": " def test_format_ner_list_empty(self):\n string = \"I live in a city\"\n groups = []\n result = [(\"I live in a city\", None)]\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 140, "test_prefix_end_lineno": 144, "test_target": "test/test_utils.py::TestFormatNERList::test_format_ner_list_empty", "ground_truth_oracle": "assert format_ner_list(string, groups) == result", "ground_truth_oracle_lineno": 144, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def format_ner_list(input_string: str, ner_groups: list[dict[str, str | int]]):\n if len(ner_groups) == 0:\n return [(input_string, None)]\n\n output = []\n end = 0\n prev_end = 0\n\n for group in ner_groups:\n entity, start, end = group[\"entity_group\"], group[\"start\"], group[\"end\"]\n output.append((input_string[prev_end:start], None))\n output.append((input_string[start:end], entity))\n prev_end = end\n\n output.append((input_string[end:], None))\n return output", "focal_method_file_path": "gradio/external_utils.py", "focal_method_start_lineno": 177, "focal_method_end_lineno": 192} {"index": 136, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_dump_and_load", "test_class_name": "TestThemeUploadDownload", "original_test_prefix": " def test_dump_and_load(self):\n with tempfile.NamedTemporaryFile(suffix=\".json\", delete=False) as path:\n dracula.dump(path.name)\n assert gr.themes.Base.load(path.name).to_dict() == dracula.to_dict()", "test_prefix": " def test_dump_and_load(self):\n with tempfile.NamedTemporaryFile(suffix=\".json\", delete=False) as path:\n dracula.dump(path.name)\n ", "test_prefix_file_path": "test/test_theme_sharing.py", "test_prefix_start_lineno": 319, "test_prefix_end_lineno": 322, "test_target": "test/test_theme_sharing.py::TestThemeUploadDownload::test_dump_and_load", "ground_truth_oracle": "assert gr.themes.Base.load(path.name).to_dict() == dracula.to_dict()", "ground_truth_oracle_lineno": 322, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def to_dict(self):\n \"\"\"Convert the theme into a python dictionary.\"\"\"\n schema = {\"theme\": {}}\n for prop in dir(self):\n if (\n not prop.startswith(\"_\")\n or prop.startswith(\"_font\")\n or prop in (\"_stylesheets\", \"name\")\n ) and isinstance(getattr(self, prop), (list, str)):\n schema[\"theme\"][prop] = getattr(self, prop)\n return schema", "focal_method_file_path": "gradio/themes/base.py", "focal_method_start_lineno": 122, "focal_method_end_lineno": 132} {"index": 137, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_does_not_exist", "test_class_name": "TestSemverMatch", "original_test_prefix": " def test_does_not_exist(self):\n assert get_matching_version(assets, \">4.0.0\") is None", "test_prefix": " def test_does_not_exist(self):\n ", "test_prefix_file_path": "test/test_theme_sharing.py", "test_prefix_start_lineno": 200, "test_prefix_end_lineno": 201, "test_target": "test/test_theme_sharing.py::TestSemverMatch::test_does_not_exist", "ground_truth_oracle": "assert get_matching_version(assets, \">4.0.0\") is None", "ground_truth_oracle_lineno": 201, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_matching_version(\n assets: list[ThemeAsset], expression: str | None\n) -> ThemeAsset | None:\n expression = expression or \"*\"\n\n # Return most recent version that matches\n matching_version = semantic_version.SimpleSpec(expression).select(\n [a.version for a in assets]\n )\n\n return next((a for a in assets if a.version == matching_version), None)", "focal_method_file_path": "gradio/themes/utils/semver_match.py", "focal_method_start_lineno": 31, "focal_method_end_lineno": 41} {"index": 138, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_later_suffix", "test_class_name": "TestAppendUniqueSuffix", "original_test_prefix": " def test_later_suffix(self):\n name = \"test\"\n list_of_names = [\"test\", \"test_1\", \"test_2\", \"test_3\"]\n assert append_unique_suffix(name, list_of_names) == \"test_4\"", "test_prefix": " def test_later_suffix(self):\n name = \"test\"\n list_of_names = [\"test\", \"test_1\", \"test_2\", \"test_3\"]\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 224, "test_prefix_end_lineno": 227, "test_target": "test/test_utils.py::TestAppendUniqueSuffix::test_later_suffix", "ground_truth_oracle": "assert append_unique_suffix(name, list_of_names) == \"test_4\"", "ground_truth_oracle_lineno": 227, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def append_unique_suffix(name: str, list_of_names: list[str]):\n \"\"\"Appends a numerical suffix to `name` so that it does not appear in `list_of_names`.\"\"\"\n set_of_names: set[str] = set(list_of_names) # for O(1) lookup\n if name not in set_of_names:\n return name\n else:\n suffix_counter = 1\n new_name = f\"{name}_{suffix_counter}\"\n while new_name in set_of_names:\n suffix_counter += 1\n new_name = f\"{name}_{suffix_counter}\"\n return new_name", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 815, "focal_method_end_lineno": 826} {"index": 139, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_abspath_symlink_dir", "test_class_name": "TestAbspath", "original_test_prefix": " @pytest.mark.skipif(\n sys.platform.startswith(\"win\"),\n reason=\"Windows doesn't allow creation of sym links without administrative privileges\",\n )\n def test_abspath_symlink_dir(self):\n os.symlink(\"gradio/test_data\", \"gradio/test_link\", True)\n full_path = os.path.join(os.getcwd(), \"gradio/test_link/lion.jpg\")\n resolved_path = str(abspath(full_path))\n os.unlink(\"gradio/test_link\")\n assert \"test_link\" in resolved_path\n assert full_path == resolved_path", "test_prefix": " @pytest.mark.skipif(\n sys.platform.startswith(\"win\"),\n reason=\"Windows doesn't allow creation of sym links without administrative privileges\",\n )\n def test_abspath_symlink_dir(self):\n os.symlink(\"gradio/test_data\", \"gradio/test_link\", True)\n full_path = os.path.join(os.getcwd(), \"gradio/test_link/lion.jpg\")\n resolved_path = str(abspath(full_path))\n os.unlink(\"gradio/test_link\")\n assert \"test_link\" in resolved_path\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 245, "test_prefix_end_lineno": 255, "test_target": "test/test_utils.py::TestAbspath::test_abspath_symlink_dir", "ground_truth_oracle": "assert full_path == resolved_path", "ground_truth_oracle_lineno": 255, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def abspath(path: str | Path) -> Path:\n return Path(os.path.abspath(str(path)))", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1129, "focal_method_end_lineno": 1130} {"index": 140, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_use_default_theme_as_fallback", "test_class_name": "TestBlocksMethods", "original_test_prefix": " @patch(\n \"gradio.themes.ThemeClass.from_hub\",\n side_effect=ValueError(\"Something went wrong!\"),\n )\n def test_use_default_theme_as_fallback(self, mock_from_hub):\n with pytest.warns(\n UserWarning, match=\"Cannot load freddyaboulton/this-theme-does-not-exist\"\n ):\n with gr.Blocks(theme=\"freddyaboulton/this-theme-does-not-exist\") as demo:\n assert demo.theme.to_dict() == gr.themes.Default().to_dict()", "test_prefix": " @patch(\n \"gradio.themes.ThemeClass.from_hub\",\n side_effect=ValueError(\"Something went wrong!\"),\n )\n def test_use_default_theme_as_fallback(self, mock_from_hub):\n with pytest.warns(\n UserWarning, match=\"Cannot load freddyaboulton/this-theme-does-not-exist\"\n ):\n with gr.Blocks(theme=\"freddyaboulton/this-theme-does-not-exist\") as demo:\n ", "test_prefix_file_path": "test/test_blocks.py", "test_prefix_start_lineno": 372, "test_prefix_end_lineno": 381, "test_target": "test/test_blocks.py::TestBlocksMethods::test_use_default_theme_as_fallback", "ground_truth_oracle": "assert demo.theme.to_dict() == gr.themes.Default().to_dict()", "ground_truth_oracle_lineno": 381, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def to_dict(self):\n \"\"\"Convert the theme into a python dictionary.\"\"\"\n schema = {\"theme\": {}}\n for prop in dir(self):\n if (\n not prop.startswith(\"_\")\n or prop.startswith(\"_font\")\n or prop in (\"_stylesheets\", \"name\")\n ) and isinstance(getattr(self, prop), (list, str)):\n schema[\"theme\"][prop] = getattr(self, prop)\n return schema", "focal_method_file_path": "gradio/themes/base.py", "focal_method_start_lineno": 122, "focal_method_end_lineno": 132} {"index": 141, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_load_from_config", "test_class_name": "TestBlocksMethods", "original_test_prefix": " def test_load_from_config(self):\n fake_url = \"https://fake.hf.space\"\n\n def update(name):\n return f\"Welcome to Gradio, {name}!\"\n\n with gr.Blocks() as demo1:\n inp = gr.Textbox(placeholder=\"What is your name?\")\n out = gr.Textbox()\n\n inp.submit(fn=update, inputs=inp, outputs=out, api_name=\"greet\")\n\n gr.Image(height=54, width=240)\n\n config1 = demo1.get_config_file()\n demo2 = gr.Blocks.from_config(config1, [update], \"https://fake.hf.space\")\n\n for component in config1[\"components\"]:\n component[\"props\"][\"proxy_url\"] = f\"{fake_url}/\"\n config2 = demo2.get_config_file()\n assert assert_configs_are_equivalent_besides_ids(config1, config2)", "test_prefix": " def test_load_from_config(self):\n fake_url = \"https://fake.hf.space\"\n\n def update(name):\n return f\"Welcome to Gradio, {name}!\"\n\n with gr.Blocks() as demo1:\n inp = gr.Textbox(placeholder=\"What is your name?\")\n out = gr.Textbox()\n\n inp.submit(fn=update, inputs=inp, outputs=out, api_name=\"greet\")\n\n gr.Image(height=54, width=240)\n\n config1 = demo1.get_config_file()\n demo2 = gr.Blocks.from_config(config1, [update], \"https://fake.hf.space\")\n\n for component in config1[\"components\"]:\n component[\"props\"][\"proxy_url\"] = f\"{fake_url}/\"\n config2 = demo2.get_config_file()\n ", "test_prefix_file_path": "test/test_blocks.py", "test_prefix_start_lineno": 75, "test_prefix_end_lineno": 95, "test_target": "test/test_blocks.py::TestBlocksMethods::test_load_from_config", "ground_truth_oracle": "assert assert_configs_are_equivalent_besides_ids(config1, config2)", "ground_truth_oracle_lineno": 95, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_config_file(self) -> BlocksConfigDict:\n config: BlocksConfigDict = {\n \"version\": VERSION,\n \"api_prefix\": API_PREFIX,\n \"mode\": self.mode,\n \"app_id\": self.app_id,\n \"dev_mode\": self.dev_mode,\n \"vibe_mode\": self.vibe_mode,\n \"analytics_enabled\": self.analytics_enabled,\n \"components\": [],\n \"css\": self.css,\n \"connect_heartbeat\": False,\n \"js\": cast(str | Literal[True] | None, self.js),\n \"head\": self.head,\n \"title\": self.title or \"Gradio\",\n \"space_id\": self.space_id,\n \"enable_queue\": True, # launch attributes\n \"show_error\": getattr(self, \"show_error\", False),\n \"show_api\": getattr(self, \"show_api\", True),\n \"is_colab\": utils.colab_check(),\n \"max_file_size\": getattr(self, \"max_file_size\", None),\n \"stylesheets\": self.stylesheets,\n \"theme\": self.theme.name,\n \"protocol\": \"sse_v3\",\n \"body_css\": {\n \"body_background_fill\": self.theme._get_computed_value(\n \"body_background_fill\"\n ),\n \"body_text_color\": self.theme._get_computed_value(\"body_text_color\"),\n \"body_background_fill_dark\": self.theme._get_computed_value(\n \"body_background_fill_dark\"\n ),\n \"body_text_color_dark\": self.theme._get_computed_value(\n \"body_text_color_dark\"\n ),\n },\n \"fill_height\": self.fill_height,\n \"fill_width\": self.fill_width,\n \"theme_hash\": self.theme_hash,\n \"pwa\": self.pwa,\n \"pages\": self.pages,\n \"page\": {},\n \"mcp_server\": self.mcp_server,\n \"i18n_translations\": (\n getattr(self.i18n_instance, \"translations_dict\", None)\n if getattr(self, \"i18n_instance\", None) is not None\n else None\n ),\n }\n config.update(self.default_config.get_config()) # type: ignore\n config[\"connect_heartbeat\"] = utils.connect_heartbeat(\n config, self.blocks.values()\n )\n return config", "focal_method_file_path": "gradio/blocks.py", "focal_method_start_lineno": 2209, "focal_method_end_lineno": 2262} {"index": 142, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_hash_file", "test_class_name": "TestTempFileManagement", "original_test_prefix": " def test_hash_file(self):\n from gradio.media import get_image\n\n h1 = processing_utils.hash_file(get_image(\"cheetah1.jpg\"))\n h2 = processing_utils.hash_file(get_image(\"cheetah1.jpg\"))\n h3 = processing_utils.hash_file(\"gradio/test_data/cheetah2.jpg\")\n assert h1 == h2\n assert h1 != h3", "test_prefix": " def test_hash_file(self):\n from gradio.media import get_image\n\n h1 = processing_utils.hash_file(get_image(\"cheetah1.jpg\"))\n h2 = processing_utils.hash_file(get_image(\"cheetah1.jpg\"))\n h3 = processing_utils.hash_file(\"gradio/test_data/cheetah2.jpg\")\n assert h1 == h2\n ", "test_prefix_file_path": "test/test_processing_utils.py", "test_prefix_start_lineno": 18, "test_prefix_end_lineno": 25, "test_target": "test/test_processing_utils.py::TestTempFileManagement::test_hash_file", "ground_truth_oracle": "assert h1 != h3", "ground_truth_oracle_lineno": 25, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def hash_file(file_path: str | Path, chunk_num_blocks: int = 128) -> str:\n sha = hashlib.sha256()\n sha.update(hash_seed)\n with open(file_path, \"rb\") as f:\n for chunk in iter(lambda: f.read(chunk_num_blocks * sha.block_size), b\"\"):\n sha.update(chunk)\n return sha.hexdigest()", "focal_method_file_path": "gradio/processing_utils.py", "focal_method_start_lineno": 126, "focal_method_end_lineno": 132} {"index": 143, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_function_no_params", "test_class_name": "TestFunctionParams", "original_test_prefix": " def test_function_no_params(self):\n def func():\n pass\n\n assert get_function_params(func) == []", "test_prefix": " def test_function_no_params(self):\n def func():\n pass\n\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 559, "test_prefix_end_lineno": 563, "test_target": "test/test_utils.py::TestFunctionParams::test_function_no_params", "ground_truth_oracle": "assert get_function_params(func) == []", "ground_truth_oracle_lineno": 563, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_function_params(func: Callable) -> list[tuple[str, bool, Any, Any]]:\n \"\"\"\n Gets the parameters of a function as a list of tuples of the form (name, has_default, default_value, type_hint).\n Excludes *args and **kwargs, as well as args that are Gradio-specific, such as gr.Request, gr.EventData, gr.OAuthProfile, and gr.OAuthToken.\n \"\"\"\n params_info = []\n try:\n signature = inspect.signature(func)\n except ValueError:\n signature = inspect.Signature()\n type_hints = get_type_hints(func)\n for name, parameter in signature.parameters.items():\n if parameter.kind in (\n inspect.Parameter.VAR_POSITIONAL,\n inspect.Parameter.VAR_KEYWORD,\n ):\n break\n if is_special_typed_parameter(name, type_hints):\n continue\n if parameter.default is inspect.Parameter.empty:\n params_info.append((name, False, None, type_hints.get(name, None)))\n else:\n params_info.append(\n (name, True, parameter.default, type_hints.get(name, None))\n )\n return params_info", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1346, "focal_method_end_lineno": 1371} {"index": 144, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ipython_check_import_fail", "test_class_name": "TestUtils", "original_test_prefix": " @patch(\"IPython.get_ipython\")\n def test_ipython_check_import_fail(self, mock_get_ipython):\n mock_get_ipython.side_effect = ImportError()\n assert ipython_check() is False", "test_prefix": " @patch(\"IPython.get_ipython\")\n def test_ipython_check_import_fail(self, mock_get_ipython):\n mock_get_ipython.side_effect = ImportError()\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 60, "test_prefix_end_lineno": 63, "test_target": "test/test_utils.py::TestUtils::test_ipython_check_import_fail", "ground_truth_oracle": "assert ipython_check() is False", "ground_truth_oracle_lineno": 63, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def ipython_check() -> bool:\n \"\"\"\n Check if interface is launching from iPython (not colab)\n :return is_ipython (bool): True or False\n \"\"\"\n is_ipython = False\n try: # Check if running interactively using ipython.\n from IPython.core.getipython import get_ipython\n\n if get_ipython() is not None:\n is_ipython = True\n except (ImportError, NameError):\n pass\n return is_ipython", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 449, "focal_method_end_lineno": 462} {"index": 145, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_invalid_urls", "test_class_name": "TestValidateURL", "original_test_prefix": " def test_invalid_urls(self):\n assert not (validate_url(\"C:/Users/\"))\n assert not (validate_url(\"C:\\\\Users\\\\\"))\n assert not (validate_url(\"/home/user\"))", "test_prefix": " def test_invalid_urls(self):\n assert not (validate_url(\"C:/Users/\"))\n \n assert not (validate_url(\"/home/user\"))", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 207, "test_prefix_end_lineno": 210, "test_target": "test/test_utils.py::TestValidateURL::test_invalid_urls", "ground_truth_oracle": "assert not (validate_url(\"C:\\\\Users\\\\\"))", "ground_truth_oracle_lineno": 209, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def validate_url(possible_url: str) -> bool:\n headers = {\"User-Agent\": \"gradio (https://gradio.app/; gradio-team@huggingface.co)\"}\n try:\n head_request = httpx.head(possible_url, headers=headers, follow_redirects=True)\n # some URLs, such as AWS S3 presigned URLs, return a 405 or a 403 for HEAD requests\n if head_request.status_code in (403, 405):\n return httpx.get(\n possible_url, headers=headers, follow_redirects=True\n ).is_success\n return head_request.is_success\n except Exception:\n return False", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 829, "focal_method_end_lineno": 840} {"index": 146, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_is_allowed_file_fuzzer", "test_class_name": "", "original_test_prefix": "@settings(derandomize=os.getenv(\"CI\") is not None)\n@given(\n path=create_path_string(),\n blocked_paths=create_path_list(),\n allowed_paths=create_path_list(),\n created_paths=create_path_list(),\n)\ndef test_is_allowed_file_fuzzer(\n path: Path,\n blocked_paths: Sequence[Path],\n allowed_paths: Sequence[Path],\n created_paths: Sequence[Path],\n):\n result, reason = is_allowed_file(path, blocked_paths, allowed_paths, created_paths)\n\n assert isinstance(result, bool)\n assert reason in [\n \"in_blocklist\",\n \"allowed\",\n \"not_created_or_allowed\",\n \"created\",\n ]\n\n if result:\n assert reason in (\"allowed\", \"created\")\n elif reason == \"in_blocklist\":\n assert any(is_in_or_equal(path, blocked_path) for blocked_path in blocked_paths)\n elif reason == \"not_created_or_allowed\":\n assert not any(\n is_in_or_equal(path, allowed_path) for allowed_path in allowed_paths\n )\n\n if reason == \"allowed\":\n assert any(is_in_or_equal(path, allowed_path) for allowed_path in allowed_paths)\n elif reason == \"created\":\n assert any(is_in_or_equal(path, created_path) for created_path in created_paths)", "test_prefix": "@settings(derandomize=os.getenv(\"CI\") is not None)\n@given(\n path=create_path_string(),\n blocked_paths=create_path_list(),\n allowed_paths=create_path_list(),\n created_paths=create_path_list(),\n)\ndef test_is_allowed_file_fuzzer(\n path: Path,\n blocked_paths: Sequence[Path],\n allowed_paths: Sequence[Path],\n created_paths: Sequence[Path],\n):\n result, reason = is_allowed_file(path, blocked_paths, allowed_paths, created_paths)\n\n assert isinstance(result, bool)\n assert reason in [\n \"in_blocklist\",\n \"allowed\",\n \"not_created_or_allowed\",\n \"created\",\n ]\n\n if result:\n assert reason in (\"allowed\", \"created\")\n elif reason == \"in_blocklist\":\n assert any(is_in_or_equal(path, blocked_path) for blocked_path in blocked_paths)\n elif reason == \"not_created_or_allowed\":\n assert not any(\n is_in_or_equal(path, allowed_path) for allowed_path in allowed_paths\n )\n\n if reason == \"allowed\":\n assert any(is_in_or_equal(path, allowed_path) for allowed_path in allowed_paths)\n elif reason == \"created\":\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 406, "test_prefix_end_lineno": 441, "test_target": "test/test_utils.py::test_is_allowed_file_fuzzer", "ground_truth_oracle": "assert any(is_in_or_equal(path, created_path) for created_path in created_paths)", "ground_truth_oracle_lineno": 441, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def is_in_or_equal(path_1: str | Path, path_2: str | Path) -> bool:\n \"\"\"\n True if path_1 is a descendant (i.e. located within) path_2 or if the paths are the\n same, returns False otherwise.\n Parameters:\n path_1: str or Path (to file or directory)\n path_2: str or Path (to file or directory)\n \"\"\"\n path_1, path_2 = abspath(path_1).resolve(), abspath(path_2).resolve()\n try:\n path_1.relative_to(path_2)\n return True\n except ValueError:\n return False", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 1133, "focal_method_end_lineno": 1146} {"index": 147, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_is_hosted_notebook_false", "test_class_name": "TestUtils", "original_test_prefix": " def test_is_hosted_notebook_false(self):\n assert not is_hosted_notebook()", "test_prefix": " def test_is_hosted_notebook_false(self):\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 99, "test_prefix_end_lineno": 100, "test_target": "test/test_utils.py::TestUtils::test_is_hosted_notebook_false", "ground_truth_oracle": "assert not is_hosted_notebook()", "ground_truth_oracle_lineno": 100, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def is_hosted_notebook() -> bool:\n \"\"\"\n Check if Gradio app is launching from a hosted notebook such as Kaggle or Sagemaker.\n \"\"\"\n return bool(\n os.environ.get(\"KAGGLE_KERNEL_RUN_TYPE\")\n or os.path.exists(\"/home/ec2-user/SageMaker\")\n )", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 439, "focal_method_end_lineno": 446} {"index": 148, "repo_name": "gradio", "github": "https://github.com/gradio-app/gradio.git", "version": "gradio@5.49.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\npip install pytest pytest-asyncio hypothesis\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ipython_check_no_ipython", "test_class_name": "TestUtils", "original_test_prefix": " @patch(\"IPython.get_ipython\")\n def test_ipython_check_no_ipython(self, mock_get_ipython):\n mock_get_ipython.return_value = None\n assert ipython_check() is False", "test_prefix": " @patch(\"IPython.get_ipython\")\n def test_ipython_check_no_ipython(self, mock_get_ipython):\n mock_get_ipython.return_value = None\n ", "test_prefix_file_path": "test/test_utils.py", "test_prefix_start_lineno": 65, "test_prefix_end_lineno": 68, "test_target": "test/test_utils.py::TestUtils::test_ipython_check_no_ipython", "ground_truth_oracle": "assert ipython_check() is False", "ground_truth_oracle_lineno": 68, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def ipython_check() -> bool:\n \"\"\"\n Check if interface is launching from iPython (not colab)\n :return is_ipython (bool): True or False\n \"\"\"\n is_ipython = False\n try: # Check if running interactively using ipython.\n from IPython.core.getipython import get_ipython\n\n if get_ipython() is not None:\n is_ipython = True\n except (ImportError, NameError):\n pass\n return is_ipython", "focal_method_file_path": "gradio/utils.py", "focal_method_start_lineno": 449, "focal_method_end_lineno": 462} {"index": 149, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_add_with_markers", "test_class_name": "", "original_test_prefix": "def test_add_with_markers(app: PoetryTestApplication, tester: CommandTester) -> None:\n marker = \"python_version <= '3.4' or sys_platform == 'win32'\"\n tester.execute(f\"\"\"cachy --markers \"{marker}\" \"\"\")\n\n pyproject: dict[str, Any] = app.poetry.file.read()\n content = pyproject[\"tool\"][\"poetry\"]\n\n assert \"cachy\" in content[\"dependencies\"]\n assert content[\"dependencies\"][\"cachy\"][\"version\"] == \"^0.2.0\"\n assert content[\"dependencies\"][\"cachy\"][\"markers\"] == marker", "test_prefix": "def test_add_with_markers(app: PoetryTestApplication, tester: CommandTester) -> None:\n marker = \"python_version <= '3.4' or sys_platform == 'win32'\"\n tester.execute(f\"\"\"cachy --markers \"{marker}\" \"\"\")\n\n pyproject: dict[str, Any] = app.poetry.file.read()\n content = pyproject[\"tool\"][\"poetry\"]\n\n assert \"cachy\" in content[\"dependencies\"]\n \n assert content[\"dependencies\"][\"cachy\"][\"markers\"] == marker", "test_prefix_file_path": "tests/console/commands/test_add.py", "test_prefix_start_lineno": 352, "test_prefix_end_lineno": 361, "test_target": "tests/console/commands/test_add.py::test_add_with_markers", "ground_truth_oracle": "assert content[\"dependencies\"][\"cachy\"][\"version\"] == \"^0.2.0\"", "ground_truth_oracle_lineno": 360, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def read(self) -> TOMLDocument:\n from tomlkit.exceptions import TOMLKitError\n\n from poetry.toml import TOMLError\n\n try:\n return super().read()\n except (ValueError, TOMLKitError) as e:\n raise TOMLError(f\"Invalid TOML file {self.path.as_posix()}: {e}\")", "focal_method_file_path": "src/poetry/toml/file.py", "focal_method_start_lineno": 26, "focal_method_end_lineno": 34} {"index": 150, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_pool_get_package_in_any_repository", "test_class_name": "", "original_test_prefix": "def test_pool_get_package_in_any_repository() -> None:\n package1 = get_package(\"foo\", \"1.0.0\")\n repo1 = Repository(\"repo1\", [package1])\n package2 = get_package(\"bar\", \"1.0.0\")\n repo2 = Repository(\"repo2\", [package1, package2])\n pool = RepositoryPool([repo1, repo2])\n\n returned_package1 = pool.package(\"foo\", Version.parse(\"1.0.0\"))\n returned_package2 = pool.package(\"bar\", Version.parse(\"1.0.0\"))\n\n assert returned_package1 == package1\n assert returned_package2 == package2", "test_prefix": "def test_pool_get_package_in_any_repository() -> None:\n package1 = get_package(\"foo\", \"1.0.0\")\n repo1 = Repository(\"repo1\", [package1])\n package2 = get_package(\"bar\", \"1.0.0\")\n repo2 = Repository(\"repo2\", [package1, package2])\n pool = RepositoryPool([repo1, repo2])\n\n returned_package1 = pool.package(\"foo\", Version.parse(\"1.0.0\"))\n returned_package2 = pool.package(\"bar\", Version.parse(\"1.0.0\"))\n\n \n assert returned_package2 == package2", "test_prefix_file_path": "tests/repositories/test_repository_pool.py", "test_prefix_start_lineno": 149, "test_prefix_end_lineno": 160, "test_target": "tests/repositories/test_repository_pool.py::test_pool_get_package_in_any_repository", "ground_truth_oracle": "assert returned_package1 == package1", "ground_truth_oracle_lineno": 159, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def package(\n self, name: str, version: Version, repository_name: str | None = None\n ) -> Package:\n if repository_name:\n return self.repository(repository_name).package(name, version)\n\n for repo in self.repositories:\n try:\n return repo.package(name, version)\n except PackageNotFoundError:\n continue\n raise PackageNotFoundError(f\"Package {name} ({version}) not found.\")", "focal_method_file_path": "src/poetry/repositories/repository_pool.py", "focal_method_start_lineno": 154, "focal_method_end_lineno": 165} {"index": 151, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_find_links_for_package_of_supported_types", "test_class_name": "", "original_test_prefix": "def test_find_links_for_package_of_supported_types(\n pypi_repository: PyPiRepository,\n) -> None:\n repo = pypi_repository\n package = repo.find_packages(Factory.create_dependency(\"hbmqtt\", \"0.9.6\"))\n\n assert len(package) == 1\n\n links = repo.find_links_for_package(package[0])\n\n assert len(links) == 1\n assert links[0].is_sdist\n assert links[0].show_url == \"hbmqtt-0.9.6.tar.gz\"", "test_prefix": "def test_find_links_for_package_of_supported_types(\n pypi_repository: PyPiRepository,\n) -> None:\n repo = pypi_repository\n package = repo.find_packages(Factory.create_dependency(\"hbmqtt\", \"0.9.6\"))\n\n assert len(package) == 1\n\n links = repo.find_links_for_package(package[0])\n\n assert len(links) == 1\n \n assert links[0].show_url == \"hbmqtt-0.9.6.tar.gz\"", "test_prefix_file_path": "tests/repositories/test_pypi_repository.py", "test_prefix_start_lineno": 342, "test_prefix_end_lineno": 354, "test_target": "tests/repositories/test_pypi_repository.py::test_find_links_for_package_of_supported_types", "ground_truth_oracle": "assert links[0].is_sdist", "ground_truth_oracle_lineno": 353, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def find_links_for_package(self, package: Package) -> list[Link]:\n json_data = self._get(f\"pypi/{package.name}/{package.version}/json\")\n if json_data is None:\n return []\n\n links = []\n for url in json_data[\"urls\"]:\n if url[\"packagetype\"] in SUPPORTED_PACKAGE_TYPES:\n h = f\"sha256={url['digests']['sha256']}\"\n links.append(Link(url[\"url\"] + \"#\" + h, yanked=self._get_yanked(url)))\n\n return links", "focal_method_file_path": "src/poetry/repositories/pypi_repository.py", "focal_method_start_lineno": 133, "focal_method_end_lineno": 144} {"index": 152, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_preferred_python_use_poetry_python_disabled_fallback", "test_class_name": "", "original_test_prefix": "def test_get_preferred_python_use_poetry_python_disabled_fallback(\n config: Config, with_no_active_python: MagicMock\n) -> None:\n config.config[\"virtualenvs\"][\"use-poetry-python\"] = False\n python = Python.get_preferred_python(config)\n\n assert with_no_active_python.call_count == 1\n assert python.executable.resolve() == Path(sys.executable).resolve()", "test_prefix": "def test_get_preferred_python_use_poetry_python_disabled_fallback(\n config: Config, with_no_active_python: MagicMock\n) -> None:\n config.config[\"virtualenvs\"][\"use-poetry-python\"] = False\n python = Python.get_preferred_python(config)\n\n \n assert python.executable.resolve() == Path(sys.executable).resolve()", "test_prefix_file_path": "tests/utils/test_python_manager.py", "test_prefix_start_lineno": 88, "test_prefix_end_lineno": 95, "test_target": "tests/utils/test_python_manager.py::test_get_preferred_python_use_poetry_python_disabled_fallback", "ground_truth_oracle": "assert with_no_active_python.call_count == 1", "ground_truth_oracle_lineno": 94, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def get_preferred_python(cls, config: Config, io: IO | None = None) -> Python:\n \"\"\"\n Determine and return the \"preferred\" Python interpreter based on the provided\n configuration and optional input/output stream.\n\n This method first attempts to get the active Python interpreter if the configuration\n does not mandate using Poetry's Python. If an active interpreter is found, it is returned.\n Otherwise, the method defaults to retrieving the Poetry's Python interpreter (System Python).\n\n This method **does not** attempt to sort versions or determine Python version constraint\n compatibility.\n \"\"\"\n io = io or NullIO()\n\n if not config.get(\"virtualenvs.use-poetry-python\") and (\n active_python := Python.get_active_python()\n ):\n io.write_error_line(\n f\"Found: {active_python.executable}\", verbosity=Verbosity.VERBOSE\n )\n return active_python\n\n return cls.get_system_python()", "focal_method_file_path": "src/poetry/utils/env/python/manager.py", "focal_method_start_lineno": 258, "focal_method_end_lineno": 281} {"index": 153, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_complete_package_finds_locked_package_in_other_source", "test_class_name": "", "original_test_prefix": "def test_complete_package_finds_locked_package_in_other_source(\n root: ProjectPackage, repository: Repository, pool: RepositoryPool\n) -> None:\n package = Package(\"a\", \"1.0\")\n repository.add_package(package)\n explicit_repo = Repository(\"explicit\")\n pool.add_repository(explicit_repo)\n\n root_dependency = get_dependency(\"a\", \">0\") # no explicit source\n root.add_dependency(root_dependency)\n locked_package = Package(\"a\", \"1.0\", source_reference=\"explicit\") # explicit source\n provider = Provider(root, pool, NullIO(), locked=[locked_package])\n provider.complete_package(DependencyPackage(root.to_dependency(), root))\n\n # transitive dependency without explicit source\n dependency = get_dependency(\"a\", \">=1\")\n\n locked = provider.get_locked(dependency)\n assert locked is not None\n provider.complete_package(locked) # must not fail", "test_prefix": "def test_complete_package_finds_locked_package_in_other_source(\n root: ProjectPackage, repository: Repository, pool: RepositoryPool\n) -> None:\n package = Package(\"a\", \"1.0\")\n repository.add_package(package)\n explicit_repo = Repository(\"explicit\")\n pool.add_repository(explicit_repo)\n\n root_dependency = get_dependency(\"a\", \">0\") # no explicit source\n root.add_dependency(root_dependency)\n locked_package = Package(\"a\", \"1.0\", source_reference=\"explicit\") # explicit source\n provider = Provider(root, pool, NullIO(), locked=[locked_package])\n provider.complete_package(DependencyPackage(root.to_dependency(), root))\n\n # transitive dependency without explicit source\n dependency = get_dependency(\"a\", \">=1\")\n\n locked = provider.get_locked(dependency)\n \n provider.complete_package(locked) # must not fail", "test_prefix_file_path": "tests/puzzle/test_provider.py", "test_prefix_start_lineno": 821, "test_prefix_end_lineno": 840, "test_target": "tests/puzzle/test_provider.py::test_complete_package_finds_locked_package_in_other_source", "ground_truth_oracle": "assert locked is not None", "ground_truth_oracle_lineno": 839, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_locked(self, dependency: Dependency) -> DependencyPackage | None:\n if dependency.name in self._use_latest:\n return None\n\n locked = self._locked.get(dependency.name, [])\n for dependency_package in locked:\n package = dependency_package.package\n if package.satisfies(dependency):\n if explicit_source := self._explicit_sources.get(dependency.name):\n dependency.source_name = explicit_source\n elif (\n not dependency.source_name\n and package.source_type == \"legacy\"\n and package.source_reference\n and self._pool.get_priority(package.source_reference)\n == Priority.EXPLICIT\n ):\n continue\n return DependencyPackage(dependency, package)\n return None", "focal_method_file_path": "src/poetry/puzzle/provider.py", "focal_method_start_lineno": 750, "focal_method_end_lineno": 769} {"index": 154, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_poetry_with_supplemental_source", "test_class_name": "", "original_test_prefix": "def test_poetry_with_supplemental_source(\n fixture_dir: FixtureDirGetter, with_simple_keyring: None\n) -> None:\n io = BufferedIO()\n poetry = Factory().create_poetry(fixture_dir(\"with_supplemental_source\"), io=io)\n\n assert poetry.pool.has_repository(\"PyPI\")\n assert poetry.pool.get_priority(\"PyPI\") is Priority.PRIMARY\n assert isinstance(poetry.pool.repository(\"PyPI\"), PyPiRepository)\n assert poetry.pool.has_repository(\"supplemental\")\n assert poetry.pool.get_priority(\"supplemental\") is Priority.SUPPLEMENTAL\n assert isinstance(poetry.pool.repository(\"supplemental\"), LegacyRepository)\n assert {repo.name for repo in poetry.pool.repositories} == {\"PyPI\", \"supplemental\"}\n assert io.fetch_error() == \"\"", "test_prefix": "def test_poetry_with_supplemental_source(\n fixture_dir: FixtureDirGetter, with_simple_keyring: None\n) -> None:\n io = BufferedIO()\n poetry = Factory().create_poetry(fixture_dir(\"with_supplemental_source\"), io=io)\n\n assert poetry.pool.has_repository(\"PyPI\")\n assert poetry.pool.get_priority(\"PyPI\") is Priority.PRIMARY\n assert isinstance(poetry.pool.repository(\"PyPI\"), PyPiRepository)\n assert poetry.pool.has_repository(\"supplemental\")\n assert poetry.pool.get_priority(\"supplemental\") is Priority.SUPPLEMENTAL\n \n assert {repo.name for repo in poetry.pool.repositories} == {\"PyPI\", \"supplemental\"}\n assert io.fetch_error() == \"\"", "test_prefix_file_path": "tests/test_factory.py", "test_prefix_start_lineno": 328, "test_prefix_end_lineno": 341, "test_target": "tests/test_factory.py::test_poetry_with_supplemental_source", "ground_truth_oracle": "assert isinstance(poetry.pool.repository(\"supplemental\"), LegacyRepository)", "ground_truth_oracle_lineno": 339, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def repository(self, name: str) -> Repository:\n return self._get_prioritized_repository(name).repository", "focal_method_file_path": "src/poetry/repositories/repository_pool.py", "focal_method_start_lineno": 117, "focal_method_end_lineno": 118} {"index": 155, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_prepare_directory", "test_class_name": "", "original_test_prefix": "def test_prepare_directory(\n config: Config,\n config_cache_dir: Path,\n artifact_cache: ArtifactCache,\n fixture_dir: FixtureDirGetter,\n) -> None:\n chef = Chef(\n artifact_cache, EnvManager.get_system_env(), Factory.create_pool(config)\n )\n archive = fixture_dir(\"simple_project_legacy\").resolve()\n\n wheel = chef.prepare(archive)\n\n assert wheel.name == \"simple_project-1.2.3-py2.py3-none-any.whl\"\n\n assert wheel.parent.parent == Path(tempfile.gettempdir())\n # cleanup generated tmp dir artifact\n os.unlink(wheel)", "test_prefix": "def test_prepare_directory(\n config: Config,\n config_cache_dir: Path,\n artifact_cache: ArtifactCache,\n fixture_dir: FixtureDirGetter,\n) -> None:\n chef = Chef(\n artifact_cache, EnvManager.get_system_env(), Factory.create_pool(config)\n )\n archive = fixture_dir(\"simple_project_legacy\").resolve()\n\n wheel = chef.prepare(archive)\n\n \n\n assert wheel.parent.parent == Path(tempfile.gettempdir())\n # cleanup generated tmp dir artifact\n os.unlink(wheel)", "test_prefix_file_path": "tests/installation/test_chef.py", "test_prefix_start_lineno": 63, "test_prefix_end_lineno": 80, "test_target": "tests/installation/test_chef.py::test_prepare_directory", "ground_truth_oracle": "assert wheel.name == \"simple_project-1.2.3-py2.py3-none-any.whl\"", "ground_truth_oracle_lineno": 76, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def prepare(\n self,\n archive: Path,\n output_dir: Path | None = None,\n *,\n editable: bool = False,\n config_settings: Mapping[str, str | Sequence[str]] | None = None,\n ) -> Path:\n if not self._should_prepare(archive):\n return archive\n\n if archive.is_dir():\n destination = output_dir or Path(tempfile.mkdtemp(prefix=\"poetry-chef-\"))\n return self._prepare(\n archive,\n destination=destination,\n editable=editable,\n config_settings=config_settings,\n )\n\n return self._prepare_sdist(\n archive, destination=output_dir, config_settings=config_settings\n )", "focal_method_file_path": "src/poetry/installation/chef.py", "focal_method_start_lineno": 36, "focal_method_end_lineno": 58} {"index": 156, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_html_page_parser_base_url", "test_class_name": "", "original_test_prefix": "def test_html_page_parser_base_url() -> None:\n content = \"\"\"\n \n \n \n \n \n Links for demo\n \n \n

Links for demo

\n demo-0.1.whl
\n \n \n \"\"\"\n parser = HTMLPageParser()\n parser.feed(content)\n\n assert parser.base_url == \"https://example.org/\"", "test_prefix": "def test_html_page_parser_base_url() -> None:\n content = \"\"\"\n \n \n \n \n \n Links for demo\n \n \n

Links for demo

\n demo-0.1.whl
\n \n \n \"\"\"\n parser = HTMLPageParser()\n parser.feed(content)\n\n ", "test_prefix_file_path": "tests/repositories/parsers/test_html_page_parser.py", "test_prefix_start_lineno": 51, "test_prefix_end_lineno": 69, "test_target": "tests/repositories/parsers/test_html_page_parser.py::test_html_page_parser_base_url", "ground_truth_oracle": "assert parser.base_url == \"https://example.org/\"", "ground_truth_oracle_lineno": 69, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class HTMLPageParser(HTMLParser):\n def __init__(self) -> None:\n super().__init__()\n self.base_url: str | None = None\n self.anchors: list[dict[str, str | None]] = []\n\n def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:\n if tag == \"base\" and self.base_url is None:\n base_url = dict(attrs).get(\"href\")\n if base_url is not None:\n self.base_url = base_url\n elif tag == \"a\":\n self.anchors.append(dict(attrs))", "focal_method_file_path": "src/poetry/repositories/parsers/html_page_parser.py", "focal_method_start_lineno": 6, "focal_method_end_lineno": 18} {"index": 157, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_cached_archive_for_link_no_race_condition", "test_class_name": "", "original_test_prefix": "def test_get_cached_archive_for_link_no_race_condition(\n tmp_path: Path, mocker: MockerFixture\n) -> None:\n cache = ArtifactCache(cache_dir=tmp_path)\n link = Link(\"https://files.pythonhosted.org/demo-0.1.0.tar.gz\")\n\n def replace_file(_: str, dest: Path) -> None:\n dest.unlink(missing_ok=True)\n # write some data (so it takes a while) to provoke possible race conditions\n dest.write_text(\"a\" * 2**20, encoding=\"utf-8\")\n\n download_mock = mocker.Mock(side_effect=replace_file)\n\n def get_archive(link: Link) -> Path:\n path: Path = cache.get_cached_archive_for_link(\n link, strict=True, download_func=download_mock\n )\n return path\n\n with concurrent.futures.ThreadPoolExecutor() as executor:\n tasks = []\n for _ in range(4):\n tasks.append(executor.submit(get_archive, link))\n\n concurrent.futures.wait(tasks)\n results = set()\n for task in tasks:\n try:\n results.add(task.result())\n except Exception:\n pytest.fail(traceback.format_exc())\n assert results == {cache.get_cache_directory_for_link(link) / link.filename}\n download_mock.assert_called_once()", "test_prefix": "def test_get_cached_archive_for_link_no_race_condition(\n tmp_path: Path, mocker: MockerFixture\n) -> None:\n cache = ArtifactCache(cache_dir=tmp_path)\n link = Link(\"https://files.pythonhosted.org/demo-0.1.0.tar.gz\")\n\n def replace_file(_: str, dest: Path) -> None:\n dest.unlink(missing_ok=True)\n # write some data (so it takes a while) to provoke possible race conditions\n dest.write_text(\"a\" * 2**20, encoding=\"utf-8\")\n\n download_mock = mocker.Mock(side_effect=replace_file)\n\n def get_archive(link: Link) -> Path:\n path: Path = cache.get_cached_archive_for_link(\n link, strict=True, download_func=download_mock\n )\n return path\n\n with concurrent.futures.ThreadPoolExecutor() as executor:\n tasks = []\n for _ in range(4):\n tasks.append(executor.submit(get_archive, link))\n\n concurrent.futures.wait(tasks)\n results = set()\n for task in tasks:\n try:\n results.add(task.result())\n except Exception:\n pytest.fail(traceback.format_exc())\n \n download_mock.assert_called_once()", "test_prefix_file_path": "tests/utils/test_cache.py", "test_prefix_start_lineno": 330, "test_prefix_end_lineno": 362, "test_target": "tests/utils/test_cache.py::test_get_cached_archive_for_link_no_race_condition", "ground_truth_oracle": "assert results == {cache.get_cache_directory_for_link(link) / link.filename}", "ground_truth_oracle_lineno": 361, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_cache_directory_for_link(self, link: Link) -> Path:\n key_parts = {\"url\": link.url_without_fragment}\n\n if hash_name := get_highest_priority_hash_type(link.hashes, link.filename):\n key_parts[hash_name] = link.hashes[hash_name]\n\n if link.subdirectory_fragment:\n key_parts[\"subdirectory\"] = link.subdirectory_fragment\n\n return self._get_directory_from_hash(key_parts)", "focal_method_file_path": "src/poetry/utils/cache.py", "focal_method_start_lineno": 198, "focal_method_end_lineno": 207} {"index": 158, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_find_all_with_poetry_managed", "test_class_name": "", "original_test_prefix": "def test_find_all_with_poetry_managed(\n without_mocked_findpython: None,\n mocked_poetry_managed_python_register: MockedPoetryPythonRegister,\n) -> None:\n cpython_path = mocked_poetry_managed_python_register(\"3.9.1\", \"cpython\")\n pypy_path = mocked_poetry_managed_python_register(\"3.10.8\", \"pypy\")\n found_pythons = list(Python.find_all())\n assert len(found_pythons) > 3\n for poetry_python in (cpython_path, pypy_path):\n assert any(p.executable.parent == poetry_python for p in found_pythons)", "test_prefix": "def test_find_all_with_poetry_managed(\n without_mocked_findpython: None,\n mocked_poetry_managed_python_register: MockedPoetryPythonRegister,\n) -> None:\n cpython_path = mocked_poetry_managed_python_register(\"3.9.1\", \"cpython\")\n pypy_path = mocked_poetry_managed_python_register(\"3.10.8\", \"pypy\")\n found_pythons = list(Python.find_all())\n \n for poetry_python in (cpython_path, pypy_path):\n assert any(p.executable.parent == poetry_python for p in found_pythons)", "test_prefix_file_path": "tests/utils/env/python/test_manager.py", "test_prefix_start_lineno": 26, "test_prefix_end_lineno": 35, "test_target": "tests/utils/env/python/test_manager.py::test_find_all_with_poetry_managed", "ground_truth_oracle": "assert len(found_pythons) > 3", "ground_truth_oracle_lineno": 33, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def find_all(cls) -> Iterator[Python]:\n venv_path: Path | None = (\n Path(os.environ[\"VIRTUAL_ENV\"]) if \"VIRTUAL_ENV\" in os.environ else None\n )\n for python in findpython.find_all():\n if venv_path and python.executable.is_relative_to(venv_path):\n continue\n yield cls(python=python)", "focal_method_file_path": "src/poetry/utils/env/python/manager.py", "focal_method_start_lineno": 83, "focal_method_end_lineno": 91} {"index": 159, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_prepare_sdist", "test_class_name": "", "original_test_prefix": "def test_prepare_sdist(\n config: Config,\n config_cache_dir: Path,\n artifact_cache: ArtifactCache,\n fixture_dir: FixtureDirGetter,\n) -> None:\n chef = Chef(\n artifact_cache, EnvManager.get_system_env(), Factory.create_pool(config)\n )\n archive = (fixture_dir(\"distributions\") / \"demo-0.1.0.tar.gz\").resolve()\n destination = artifact_cache.get_cache_directory_for_link(Link(archive.as_uri()))\n\n wheel = chef.prepare(archive)\n\n assert wheel.parent == destination\n assert wheel.name == \"demo-0.1.0-py3-none-any.whl\"", "test_prefix": "def test_prepare_sdist(\n config: Config,\n config_cache_dir: Path,\n artifact_cache: ArtifactCache,\n fixture_dir: FixtureDirGetter,\n) -> None:\n chef = Chef(\n artifact_cache, EnvManager.get_system_env(), Factory.create_pool(config)\n )\n archive = (fixture_dir(\"distributions\") / \"demo-0.1.0.tar.gz\").resolve()\n destination = artifact_cache.get_cache_directory_for_link(Link(archive.as_uri()))\n\n wheel = chef.prepare(archive)\n\n \n assert wheel.name == \"demo-0.1.0-py3-none-any.whl\"", "test_prefix_file_path": "tests/installation/test_chef.py", "test_prefix_start_lineno": 45, "test_prefix_end_lineno": 60, "test_target": "tests/installation/test_chef.py::test_prepare_sdist", "ground_truth_oracle": "assert wheel.parent == destination", "ground_truth_oracle_lineno": 59, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def prepare(\n self,\n archive: Path,\n output_dir: Path | None = None,\n *,\n editable: bool = False,\n config_settings: Mapping[str, str | Sequence[str]] | None = None,\n ) -> Path:\n if not self._should_prepare(archive):\n return archive\n\n if archive.is_dir():\n destination = output_dir or Path(tempfile.mkdtemp(prefix=\"poetry-chef-\"))\n return self._prepare(\n archive,\n destination=destination,\n editable=editable,\n config_settings=config_settings,\n )\n\n return self._prepare_sdist(\n archive, destination=output_dir, config_settings=config_settings\n )", "focal_method_file_path": "src/poetry/installation/chef.py", "focal_method_start_lineno": 36, "focal_method_end_lineno": 58} {"index": 160, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_generate_env_name_uses_real_path", "test_class_name": "", "original_test_prefix": "def test_generate_env_name_uses_real_path(\n tmp_path: Path, mocker: MockerFixture\n) -> None:\n mocker.patch(\"os.path.realpath\", return_value=\"the_real_dir\")\n venv_name1 = EnvManager.generate_env_name(\"simple-project\", \"the_real_dir\")\n venv_name2 = EnvManager.generate_env_name(\"simple-project\", \"linked_dir\")\n assert venv_name1 == venv_name2", "test_prefix": "def test_generate_env_name_uses_real_path(\n tmp_path: Path, mocker: MockerFixture\n) -> None:\n mocker.patch(\"os.path.realpath\", return_value=\"the_real_dir\")\n venv_name1 = EnvManager.generate_env_name(\"simple-project\", \"the_real_dir\")\n venv_name2 = EnvManager.generate_env_name(\"simple-project\", \"linked_dir\")\n ", "test_prefix_file_path": "tests/utils/env/test_env_manager.py", "test_prefix_start_lineno": 1298, "test_prefix_end_lineno": 1304, "test_target": "tests/utils/env/test_env_manager.py::test_generate_env_name_uses_real_path", "ground_truth_oracle": "assert venv_name1 == venv_name2", "ground_truth_oracle_lineno": 1304, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def generate_env_name(cls, name: str, cwd: str) -> str:\n name = name.lower()\n sanitized_name = re.sub(r'[ $`!*@\"\\\\\\r\\n\\t]', \"_\", name)[:42]\n normalized_cwd = os.path.normcase(os.path.realpath(cwd))\n h_bytes = hashlib.sha256(encode(normalized_cwd)).digest()\n h_str = base64.urlsafe_b64encode(h_bytes).decode()[:8]\n\n return f\"{sanitized_name}-{h_str}\"", "focal_method_file_path": "src/poetry/utils/env/env_manager.py", "focal_method_start_lineno": 620, "focal_method_end_lineno": 628} {"index": 161, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_package_with_dist_and_universal_py3_wheel", "test_class_name": "", "original_test_prefix": "def test_get_package_with_dist_and_universal_py3_wheel(\n legacy_repository: LegacyRepository,\n) -> None:\n repo = legacy_repository\n\n package = repo.package(\"ipython\", Version.parse(\"7.5.0\"))\n\n assert package.name == \"ipython\"\n assert package.version.text == \"7.5.0\"\n assert package.python_versions == \">=3.5\"\n\n expected = [\n Dependency(\"appnope\", \"*\"),\n Dependency(\"backcall\", \"*\"),\n Dependency(\"colorama\", \"*\"),\n Dependency(\"decorator\", \"*\"),\n Dependency(\"jedi\", \">=0.10\"),\n Dependency(\"pexpect\", \"*\"),\n Dependency(\"pickleshare\", \"*\"),\n Dependency(\"prompt-toolkit\", \">=2.0.0,<2.1.0\"),\n Dependency(\"pygments\", \"*\"),\n Dependency(\"setuptools\", \">=18.5\"),\n Dependency(\"traitlets\", \">=4.2\"),\n Dependency(\"typing\", \"*\"),\n Dependency(\"win-unicode-console\", \">=0.5\"),\n ]\n required = [r for r in package.requires if not r.is_optional()]\n assert sorted(required, key=lambda dep: dep.name) == expected", "test_prefix": "def test_get_package_with_dist_and_universal_py3_wheel(\n legacy_repository: LegacyRepository,\n) -> None:\n repo = legacy_repository\n\n package = repo.package(\"ipython\", Version.parse(\"7.5.0\"))\n\n assert package.name == \"ipython\"\n \n assert package.python_versions == \">=3.5\"\n\n expected = [\n Dependency(\"appnope\", \"*\"),\n Dependency(\"backcall\", \"*\"),\n Dependency(\"colorama\", \"*\"),\n Dependency(\"decorator\", \"*\"),\n Dependency(\"jedi\", \">=0.10\"),\n Dependency(\"pexpect\", \"*\"),\n Dependency(\"pickleshare\", \"*\"),\n Dependency(\"prompt-toolkit\", \">=2.0.0,<2.1.0\"),\n Dependency(\"pygments\", \"*\"),\n Dependency(\"setuptools\", \">=18.5\"),\n Dependency(\"traitlets\", \">=4.2\"),\n Dependency(\"typing\", \"*\"),\n Dependency(\"win-unicode-console\", \">=0.5\"),\n ]\n required = [r for r in package.requires if not r.is_optional()]\n assert sorted(required, key=lambda dep: dep.name) == expected", "test_prefix_file_path": "tests/repositories/test_legacy_repository.py", "test_prefix_start_lineno": 372, "test_prefix_end_lineno": 399, "test_target": "tests/repositories/test_legacy_repository.py::test_get_package_with_dist_and_universal_py3_wheel", "ground_truth_oracle": "assert package.version.text == \"7.5.0\"", "ground_truth_oracle_lineno": 380, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def package(self, name: str, version: Version) -> Package:\n \"\"\"\n Retrieve the release information.\n\n This is a heavy task which takes time.\n We have to download a package to get the dependencies.\n We also need to download every file matching this release\n to get the various hashes.\n\n Note that this will be cached so the subsequent operations\n should be much faster.\n \"\"\"\n try:\n index = self._packages.index(Package(name, version))\n\n return self._packages[index]\n except ValueError:\n package = super().package(name, version)\n package._source_type = \"legacy\"\n package._source_url = self._url\n package._source_reference = self.name\n\n return package", "focal_method_file_path": "src/poetry/repositories/legacy_repository.py", "focal_method_start_lineno": 49, "focal_method_end_lineno": 71} {"index": 162, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_info_from_wheel_metadata_incomplete", "test_class_name": "", "original_test_prefix": "def test_info_from_wheel_metadata_incomplete() -> None:\n \"\"\"\n To avoid differences in cached metadata,\n it is important that the representation of missing fields does not change!\n \"\"\"\n metadata, _ = parse_email(b\"Metadata-Version: 2.1\\nName: demo\\nVersion: 0.1.0\\n\")\n info = PackageInfo.from_metadata(metadata)\n assert info.name == \"demo\"\n assert info.version == \"0.1.0\"\n assert info.summary is None\n assert info.requires_dist is None\n assert info.requires_python is None", "test_prefix": "def test_info_from_wheel_metadata_incomplete() -> None:\n \"\"\"\n To avoid differences in cached metadata,\n it is important that the representation of missing fields does not change!\n \"\"\"\n metadata, _ = parse_email(b\"Metadata-Version: 2.1\\nName: demo\\nVersion: 0.1.0\\n\")\n info = PackageInfo.from_metadata(metadata)\n assert info.name == \"demo\"\n assert info.version == \"0.1.0\"\n assert info.summary is None\n assert info.requires_dist is None\n ", "test_prefix_file_path": "tests/inspection/test_info.py", "test_prefix_start_lineno": 247, "test_prefix_end_lineno": 258, "test_target": "tests/inspection/test_info.py::test_info_from_wheel_metadata_incomplete", "ground_truth_oracle": "assert info.requires_python is None", "ground_truth_oracle_lineno": 258, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def from_metadata(cls, metadata: RawMetadata) -> PackageInfo:\n \"\"\"\n Create package information from core metadata.\n\n :param metadata: raw metadata\n \"\"\"\n return cls(\n name=metadata.get(\"name\"),\n version=metadata.get(\"version\"),\n summary=metadata.get(\"summary\"),\n requires_dist=metadata.get(\"requires_dist\"),\n requires_python=metadata.get(\"requires_python\"),\n )", "focal_method_file_path": "src/poetry/inspection/info.py", "focal_method_start_lineno": 360, "focal_method_end_lineno": 373} {"index": 163, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_repository_supplemental_repositories_do_show", "test_class_name": "", "original_test_prefix": "def test_repository_supplemental_repositories_do_show() -> None:\n supplemental = LegacyRepository(\"supplemental\", \"https://supplemental.com\")\n\n pool = RepositoryPool()\n pool.add_repository(supplemental, priority=Priority.SUPPLEMENTAL)\n\n assert pool.repository(\"supplemental\") is supplemental\n assert pool.repositories == [supplemental]", "test_prefix": "def test_repository_supplemental_repositories_do_show() -> None:\n supplemental = LegacyRepository(\"supplemental\", \"https://supplemental.com\")\n\n pool = RepositoryPool()\n pool.add_repository(supplemental, priority=Priority.SUPPLEMENTAL)\n\n \n assert pool.repositories == [supplemental]", "test_prefix_file_path": "tests/repositories/test_repository_pool.py", "test_prefix_start_lineno": 80, "test_prefix_end_lineno": 87, "test_target": "tests/repositories/test_repository_pool.py::test_repository_supplemental_repositories_do_show", "ground_truth_oracle": "assert pool.repository(\"supplemental\") is supplemental", "ground_truth_oracle_lineno": 86, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def repository(self, name: str) -> Repository:\n return self._get_prioritized_repository(name).repository", "focal_method_file_path": "src/poetry/repositories/repository_pool.py", "focal_method_start_lineno": 117, "focal_method_end_lineno": 118} {"index": 164, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_poetry_with_multiple_sources", "test_class_name": "", "original_test_prefix": "def test_poetry_with_multiple_sources(\n fixture_dir: FixtureDirGetter, with_simple_keyring: None\n) -> None:\n poetry = Factory().create_poetry(fixture_dir(\"with_multiple_sources\"))\n\n assert not poetry.pool.has_repository(\"PyPI\")\n assert poetry.pool.has_repository(\"bar\")\n assert isinstance(poetry.pool.repository(\"bar\"), LegacyRepository)\n assert poetry.pool.has_repository(\"foo\")\n assert isinstance(poetry.pool.repository(\"foo\"), LegacyRepository)\n assert {repo.name for repo in poetry.pool.repositories} == {\"bar\", \"foo\"}", "test_prefix": "def test_poetry_with_multiple_sources(\n fixture_dir: FixtureDirGetter, with_simple_keyring: None\n) -> None:\n poetry = Factory().create_poetry(fixture_dir(\"with_multiple_sources\"))\n\n assert not poetry.pool.has_repository(\"PyPI\")\n assert poetry.pool.has_repository(\"bar\")\n \n assert poetry.pool.has_repository(\"foo\")\n assert isinstance(poetry.pool.repository(\"foo\"), LegacyRepository)\n assert {repo.name for repo in poetry.pool.repositories} == {\"bar\", \"foo\"}", "test_prefix_file_path": "tests/test_factory.py", "test_prefix_start_lineno": 291, "test_prefix_end_lineno": 301, "test_target": "tests/test_factory.py::test_poetry_with_multiple_sources", "ground_truth_oracle": "assert isinstance(poetry.pool.repository(\"bar\"), LegacyRepository)", "ground_truth_oracle_lineno": 298, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def repository(self, name: str) -> Repository:\n return self._get_prioritized_repository(name).repository", "focal_method_file_path": "src/poetry/repositories/repository_pool.py", "focal_method_start_lineno": 117, "focal_method_end_lineno": 118} {"index": 165, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_cache_get_limited_minutes", "test_class_name": "", "original_test_prefix": "def test_cache_get_limited_minutes(\n repository_cache_dir: Path, mocker: MockerFixture\n) -> None:\n cache: FileCache[Any] = FileCache(repository_cache_dir / \"cache\")\n\n start_time = 1111111111\n\n mocker.patch(\"time.time\", return_value=start_time)\n cache.put(\"key1\", \"value\", minutes=5)\n cache.put(\"key2\", \"value\", minutes=5)\n\n assert cache.get(\"key1\") is not None\n assert cache.get(\"key2\") is not None\n\n mocker.patch(\"time.time\", return_value=start_time + 5 * 60 + 1)\n # check to make sure that the cache deletes for has() and get()\n assert not cache.has(\"key1\")\n assert cache.get(\"key2\") is None", "test_prefix": "def test_cache_get_limited_minutes(\n repository_cache_dir: Path, mocker: MockerFixture\n) -> None:\n cache: FileCache[Any] = FileCache(repository_cache_dir / \"cache\")\n\n start_time = 1111111111\n\n mocker.patch(\"time.time\", return_value=start_time)\n cache.put(\"key1\", \"value\", minutes=5)\n cache.put(\"key2\", \"value\", minutes=5)\n\n assert cache.get(\"key1\") is not None\n \n\n mocker.patch(\"time.time\", return_value=start_time + 5 * 60 + 1)\n # check to make sure that the cache deletes for has() and get()\n assert not cache.has(\"key1\")\n assert cache.get(\"key2\") is None", "test_prefix_file_path": "tests/utils/test_cache.py", "test_prefix_start_lineno": 101, "test_prefix_end_lineno": 118, "test_target": "tests/utils/test_cache.py::test_cache_get_limited_minutes", "ground_truth_oracle": "assert cache.get(\"key2\") is not None", "ground_truth_oracle_lineno": 113, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get(self, key: str) -> T | None:\n return self._get_payload(key)", "focal_method_file_path": "src/poetry/utils/cache.py", "focal_method_start_lineno": 92, "focal_method_end_lineno": 93} {"index": 166, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_find_packages", "test_class_name": "", "original_test_prefix": "def test_find_packages(pypi_repository: PyPiRepository) -> None:\n repo = pypi_repository\n packages = repo.find_packages(Factory.create_dependency(\"requests\", \"~2.18.0\"))\n\n assert len(packages) == 5", "test_prefix": "def test_find_packages(pypi_repository: PyPiRepository) -> None:\n repo = pypi_repository\n packages = repo.find_packages(Factory.create_dependency(\"requests\", \"~2.18.0\"))\n\n ", "test_prefix_file_path": "tests/repositories/test_pypi_repository.py", "test_prefix_start_lineno": 29, "test_prefix_end_lineno": 33, "test_target": "tests/repositories/test_pypi_repository.py::test_find_packages", "ground_truth_oracle": "assert len(packages) == 5", "ground_truth_oracle_lineno": 33, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def find_packages(self, dependency: Dependency) -> list[Package]:\n packages = []\n ignored_pre_release_packages = []\n\n constraint = dependency.constraint\n allow_prereleases = dependency.allows_prereleases()\n for package in self._find_packages(dependency.name, constraint):\n if package.yanked and not isinstance(constraint, Version):\n # PEP 592: yanked files are always ignored, unless they are the only\n # file that matches a version specifier that \"pins\" to an exact\n # version\n continue\n if (\n package.is_prerelease()\n and not allow_prereleases\n and not package.is_direct_origin()\n ):\n ignored_pre_release_packages.append(package)\n continue\n\n packages.append(package)\n\n self._log(\n f\"{len(packages)} packages found for {dependency.name} {constraint!s}\",\n level=\"debug\",\n )\n\n if allow_prereleases is False: # in contrast to None!\n return packages\n return packages or ignored_pre_release_packages", "focal_method_file_path": "src/poetry/repositories/repository.py", "focal_method_start_lineno": 36, "focal_method_end_lineno": 65} {"index": 167, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_authenticator_git_repositories", "test_class_name": "", "original_test_prefix": "def test_authenticator_git_repositories(\n config: Config,\n mock_remote: None,\n http: type[httpretty.httpretty],\n with_simple_keyring: None,\n dummy_keyring: DummyBackend,\n) -> None:\n config.merge(\n {\n \"repositories\": {\n \"one\": {\"url\": \"https://foo.bar/org/one.git\"},\n \"two\": {\"url\": \"https://foo.bar/org/two.git\"},\n },\n \"http-basic\": {\n \"one\": {\"username\": \"foo\", \"password\": \"bar\"},\n \"two\": {\"username\": \"baz\", \"password\": \"qux\"},\n },\n }\n )\n\n authenticator = Authenticator(config, NullIO())\n\n one = authenticator.get_credentials_for_git_url(\"https://foo.bar/org/one.git\")\n assert one.username == \"foo\"\n assert one.password == \"bar\"\n\n two = authenticator.get_credentials_for_git_url(\"https://foo.bar/org/two.git\")\n assert two.username == \"baz\"\n assert two.password == \"qux\"\n\n two_ssh = authenticator.get_credentials_for_git_url(\"ssh://git@foo.bar/org/two.git\")\n assert not two_ssh.username\n assert not two_ssh.password\n\n three = authenticator.get_credentials_for_git_url(\"https://foo.bar/org/three.git\")\n assert not three.username\n assert not three.password", "test_prefix": "def test_authenticator_git_repositories(\n config: Config,\n mock_remote: None,\n http: type[httpretty.httpretty],\n with_simple_keyring: None,\n dummy_keyring: DummyBackend,\n) -> None:\n config.merge(\n {\n \"repositories\": {\n \"one\": {\"url\": \"https://foo.bar/org/one.git\"},\n \"two\": {\"url\": \"https://foo.bar/org/two.git\"},\n },\n \"http-basic\": {\n \"one\": {\"username\": \"foo\", \"password\": \"bar\"},\n \"two\": {\"username\": \"baz\", \"password\": \"qux\"},\n },\n }\n )\n\n authenticator = Authenticator(config, NullIO())\n\n one = authenticator.get_credentials_for_git_url(\"https://foo.bar/org/one.git\")\n assert one.username == \"foo\"\n assert one.password == \"bar\"\n\n two = authenticator.get_credentials_for_git_url(\"https://foo.bar/org/two.git\")\n assert two.username == \"baz\"\n \n\n two_ssh = authenticator.get_credentials_for_git_url(\"ssh://git@foo.bar/org/two.git\")\n assert not two_ssh.username\n assert not two_ssh.password\n\n three = authenticator.get_credentials_for_git_url(\"https://foo.bar/org/three.git\")\n assert not three.username\n assert not three.password", "test_prefix_file_path": "tests/utils/test_authenticator.py", "test_prefix_start_lineno": 640, "test_prefix_end_lineno": 676, "test_target": "tests/utils/test_authenticator.py::test_authenticator_git_repositories", "ground_truth_oracle": "assert two.password == \"qux\"", "ground_truth_oracle_lineno": 668, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_credentials_for_git_url(self, url: str) -> HTTPAuthCredential:\n parsed_url = urllib.parse.urlsplit(url)\n\n if parsed_url.scheme not in {\"http\", \"https\"}:\n return HTTPAuthCredential()\n\n key = f\"git+{url}\"\n\n if key not in self._credentials:\n self._credentials[key] = self._get_credentials_for_url(url, True)\n\n return self._credentials[key]", "focal_method_file_path": "src/poetry/utils/authenticator.py", "focal_method_start_lineno": 329, "focal_method_end_lineno": 340} {"index": 168, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_find_packages_with_prereleases", "test_class_name": "", "original_test_prefix": "def test_find_packages_with_prereleases(pypi_repository: PyPiRepository) -> None:\n repo = pypi_repository\n packages = repo.find_packages(Factory.create_dependency(\"toga\", \">=0.3.0.dev2\"))\n\n assert len(packages) == 2", "test_prefix": "def test_find_packages_with_prereleases(pypi_repository: PyPiRepository) -> None:\n repo = pypi_repository\n packages = repo.find_packages(Factory.create_dependency(\"toga\", \">=0.3.0.dev2\"))\n\n ", "test_prefix_file_path": "tests/repositories/test_pypi_repository.py", "test_prefix_start_lineno": 36, "test_prefix_end_lineno": 40, "test_target": "tests/repositories/test_pypi_repository.py::test_find_packages_with_prereleases", "ground_truth_oracle": "assert len(packages) == 2", "ground_truth_oracle_lineno": 40, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def find_packages(self, dependency: Dependency) -> list[Package]:\n packages = []\n ignored_pre_release_packages = []\n\n constraint = dependency.constraint\n allow_prereleases = dependency.allows_prereleases()\n for package in self._find_packages(dependency.name, constraint):\n if package.yanked and not isinstance(constraint, Version):\n # PEP 592: yanked files are always ignored, unless they are the only\n # file that matches a version specifier that \"pins\" to an exact\n # version\n continue\n if (\n package.is_prerelease()\n and not allow_prereleases\n and not package.is_direct_origin()\n ):\n ignored_pre_release_packages.append(package)\n continue\n\n packages.append(package)\n\n self._log(\n f\"{len(packages)} packages found for {dependency.name} {constraint!s}\",\n level=\"debug\",\n )\n\n if allow_prereleases is False: # in contrast to None!\n return packages\n return packages or ignored_pre_release_packages", "focal_method_file_path": "src/poetry/repositories/repository.py", "focal_method_start_lineno": 36, "focal_method_end_lineno": 65} {"index": 169, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_installer_does_not_write_lock_file_when_installation_fails", "test_class_name": "", "original_test_prefix": "def test_installer_does_not_write_lock_file_when_installation_fails(\n installer: Installer,\n locker: Locker,\n repo: Repository,\n package: ProjectPackage,\n mocker: MockerFixture,\n) -> None:\n repo.add_package(get_package(\"A\", \"1.0\"))\n package.add_dependency(Factory.create_dependency(\"A\", \"~1.0\"))\n\n locker.locked(False)\n\n mocker.patch(\"poetry.installation.installer.Installer._execute\", return_value=1)\n result = installer.run()\n assert result == 1 # error\n\n assert locker._lock_data is None\n\n assert installer.executor.installations_count == 0\n assert installer.executor.updates_count == 0\n assert installer.executor.removals_count == 0", "test_prefix": "def test_installer_does_not_write_lock_file_when_installation_fails(\n installer: Installer,\n locker: Locker,\n repo: Repository,\n package: ProjectPackage,\n mocker: MockerFixture,\n) -> None:\n repo.add_package(get_package(\"A\", \"1.0\"))\n package.add_dependency(Factory.create_dependency(\"A\", \"~1.0\"))\n\n locker.locked(False)\n\n mocker.patch(\"poetry.installation.installer.Installer._execute\", return_value=1)\n result = installer.run()\n assert result == 1 # error\n\n assert locker._lock_data is None\n\n \n assert installer.executor.updates_count == 0\n assert installer.executor.removals_count == 0", "test_prefix_file_path": "tests/installation/test_installer.py", "test_prefix_start_lineno": 2753, "test_prefix_end_lineno": 2773, "test_target": "tests/installation/test_installer.py::test_installer_does_not_write_lock_file_when_installation_fails", "ground_truth_oracle": "assert installer.executor.installations_count == 0", "ground_truth_oracle_lineno": 2771, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def run(self) -> int:\n # Check if refresh\n if not self._update and self._lock and self._locker.is_locked():\n return self._do_refresh()\n\n # Force update if there is no lock file present\n if not self._update and not self._locker.is_locked():\n self._update = True\n\n if self.is_dry_run():\n self.verbose(True)\n\n return self._do_install()", "focal_method_file_path": "src/poetry/installation/installer.py", "focal_method_start_lineno": 91, "focal_method_end_lineno": 103} {"index": 170, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_marker_env_untagged_cpython", "test_class_name": "", "original_test_prefix": "def test_get_marker_env_untagged_cpython(mocker: MockerFixture) -> None:\n mocker.patch(\"platform.python_version\", return_value=\"3.11.9+\")\n env = SystemEnv(Path(sys.prefix))\n marker_env = env.get_marker_env()\n assert marker_env[\"python_full_version\"] == \"3.11.9\"", "test_prefix": "def test_get_marker_env_untagged_cpython(mocker: MockerFixture) -> None:\n mocker.patch(\"platform.python_version\", return_value=\"3.11.9+\")\n env = SystemEnv(Path(sys.prefix))\n marker_env = env.get_marker_env()\n ", "test_prefix_file_path": "tests/utils/env/test_system_env.py", "test_prefix_start_lineno": 15, "test_prefix_end_lineno": 19, "test_target": "tests/utils/env/test_system_env.py::test_get_marker_env_untagged_cpython", "ground_truth_oracle": "assert marker_env[\"python_full_version\"] == \"3.11.9\"", "ground_truth_oracle_lineno": 19, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_marker_env(self) -> MarkerEnv:\n if hasattr(sys, \"implementation\"):\n info = sys.implementation.version\n iver = f\"{info.major}.{info.minor}.{info.micro}\"\n kind = info.releaselevel\n if kind != \"final\":\n iver += kind[0] + str(info.serial)\n\n implementation_name = sys.implementation.name\n else:\n iver = \"0\"\n implementation_name = \"\"\n\n return {\n \"implementation_name\": implementation_name,\n \"implementation_version\": iver,\n \"os_name\": os.name,\n \"platform_machine\": platform.machine(),\n \"platform_release\": platform.release(),\n \"platform_system\": platform.system(),\n \"platform_version\": platform.version(),\n # Workaround for https://github.com/python/cpython/issues/99968\n \"python_full_version\": platform.python_version().rstrip(\"+\"),\n \"platform_python_implementation\": platform.python_implementation(),\n \"python_version\": \".\".join(platform.python_version().split(\".\")[:2]),\n \"sys_platform\": sys.platform,\n \"version_info\": sys.version_info,\n \"interpreter_name\": interpreter_name(),\n \"interpreter_version\": interpreter_version(),\n \"sysconfig_platform\": sysconfig.get_platform(),\n }", "focal_method_file_path": "src/poetry/utils/env/system_env.py", "focal_method_start_lineno": 47, "focal_method_end_lineno": 77} {"index": 171, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_keyring_with_chainer_backend_and_fail_keyring_should_be_unavailable", "test_class_name": "", "original_test_prefix": "def test_keyring_with_chainer_backend_and_fail_keyring_should_be_unavailable(\n with_chained_fail_keyring: None,\n) -> None:\n key_ring = PoetryKeyring(\"poetry\")\n\n assert not key_ring.is_available()", "test_prefix": "def test_keyring_with_chainer_backend_and_fail_keyring_should_be_unavailable(\n with_chained_fail_keyring: None,\n) -> None:\n key_ring = PoetryKeyring(\"poetry\")\n\n ", "test_prefix_file_path": "tests/utils/test_password_manager.py", "test_prefix_start_lineno": 256, "test_prefix_end_lineno": 261, "test_target": "tests/utils/test_password_manager.py::test_keyring_with_chainer_backend_and_fail_keyring_should_be_unavailable", "ground_truth_oracle": "assert not key_ring.is_available()", "ground_truth_oracle_lineno": 261, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n @functools.cache\n def is_available(cls) -> bool:\n logger.debug(\"Checking if keyring is available\")\n try:\n import keyring\n import keyring.backend\n import keyring.errors\n except ImportError as e:\n logger.debug(\"An error occurred while importing keyring: %s\", e)\n return False\n\n def backend_name(backend: keyring.backend.KeyringBackend) -> str:\n name: str = backend.name\n return name.split(\" \")[0]\n\n def backend_is_valid(backend: keyring.backend.KeyringBackend) -> bool:\n name = backend_name(backend)\n if name in (\"chainer\", \"fail\", \"null\"):\n logger.debug(f\"Backend {backend.name!r} is not suitable\")\n return False\n elif \"plaintext\" in backend.name.lower():\n logger.debug(f\"Not using plaintext keyring backend {backend.name!r}\")\n return False\n\n return True\n\n backend = keyring.get_keyring()\n if backend_name(backend) == \"chainer\":\n backends = keyring.backend.get_all_keyring()\n valid_backend = next((b for b in backends if backend_is_valid(b)), None)\n else:\n valid_backend = backend if backend_is_valid(backend) else None\n\n if valid_backend is None:\n logger.debug(\"No valid keyring backend was found\")\n return False\n\n logger.debug(f\"Using keyring backend {backend.name!r}\")\n\n try:\n # unfortunately there is no clean way of checking if keyring is unlocked\n keyring.get_password(\"python-poetry-check\", \"python-poetry\")\n except (RuntimeError, keyring.errors.KeyringError):\n logger.debug(\n \"Accessing keyring failed during availability check\", exc_info=True\n )\n return False\n\n return True", "focal_method_file_path": "src/poetry/utils/password_manager.py", "focal_method_start_lineno": 139, "focal_method_end_lineno": 188} {"index": 172, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_info_from_wheel_metadata", "test_class_name": "", "original_test_prefix": "def test_info_from_wheel_metadata(demo_wheel_metadata: RawMetadata) -> None:\n info = PackageInfo.from_metadata(demo_wheel_metadata)\n demo_check_info(info)\n assert info.requires_python == \">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*\"\n assert info._source_type is None\n assert info._source_url is None", "test_prefix": "def test_info_from_wheel_metadata(demo_wheel_metadata: RawMetadata) -> None:\n info = PackageInfo.from_metadata(demo_wheel_metadata)\n demo_check_info(info)\n assert info.requires_python == \">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*\"\n \n assert info._source_url is None", "test_prefix_file_path": "tests/inspection/test_info.py", "test_prefix_start_lineno": 239, "test_prefix_end_lineno": 244, "test_target": "tests/inspection/test_info.py::test_info_from_wheel_metadata", "ground_truth_oracle": "assert info._source_type is None", "ground_truth_oracle_lineno": 243, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def from_metadata(cls, metadata: RawMetadata) -> PackageInfo:\n \"\"\"\n Create package information from core metadata.\n\n :param metadata: raw metadata\n \"\"\"\n return cls(\n name=metadata.get(\"name\"),\n version=metadata.get(\"version\"),\n summary=metadata.get(\"summary\"),\n requires_dist=metadata.get(\"requires_dist\"),\n requires_python=metadata.get(\"requires_python\"),\n )", "focal_method_file_path": "src/poetry/inspection/info.py", "focal_method_start_lineno": 360, "focal_method_end_lineno": 373} {"index": 173, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_delete_pypi_token_with_unavailable_backend", "test_class_name": "", "original_test_prefix": "def test_delete_pypi_token_with_unavailable_backend(\n config: Config, with_fail_keyring: None\n) -> None:\n config.auth_config_source.add_property(\"pypi-token.foo\", \"baz\")\n manager = PasswordManager(config)\n\n assert not PoetryKeyring.is_available()\n manager.delete_pypi_token(\"foo\")\n\n assert config.get(\"pypi-token.foo\") is None", "test_prefix": "def test_delete_pypi_token_with_unavailable_backend(\n config: Config, with_fail_keyring: None\n) -> None:\n config.auth_config_source.add_property(\"pypi-token.foo\", \"baz\")\n manager = PasswordManager(config)\n\n \n manager.delete_pypi_token(\"foo\")\n\n assert config.get(\"pypi-token.foo\") is None", "test_prefix_file_path": "tests/utils/test_password_manager.py", "test_prefix_start_lineno": 202, "test_prefix_end_lineno": 211, "test_target": "tests/utils/test_password_manager.py::test_delete_pypi_token_with_unavailable_backend", "ground_truth_oracle": "assert not PoetryKeyring.is_available()", "ground_truth_oracle_lineno": 208, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n @functools.cache\n def is_available(cls) -> bool:\n logger.debug(\"Checking if keyring is available\")\n try:\n import keyring\n import keyring.backend\n import keyring.errors\n except ImportError as e:\n logger.debug(\"An error occurred while importing keyring: %s\", e)\n return False\n\n def backend_name(backend: keyring.backend.KeyringBackend) -> str:\n name: str = backend.name\n return name.split(\" \")[0]\n\n def backend_is_valid(backend: keyring.backend.KeyringBackend) -> bool:\n name = backend_name(backend)\n if name in (\"chainer\", \"fail\", \"null\"):\n logger.debug(f\"Backend {backend.name!r} is not suitable\")\n return False\n elif \"plaintext\" in backend.name.lower():\n logger.debug(f\"Not using plaintext keyring backend {backend.name!r}\")\n return False\n\n return True\n\n backend = keyring.get_keyring()\n if backend_name(backend) == \"chainer\":\n backends = keyring.backend.get_all_keyring()\n valid_backend = next((b for b in backends if backend_is_valid(b)), None)\n else:\n valid_backend = backend if backend_is_valid(backend) else None\n\n if valid_backend is None:\n logger.debug(\"No valid keyring backend was found\")\n return False\n\n logger.debug(f\"Using keyring backend {backend.name!r}\")\n\n try:\n # unfortunately there is no clean way of checking if keyring is unlocked\n keyring.get_password(\"python-poetry-check\", \"python-poetry\")\n except (RuntimeError, keyring.errors.KeyringError):\n logger.debug(\n \"Accessing keyring failed during availability check\", exc_info=True\n )\n return False\n\n return True", "focal_method_file_path": "src/poetry/utils/password_manager.py", "focal_method_start_lineno": 139, "focal_method_end_lineno": 188} {"index": 174, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_pyproject_toml_save", "test_class_name": "", "original_test_prefix": "def test_pyproject_toml_save(\n pyproject_toml: Path, poetry_section: str, build_system_section: str\n) -> None:\n pyproject = PyProjectTOML(pyproject_toml)\n\n name = str(uuid.uuid4())\n build_backend = str(uuid.uuid4())\n build_requires = str(uuid.uuid4())\n\n pyproject.poetry_config[\"name\"] = name\n pyproject.build_system.build_backend = build_backend\n pyproject.build_system.requires.append(build_requires)\n\n pyproject.save()\n\n pyproject = PyProjectTOML(pyproject_toml)\n\n assert isinstance(pyproject.poetry_config[\"name\"], str)\n assert pyproject.poetry_config[\"name\"] == name\n assert pyproject.build_system.build_backend == build_backend\n assert build_requires in pyproject.build_system.requires", "test_prefix": "def test_pyproject_toml_save(\n pyproject_toml: Path, poetry_section: str, build_system_section: str\n) -> None:\n pyproject = PyProjectTOML(pyproject_toml)\n\n name = str(uuid.uuid4())\n build_backend = str(uuid.uuid4())\n build_requires = str(uuid.uuid4())\n\n pyproject.poetry_config[\"name\"] = name\n pyproject.build_system.build_backend = build_backend\n pyproject.build_system.requires.append(build_requires)\n\n pyproject.save()\n\n pyproject = PyProjectTOML(pyproject_toml)\n\n assert isinstance(pyproject.poetry_config[\"name\"], str)\n assert pyproject.poetry_config[\"name\"] == name\n assert pyproject.build_system.build_backend == build_backend\n ", "test_prefix_file_path": "tests/pyproject/test_pyproject_toml.py", "test_prefix_start_lineno": 27, "test_prefix_end_lineno": 47, "test_target": "tests/pyproject/test_pyproject_toml.py::test_pyproject_toml_save", "ground_truth_oracle": "assert build_requires in pyproject.build_system.requires", "ground_truth_oracle_lineno": 47, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class PyProjectTOML(BasePyProjectTOML):\n \"\"\"\n Enhanced version of poetry-core's PyProjectTOML\n which is capable of writing pyproject.toml\n\n The poetry-core class uses tomli to read the file,\n here we use tomlkit to preserve comments and formatting when writing.\n \"\"\"\n\n def __init__(self, path: Path) -> None:\n super().__init__(path)\n self._toml_file = TOMLFile(path=path)\n self._toml_document: TOMLDocument | None = None\n\n @property\n def file(self) -> TOMLFile:\n return self._toml_file\n\n @property\n def data(self) -> TOMLDocument:\n if self._toml_document is None:\n if not self.file.exists():\n self._toml_document = TOMLDocument()\n else:\n self._toml_document = self.file.read()\n\n return self._toml_document\n\n def save(self) -> None:\n data = self.data\n\n if self._build_system is not None:\n if \"build-system\" not in data:\n data[\"build-system\"] = table()\n\n build_system = data[\"build-system\"]\n assert isinstance(build_system, Table)\n\n build_system[\"requires\"] = self._build_system.requires\n build_system[\"build-backend\"] = self._build_system.build_backend\n\n self.file.write(data=data)\n\n def reload(self) -> None:\n self._toml_document = None\n self._build_system = None", "focal_method_file_path": "src/poetry/pyproject/toml.py", "focal_method_start_lineno": 17, "focal_method_end_lineno": 62} {"index": 175, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_run_installs_with_local_poetry_file_transitive", "test_class_name": "", "original_test_prefix": "def test_run_installs_with_local_poetry_file_transitive(\n installer: Installer,\n locker: Locker,\n repo: Repository,\n package: ProjectPackage,\n tmpdir: str,\n fixture_dir: FixtureDirGetter,\n) -> None:\n root_dir = fixture_dir(\"directory\")\n package.root_dir = root_dir\n locker.set_lock_path(root_dir)\n directory = fixture_dir(\"directory\").joinpath(\n \"project_with_transitive_file_dependencies\"\n )\n package.add_dependency(\n Factory.create_dependency(\n \"project-with-transitive-file-dependencies\",\n {\"path\": str(directory.relative_to(root_dir))},\n root_dir=root_dir,\n )\n )\n\n repo.add_package(get_package(\"pendulum\", \"1.4.4\"))\n repo.add_package(get_package(\"cachy\", \"0.2.0\"))\n\n result = installer.run()\n assert result == 0\n\n expected = fixture(\"with-file-dependency-transitive\")\n\n assert locker.written_data == expected\n\n assert installer.executor.installations_count == 4", "test_prefix": "def test_run_installs_with_local_poetry_file_transitive(\n installer: Installer,\n locker: Locker,\n repo: Repository,\n package: ProjectPackage,\n tmpdir: str,\n fixture_dir: FixtureDirGetter,\n) -> None:\n root_dir = fixture_dir(\"directory\")\n package.root_dir = root_dir\n locker.set_lock_path(root_dir)\n directory = fixture_dir(\"directory\").joinpath(\n \"project_with_transitive_file_dependencies\"\n )\n package.add_dependency(\n Factory.create_dependency(\n \"project-with-transitive-file-dependencies\",\n {\"path\": str(directory.relative_to(root_dir))},\n root_dir=root_dir,\n )\n )\n\n repo.add_package(get_package(\"pendulum\", \"1.4.4\"))\n repo.add_package(get_package(\"cachy\", \"0.2.0\"))\n\n result = installer.run()\n \n\n expected = fixture(\"with-file-dependency-transitive\")\n\n assert locker.written_data == expected\n\n assert installer.executor.installations_count == 4", "test_prefix_file_path": "tests/installation/test_installer.py", "test_prefix_start_lineno": 1748, "test_prefix_end_lineno": 1780, "test_target": "tests/installation/test_installer.py::test_run_installs_with_local_poetry_file_transitive", "ground_truth_oracle": "assert result == 0", "ground_truth_oracle_lineno": 1774, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def run(self) -> int:\n # Check if refresh\n if not self._update and self._lock and self._locker.is_locked():\n return self._do_refresh()\n\n # Force update if there is no lock file present\n if not self._update and not self._locker.is_locked():\n self._update = True\n\n if self.is_dry_run():\n self.verbose(True)\n\n return self._do_install()", "focal_method_file_path": "src/poetry/installation/installer.py", "focal_method_start_lineno": 91, "focal_method_end_lineno": 103} {"index": 176, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_cached_archive_for_git", "test_class_name": "", "original_test_prefix": "def test_get_cached_archive_for_git() -> None:\n \"\"\"Smoke test that checks that no assertion is raised.\"\"\"\n cache = ArtifactCache(cache_dir=Path())\n archive = cache.get_cached_archive_for_git(\"url\", \"ref\", \"subdirectory\", MockEnv())\n assert archive is None", "test_prefix": "def test_get_cached_archive_for_git() -> None:\n \"\"\"Smoke test that checks that no assertion is raised.\"\"\"\n cache = ArtifactCache(cache_dir=Path())\n archive = cache.get_cached_archive_for_git(\"url\", \"ref\", \"subdirectory\", MockEnv())\n ", "test_prefix_file_path": "tests/utils/test_cache.py", "test_prefix_start_lineno": 365, "test_prefix_end_lineno": 369, "test_target": "tests/utils/test_cache.py::test_get_cached_archive_for_git", "ground_truth_oracle": "assert archive is None", "ground_truth_oracle_lineno": 369, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_cached_archive_for_git(\n self, url: str, reference: str, subdirectory: str | None, env: Env\n ) -> Path | None:\n cache_dir = self.get_cache_directory_for_git(url, reference, subdirectory)\n\n return self._get_cached_archive(cache_dir, strict=False, env=env)", "focal_method_file_path": "src/poetry/utils/cache.py", "focal_method_start_lineno": 277, "focal_method_end_lineno": 282} {"index": 177, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_pool_find_packages_in_any_repository", "test_class_name": "", "original_test_prefix": "def test_pool_find_packages_in_any_repository() -> None:\n package1 = get_package(\"foo\", \"1.1.1\")\n package2 = get_package(\"foo\", \"1.2.3\")\n package3 = get_package(\"foo\", \"2.0.0\")\n package4 = get_package(\"bar\", \"1.2.3\")\n repo1 = Repository(\"repo1\", [package1, package3])\n repo2 = Repository(\"repo2\", [package1, package2, package4])\n pool = RepositoryPool([repo1, repo2])\n\n available_dependency = get_dependency(\"foo\", \"^1.0.0\")\n returned_packages_available = pool.find_packages(available_dependency)\n unavailable_dependency = get_dependency(\"foo\", \"999.9.9\")\n returned_packages_unavailable = pool.find_packages(unavailable_dependency)\n\n assert returned_packages_available == [package1, package1, package2]\n assert returned_packages_unavailable == []", "test_prefix": "def test_pool_find_packages_in_any_repository() -> None:\n package1 = get_package(\"foo\", \"1.1.1\")\n package2 = get_package(\"foo\", \"1.2.3\")\n package3 = get_package(\"foo\", \"2.0.0\")\n package4 = get_package(\"bar\", \"1.2.3\")\n repo1 = Repository(\"repo1\", [package1, package3])\n repo2 = Repository(\"repo2\", [package1, package2, package4])\n pool = RepositoryPool([repo1, repo2])\n\n available_dependency = get_dependency(\"foo\", \"^1.0.0\")\n returned_packages_available = pool.find_packages(available_dependency)\n unavailable_dependency = get_dependency(\"foo\", \"999.9.9\")\n returned_packages_unavailable = pool.find_packages(unavailable_dependency)\n\n assert returned_packages_available == [package1, package1, package2]\n ", "test_prefix_file_path": "tests/repositories/test_repository_pool.py", "test_prefix_start_lineno": 215, "test_prefix_end_lineno": 230, "test_target": "tests/repositories/test_repository_pool.py::test_pool_find_packages_in_any_repository", "ground_truth_oracle": "assert returned_packages_unavailable == []", "ground_truth_oracle_lineno": 230, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def find_packages(self, dependency: Dependency) -> list[Package]:\n repository_name = dependency.source_name\n if repository_name:\n return self.repository(repository_name).find_packages(dependency)\n\n packages: list[Package] = []\n for repo in self.repositories:\n if packages and self.get_priority(repo.name) is Priority.SUPPLEMENTAL:\n break\n packages += repo.find_packages(dependency)\n return packages", "focal_method_file_path": "src/poetry/repositories/repository_pool.py", "focal_method_start_lineno": 167, "focal_method_end_lineno": 177} {"index": 178, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_remove_existing_repository_successful", "test_class_name": "", "original_test_prefix": "def test_remove_existing_repository_successful() -> None:\n repo1 = LegacyRepository(\"foo\", \"https://foo.bar\")\n repo2 = LegacyRepository(\"bar\", \"https://bar.baz\")\n repo3 = LegacyRepository(\"baz\", \"https://baz.quux\")\n\n pool = RepositoryPool()\n pool.add_repository(repo1)\n pool.add_repository(repo2)\n pool.add_repository(repo3)\n pool.remove_repository(\"bar\")\n\n assert pool.repository(\"foo\") is repo1\n assert not pool.has_repository(\"bar\")\n assert pool.repository(\"baz\") is repo3", "test_prefix": "def test_remove_existing_repository_successful() -> None:\n repo1 = LegacyRepository(\"foo\", \"https://foo.bar\")\n repo2 = LegacyRepository(\"bar\", \"https://bar.baz\")\n repo3 = LegacyRepository(\"baz\", \"https://baz.quux\")\n\n pool = RepositoryPool()\n pool.add_repository(repo1)\n pool.add_repository(repo2)\n pool.add_repository(repo3)\n pool.remove_repository(\"bar\")\n\n \n assert not pool.has_repository(\"bar\")\n assert pool.repository(\"baz\") is repo3", "test_prefix_file_path": "tests/repositories/test_repository_pool.py", "test_prefix_start_lineno": 111, "test_prefix_end_lineno": 124, "test_target": "tests/repositories/test_repository_pool.py::test_remove_existing_repository_successful", "ground_truth_oracle": "assert pool.repository(\"foo\") is repo1", "ground_truth_oracle_lineno": 122, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def repository(self, name: str) -> Repository:\n return self._get_prioritized_repository(name).repository", "focal_method_file_path": "src/poetry/repositories/repository_pool.py", "focal_method_start_lineno": 117, "focal_method_end_lineno": 118} {"index": 179, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_invalid_versions_ignored", "test_class_name": "", "original_test_prefix": "def test_invalid_versions_ignored(pypi_repository: PyPiRepository) -> None:\n repo = pypi_repository\n\n # the json metadata for this package contains one malformed version\n # and a correct one.\n packages = repo.find_packages(\n Factory.create_dependency(\"invalid-version-package\", \"*\")\n )\n assert len(packages) == 1", "test_prefix": "def test_invalid_versions_ignored(pypi_repository: PyPiRepository) -> None:\n repo = pypi_repository\n\n # the json metadata for this package contains one malformed version\n # and a correct one.\n packages = repo.find_packages(\n Factory.create_dependency(\"invalid-version-package\", \"*\")\n )\n ", "test_prefix_file_path": "tests/repositories/test_pypi_repository.py", "test_prefix_start_lineno": 304, "test_prefix_end_lineno": 312, "test_target": "tests/repositories/test_pypi_repository.py::test_invalid_versions_ignored", "ground_truth_oracle": "assert len(packages) == 1", "ground_truth_oracle_lineno": 312, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def find_packages(self, dependency: Dependency) -> list[Package]:\n packages = []\n ignored_pre_release_packages = []\n\n constraint = dependency.constraint\n allow_prereleases = dependency.allows_prereleases()\n for package in self._find_packages(dependency.name, constraint):\n if package.yanked and not isinstance(constraint, Version):\n # PEP 592: yanked files are always ignored, unless they are the only\n # file that matches a version specifier that \"pins\" to an exact\n # version\n continue\n if (\n package.is_prerelease()\n and not allow_prereleases\n and not package.is_direct_origin()\n ):\n ignored_pre_release_packages.append(package)\n continue\n\n packages.append(package)\n\n self._log(\n f\"{len(packages)} packages found for {dependency.name} {constraint!s}\",\n level=\"debug\",\n )\n\n if allow_prereleases is False: # in contrast to None!\n return packages\n return packages or ignored_pre_release_packages", "focal_method_file_path": "src/poetry/repositories/repository.py", "focal_method_start_lineno": 36, "focal_method_end_lineno": 65} {"index": 180, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_repository_explicit_repositories_do_not_show", "test_class_name": "", "original_test_prefix": "def test_repository_explicit_repositories_do_not_show() -> None:\n explicit = LegacyRepository(\"explicit\", \"https://explicit.com\")\n primary = LegacyRepository(\"primary\", \"https://primary.com\")\n\n pool = RepositoryPool()\n pool.add_repository(explicit, priority=Priority.EXPLICIT)\n pool.add_repository(primary, priority=Priority.PRIMARY)\n\n assert pool.repository(\"explicit\") is explicit\n assert pool.repository(\"primary\") is primary\n assert pool.repositories == [primary]\n assert pool.all_repositories == [primary, explicit]", "test_prefix": "def test_repository_explicit_repositories_do_not_show() -> None:\n explicit = LegacyRepository(\"explicit\", \"https://explicit.com\")\n primary = LegacyRepository(\"primary\", \"https://primary.com\")\n\n pool = RepositoryPool()\n pool.add_repository(explicit, priority=Priority.EXPLICIT)\n pool.add_repository(primary, priority=Priority.PRIMARY)\n\n assert pool.repository(\"explicit\") is explicit\n \n assert pool.repositories == [primary]\n assert pool.all_repositories == [primary, explicit]", "test_prefix_file_path": "tests/repositories/test_repository_pool.py", "test_prefix_start_lineno": 90, "test_prefix_end_lineno": 101, "test_target": "tests/repositories/test_repository_pool.py::test_repository_explicit_repositories_do_not_show", "ground_truth_oracle": "assert pool.repository(\"primary\") is primary", "ground_truth_oracle_lineno": 99, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def repository(self, name: str) -> Repository:\n return self._get_prioritized_repository(name).repository", "focal_method_file_path": "src/poetry/repositories/repository_pool.py", "focal_method_start_lineno": 117, "focal_method_end_lineno": 118} {"index": 181, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_dfs_depth_with_extra", "test_class_name": "", "original_test_prefix": "def test_dfs_depth_with_extra(package: ProjectPackage) -> None:\n a_foo = Package(\"a\", \"1\", features=[\"foo\"])\n a = Package(\"a\", \"1\")\n b = Package(\"b\", \"1\")\n c = Package(\"c\", \"1\")\n packages = [package, a_foo, a, b, c]\n package.add_dependency(dep(\"a\", extras=[\"foo\"]))\n a_foo.add_dependency(dep(\"a\"))\n a_foo.add_dependency(dep(\"b\"))\n a_foo.add_dependency(dep(\"c\", 'extra == \"foo\"'))\n a.add_dependency(dep(\"b\"))\n\n result, __ = depth_first_search(PackageNode(package, packages))\n depths = {\n nodes[0].package.complete_name: [node.depth for node in nodes]\n for nodes in result\n }\n\n assert depths == {\"root\": [-1], \"a[foo]\": [0], \"a\": [0], \"b\": [1], \"c\": [1]}", "test_prefix": "def test_dfs_depth_with_extra(package: ProjectPackage) -> None:\n a_foo = Package(\"a\", \"1\", features=[\"foo\"])\n a = Package(\"a\", \"1\")\n b = Package(\"b\", \"1\")\n c = Package(\"c\", \"1\")\n packages = [package, a_foo, a, b, c]\n package.add_dependency(dep(\"a\", extras=[\"foo\"]))\n a_foo.add_dependency(dep(\"a\"))\n a_foo.add_dependency(dep(\"b\"))\n a_foo.add_dependency(dep(\"c\", 'extra == \"foo\"'))\n a.add_dependency(dep(\"b\"))\n\n result, __ = depth_first_search(PackageNode(package, packages))\n depths = {\n nodes[0].package.complete_name: [node.depth for node in nodes]\n for nodes in result\n }\n\n ", "test_prefix_file_path": "tests/puzzle/test_solver_internals.py", "test_prefix_start_lineno": 90, "test_prefix_end_lineno": 108, "test_target": "tests/puzzle/test_solver_internals.py::test_dfs_depth_with_extra", "ground_truth_oracle": "assert depths == {\"root\": [-1], \"a[foo]\": [0], \"a\": [0], \"b\": [1], \"c\": [1]}", "ground_truth_oracle_lineno": 108, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def depth_first_search(\n source: PackageNode,\n) -> tuple[list[list[PackageNode]], MarkerOriginDict]:\n back_edges: dict[DFSNodeID, list[PackageNode]] = defaultdict(list)\n markers: MarkerOriginDict = defaultdict(lambda: defaultdict(EmptyMarker))\n visited: set[DFSNodeID] = set()\n topo_sorted_nodes: list[PackageNode] = []\n\n dfs_visit(source, back_edges, visited, topo_sorted_nodes, markers)\n\n # Combine the nodes by name\n combined_nodes: dict[str, list[PackageNode]] = defaultdict(list)\n for node in topo_sorted_nodes:\n node.visit(back_edges[node.id])\n combined_nodes[node.name].append(node)\n\n combined_topo_sorted_nodes: list[list[PackageNode]] = [\n combined_nodes.pop(node.name)\n for node in topo_sorted_nodes\n if node.name in combined_nodes\n ]\n\n return combined_topo_sorted_nodes, markers", "focal_method_file_path": "src/poetry/puzzle/solver.py", "focal_method_start_lineno": 237, "focal_method_end_lineno": 259} {"index": 182, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_package_not_canonicalized", "test_class_name": "", "original_test_prefix": "def test_package_not_canonicalized(pypi_repository: PyPiRepository) -> None:\n repo = pypi_repository\n\n package = repo.package(\"discord.py\", Version.parse(\"2.0.0\"))\n\n assert package.name == \"discord-py\"\n assert package.pretty_name == \"discord.py\"", "test_prefix": "def test_package_not_canonicalized(pypi_repository: PyPiRepository) -> None:\n repo = pypi_repository\n\n package = repo.package(\"discord.py\", Version.parse(\"2.0.0\"))\n\n \n assert package.pretty_name == \"discord.py\"", "test_prefix_file_path": "tests/repositories/test_pypi_repository.py", "test_prefix_start_lineno": 167, "test_prefix_end_lineno": 173, "test_target": "tests/repositories/test_pypi_repository.py::test_package_not_canonicalized", "ground_truth_oracle": "assert package.name == \"discord-py\"", "ground_truth_oracle_lineno": 172, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def package(self, name: str, version: Version) -> Package:\n return self.get_release_info(canonicalize_name(name), version).to_package(\n name=name\n )", "focal_method_file_path": "src/poetry/repositories/cached_repository.py", "focal_method_start_lineno": 69, "focal_method_end_lineno": 72} {"index": 183, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_info_from_requires_txt", "test_class_name": "", "original_test_prefix": "def test_info_from_requires_txt(fixture_dir: FixtureDirGetter) -> None:\n info = PackageInfo.from_metadata_directory(\n fixture_dir(\"inspection\") / \"demo_only_requires_txt.egg-info\"\n )\n assert info is not None\n demo_check_info(info)", "test_prefix": "def test_info_from_requires_txt(fixture_dir: FixtureDirGetter) -> None:\n info = PackageInfo.from_metadata_directory(\n fixture_dir(\"inspection\") / \"demo_only_requires_txt.egg-info\"\n )\n \n demo_check_info(info)", "test_prefix_file_path": "tests/inspection/test_info.py", "test_prefix_start_lineno": 291, "test_prefix_end_lineno": 296, "test_target": "tests/inspection/test_info.py::test_info_from_requires_txt", "ground_truth_oracle": "assert info is not None", "ground_truth_oracle_lineno": 295, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def from_metadata_directory(cls, path: Path) -> PackageInfo | None:\n \"\"\"\n Helper method to parse package information from an unpacked metadata directory.\n\n :param path: The metadata directory to parse information from.\n \"\"\"\n if path.suffix in {\".dist-info\", \".egg-info\"}:\n directories = [path]\n else:\n directories = list(cls._find_dist_info(path=path))\n\n dist: pkginfo.BDist | pkginfo.SDist | pkginfo.Wheel\n for directory in directories:\n try:\n if directory.suffix == \".egg-info\":\n dist = pkginfo.UnpackedSDist(directory.as_posix())\n elif directory.suffix == \".dist-info\":\n dist = pkginfo.Wheel(directory.as_posix())\n else:\n continue\n break\n except ValueError:\n continue\n else:\n try:\n # handle PKG-INFO in unpacked sdist root\n dist = pkginfo.UnpackedSDist(path.as_posix())\n except ValueError:\n return None\n\n return cls._from_distribution(dist=dist)", "focal_method_file_path": "src/poetry/inspection/info.py", "focal_method_start_lineno": 375, "focal_method_end_lineno": 406} {"index": 184, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_python_get_preferred_default", "test_class_name": "", "original_test_prefix": "def test_python_get_preferred_default(config: Config, python_version: Version) -> None:\n python = Python.get_preferred_python(config)\n\n assert python.executable.resolve() == Path(sys.executable).resolve()\n assert python.version == python_version", "test_prefix": "def test_python_get_preferred_default(config: Config, python_version: Version) -> None:\n python = Python.get_preferred_python(config)\n\n assert python.executable.resolve() == Path(sys.executable).resolve()\n ", "test_prefix_file_path": "tests/utils/test_python_manager.py", "test_prefix_start_lineno": 60, "test_prefix_end_lineno": 64, "test_target": "tests/utils/test_python_manager.py::test_python_get_preferred_default", "ground_truth_oracle": "assert python.version == python_version", "ground_truth_oracle_lineno": 64, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def get_preferred_python(cls, config: Config, io: IO | None = None) -> Python:\n \"\"\"\n Determine and return the \"preferred\" Python interpreter based on the provided\n configuration and optional input/output stream.\n\n This method first attempts to get the active Python interpreter if the configuration\n does not mandate using Poetry's Python. If an active interpreter is found, it is returned.\n Otherwise, the method defaults to retrieving the Poetry's Python interpreter (System Python).\n\n This method **does not** attempt to sort versions or determine Python version constraint\n compatibility.\n \"\"\"\n io = io or NullIO()\n\n if not config.get(\"virtualenvs.use-poetry-python\") and (\n active_python := Python.get_active_python()\n ):\n io.write_error_line(\n f\"Found: {active_python.executable}\", verbosity=Verbosity.VERBOSE\n )\n return active_python\n\n return cls.get_system_python()", "focal_method_file_path": "src/poetry/utils/env/python/manager.py", "focal_method_start_lineno": 258, "focal_method_end_lineno": 281} {"index": 185, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_source_dependency_is_not_satisfied_by_incompatible_direct_origin", "test_class_name": "", "original_test_prefix": "def test_source_dependency_is_not_satisfied_by_incompatible_direct_origin(\n provider: Provider, repository: Repository\n) -> None:\n repo_package = Package(\"foo\", \"2.0\")\n repository.add_package(repo_package)\n provider._direct_origin_packages = {\"foo\": Package(\"foo\", \"1.0\", source_type=\"url\")}\n dep = Dependency(\"foo\", \">=2\")\n dep.source_name = repository.name\n\n assert provider.search_for(dep) == [repo_package]", "test_prefix": "def test_source_dependency_is_not_satisfied_by_incompatible_direct_origin(\n provider: Provider, repository: Repository\n) -> None:\n repo_package = Package(\"foo\", \"2.0\")\n repository.add_package(repo_package)\n provider._direct_origin_packages = {\"foo\": Package(\"foo\", \"1.0\", source_type=\"url\")}\n dep = Dependency(\"foo\", \">=2\")\n dep.source_name = repository.name\n\n ", "test_prefix_file_path": "tests/puzzle/test_provider.py", "test_prefix_start_lineno": 882, "test_prefix_end_lineno": 891, "test_target": "tests/puzzle/test_provider.py::test_source_dependency_is_not_satisfied_by_incompatible_direct_origin", "ground_truth_oracle": "assert provider.search_for(dep) == [repo_package]", "ground_truth_oracle_lineno": 891, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def search_for(self, dependency: Dependency) -> list[DependencyPackage]:\n \"\"\"\n Search for the specifications that match the given dependency.\n\n The specifications in the returned list will be considered in reverse\n order, so the latest version ought to be last.\n \"\"\"\n if dependency.is_root:\n return PackageCollection(dependency, [self._package])\n\n if dependency.is_direct_origin():\n package = self.search_for_direct_origin_dependency(dependency)\n self._direct_origin_packages[dependency.name] = package\n return PackageCollection(dependency, [package])\n\n # If we've previously found a direct-origin package that meets this dependency,\n # use it.\n #\n # We rely on the VersionSolver resolving direct-origin dependencies first.\n direct_origin_package = self._direct_origin_packages.get(dependency.name)\n if direct_origin_package and direct_origin_package.satisfies(dependency):\n packages = [direct_origin_package]\n return PackageCollection(dependency, packages)\n\n packages = self._pool.find_packages(dependency)\n\n packages.sort(\n key=lambda p: (\n not p.yanked,\n not p.is_prerelease() and not dependency.allows_prereleases(),\n p.version,\n ),\n reverse=True,\n )\n\n return PackageCollection(dependency, packages)", "focal_method_file_path": "src/poetry/puzzle/provider.py", "focal_method_start_lineno": 276, "focal_method_end_lineno": 311} {"index": 186, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_solver_dependency_cache_respects_source_type", "test_class_name": "", "original_test_prefix": "def test_solver_dependency_cache_respects_source_type(\n root: ProjectPackage, provider: Provider, repo: Repository\n) -> None:\n dependency_pypi = Factory.create_dependency(\"demo\", \">=0.1.0\")\n dependency_git = Factory.create_dependency(\n \"demo\", {\"git\": \"https://github.com/demo/demo.git\"}, groups=[\"dev\"]\n )\n root.add_dependency(dependency_pypi)\n root.add_dependency(dependency_git)\n\n add_to_repo(repo, \"demo\", \"1.0.0\")\n\n cache = DependencyCache(provider)\n cache._search_for_cached.cache_clear()\n\n # ensure cache was never hit for both calls\n cache.search_for(dependency_pypi, 0)\n cache.search_for(dependency_git, 0)\n assert not cache._search_for_cached.cache_info().hits\n\n # increase test coverage by searching for copies\n # (when searching for the exact same object, __eq__ is never called)\n packages_pypi = cache.search_for(deepcopy(dependency_pypi), 0)\n packages_git = cache.search_for(deepcopy(dependency_git), 0)\n\n assert cache._search_for_cached.cache_info().hits == 2\n assert cache._search_for_cached.cache_info().currsize == 2\n\n assert len(packages_pypi) == len(packages_git) == 1\n assert packages_pypi != packages_git\n\n package_pypi = packages_pypi[0]\n package_git = packages_git[0]\n\n assert package_pypi.package.name == dependency_pypi.name\n assert package_pypi.package.version.text == \"1.0.0\"\n\n assert package_git.package.name == dependency_git.name\n assert package_git.package.version.text == \"0.1.2\"\n assert package_git.package.source_type == dependency_git.source_type\n assert package_git.package.source_url == dependency_git.source_url\n assert package_git.package.source_resolved_reference == MOCK_DEFAULT_GIT_REVISION", "test_prefix": "def test_solver_dependency_cache_respects_source_type(\n root: ProjectPackage, provider: Provider, repo: Repository\n) -> None:\n dependency_pypi = Factory.create_dependency(\"demo\", \">=0.1.0\")\n dependency_git = Factory.create_dependency(\n \"demo\", {\"git\": \"https://github.com/demo/demo.git\"}, groups=[\"dev\"]\n )\n root.add_dependency(dependency_pypi)\n root.add_dependency(dependency_git)\n\n add_to_repo(repo, \"demo\", \"1.0.0\")\n\n cache = DependencyCache(provider)\n cache._search_for_cached.cache_clear()\n\n # ensure cache was never hit for both calls\n cache.search_for(dependency_pypi, 0)\n cache.search_for(dependency_git, 0)\n assert not cache._search_for_cached.cache_info().hits\n\n # increase test coverage by searching for copies\n # (when searching for the exact same object, __eq__ is never called)\n packages_pypi = cache.search_for(deepcopy(dependency_pypi), 0)\n packages_git = cache.search_for(deepcopy(dependency_git), 0)\n\n assert cache._search_for_cached.cache_info().hits == 2\n assert cache._search_for_cached.cache_info().currsize == 2\n\n assert len(packages_pypi) == len(packages_git) == 1\n assert packages_pypi != packages_git\n\n package_pypi = packages_pypi[0]\n package_git = packages_git[0]\n\n \n assert package_pypi.package.version.text == \"1.0.0\"\n\n assert package_git.package.name == dependency_git.name\n assert package_git.package.version.text == \"0.1.2\"\n assert package_git.package.source_type == dependency_git.source_type\n assert package_git.package.source_url == dependency_git.source_url\n assert package_git.package.source_resolved_reference == MOCK_DEFAULT_GIT_REVISION", "test_prefix_file_path": "tests/mixology/version_solver/test_dependency_cache.py", "test_prefix_start_lineno": 20, "test_prefix_end_lineno": 61, "test_target": "tests/mixology/version_solver/test_dependency_cache.py::test_solver_dependency_cache_respects_source_type", "ground_truth_oracle": "assert package_pypi.package.name == dependency_pypi.name", "ground_truth_oracle_lineno": 54, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def search_for(\n self,\n dependency: Dependency,\n decision_level: int,\n ) -> list[DependencyPackage]:\n key = (\n dependency.name,\n dependency.source_type,\n dependency.source_url,\n dependency.source_reference,\n dependency.source_subdirectory,\n )\n\n # We could always use dependency.without_features() here,\n # but for performance reasons we only do it if necessary.\n packages = self._search_for_cached(\n dependency.without_features() if dependency.features else dependency, key\n )\n if not self._cache[key] or self._cache[key][-1] is not packages:\n self._cache[key].append(packages)\n self._cached_dependencies_by_level[decision_level].append(key)\n\n if dependency.features and packages:\n # Use the cached dependency so that a possible explicit source is set.\n return PackageCollection(\n packages[0].dependency.with_features(dependency.features), packages\n )\n\n return packages", "focal_method_file_path": "src/poetry/mixology/version_solver.py", "focal_method_start_lineno": 113, "focal_method_end_lineno": 141} {"index": 187, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_pypi_token_with_unavailable_backend", "test_class_name": "", "original_test_prefix": "def test_get_pypi_token_with_unavailable_backend(\n config: Config, with_fail_keyring: None\n) -> None:\n config.auth_config_source.add_property(\"pypi-token.foo\", \"baz\")\n manager = PasswordManager(config)\n\n assert not PoetryKeyring.is_available()\n assert manager.get_pypi_token(\"foo\") == \"baz\"", "test_prefix": "def test_get_pypi_token_with_unavailable_backend(\n config: Config, with_fail_keyring: None\n) -> None:\n config.auth_config_source.add_property(\"pypi-token.foo\", \"baz\")\n manager = PasswordManager(config)\n\n \n assert manager.get_pypi_token(\"foo\") == \"baz\"", "test_prefix_file_path": "tests/utils/test_password_manager.py", "test_prefix_start_lineno": 192, "test_prefix_end_lineno": 199, "test_target": "tests/utils/test_password_manager.py::test_get_pypi_token_with_unavailable_backend", "ground_truth_oracle": "assert not PoetryKeyring.is_available()", "ground_truth_oracle_lineno": 198, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n @functools.cache\n def is_available(cls) -> bool:\n logger.debug(\"Checking if keyring is available\")\n try:\n import keyring\n import keyring.backend\n import keyring.errors\n except ImportError as e:\n logger.debug(\"An error occurred while importing keyring: %s\", e)\n return False\n\n def backend_name(backend: keyring.backend.KeyringBackend) -> str:\n name: str = backend.name\n return name.split(\" \")[0]\n\n def backend_is_valid(backend: keyring.backend.KeyringBackend) -> bool:\n name = backend_name(backend)\n if name in (\"chainer\", \"fail\", \"null\"):\n logger.debug(f\"Backend {backend.name!r} is not suitable\")\n return False\n elif \"plaintext\" in backend.name.lower():\n logger.debug(f\"Not using plaintext keyring backend {backend.name!r}\")\n return False\n\n return True\n\n backend = keyring.get_keyring()\n if backend_name(backend) == \"chainer\":\n backends = keyring.backend.get_all_keyring()\n valid_backend = next((b for b in backends if backend_is_valid(b)), None)\n else:\n valid_backend = backend if backend_is_valid(backend) else None\n\n if valid_backend is None:\n logger.debug(\"No valid keyring backend was found\")\n return False\n\n logger.debug(f\"Using keyring backend {backend.name!r}\")\n\n try:\n # unfortunately there is no clean way of checking if keyring is unlocked\n keyring.get_password(\"python-poetry-check\", \"python-poetry\")\n except (RuntimeError, keyring.errors.KeyringError):\n logger.debug(\n \"Accessing keyring failed during availability check\", exc_info=True\n )\n return False\n\n return True", "focal_method_file_path": "src/poetry/utils/password_manager.py", "focal_method_start_lineno": 139, "focal_method_end_lineno": 188} {"index": 188, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_package_information_chooses_correct_distribution", "test_class_name": "", "original_test_prefix": "def test_get_package_information_chooses_correct_distribution(\n legacy_repository: LegacyRepository,\n) -> None:\n repo = legacy_repository\n\n package = repo.package(\"isort\", Version.parse(\"4.3.4\"))\n\n assert package.name == \"isort\"\n assert package.version.text == \"4.3.4\"\n\n assert package.requires == [Dependency(\"futures\", \"*\")]\n futures_dep = package.requires[0]\n assert futures_dep.python_versions == \"~2.7\"", "test_prefix": "def test_get_package_information_chooses_correct_distribution(\n legacy_repository: LegacyRepository,\n) -> None:\n repo = legacy_repository\n\n package = repo.package(\"isort\", Version.parse(\"4.3.4\"))\n\n \n assert package.version.text == \"4.3.4\"\n\n assert package.requires == [Dependency(\"futures\", \"*\")]\n futures_dep = package.requires[0]\n assert futures_dep.python_versions == \"~2.7\"", "test_prefix_file_path": "tests/repositories/test_legacy_repository.py", "test_prefix_start_lineno": 281, "test_prefix_end_lineno": 293, "test_target": "tests/repositories/test_legacy_repository.py::test_get_package_information_chooses_correct_distribution", "ground_truth_oracle": "assert package.name == \"isort\"", "ground_truth_oracle_lineno": 288, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def package(self, name: str, version: Version) -> Package:\n \"\"\"\n Retrieve the release information.\n\n This is a heavy task which takes time.\n We have to download a package to get the dependencies.\n We also need to download every file matching this release\n to get the various hashes.\n\n Note that this will be cached so the subsequent operations\n should be much faster.\n \"\"\"\n try:\n index = self._packages.index(Package(name, version))\n\n return self._packages[index]\n except ValueError:\n package = super().package(name, version)\n package._source_type = \"legacy\"\n package._source_url = self._url\n package._source_reference = self.name\n\n return package", "focal_method_file_path": "src/poetry/repositories/legacy_repository.py", "focal_method_start_lineno": 49, "focal_method_end_lineno": 71} {"index": 189, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_page_invalid_version_link", "test_class_name": "", "original_test_prefix": "def test_page_invalid_version_link(legacy_repository: LegacyRepository) -> None:\n repo = legacy_repository\n\n page = repo.get_page(\"invalid-version\")\n assert page is not None\n\n links = list(page.links)\n assert len(links) == 1\n\n versions = list(page.versions(canonicalize_name(\"poetry\")))\n assert len(versions) == 1\n assert versions[0].to_string() == \"0.1.0\"\n\n packages = list(page.packages)\n assert len(packages) == 1\n assert packages[0].name == \"poetry\"\n assert packages[0].version.to_string() == \"0.1.0\"", "test_prefix": "def test_page_invalid_version_link(legacy_repository: LegacyRepository) -> None:\n repo = legacy_repository\n\n page = repo.get_page(\"invalid-version\")\n assert page is not None\n\n links = list(page.links)\n assert len(links) == 1\n\n versions = list(page.versions(canonicalize_name(\"poetry\")))\n \n assert versions[0].to_string() == \"0.1.0\"\n\n packages = list(page.packages)\n assert len(packages) == 1\n assert packages[0].name == \"poetry\"\n assert packages[0].version.to_string() == \"0.1.0\"", "test_prefix_file_path": "tests/repositories/test_legacy_repository.py", "test_prefix_start_lineno": 73, "test_prefix_end_lineno": 89, "test_target": "tests/repositories/test_legacy_repository.py::test_page_invalid_version_link", "ground_truth_oracle": "assert len(versions) == 1", "ground_truth_oracle_lineno": 83, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def versions(self, name: NormalizedName) -> Iterator[Version]:\n yield from self._link_cache[name]", "focal_method_file_path": "src/poetry/repositories/link_sources/base.py", "focal_method_start_lineno": 51, "focal_method_end_lineno": 52} {"index": 190, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_search", "test_class_name": "", "original_test_prefix": "def test_search() -> None:\n package_foo1 = get_package(\"foo\", \"1.0.0\")\n package_foo2 = get_package(\"foo\", \"2.0.0\")\n package_foobar = get_package(\"foobar\", \"1.0.0\")\n repo = Repository(\"repo\", [package_foo1, package_foo2, package_foobar])\n\n assert repo.search(\"foo\") == [package_foo1, package_foo2, package_foobar]\n assert repo.search(\"bar\") == [package_foobar]\n assert repo.search(\"nothing\") == []", "test_prefix": "def test_search() -> None:\n package_foo1 = get_package(\"foo\", \"1.0.0\")\n package_foo2 = get_package(\"foo\", \"2.0.0\")\n package_foobar = get_package(\"foobar\", \"1.0.0\")\n repo = Repository(\"repo\", [package_foo1, package_foo2, package_foobar])\n\n assert repo.search(\"foo\") == [package_foo1, package_foo2, package_foobar]\n \n assert repo.search(\"nothing\") == []", "test_prefix_file_path": "tests/repositories/test_repository.py", "test_prefix_start_lineno": 103, "test_prefix_end_lineno": 111, "test_target": "tests/repositories/test_repository.py::test_search", "ground_truth_oracle": "assert repo.search(\"bar\") == [package_foobar]", "ground_truth_oracle_lineno": 110, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def search(self, query: str | list[str]) -> list[Package]:\n results: list[Package] = []\n tokens = query if isinstance(query, list) else [query]\n\n for package in self.packages:\n if any(token in package.name for token in tokens):\n results.append(package)\n\n return results", "focal_method_file_path": "src/poetry/repositories/repository.py", "focal_method_start_lineno": 76, "focal_method_end_lineno": 84} {"index": 191, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_chooser_does_not_choose_yanked_if_others", "test_class_name": "", "original_test_prefix": "def test_chooser_does_not_choose_yanked_if_others(\n specialized_legacy_repository_mocker: SpecializedLegacyRepositoryMocker,\n pool: RepositoryPool,\n dist_hash_getter: DistributionHashGetter,\n) -> None:\n chooser = Chooser(pool, MockEnv(supported_tags=[Tag(\"py2\", \"none\", \"any\")]))\n\n repo = pool.repository(\"foo2\")\n pool.remove_repository(\"foo2\")\n\n assert isinstance(repo, LegacyRepository)\n pool.add_repository(\n specialized_legacy_repository_mocker(\"-partial-yank\", repo.name, repo.url)\n )\n\n package = Package(\"futures\", \"3.2.0\")\n files = [\n {\n \"filename\": filename,\n \"hash\": (f\"sha256:{dist_hash_getter(filename).sha256}\"),\n }\n for filename in [\n f\"{package.name}-{package.version}-py2-none-any.whl\",\n f\"{package.name}-{package.version}.tar.gz\",\n ]\n ]\n package = Package(\n package.name,\n package.version.text,\n source_type=\"legacy\",\n source_reference=\"foo\",\n source_url=\"https://legacy.foo.bar/simple/\",\n )\n package_partial_yank = Package(\n package.name,\n package.version.text,\n source_type=\"legacy\",\n source_reference=\"foo2\",\n source_url=\"https://legacy.foo2.bar/simple/\",\n )\n\n package.files = files\n package_partial_yank.files = files\n\n link = chooser.choose_for(package)\n link_partial_yank = chooser.choose_for(package_partial_yank)\n\n assert link.filename == \"futures-3.2.0-py2-none-any.whl\"\n assert link_partial_yank.filename == \"futures-3.2.0.tar.gz\"", "test_prefix": "def test_chooser_does_not_choose_yanked_if_others(\n specialized_legacy_repository_mocker: SpecializedLegacyRepositoryMocker,\n pool: RepositoryPool,\n dist_hash_getter: DistributionHashGetter,\n) -> None:\n chooser = Chooser(pool, MockEnv(supported_tags=[Tag(\"py2\", \"none\", \"any\")]))\n\n repo = pool.repository(\"foo2\")\n pool.remove_repository(\"foo2\")\n\n \n pool.add_repository(\n specialized_legacy_repository_mocker(\"-partial-yank\", repo.name, repo.url)\n )\n\n package = Package(\"futures\", \"3.2.0\")\n files = [\n {\n \"filename\": filename,\n \"hash\": (f\"sha256:{dist_hash_getter(filename).sha256}\"),\n }\n for filename in [\n f\"{package.name}-{package.version}-py2-none-any.whl\",\n f\"{package.name}-{package.version}.tar.gz\",\n ]\n ]\n package = Package(\n package.name,\n package.version.text,\n source_type=\"legacy\",\n source_reference=\"foo\",\n source_url=\"https://legacy.foo.bar/simple/\",\n )\n package_partial_yank = Package(\n package.name,\n package.version.text,\n source_type=\"legacy\",\n source_reference=\"foo2\",\n source_url=\"https://legacy.foo2.bar/simple/\",\n )\n\n package.files = files\n package_partial_yank.files = files\n\n link = chooser.choose_for(package)\n link_partial_yank = chooser.choose_for(package_partial_yank)\n\n assert link.filename == \"futures-3.2.0-py2-none-any.whl\"\n assert link_partial_yank.filename == \"futures-3.2.0.tar.gz\"", "test_prefix_file_path": "tests/installation/test_chooser.py", "test_prefix_start_lineno": 273, "test_prefix_end_lineno": 321, "test_target": "tests/installation/test_chooser.py::test_chooser_does_not_choose_yanked_if_others", "ground_truth_oracle": "assert isinstance(repo, LegacyRepository)", "ground_truth_oracle_lineno": 283, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def repository(self, name: str) -> Repository:\n return self._get_prioritized_repository(name).repository", "focal_method_file_path": "src/poetry/repositories/repository_pool.py", "focal_method_start_lineno": 117, "focal_method_end_lineno": 118} {"index": 192, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_locker_properly_loads_extras", "test_class_name": "", "original_test_prefix": "def test_locker_properly_loads_extras(locker: Locker) -> None:\n content = f\"\"\"\\\n# {GENERATED_COMMENT}\n\n[[package]]\nname = \"cachecontrol\"\nversion = \"0.12.5\"\ndescription = \"httplib2 caching for requests\"\noptional = false\npython-versions = \">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*\"\ngroups = [\"main\"]\nfiles = []\n\n[package.dependencies]\nmsgpack = \"*\"\nrequests = \"*\"\n\n[package.dependencies.lockfile]\noptional = true\nversion = \">=0.9\"\n\n[package.extras]\nfilecache = [\"lockfile (>=0.9)\"]\nredis = [\"redis (>=2.10.5)\"]\n\n[metadata]\nlock-version = \"2.1\"\npython-versions = \"~2.7 || ^3.4\"\ncontent-hash = \"c3d07fca33fba542ef2b2a4d75bf5b48d892d21a830e2ad9c952ba5123a52f77\"\n\"\"\"\n\n with open(locker.lock, \"w\", encoding=\"utf-8\") as f:\n f.write(content)\n\n packages = locker.locked_repository().packages\n\n assert len(packages) == 1\n\n package = packages[0]\n assert len(package.requires) == 3\n assert len(package.extras) == 2\n\n lockfile_dep = package.extras[canonicalize_name(\"filecache\")][0]\n assert lockfile_dep.name == \"lockfile\"", "test_prefix": "def test_locker_properly_loads_extras(locker: Locker) -> None:\n content = f\"\"\"\\\n# {GENERATED_COMMENT}\n\n[[package]]\nname = \"cachecontrol\"\nversion = \"0.12.5\"\ndescription = \"httplib2 caching for requests\"\noptional = false\npython-versions = \">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*\"\ngroups = [\"main\"]\nfiles = []\n\n[package.dependencies]\nmsgpack = \"*\"\nrequests = \"*\"\n\n[package.dependencies.lockfile]\noptional = true\nversion = \">=0.9\"\n\n[package.extras]\nfilecache = [\"lockfile (>=0.9)\"]\nredis = [\"redis (>=2.10.5)\"]\n\n[metadata]\nlock-version = \"2.1\"\npython-versions = \"~2.7 || ^3.4\"\ncontent-hash = \"c3d07fca33fba542ef2b2a4d75bf5b48d892d21a830e2ad9c952ba5123a52f77\"\n\"\"\"\n\n with open(locker.lock, \"w\", encoding=\"utf-8\") as f:\n f.write(content)\n\n packages = locker.locked_repository().packages\n\n \n\n package = packages[0]\n assert len(package.requires) == 3\n assert len(package.extras) == 2\n\n lockfile_dep = package.extras[canonicalize_name(\"filecache\")][0]\n assert lockfile_dep.name == \"lockfile\"", "test_prefix_file_path": "tests/packages/test_locker.py", "test_prefix_start_lineno": 254, "test_prefix_end_lineno": 297, "test_target": "tests/packages/test_locker.py::test_locker_properly_loads_extras", "ground_truth_oracle": "assert len(packages) == 1", "ground_truth_oracle_lineno": 290, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def locked_repository(self) -> LockfileRepository:\n \"\"\"\n Searches and returns a repository of locked packages.\n \"\"\"\n from poetry.repositories.lockfile_repository import LockfileRepository\n\n repository = LockfileRepository()\n\n if not self.is_locked():\n return repository\n\n locked_packages = cast(\"list[dict[str, Any]]\", self.lock_data[\"package\"])\n\n if not locked_packages:\n return repository\n\n for info in locked_packages:\n repository.add_package(self._get_locked_package(info))\n\n return repository", "focal_method_file_path": "src/poetry/packages/locker.py", "focal_method_start_lineno": 128, "focal_method_end_lineno": 147} {"index": 193, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_package_information_includes_python_requires", "test_class_name": "", "original_test_prefix": "def test_get_package_information_includes_python_requires(\n legacy_repository: LegacyRepository,\n) -> None:\n repo = legacy_repository\n\n package = repo.package(\"futures\", Version.parse(\"3.2.0\"))\n\n assert package.name == \"futures\"\n assert package.version.text == \"3.2.0\"\n assert package.python_versions == \">=2.6, <3\"", "test_prefix": "def test_get_package_information_includes_python_requires(\n legacy_repository: LegacyRepository,\n) -> None:\n repo = legacy_repository\n\n package = repo.package(\"futures\", Version.parse(\"3.2.0\"))\n\n assert package.name == \"futures\"\n \n assert package.python_versions == \">=2.6, <3\"", "test_prefix_file_path": "tests/repositories/test_legacy_repository.py", "test_prefix_start_lineno": 296, "test_prefix_end_lineno": 305, "test_target": "tests/repositories/test_legacy_repository.py::test_get_package_information_includes_python_requires", "ground_truth_oracle": "assert package.version.text == \"3.2.0\"", "ground_truth_oracle_lineno": 304, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def package(self, name: str, version: Version) -> Package:\n \"\"\"\n Retrieve the release information.\n\n This is a heavy task which takes time.\n We have to download a package to get the dependencies.\n We also need to download every file matching this release\n to get the various hashes.\n\n Note that this will be cached so the subsequent operations\n should be much faster.\n \"\"\"\n try:\n index = self._packages.index(Package(name, version))\n\n return self._packages[index]\n except ValueError:\n package = super().package(name, version)\n package._source_type = \"legacy\"\n package._source_url = self._url\n package._source_reference = self.name\n\n return package", "focal_method_file_path": "src/poetry/repositories/legacy_repository.py", "focal_method_start_lineno": 49, "focal_method_end_lineno": 71} {"index": 194, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_activate_does_not_recreate_when_switching_minor", "test_class_name": "", "original_test_prefix": "def test_activate_does_not_recreate_when_switching_minor(\n tmp_path: Path,\n manager: EnvManager,\n poetry: Poetry,\n config: Config,\n mocker: MockerFixture,\n venv_name: str,\n mocked_python_register: MockedPythonRegister,\n) -> None:\n if \"VIRTUAL_ENV\" in os.environ:\n del os.environ[\"VIRTUAL_ENV\"]\n\n envs_file = TOMLFile(tmp_path / \"envs.toml\")\n doc = tomlkit.document()\n doc[venv_name] = {\"minor\": \"3.7\", \"patch\": \"3.7.0\"}\n envs_file.write(doc)\n\n os.mkdir(tmp_path / f\"{venv_name}-py3.7\")\n os.mkdir(tmp_path / f\"{venv_name}-py3.6\")\n\n config.merge({\"virtualenvs\": {\"path\": str(tmp_path)}})\n\n mocked_python_register(\"3.7.1\")\n mocked_python_register(\"3.6.6\")\n\n build_venv_m = mocker.patch(\n \"poetry.utils.env.EnvManager.build_venv\", side_effect=build_venv\n )\n remove_venv_m = mocker.patch(\n \"poetry.utils.env.EnvManager.remove_venv\", side_effect=EnvManager.remove_venv\n )\n\n env = manager.activate(\"python3.6\")\n\n build_venv_m.assert_not_called()\n remove_venv_m.assert_not_called()\n\n assert envs_file.exists()\n envs: dict[str, Any] = envs_file.read()\n assert envs[venv_name][\"minor\"] == \"3.6\"\n assert envs[venv_name][\"patch\"] == \"3.6.6\"\n\n assert env.path == tmp_path / f\"{venv_name}-py3.6\"\n assert env.base == Path(sys.base_prefix)\n assert (tmp_path / f\"{venv_name}-py3.6\").exists()", "test_prefix": "def test_activate_does_not_recreate_when_switching_minor(\n tmp_path: Path,\n manager: EnvManager,\n poetry: Poetry,\n config: Config,\n mocker: MockerFixture,\n venv_name: str,\n mocked_python_register: MockedPythonRegister,\n) -> None:\n if \"VIRTUAL_ENV\" in os.environ:\n del os.environ[\"VIRTUAL_ENV\"]\n\n envs_file = TOMLFile(tmp_path / \"envs.toml\")\n doc = tomlkit.document()\n doc[venv_name] = {\"minor\": \"3.7\", \"patch\": \"3.7.0\"}\n envs_file.write(doc)\n\n os.mkdir(tmp_path / f\"{venv_name}-py3.7\")\n os.mkdir(tmp_path / f\"{venv_name}-py3.6\")\n\n config.merge({\"virtualenvs\": {\"path\": str(tmp_path)}})\n\n mocked_python_register(\"3.7.1\")\n mocked_python_register(\"3.6.6\")\n\n build_venv_m = mocker.patch(\n \"poetry.utils.env.EnvManager.build_venv\", side_effect=build_venv\n )\n remove_venv_m = mocker.patch(\n \"poetry.utils.env.EnvManager.remove_venv\", side_effect=EnvManager.remove_venv\n )\n\n env = manager.activate(\"python3.6\")\n\n build_venv_m.assert_not_called()\n remove_venv_m.assert_not_called()\n\n assert envs_file.exists()\n envs: dict[str, Any] = envs_file.read()\n \n assert envs[venv_name][\"patch\"] == \"3.6.6\"\n\n assert env.path == tmp_path / f\"{venv_name}-py3.6\"\n assert env.base == Path(sys.base_prefix)\n assert (tmp_path / f\"{venv_name}-py3.6\").exists()", "test_prefix_file_path": "tests/utils/env/test_env_manager.py", "test_prefix_start_lineno": 387, "test_prefix_end_lineno": 431, "test_target": "tests/utils/env/test_env_manager.py::test_activate_does_not_recreate_when_switching_minor", "ground_truth_oracle": "assert envs[venv_name][\"minor\"] == \"3.6\"", "ground_truth_oracle_lineno": 426, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def read(self) -> TOMLDocument:\n from tomlkit.exceptions import TOMLKitError\n\n from poetry.toml import TOMLError\n\n try:\n return super().read()\n except (ValueError, TOMLKitError) as e:\n raise TOMLError(f\"Invalid TOML file {self.path.as_posix()}: {e}\")", "focal_method_file_path": "src/poetry/toml/file.py", "focal_method_start_lineno": 26, "focal_method_end_lineno": 34} {"index": 195, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_direct_origin_get_package_from_file", "test_class_name": "", "original_test_prefix": "def test_direct_origin_get_package_from_file(fixture_dir: FixtureDirGetter) -> None:\n wheel_path = fixture_dir(\"distributions\") / \"demo-0.1.2-py2.py3-none-any.whl\"\n package = DirectOrigin.get_package_from_file(wheel_path)\n assert package.name == \"demo\"", "test_prefix": "def test_direct_origin_get_package_from_file(fixture_dir: FixtureDirGetter) -> None:\n wheel_path = fixture_dir(\"distributions\") / \"demo-0.1.2-py2.py3-none-any.whl\"\n package = DirectOrigin.get_package_from_file(wheel_path)\n ", "test_prefix_file_path": "tests/packages/test_direct_origin.py", "test_prefix_start_lineno": 20, "test_prefix_end_lineno": 23, "test_target": "tests/packages/test_direct_origin.py::test_direct_origin_get_package_from_file", "ground_truth_oracle": "assert package.name == \"demo\"", "ground_truth_oracle_lineno": 23, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def get_package_from_file(cls, file_path: Path) -> Package:\n try:\n package = PackageInfo.from_path(path=file_path).to_package(\n root_dir=file_path\n )\n except PackageInfoError:\n raise RuntimeError(\n f\"Unable to determine package info from path: {file_path}\"\n )\n\n return package", "focal_method_file_path": "src/poetry/packages/direct_origin.py", "focal_method_start_lineno": 65, "focal_method_end_lineno": 76} {"index": 196, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_package_from_both_py2_and_py3_specific_wheels", "test_class_name": "", "original_test_prefix": "def test_get_package_from_both_py2_and_py3_specific_wheels(\n legacy_repository: LegacyRepository,\n) -> None:\n repo = legacy_repository\n\n package = repo.package(\"ipython\", Version.parse(\"5.7.0\"))\n\n assert package.name == \"ipython\"\n assert package.version.text == \"5.7.0\"\n assert package.python_versions == \"*\"\n assert len(package.requires) == 41\n\n expected = [\n Dependency(\"appnope\", \"*\"),\n Dependency(\"backports.shutil-get-terminal-size\", \"*\"),\n Dependency(\"colorama\", \"*\"),\n Dependency(\"decorator\", \"*\"),\n Dependency(\"pathlib2\", \"*\"),\n Dependency(\"pexpect\", \"*\"),\n Dependency(\"pickleshare\", \"*\"),\n Dependency(\"prompt-toolkit\", \">=1.0.4,<2.0.0\"),\n Dependency(\"pygments\", \"*\"),\n Dependency(\"setuptools\", \">=18.5\"),\n Dependency(\"simplegeneric\", \">0.8\"),\n Dependency(\"traitlets\", \">=4.2\"),\n Dependency(\"win-unicode-console\", \">=0.5\"),\n ]\n required = [r for r in package.requires if not r.is_optional()]\n assert required == expected\n\n assert str(required[1].marker) == 'python_version == \"2.7\"'\n assert (\n str(required[12].marker) == 'sys_platform == \"win32\" and python_version < \"3.6\"'\n )\n assert (\n str(required[4].marker) == 'python_version == \"2.7\" or python_version == \"3.3\"'\n )\n assert str(required[5].marker) == 'sys_platform != \"win32\"'", "test_prefix": "def test_get_package_from_both_py2_and_py3_specific_wheels(\n legacy_repository: LegacyRepository,\n) -> None:\n repo = legacy_repository\n\n package = repo.package(\"ipython\", Version.parse(\"5.7.0\"))\n\n \n assert package.version.text == \"5.7.0\"\n assert package.python_versions == \"*\"\n assert len(package.requires) == 41\n\n expected = [\n Dependency(\"appnope\", \"*\"),\n Dependency(\"backports.shutil-get-terminal-size\", \"*\"),\n Dependency(\"colorama\", \"*\"),\n Dependency(\"decorator\", \"*\"),\n Dependency(\"pathlib2\", \"*\"),\n Dependency(\"pexpect\", \"*\"),\n Dependency(\"pickleshare\", \"*\"),\n Dependency(\"prompt-toolkit\", \">=1.0.4,<2.0.0\"),\n Dependency(\"pygments\", \"*\"),\n Dependency(\"setuptools\", \">=18.5\"),\n Dependency(\"simplegeneric\", \">0.8\"),\n Dependency(\"traitlets\", \">=4.2\"),\n Dependency(\"win-unicode-console\", \">=0.5\"),\n ]\n required = [r for r in package.requires if not r.is_optional()]\n assert required == expected\n\n assert str(required[1].marker) == 'python_version == \"2.7\"'\n assert (\n str(required[12].marker) == 'sys_platform == \"win32\" and python_version < \"3.6\"'\n )\n assert (\n str(required[4].marker) == 'python_version == \"2.7\" or python_version == \"3.3\"'\n )\n assert str(required[5].marker) == 'sys_platform != \"win32\"'", "test_prefix_file_path": "tests/repositories/test_legacy_repository.py", "test_prefix_start_lineno": 320, "test_prefix_end_lineno": 357, "test_target": "tests/repositories/test_legacy_repository.py::test_get_package_from_both_py2_and_py3_specific_wheels", "ground_truth_oracle": "assert package.name == \"ipython\"", "ground_truth_oracle_lineno": 327, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def package(self, name: str, version: Version) -> Package:\n \"\"\"\n Retrieve the release information.\n\n This is a heavy task which takes time.\n We have to download a package to get the dependencies.\n We also need to download every file matching this release\n to get the various hashes.\n\n Note that this will be cached so the subsequent operations\n should be much faster.\n \"\"\"\n try:\n index = self._packages.index(Package(name, version))\n\n return self._packages[index]\n except ValueError:\n package = super().package(name, version)\n package._source_type = \"legacy\"\n package._source_url = self._url\n package._source_reference = self.name\n\n return package", "focal_method_file_path": "src/poetry/repositories/legacy_repository.py", "focal_method_start_lineno": 49, "focal_method_end_lineno": 71} {"index": 197, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_remove_package_no_dependencies", "test_class_name": "", "original_test_prefix": "def test_remove_package_no_dependencies(\n tester: CommandTester,\n app: PoetryTestApplication,\n repo: TestRepository,\n command_tester_factory: CommandTesterFactory,\n) -> None:\n repo.add_package(Package(\"foo\", \"2.0.0\"))\n\n pyproject: dict[str, Any] = app.poetry.file.read()\n assert \"dependencies\" not in pyproject[\"project\"]\n del pyproject[\"tool\"][\"poetry\"][\"dependencies\"]\n pyproject = cast(\"TOMLDocument\", pyproject)\n app.poetry.file.write(pyproject)\n app.poetry.package._dependency_groups = {}\n\n with pytest.raises(ValueError) as e:\n tester.execute(\"foo\")\n\n assert str(e.value) == \"The following packages were not found: foo\"", "test_prefix": "def test_remove_package_no_dependencies(\n tester: CommandTester,\n app: PoetryTestApplication,\n repo: TestRepository,\n command_tester_factory: CommandTesterFactory,\n) -> None:\n repo.add_package(Package(\"foo\", \"2.0.0\"))\n\n pyproject: dict[str, Any] = app.poetry.file.read()\n \n del pyproject[\"tool\"][\"poetry\"][\"dependencies\"]\n pyproject = cast(\"TOMLDocument\", pyproject)\n app.poetry.file.write(pyproject)\n app.poetry.package._dependency_groups = {}\n\n with pytest.raises(ValueError) as e:\n tester.execute(\"foo\")\n\n assert str(e.value) == \"The following packages were not found: foo\"", "test_prefix_file_path": "tests/console/commands/test_remove.py", "test_prefix_start_lineno": 555, "test_prefix_end_lineno": 573, "test_target": "tests/console/commands/test_remove.py::test_remove_package_no_dependencies", "ground_truth_oracle": "assert \"dependencies\" not in pyproject[\"project\"]", "ground_truth_oracle_lineno": 564, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def read(self) -> TOMLDocument:\n from tomlkit.exceptions import TOMLKitError\n\n from poetry.toml import TOMLError\n\n try:\n return super().read()\n except (ValueError, TOMLKitError) as e:\n raise TOMLError(f\"Invalid TOML file {self.path.as_posix()}: {e}\")", "focal_method_file_path": "src/poetry/toml/file.py", "focal_method_start_lineno": 26, "focal_method_end_lineno": 34} {"index": 198, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_pool", "test_class_name": "", "original_test_prefix": "def test_pool() -> None:\n pool = RepositoryPool()\n\n assert len(pool.repositories) == 0\n assert not pool.has_primary_repositories()", "test_prefix": "def test_pool() -> None:\n pool = RepositoryPool()\n\n assert len(pool.repositories) == 0\n ", "test_prefix_file_path": "tests/repositories/test_repository_pool.py", "test_prefix_start_lineno": 16, "test_prefix_end_lineno": 20, "test_target": "tests/repositories/test_repository_pool.py::test_pool", "ground_truth_oracle": "assert not pool.has_primary_repositories()", "ground_truth_oracle_lineno": 20, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def has_primary_repositories(self) -> bool:\n return self._contains_priority(Priority.PRIMARY)", "focal_method_file_path": "src/poetry/repositories/repository_pool.py", "focal_method_start_lineno": 106, "focal_method_end_lineno": 107} {"index": 199, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_locker_properly_loads_extras_legacy", "test_class_name": "", "original_test_prefix": "def test_locker_properly_loads_extras_legacy(locker: Locker) -> None:\n content = f\"\"\"\\\n# {GENERATED_COMMENT}\n\n[[package]]\nname = \"a\"\nversion = \"1.0\"\ndescription = \"\"\noptional = false\npython-versions = \"*\"\ngroups = [\"main\"]\nfiles = []\n\n[package.dependencies]\nb = {{version = \"^1.0\", optional = true}}\n\n[package.extras]\nb = [\"b (^1.0)\"]\n\n[[package]]\nname = \"b\"\nversion = \"1.0\"\ndescription = \"\"\noptional = false\npython-versions = \"*\"\ngroups = [\"main\"]\nfiles = []\n\n[metadata]\npython-versions = \"*\"\nlock-version = \"2.1\"\ncontent-hash = \"123456789\"\n\"\"\"\n\n with open(locker.lock, \"w\", encoding=\"utf-8\") as f:\n f.write(content)\n\n repository = locker.locked_repository()\n assert len(repository.packages) == 2\n\n packages = repository.find_packages(get_dependency(\"a\", \"1.0\"))\n assert len(packages) == 1\n\n package = packages[0]\n assert len(package.requires) == 1\n assert len(package.extras) == 1\n\n dependency_b = package.extras[canonicalize_name(\"b\")][0]\n assert dependency_b.name == \"b\"", "test_prefix": "def test_locker_properly_loads_extras_legacy(locker: Locker) -> None:\n content = f\"\"\"\\\n# {GENERATED_COMMENT}\n\n[[package]]\nname = \"a\"\nversion = \"1.0\"\ndescription = \"\"\noptional = false\npython-versions = \"*\"\ngroups = [\"main\"]\nfiles = []\n\n[package.dependencies]\nb = {{version = \"^1.0\", optional = true}}\n\n[package.extras]\nb = [\"b (^1.0)\"]\n\n[[package]]\nname = \"b\"\nversion = \"1.0\"\ndescription = \"\"\noptional = false\npython-versions = \"*\"\ngroups = [\"main\"]\nfiles = []\n\n[metadata]\npython-versions = \"*\"\nlock-version = \"2.1\"\ncontent-hash = \"123456789\"\n\"\"\"\n\n with open(locker.lock, \"w\", encoding=\"utf-8\") as f:\n f.write(content)\n\n repository = locker.locked_repository()\n assert len(repository.packages) == 2\n\n packages = repository.find_packages(get_dependency(\"a\", \"1.0\"))\n \n\n package = packages[0]\n assert len(package.requires) == 1\n assert len(package.extras) == 1\n\n dependency_b = package.extras[canonicalize_name(\"b\")][0]\n assert dependency_b.name == \"b\"", "test_prefix_file_path": "tests/packages/test_locker.py", "test_prefix_start_lineno": 381, "test_prefix_end_lineno": 429, "test_target": "tests/packages/test_locker.py::test_locker_properly_loads_extras_legacy", "ground_truth_oracle": "assert len(packages) == 1", "ground_truth_oracle_lineno": 422, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def find_packages(self, dependency: Dependency) -> list[Package]:\n packages = []\n ignored_pre_release_packages = []\n\n constraint = dependency.constraint\n allow_prereleases = dependency.allows_prereleases()\n for package in self._find_packages(dependency.name, constraint):\n if package.yanked and not isinstance(constraint, Version):\n # PEP 592: yanked files are always ignored, unless they are the only\n # file that matches a version specifier that \"pins\" to an exact\n # version\n continue\n if (\n package.is_prerelease()\n and not allow_prereleases\n and not package.is_direct_origin()\n ):\n ignored_pre_release_packages.append(package)\n continue\n\n packages.append(package)\n\n self._log(\n f\"{len(packages)} packages found for {dependency.name} {constraint!s}\",\n level=\"debug\",\n )\n\n if allow_prereleases is False: # in contrast to None!\n return packages\n return packages or ignored_pre_release_packages", "focal_method_file_path": "src/poetry/repositories/repository.py", "focal_method_start_lineno": 36, "focal_method_end_lineno": 65} {"index": 200, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_search_legacy_repositories_are_not_skipped", "test_class_name": "", "original_test_prefix": "def test_search_legacy_repositories_are_not_skipped(\n legacy_repository: LegacyRepository,\n) -> None:\n foo_package = get_package(\"foo\", \"1.0.0\")\n demo_package = get_package(\"demo\", \"0.1.0\")\n\n repo1 = Repository(\"repo1\", [foo_package])\n repo2 = legacy_repository\n pool = RepositoryPool([repo1, repo2])\n\n assert pool.search(\"foo\") == [foo_package]\n\n assert repo1.search(\"demo\") == []\n assert repo2.search(\"demo\") == pool.search(\"demo\") == [demo_package]", "test_prefix": "def test_search_legacy_repositories_are_not_skipped(\n legacy_repository: LegacyRepository,\n) -> None:\n foo_package = get_package(\"foo\", \"1.0.0\")\n demo_package = get_package(\"demo\", \"0.1.0\")\n\n repo1 = Repository(\"repo1\", [foo_package])\n repo2 = legacy_repository\n pool = RepositoryPool([repo1, repo2])\n\n \n\n assert repo1.search(\"demo\") == []\n assert repo2.search(\"demo\") == pool.search(\"demo\") == [demo_package]", "test_prefix_file_path": "tests/repositories/test_repository_pool.py", "test_prefix_start_lineno": 271, "test_prefix_end_lineno": 284, "test_target": "tests/repositories/test_repository_pool.py::test_search_legacy_repositories_are_not_skipped", "ground_truth_oracle": "assert pool.search(\"foo\") == [foo_package]", "ground_truth_oracle_lineno": 281, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def search(self, query: str | list[str]) -> list[Package]:\n results: list[Package] = []\n for repo in self.repositories:\n results += repo.search(query)\n return results", "focal_method_file_path": "src/poetry/repositories/repository_pool.py", "focal_method_start_lineno": 179, "focal_method_end_lineno": 183} {"index": 201, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_complete_package_raises_packagenotfound_if_locked_source_not_available", "test_class_name": "", "original_test_prefix": "def test_complete_package_raises_packagenotfound_if_locked_source_not_available(\n root: ProjectPackage, pool: RepositoryPool, provider: Provider\n) -> None:\n locked_package = Package(\"a\", \"1.0\", source_reference=\"outdated\")\n provider = Provider(root, pool, NullIO(), locked=[locked_package])\n provider.complete_package(DependencyPackage(root.to_dependency(), root))\n\n # transitive dependency without explicit source\n dependency = get_dependency(\"a\", \">=1\")\n\n locked = provider.get_locked(dependency)\n assert locked is not None\n with pytest.raises(PackageNotFoundError):\n provider.complete_package(locked)", "test_prefix": "def test_complete_package_raises_packagenotfound_if_locked_source_not_available(\n root: ProjectPackage, pool: RepositoryPool, provider: Provider\n) -> None:\n locked_package = Package(\"a\", \"1.0\", source_reference=\"outdated\")\n provider = Provider(root, pool, NullIO(), locked=[locked_package])\n provider.complete_package(DependencyPackage(root.to_dependency(), root))\n\n # transitive dependency without explicit source\n dependency = get_dependency(\"a\", \">=1\")\n\n locked = provider.get_locked(dependency)\n \n with pytest.raises(PackageNotFoundError):\n provider.complete_package(locked)", "test_prefix_file_path": "tests/puzzle/test_provider.py", "test_prefix_start_lineno": 843, "test_prefix_end_lineno": 856, "test_target": "tests/puzzle/test_provider.py::test_complete_package_raises_packagenotfound_if_locked_source_not_available", "ground_truth_oracle": "assert locked is not None", "ground_truth_oracle_lineno": 854, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_locked(self, dependency: Dependency) -> DependencyPackage | None:\n if dependency.name in self._use_latest:\n return None\n\n locked = self._locked.get(dependency.name, [])\n for dependency_package in locked:\n package = dependency_package.package\n if package.satisfies(dependency):\n if explicit_source := self._explicit_sources.get(dependency.name):\n dependency.source_name = explicit_source\n elif (\n not dependency.source_name\n and package.source_type == \"legacy\"\n and package.source_reference\n and self._pool.get_priority(package.source_reference)\n == Priority.EXPLICIT\n ):\n continue\n return DependencyPackage(dependency, package)\n return None", "focal_method_file_path": "src/poetry/puzzle/provider.py", "focal_method_start_lineno": 750, "focal_method_end_lineno": 769} {"index": 202, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_file_hashes_returns_none_for_blake2_with_fips", "test_class_name": "", "original_test_prefix": "def test_file_hashes_returns_none_for_blake2_with_fips(\n mocker: MockerFixture, distributions_dir: Path\n) -> None:\n # disable md5\n def fips_blake2b(*args: Any, **kwargs: Any) -> Any:\n raise ValueError(\"Disabled by FIPS\")\n\n mocker.patch(\"hashlib.blake2b\", new=fips_blake2b)\n\n manager = HashManager()\n manager.hash(distributions_dir / \"demo-0.1.0.tar.gz\")\n file_hashes = manager.hexdigest()\n\n assert file_hashes.blake2_256 is None", "test_prefix": "def test_file_hashes_returns_none_for_blake2_with_fips(\n mocker: MockerFixture, distributions_dir: Path\n) -> None:\n # disable md5\n def fips_blake2b(*args: Any, **kwargs: Any) -> Any:\n raise ValueError(\"Disabled by FIPS\")\n\n mocker.patch(\"hashlib.blake2b\", new=fips_blake2b)\n\n manager = HashManager()\n manager.hash(distributions_dir / \"demo-0.1.0.tar.gz\")\n file_hashes = manager.hexdigest()\n\n ", "test_prefix_file_path": "tests/publishing/test_hash_manager.py", "test_prefix_start_lineno": 70, "test_prefix_end_lineno": 83, "test_target": "tests/publishing/test_hash_manager.py::test_file_hashes_returns_none_for_blake2_with_fips", "ground_truth_oracle": "assert file_hashes.blake2_256 is None", "ground_truth_oracle_lineno": 83, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def hexdigest(self) -> Hexdigest:\n return Hexdigest(\n self._md5_hexdigest(),\n self._sha2_hasher.hexdigest(),\n self._blake_hexdigest(),\n )", "focal_method_file_path": "src/poetry/publishing/hash_manager.py", "focal_method_start_lineno": 60, "focal_method_end_lineno": 65} {"index": 203, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_shutil_which_python_provider", "test_class_name": "", "original_test_prefix": "def test_shutil_which_python_provider() -> None:\n provider = ShutilWhichPythonProvider.create()\n assert provider\n pythons = list(provider.find_pythons())\n assert len(pythons) == 1\n assert pythons[0].minor == sys.version_info.minor", "test_prefix": "def test_shutil_which_python_provider() -> None:\n provider = ShutilWhichPythonProvider.create()\n assert provider\n pythons = list(provider.find_pythons())\n \n assert pythons[0].minor == sys.version_info.minor", "test_prefix_file_path": "tests/utils/env/python/test_python_providers.py", "test_prefix_start_lineno": 17, "test_prefix_end_lineno": 22, "test_target": "tests/utils/env/python/test_python_providers.py::test_shutil_which_python_provider", "ground_truth_oracle": "assert len(pythons) == 1", "ground_truth_oracle_lineno": 21, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def find_pythons(self) -> Iterable[findpython.PythonVersion]:\n if python := self.find_python_by_name(\"python\"):\n return [python]\n return []", "focal_method_file_path": "src/poetry/utils/env/python/providers.py", "focal_method_start_lineno": 30, "focal_method_end_lineno": 33} {"index": 204, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_pypi_token_with_env_var_not_available", "test_class_name": "", "original_test_prefix": "def test_get_pypi_token_with_env_var_not_available(\n config: Config, with_simple_keyring: None, dummy_keyring: DummyBackend\n) -> None:\n repo_name = \"foo\"\n manager = PasswordManager(config)\n\n result_token = manager.get_pypi_token(repo_name)\n\n assert result_token is None", "test_prefix": "def test_get_pypi_token_with_env_var_not_available(\n config: Config, with_simple_keyring: None, dummy_keyring: DummyBackend\n) -> None:\n repo_name = \"foo\"\n manager = PasswordManager(config)\n\n result_token = manager.get_pypi_token(repo_name)\n\n ", "test_prefix_file_path": "tests/utils/test_password_manager.py", "test_prefix_start_lineno": 363, "test_prefix_end_lineno": 371, "test_target": "tests/utils/test_password_manager.py::test_get_pypi_token_with_env_var_not_available", "ground_truth_oracle": "assert result_token is None", "ground_truth_oracle_lineno": 371, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_pypi_token(self, repo_name: str) -> str | None:\n \"\"\"Get PyPi token.\n\n First checks the environment variables for a token,\n then the configured username/password and the\n available keyring.\n\n :param repo_name: Name of repository.\n :return: Returns a token as a string if found, otherwise None.\n \"\"\"\n token: str | None = self._config.get(f\"pypi-token.{repo_name}\")\n if token:\n return token\n\n if self.use_keyring:\n return self.keyring.get_password(repo_name, \"__token__\")\n else:\n return None", "focal_method_file_path": "src/poetry/utils/password_manager.py", "focal_method_start_lineno": 221, "focal_method_end_lineno": 238} {"index": 205, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_activate_activates_non_existing_virtualenv_no_envs_file", "test_class_name": "", "original_test_prefix": "def test_activate_activates_non_existing_virtualenv_no_envs_file(\n tmp_path: Path,\n manager: EnvManager,\n poetry: Poetry,\n config: Config,\n mocker: MockerFixture,\n venv_name: str,\n venv_flags_default: dict[str, bool],\n mocked_python_register: MockedPythonRegister,\n) -> None:\n if \"VIRTUAL_ENV\" in os.environ:\n del os.environ[\"VIRTUAL_ENV\"]\n\n config.merge({\"virtualenvs\": {\"path\": str(tmp_path)}})\n\n mocked_python_register(\"3.7.1\")\n m = mocker.patch(\"poetry.utils.env.EnvManager.build_venv\", side_effect=build_venv)\n\n env = manager.activate(\"python3.7\")\n\n m.assert_called_with(\n tmp_path / f\"{venv_name}-py3.7\",\n executable=Path(\"/usr/bin/python3.7\"),\n flags=venv_flags_default,\n prompt=\"simple-project-py3.7\",\n )\n\n envs_file = TOMLFile(tmp_path / \"envs.toml\")\n\n assert envs_file.exists()\n envs: dict[str, Any] = envs_file.read()\n assert envs[venv_name][\"minor\"] == \"3.7\"\n assert envs[venv_name][\"patch\"] == \"3.7.1\"\n\n assert env.path == tmp_path / f\"{venv_name}-py3.7\"\n assert env.base == Path(sys.base_prefix)", "test_prefix": "def test_activate_activates_non_existing_virtualenv_no_envs_file(\n tmp_path: Path,\n manager: EnvManager,\n poetry: Poetry,\n config: Config,\n mocker: MockerFixture,\n venv_name: str,\n venv_flags_default: dict[str, bool],\n mocked_python_register: MockedPythonRegister,\n) -> None:\n if \"VIRTUAL_ENV\" in os.environ:\n del os.environ[\"VIRTUAL_ENV\"]\n\n config.merge({\"virtualenvs\": {\"path\": str(tmp_path)}})\n\n mocked_python_register(\"3.7.1\")\n m = mocker.patch(\"poetry.utils.env.EnvManager.build_venv\", side_effect=build_venv)\n\n env = manager.activate(\"python3.7\")\n\n m.assert_called_with(\n tmp_path / f\"{venv_name}-py3.7\",\n executable=Path(\"/usr/bin/python3.7\"),\n flags=venv_flags_default,\n prompt=\"simple-project-py3.7\",\n )\n\n envs_file = TOMLFile(tmp_path / \"envs.toml\")\n\n assert envs_file.exists()\n envs: dict[str, Any] = envs_file.read()\n assert envs[venv_name][\"minor\"] == \"3.7\"\n assert envs[venv_name][\"patch\"] == \"3.7.1\"\n\n \n assert env.base == Path(sys.base_prefix)", "test_prefix_file_path": "tests/utils/env/test_env_manager.py", "test_prefix_start_lineno": 159, "test_prefix_end_lineno": 194, "test_target": "tests/utils/env/test_env_manager.py::test_activate_activates_non_existing_virtualenv_no_envs_file", "ground_truth_oracle": "assert env.path == tmp_path / f\"{venv_name}-py3.7\"", "ground_truth_oracle_lineno": 193, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def read(self) -> TOMLDocument:\n from tomlkit.exceptions import TOMLKitError\n\n from poetry.toml import TOMLError\n\n try:\n return super().read()\n except (ValueError, TOMLKitError) as e:\n raise TOMLError(f\"Invalid TOML file {self.path.as_posix()}: {e}\")", "focal_method_file_path": "src/poetry/toml/file.py", "focal_method_start_lineno": 26, "focal_method_end_lineno": 34} {"index": 206, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_run_installs_with_local_setuptools_directory", "test_class_name": "", "original_test_prefix": "def test_run_installs_with_local_setuptools_directory(\n installer: Installer,\n locker: Locker,\n repo: Repository,\n package: ProjectPackage,\n tmp_path: Path,\n fixture_dir: FixtureDirGetter,\n) -> None:\n root_dir = tmp_path / \"root\"\n package.root_dir = root_dir\n locker.set_lock_path(root_dir)\n file_path = shutil.copytree(fixture_dir(\"project_with_setup\"), root_dir / \"project\")\n package.add_dependency(\n Factory.create_dependency(\n \"project-with-setup\",\n {\"path\": str(file_path.relative_to(root_dir))},\n root_dir=root_dir,\n )\n )\n\n repo.add_package(get_package(\"pendulum\", \"1.4.4\"))\n repo.add_package(get_package(\"cachy\", \"0.2.0\"))\n\n result = installer.run()\n assert result == 0\n\n expected = fixture(\"with-directory-dependency-setuptools\")\n\n assert locker.written_data == expected\n assert installer.executor.installations_count == 3", "test_prefix": "def test_run_installs_with_local_setuptools_directory(\n installer: Installer,\n locker: Locker,\n repo: Repository,\n package: ProjectPackage,\n tmp_path: Path,\n fixture_dir: FixtureDirGetter,\n) -> None:\n root_dir = tmp_path / \"root\"\n package.root_dir = root_dir\n locker.set_lock_path(root_dir)\n file_path = shutil.copytree(fixture_dir(\"project_with_setup\"), root_dir / \"project\")\n package.add_dependency(\n Factory.create_dependency(\n \"project-with-setup\",\n {\"path\": str(file_path.relative_to(root_dir))},\n root_dir=root_dir,\n )\n )\n\n repo.add_package(get_package(\"pendulum\", \"1.4.4\"))\n repo.add_package(get_package(\"cachy\", \"0.2.0\"))\n\n result = installer.run()\n \n\n expected = fixture(\"with-directory-dependency-setuptools\")\n\n assert locker.written_data == expected\n assert installer.executor.installations_count == 3", "test_prefix_file_path": "tests/installation/test_installer.py", "test_prefix_start_lineno": 1783, "test_prefix_end_lineno": 1812, "test_target": "tests/installation/test_installer.py::test_run_installs_with_local_setuptools_directory", "ground_truth_oracle": "assert result == 0", "ground_truth_oracle_lineno": 1807, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def run(self) -> int:\n # Check if refresh\n if not self._update and self._lock and self._locker.is_locked():\n return self._do_refresh()\n\n # Force update if there is no lock file present\n if not self._update and not self._locker.is_locked():\n self._update = True\n\n if self.is_dry_run():\n self.verbose(True)\n\n return self._do_install()", "focal_method_file_path": "src/poetry/installation/installer.py", "focal_method_start_lineno": 91, "focal_method_end_lineno": 103} {"index": 207, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_file_config_source_remove_property", "test_class_name": "", "original_test_prefix": "def test_file_config_source_remove_property(tmp_path: Path) -> None:\n config_data = {\n \"virtualenvs\": {\n \"use-poetry-python\": False,\n },\n \"system-git-client\": True,\n }\n\n config = tmp_path.joinpath(\"config.toml\")\n with config.open(mode=\"w\", encoding=\"utf-8\") as f:\n f.write(tomlkit.dumps(config_data))\n\n config_source = FileConfigSource(TOMLFile(config))\n\n config_source.remove_property(\"system-git-client\")\n assert config_source._file.read() == {\n \"virtualenvs\": {\n \"use-poetry-python\": False,\n }\n }\n\n config_source.remove_property(\"virtualenvs.use-poetry-python\")\n assert config_source._file.read() == {}", "test_prefix": "def test_file_config_source_remove_property(tmp_path: Path) -> None:\n config_data = {\n \"virtualenvs\": {\n \"use-poetry-python\": False,\n },\n \"system-git-client\": True,\n }\n\n config = tmp_path.joinpath(\"config.toml\")\n with config.open(mode=\"w\", encoding=\"utf-8\") as f:\n f.write(tomlkit.dumps(config_data))\n\n config_source = FileConfigSource(TOMLFile(config))\n\n config_source.remove_property(\"system-git-client\")\n assert config_source._file.read() == {\n \"virtualenvs\": {\n \"use-poetry-python\": False,\n }\n }\n\n config_source.remove_property(\"virtualenvs.use-poetry-python\")\n ", "test_prefix_file_path": "tests/config/test_file_config_source.py", "test_prefix_start_lineno": 37, "test_prefix_end_lineno": 59, "test_target": "tests/config/test_file_config_source.py::test_file_config_source_remove_property", "ground_truth_oracle": "assert config_source._file.read() == {}", "ground_truth_oracle_lineno": 59, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def read(self) -> TOMLDocument:\n from tomlkit.exceptions import TOMLKitError\n\n from poetry.toml import TOMLError\n\n try:\n return super().read()\n except (ValueError, TOMLKitError) as e:\n raise TOMLError(f\"Invalid TOML file {self.path.as_posix()}: {e}\")", "focal_method_file_path": "src/poetry/toml/file.py", "focal_method_start_lineno": 26, "focal_method_end_lineno": 34} {"index": 208, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_propagate_groups_with_extra", "test_class_name": "", "original_test_prefix": "def test_propagate_groups_with_extra(package: ProjectPackage, solver: Solver) -> None:\n a_foo = Package(\"a\", \"1\", features=[\"foo\"])\n a = Package(\"a\", \"1\")\n b = Package(\"b\", \"1\")\n c = Package(\"c\", \"1\")\n package.add_dependency(dep(\"a\", groups=[\"main\"]))\n package.add_dependency(dep(\"a\", groups=[\"dev\"], extras=[\"foo\"]))\n a_foo.add_dependency(dep(\"a\"))\n a_foo.add_dependency(dep(\"b\"))\n a_foo.add_dependency(dep(\"c\", 'extra == \"foo\"'))\n a.add_dependency(dep(\"b\"))\n\n packages = [package, a_foo, a, b, c]\n result = solver._aggregate_solved_packages(packages)\n\n assert len(result) == len(packages) - 1\n assert result[package].groups == set()\n assert result[a].groups == {\"main\", \"dev\"}\n assert result[b].groups == {\"main\", \"dev\"}\n assert result[c].groups == {\"dev\"}", "test_prefix": "def test_propagate_groups_with_extra(package: ProjectPackage, solver: Solver) -> None:\n a_foo = Package(\"a\", \"1\", features=[\"foo\"])\n a = Package(\"a\", \"1\")\n b = Package(\"b\", \"1\")\n c = Package(\"c\", \"1\")\n package.add_dependency(dep(\"a\", groups=[\"main\"]))\n package.add_dependency(dep(\"a\", groups=[\"dev\"], extras=[\"foo\"]))\n a_foo.add_dependency(dep(\"a\"))\n a_foo.add_dependency(dep(\"b\"))\n a_foo.add_dependency(dep(\"c\", 'extra == \"foo\"'))\n a.add_dependency(dep(\"b\"))\n\n packages = [package, a_foo, a, b, c]\n result = solver._aggregate_solved_packages(packages)\n\n assert len(result) == len(packages) - 1\n \n assert result[a].groups == {\"main\", \"dev\"}\n assert result[b].groups == {\"main\", \"dev\"}\n assert result[c].groups == {\"dev\"}", "test_prefix_file_path": "tests/puzzle/test_solver_internals.py", "test_prefix_start_lineno": 251, "test_prefix_end_lineno": 270, "test_target": "tests/puzzle/test_solver_internals.py::test_propagate_groups_with_extra", "ground_truth_oracle": "assert result[package].groups == set()", "ground_truth_oracle_lineno": 267, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def _aggregate_solved_packages(\n self, packages: list[Package]\n ) -> dict[Package, TransitivePackageInfo]:\n combined_nodes, markers = depth_first_search(\n PackageNode(self._package, packages)\n )\n results = dict(aggregate_package_nodes(nodes) for nodes in combined_nodes)\n calculate_markers(results, markers)\n\n # Merging feature packages with base packages\n solved_packages = {}\n for package in packages:\n if package.features:\n for _package in packages:\n if (\n not _package.features\n and _package.name == package.name\n and _package.version == package.version\n ):\n for dep in package.requires:\n # Prevent adding base package as a dependency to itself\n if _package.name == dep.name:\n continue\n\n # Avoid duplication.\n if any(\n _dep == dep and _dep.marker == dep.marker\n for _dep in _package.requires\n ):\n continue\n\n _package.add_dependency(dep)\n else:\n solved_packages[package] = results[package]\n\n return solved_packages", "focal_method_file_path": "src/poetry/puzzle/solver.py", "focal_method_start_lineno": 180, "focal_method_end_lineno": 215} {"index": 209, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_env_commands_with_spaces_in_their_arg_work_as_expected", "test_class_name": "", "original_test_prefix": "def test_env_commands_with_spaces_in_their_arg_work_as_expected(\n tmp_path: Path, manager: EnvManager\n) -> None:\n venv_path = tmp_path / \"Virtual Env\"\n manager.build_venv(venv_path)\n venv = VirtualEnv(venv_path)\n output = venv.run(\"python\", str(venv.pip), \"--version\")\n assert re.match(r\"pip \\S+ from\", output)", "test_prefix": "def test_env_commands_with_spaces_in_their_arg_work_as_expected(\n tmp_path: Path, manager: EnvManager\n) -> None:\n venv_path = tmp_path / \"Virtual Env\"\n manager.build_venv(venv_path)\n venv = VirtualEnv(venv_path)\n output = venv.run(\"python\", str(venv.pip), \"--version\")\n ", "test_prefix_file_path": "tests/utils/env/test_env.py", "test_prefix_start_lineno": 86, "test_prefix_end_lineno": 93, "test_target": "tests/utils/env/test_env.py::test_env_commands_with_spaces_in_their_arg_work_as_expected", "ground_truth_oracle": "assert re.match(r\"pip \\S+ from\", output)", "ground_truth_oracle_lineno": 93, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def run(self, bin: str, *args: str, **kwargs: Any) -> str:\n cmd = self.get_command_from_bin(bin) + list(args)\n return self._run(cmd, **kwargs)", "focal_method_file_path": "src/poetry/utils/env/base_env.py", "focal_method_start_lineno": 406, "focal_method_end_lineno": 408} {"index": 210, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_locked_keyring_should_not_be_available", "test_class_name": "", "original_test_prefix": "def test_locked_keyring_should_not_be_available(with_locked_keyring: None) -> None:\n key_ring = PoetryKeyring(\"poetry\")\n\n assert not key_ring.is_available()", "test_prefix": "def test_locked_keyring_should_not_be_available(with_locked_keyring: None) -> None:\n key_ring = PoetryKeyring(\"poetry\")\n\n ", "test_prefix_file_path": "tests/utils/test_password_manager.py", "test_prefix_start_lineno": 288, "test_prefix_end_lineno": 291, "test_target": "tests/utils/test_password_manager.py::test_locked_keyring_should_not_be_available", "ground_truth_oracle": "assert not key_ring.is_available()", "ground_truth_oracle_lineno": 291, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n @functools.cache\n def is_available(cls) -> bool:\n logger.debug(\"Checking if keyring is available\")\n try:\n import keyring\n import keyring.backend\n import keyring.errors\n except ImportError as e:\n logger.debug(\"An error occurred while importing keyring: %s\", e)\n return False\n\n def backend_name(backend: keyring.backend.KeyringBackend) -> str:\n name: str = backend.name\n return name.split(\" \")[0]\n\n def backend_is_valid(backend: keyring.backend.KeyringBackend) -> bool:\n name = backend_name(backend)\n if name in (\"chainer\", \"fail\", \"null\"):\n logger.debug(f\"Backend {backend.name!r} is not suitable\")\n return False\n elif \"plaintext\" in backend.name.lower():\n logger.debug(f\"Not using plaintext keyring backend {backend.name!r}\")\n return False\n\n return True\n\n backend = keyring.get_keyring()\n if backend_name(backend) == \"chainer\":\n backends = keyring.backend.get_all_keyring()\n valid_backend = next((b for b in backends if backend_is_valid(b)), None)\n else:\n valid_backend = backend if backend_is_valid(backend) else None\n\n if valid_backend is None:\n logger.debug(\"No valid keyring backend was found\")\n return False\n\n logger.debug(f\"Using keyring backend {backend.name!r}\")\n\n try:\n # unfortunately there is no clean way of checking if keyring is unlocked\n keyring.get_password(\"python-poetry-check\", \"python-poetry\")\n except (RuntimeError, keyring.errors.KeyringError):\n logger.debug(\n \"Accessing keyring failed during availability check\", exc_info=True\n )\n return False\n\n return True", "focal_method_file_path": "src/poetry/utils/password_manager.py", "focal_method_start_lineno": 139, "focal_method_end_lineno": 188} {"index": 211, "repo_name": "poetry", "github": "https://github.com/python-poetry/poetry.git", "version": "2.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npoetry install --with test\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_find_packages_does_not_select_prereleases_if_not_allowed", "test_class_name": "", "original_test_prefix": "def test_find_packages_does_not_select_prereleases_if_not_allowed(\n pypi_repository: PyPiRepository,\n) -> None:\n repo = pypi_repository\n packages = repo.find_packages(Factory.create_dependency(\"pyyaml\", \"*\"))\n\n assert len(packages) == 1", "test_prefix": "def test_find_packages_does_not_select_prereleases_if_not_allowed(\n pypi_repository: PyPiRepository,\n) -> None:\n repo = pypi_repository\n packages = repo.find_packages(Factory.create_dependency(\"pyyaml\", \"*\"))\n\n ", "test_prefix_file_path": "tests/repositories/test_pypi_repository.py", "test_prefix_start_lineno": 43, "test_prefix_end_lineno": 49, "test_target": "tests/repositories/test_pypi_repository.py::test_find_packages_does_not_select_prereleases_if_not_allowed", "ground_truth_oracle": "assert len(packages) == 1", "ground_truth_oracle_lineno": 49, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def find_packages(self, dependency: Dependency) -> list[Package]:\n packages = []\n ignored_pre_release_packages = []\n\n constraint = dependency.constraint\n allow_prereleases = dependency.allows_prereleases()\n for package in self._find_packages(dependency.name, constraint):\n if package.yanked and not isinstance(constraint, Version):\n # PEP 592: yanked files are always ignored, unless they are the only\n # file that matches a version specifier that \"pins\" to an exact\n # version\n continue\n if (\n package.is_prerelease()\n and not allow_prereleases\n and not package.is_direct_origin()\n ):\n ignored_pre_release_packages.append(package)\n continue\n\n packages.append(package)\n\n self._log(\n f\"{len(packages)} packages found for {dependency.name} {constraint!s}\",\n level=\"debug\",\n )\n\n if allow_prereleases is False: # in contrast to None!\n return packages\n return packages or ignored_pre_release_packages", "focal_method_file_path": "src/poetry/repositories/repository.py", "focal_method_start_lineno": 36, "focal_method_end_lineno": 65} {"index": 212, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_sse_client_happy_request_and_response", "test_class_name": "", "original_test_prefix": "@pytest.mark.anyio\nasync def test_sse_client_happy_request_and_response(\n initialized_sse_client_session: ClientSession,\n) -> None:\n session = initialized_sse_client_session\n response = await session.read_resource(uri=AnyUrl(\"foobar://should-work\"))\n assert len(response.contents) == 1\n assert isinstance(response.contents[0], TextResourceContents)\n assert response.contents[0].text == \"Read should-work\"", "test_prefix": "@pytest.mark.anyio\nasync def test_sse_client_happy_request_and_response(\n initialized_sse_client_session: ClientSession,\n) -> None:\n session = initialized_sse_client_session\n response = await session.read_resource(uri=AnyUrl(\"foobar://should-work\"))\n assert len(response.contents) == 1\n \n assert response.contents[0].text == \"Read should-work\"", "test_prefix_file_path": "tests/shared/test_sse.py", "test_prefix_start_lineno": 205, "test_prefix_end_lineno": 213, "test_target": "tests/shared/test_sse.py::test_sse_client_happy_request_and_response", "ground_truth_oracle": "assert isinstance(response.contents[0], TextResourceContents)", "ground_truth_oracle_lineno": 212, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " async def read_resource(self, uri: AnyUrl) -> types.ReadResourceResult:\n \"\"\"Send a resources/read request.\"\"\"\n return await self.send_request(\n types.ClientRequest(\n types.ReadResourceRequest(\n params=types.ReadResourceRequestParams(uri=uri),\n )\n ),\n types.ReadResourceResult,\n )", "focal_method_file_path": "src/mcp/client/session.py", "focal_method_start_lineno": 237, "focal_method_end_lineno": 246} {"index": 213, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_sse_client_basic_connection_mounted_app", "test_class_name": "", "original_test_prefix": "@pytest.mark.anyio\nasync def test_sse_client_basic_connection_mounted_app(mounted_server: None, server_url: str) -> None:\n async with sse_client(server_url + \"/mounted_app/sse\") as streams:\n async with ClientSession(*streams) as session:\n # Test initialization\n result = await session.initialize()\n assert isinstance(result, InitializeResult)\n assert result.serverInfo.name == SERVER_NAME\n\n # Test ping\n ping_result = await session.send_ping()\n assert isinstance(ping_result, EmptyResult)", "test_prefix": "@pytest.mark.anyio\nasync def test_sse_client_basic_connection_mounted_app(mounted_server: None, server_url: str) -> None:\n async with sse_client(server_url + \"/mounted_app/sse\") as streams:\n async with ClientSession(*streams) as session:\n # Test initialization\n result = await session.initialize()\n assert isinstance(result, InitializeResult)\n assert result.serverInfo.name == SERVER_NAME\n\n # Test ping\n ping_result = await session.send_ping()\n ", "test_prefix_file_path": "tests/shared/test_sse.py", "test_prefix_start_lineno": 289, "test_prefix_end_lineno": 300, "test_target": "tests/shared/test_sse.py::test_sse_client_basic_connection_mounted_app", "ground_truth_oracle": "assert isinstance(ping_result, EmptyResult)", "ground_truth_oracle_lineno": 300, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " async def send_ping(self) -> types.EmptyResult:\n \"\"\"Send a ping request.\"\"\"\n return await self.send_request(\n types.ClientRequest(types.PingRequest()),\n types.EmptyResult,\n )", "focal_method_file_path": "src/mcp/client/session.py", "focal_method_start_lineno": 176, "focal_method_end_lineno": 181} {"index": 214, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_request_context_propagation", "test_class_name": "", "original_test_prefix": "@pytest.mark.anyio\nasync def test_request_context_propagation(context_server: None, server_url: str) -> None:\n \"\"\"Test that request context is properly propagated through SSE transport.\"\"\"\n # Test with custom headers\n custom_headers = {\n \"Authorization\": \"Bearer test-token\",\n \"X-Custom-Header\": \"test-value\",\n \"X-Trace-Id\": \"trace-123\",\n }\n\n async with sse_client(server_url + \"/sse\", headers=custom_headers) as (\n read_stream,\n write_stream,\n ):\n async with ClientSession(read_stream, write_stream) as session:\n # Initialize the session\n result = await session.initialize()\n assert isinstance(result, InitializeResult)\n\n # Call the tool that echoes headers back\n tool_result = await session.call_tool(\"echo_headers\", {})\n\n # Parse the JSON response\n\n assert len(tool_result.content) == 1\n headers_data = json.loads(tool_result.content[0].text if tool_result.content[0].type == \"text\" else \"{}\")\n\n # Verify headers were propagated\n assert headers_data.get(\"authorization\") == \"Bearer test-token\"\n assert headers_data.get(\"x-custom-header\") == \"test-value\"\n assert headers_data.get(\"x-trace-id\") == \"trace-123\"", "test_prefix": "@pytest.mark.anyio\nasync def test_request_context_propagation(context_server: None, server_url: str) -> None:\n \"\"\"Test that request context is properly propagated through SSE transport.\"\"\"\n # Test with custom headers\n custom_headers = {\n \"Authorization\": \"Bearer test-token\",\n \"X-Custom-Header\": \"test-value\",\n \"X-Trace-Id\": \"trace-123\",\n }\n\n async with sse_client(server_url + \"/sse\", headers=custom_headers) as (\n read_stream,\n write_stream,\n ):\n async with ClientSession(read_stream, write_stream) as session:\n # Initialize the session\n result = await session.initialize()\n assert isinstance(result, InitializeResult)\n\n # Call the tool that echoes headers back\n tool_result = await session.call_tool(\"echo_headers\", {})\n\n # Parse the JSON response\n\n \n headers_data = json.loads(tool_result.content[0].text if tool_result.content[0].type == \"text\" else \"{}\")\n\n # Verify headers were propagated\n assert headers_data.get(\"authorization\") == \"Bearer test-token\"\n assert headers_data.get(\"x-custom-header\") == \"test-value\"\n assert headers_data.get(\"x-trace-id\") == \"trace-123\"", "test_prefix_file_path": "tests/shared/test_sse.py", "test_prefix_start_lineno": 403, "test_prefix_end_lineno": 433, "test_target": "tests/shared/test_sse.py::test_request_context_propagation", "ground_truth_oracle": "assert len(tool_result.content) == 1", "ground_truth_oracle_lineno": 427, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " async def call_tool(\n self,\n name: str,\n arguments: dict[str, Any] | None = None,\n read_timeout_seconds: timedelta | None = None,\n progress_callback: ProgressFnT | None = None,\n ) -> types.CallToolResult:\n \"\"\"Send a tools/call request with optional progress callback support.\"\"\"\n\n result = await self.send_request(\n types.ClientRequest(\n types.CallToolRequest(\n params=types.CallToolRequestParams(\n name=name,\n arguments=arguments,\n ),\n )\n ),\n types.CallToolResult,\n request_read_timeout_seconds=read_timeout_seconds,\n progress_callback=progress_callback,\n )\n\n if not result.isError:\n await self._validate_tool_result(name, result)\n\n return result", "focal_method_file_path": "src/mcp/client/session.py", "focal_method_start_lineno": 270, "focal_method_end_lineno": 296} {"index": 215, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_request_context_isolation", "test_class_name": "", "original_test_prefix": "@pytest.mark.anyio\nasync def test_request_context_isolation(context_server: None, server_url: str) -> None:\n \"\"\"Test that request contexts are isolated between different SSE clients.\"\"\"\n contexts: list[dict[str, Any]] = []\n\n # Create multiple clients with different headers\n for i in range(3):\n headers = {\"X-Request-Id\": f\"request-{i}\", \"X-Custom-Value\": f\"value-{i}\"}\n\n async with sse_client(server_url + \"/sse\", headers=headers) as (\n read_stream,\n write_stream,\n ):\n async with ClientSession(read_stream, write_stream) as session:\n await session.initialize()\n\n # Call the tool that echoes context\n tool_result = await session.call_tool(\"echo_context\", {\"request_id\": f\"request-{i}\"})\n\n assert len(tool_result.content) == 1\n context_data = json.loads(\n tool_result.content[0].text if tool_result.content[0].type == \"text\" else \"{}\"\n )\n contexts.append(context_data)\n\n # Verify each request had its own context\n assert len(contexts) == 3\n for i, ctx in enumerate(contexts):\n assert ctx[\"request_id\"] == f\"request-{i}\"\n assert ctx[\"headers\"].get(\"x-request-id\") == f\"request-{i}\"\n assert ctx[\"headers\"].get(\"x-custom-value\") == f\"value-{i}\"", "test_prefix": "@pytest.mark.anyio\nasync def test_request_context_isolation(context_server: None, server_url: str) -> None:\n \"\"\"Test that request contexts are isolated between different SSE clients.\"\"\"\n contexts: list[dict[str, Any]] = []\n\n # Create multiple clients with different headers\n for i in range(3):\n headers = {\"X-Request-Id\": f\"request-{i}\", \"X-Custom-Value\": f\"value-{i}\"}\n\n async with sse_client(server_url + \"/sse\", headers=headers) as (\n read_stream,\n write_stream,\n ):\n async with ClientSession(read_stream, write_stream) as session:\n await session.initialize()\n\n # Call the tool that echoes context\n tool_result = await session.call_tool(\"echo_context\", {\"request_id\": f\"request-{i}\"})\n\n \n context_data = json.loads(\n tool_result.content[0].text if tool_result.content[0].type == \"text\" else \"{}\"\n )\n contexts.append(context_data)\n\n # Verify each request had its own context\n assert len(contexts) == 3\n for i, ctx in enumerate(contexts):\n assert ctx[\"request_id\"] == f\"request-{i}\"\n assert ctx[\"headers\"].get(\"x-request-id\") == f\"request-{i}\"\n assert ctx[\"headers\"].get(\"x-custom-value\") == f\"value-{i}\"", "test_prefix_file_path": "tests/shared/test_sse.py", "test_prefix_start_lineno": 436, "test_prefix_end_lineno": 466, "test_target": "tests/shared/test_sse.py::test_request_context_isolation", "ground_truth_oracle": "assert len(tool_result.content) == 1", "ground_truth_oracle_lineno": 455, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " async def call_tool(\n self,\n name: str,\n arguments: dict[str, Any] | None = None,\n read_timeout_seconds: timedelta | None = None,\n progress_callback: ProgressFnT | None = None,\n ) -> types.CallToolResult:\n \"\"\"Send a tools/call request with optional progress callback support.\"\"\"\n\n result = await self.send_request(\n types.ClientRequest(\n types.CallToolRequest(\n params=types.CallToolRequestParams(\n name=name,\n arguments=arguments,\n ),\n )\n ),\n types.CallToolResult,\n request_read_timeout_seconds=read_timeout_seconds,\n progress_callback=progress_callback,\n )\n\n if not result.isError:\n await self._validate_tool_result(name, result)\n\n return result", "focal_method_file_path": "src/mcp/client/session.py", "focal_method_start_lineno": 270, "focal_method_end_lineno": 296} {"index": 216, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_removes_fragment", "test_class_name": "TestResourceUrlFromServerUrl", "original_test_prefix": " def test_removes_fragment(self):\n \"\"\"Fragment should be removed per RFC 8707.\"\"\"\n assert resource_url_from_server_url(\"https://example.com/path#fragment\") == \"https://example.com/path\"\n assert resource_url_from_server_url(\"https://example.com/#fragment\") == \"https://example.com/\"", "test_prefix": " def test_removes_fragment(self):\n \"\"\"Fragment should be removed per RFC 8707.\"\"\"\n assert resource_url_from_server_url(\"https://example.com/path#fragment\") == \"https://example.com/path\"\n ", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 9, "test_prefix_end_lineno": 12, "test_target": "tests/shared/test_auth_utils.py::TestResourceUrlFromServerUrl::test_removes_fragment", "ground_truth_oracle": "assert resource_url_from_server_url(\"https://example.com/#fragment\") == \"https://example.com/\"", "ground_truth_oracle_lineno": 12, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def resource_url_from_server_url(url: str | HttpUrl | AnyUrl) -> str:\n \"\"\"Convert server URL to canonical resource URL per RFC 8707.\n\n RFC 8707 section 2 states that resource URIs \"MUST NOT include a fragment component\".\n Returns absolute URI with lowercase scheme/host for canonical form.\n\n Args:\n url: Server URL to convert\n\n Returns:\n Canonical resource URL string\n \"\"\"\n # Convert to string if needed\n url_str = str(url)\n\n # Parse the URL and remove fragment, create canonical form\n parsed = urlsplit(url_str)\n canonical = urlunsplit(parsed._replace(scheme=parsed.scheme.lower(), netloc=parsed.netloc.lower(), fragment=\"\"))\n\n return canonical", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 8, "focal_method_end_lineno": 27} {"index": 217, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_preserves_path", "test_class_name": "TestResourceUrlFromServerUrl", "original_test_prefix": " def test_preserves_path(self):\n \"\"\"Path should be preserved.\"\"\"\n assert (\n resource_url_from_server_url(\"https://example.com/path/to/resource\")\n == \"https://example.com/path/to/resource\"\n )\n assert resource_url_from_server_url(\"https://example.com/\") == \"https://example.com/\"\n assert resource_url_from_server_url(\"https://example.com\") == \"https://example.com\"", "test_prefix": " def test_preserves_path(self):\n \"\"\"Path should be preserved.\"\"\"\n assert (\n resource_url_from_server_url(\"https://example.com/path/to/resource\")\n == \"https://example.com/path/to/resource\"\n )\n \n assert resource_url_from_server_url(\"https://example.com\") == \"https://example.com\"", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 14, "test_prefix_end_lineno": 21, "test_target": "tests/shared/test_auth_utils.py::TestResourceUrlFromServerUrl::test_preserves_path", "ground_truth_oracle": "assert resource_url_from_server_url(\"https://example.com/\") == \"https://example.com/\"", "ground_truth_oracle_lineno": 20, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def resource_url_from_server_url(url: str | HttpUrl | AnyUrl) -> str:\n \"\"\"Convert server URL to canonical resource URL per RFC 8707.\n\n RFC 8707 section 2 states that resource URIs \"MUST NOT include a fragment component\".\n Returns absolute URI with lowercase scheme/host for canonical form.\n\n Args:\n url: Server URL to convert\n\n Returns:\n Canonical resource URL string\n \"\"\"\n # Convert to string if needed\n url_str = str(url)\n\n # Parse the URL and remove fragment, create canonical form\n parsed = urlsplit(url_str)\n canonical = urlunsplit(parsed._replace(scheme=parsed.scheme.lower(), netloc=parsed.netloc.lower(), fragment=\"\"))\n\n return canonical", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 8, "focal_method_end_lineno": 27} {"index": 218, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_preserves_query", "test_class_name": "TestResourceUrlFromServerUrl", "original_test_prefix": " def test_preserves_query(self):\n \"\"\"Query parameters should be preserved.\"\"\"\n assert resource_url_from_server_url(\"https://example.com/path?foo=bar\") == \"https://example.com/path?foo=bar\"\n assert resource_url_from_server_url(\"https://example.com/?key=value\") == \"https://example.com/?key=value\"", "test_prefix": " def test_preserves_query(self):\n \"\"\"Query parameters should be preserved.\"\"\"\n \n assert resource_url_from_server_url(\"https://example.com/?key=value\") == \"https://example.com/?key=value\"", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 23, "test_prefix_end_lineno": 26, "test_target": "tests/shared/test_auth_utils.py::TestResourceUrlFromServerUrl::test_preserves_query", "ground_truth_oracle": "assert resource_url_from_server_url(\"https://example.com/path?foo=bar\") == \"https://example.com/path?foo=bar\"", "ground_truth_oracle_lineno": 25, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def resource_url_from_server_url(url: str | HttpUrl | AnyUrl) -> str:\n \"\"\"Convert server URL to canonical resource URL per RFC 8707.\n\n RFC 8707 section 2 states that resource URIs \"MUST NOT include a fragment component\".\n Returns absolute URI with lowercase scheme/host for canonical form.\n\n Args:\n url: Server URL to convert\n\n Returns:\n Canonical resource URL string\n \"\"\"\n # Convert to string if needed\n url_str = str(url)\n\n # Parse the URL and remove fragment, create canonical form\n parsed = urlsplit(url_str)\n canonical = urlunsplit(parsed._replace(scheme=parsed.scheme.lower(), netloc=parsed.netloc.lower(), fragment=\"\"))\n\n return canonical", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 8, "focal_method_end_lineno": 27} {"index": 219, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_preserves_port", "test_class_name": "TestResourceUrlFromServerUrl", "original_test_prefix": " def test_preserves_port(self):\n \"\"\"Non-default ports should be preserved.\"\"\"\n assert resource_url_from_server_url(\"https://example.com:8443/path\") == \"https://example.com:8443/path\"\n assert resource_url_from_server_url(\"http://example.com:8080/\") == \"http://example.com:8080/\"", "test_prefix": " def test_preserves_port(self):\n \"\"\"Non-default ports should be preserved.\"\"\"\n \n assert resource_url_from_server_url(\"http://example.com:8080/\") == \"http://example.com:8080/\"", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 28, "test_prefix_end_lineno": 31, "test_target": "tests/shared/test_auth_utils.py::TestResourceUrlFromServerUrl::test_preserves_port", "ground_truth_oracle": "assert resource_url_from_server_url(\"https://example.com:8443/path\") == \"https://example.com:8443/path\"", "ground_truth_oracle_lineno": 30, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def resource_url_from_server_url(url: str | HttpUrl | AnyUrl) -> str:\n \"\"\"Convert server URL to canonical resource URL per RFC 8707.\n\n RFC 8707 section 2 states that resource URIs \"MUST NOT include a fragment component\".\n Returns absolute URI with lowercase scheme/host for canonical form.\n\n Args:\n url: Server URL to convert\n\n Returns:\n Canonical resource URL string\n \"\"\"\n # Convert to string if needed\n url_str = str(url)\n\n # Parse the URL and remove fragment, create canonical form\n parsed = urlsplit(url_str)\n canonical = urlunsplit(parsed._replace(scheme=parsed.scheme.lower(), netloc=parsed.netloc.lower(), fragment=\"\"))\n\n return canonical", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 8, "focal_method_end_lineno": 27} {"index": 220, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_lowercase_scheme_and_host", "test_class_name": "TestResourceUrlFromServerUrl", "original_test_prefix": " def test_lowercase_scheme_and_host(self):\n \"\"\"Scheme and host should be lowercase for canonical form.\"\"\"\n assert resource_url_from_server_url(\"HTTPS://EXAMPLE.COM/path\") == \"https://example.com/path\"\n assert resource_url_from_server_url(\"Http://Example.Com:8080/\") == \"http://example.com:8080/\"", "test_prefix": " def test_lowercase_scheme_and_host(self):\n \"\"\"Scheme and host should be lowercase for canonical form.\"\"\"\n \n assert resource_url_from_server_url(\"Http://Example.Com:8080/\") == \"http://example.com:8080/\"", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 33, "test_prefix_end_lineno": 36, "test_target": "tests/shared/test_auth_utils.py::TestResourceUrlFromServerUrl::test_lowercase_scheme_and_host", "ground_truth_oracle": "assert resource_url_from_server_url(\"HTTPS://EXAMPLE.COM/path\") == \"https://example.com/path\"", "ground_truth_oracle_lineno": 35, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def resource_url_from_server_url(url: str | HttpUrl | AnyUrl) -> str:\n \"\"\"Convert server URL to canonical resource URL per RFC 8707.\n\n RFC 8707 section 2 states that resource URIs \"MUST NOT include a fragment component\".\n Returns absolute URI with lowercase scheme/host for canonical form.\n\n Args:\n url: Server URL to convert\n\n Returns:\n Canonical resource URL string\n \"\"\"\n # Convert to string if needed\n url_str = str(url)\n\n # Parse the URL and remove fragment, create canonical form\n parsed = urlsplit(url_str)\n canonical = urlunsplit(parsed._replace(scheme=parsed.scheme.lower(), netloc=parsed.netloc.lower(), fragment=\"\"))\n\n return canonical", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 8, "focal_method_end_lineno": 27} {"index": 221, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_handles_pydantic_urls", "test_class_name": "TestResourceUrlFromServerUrl", "original_test_prefix": " def test_handles_pydantic_urls(self):\n \"\"\"Should handle Pydantic URL types.\"\"\"\n from pydantic import HttpUrl\n\n url = HttpUrl(\"https://example.com/path\")\n assert resource_url_from_server_url(url) == \"https://example.com/path\"", "test_prefix": " def test_handles_pydantic_urls(self):\n \"\"\"Should handle Pydantic URL types.\"\"\"\n from pydantic import HttpUrl\n\n url = HttpUrl(\"https://example.com/path\")\n ", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 38, "test_prefix_end_lineno": 43, "test_target": "tests/shared/test_auth_utils.py::TestResourceUrlFromServerUrl::test_handles_pydantic_urls", "ground_truth_oracle": "assert resource_url_from_server_url(url) == \"https://example.com/path\"", "ground_truth_oracle_lineno": 43, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def resource_url_from_server_url(url: str | HttpUrl | AnyUrl) -> str:\n \"\"\"Convert server URL to canonical resource URL per RFC 8707.\n\n RFC 8707 section 2 states that resource URIs \"MUST NOT include a fragment component\".\n Returns absolute URI with lowercase scheme/host for canonical form.\n\n Args:\n url: Server URL to convert\n\n Returns:\n Canonical resource URL string\n \"\"\"\n # Convert to string if needed\n url_str = str(url)\n\n # Parse the URL and remove fragment, create canonical form\n parsed = urlsplit(url_str)\n canonical = urlunsplit(parsed._replace(scheme=parsed.scheme.lower(), netloc=parsed.netloc.lower(), fragment=\"\"))\n\n return canonical", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 8, "focal_method_end_lineno": 27} {"index": 222, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_identical_urls", "test_class_name": "TestCheckResourceAllowed", "original_test_prefix": " def test_identical_urls(self):\n \"\"\"Identical URLs should match.\"\"\"\n assert check_resource_allowed(\"https://example.com/path\", \"https://example.com/path\") is True\n assert check_resource_allowed(\"https://example.com/\", \"https://example.com/\") is True\n assert check_resource_allowed(\"https://example.com\", \"https://example.com\") is True", "test_prefix": " def test_identical_urls(self):\n \"\"\"Identical URLs should match.\"\"\"\n \n assert check_resource_allowed(\"https://example.com/\", \"https://example.com/\") is True\n assert check_resource_allowed(\"https://example.com\", \"https://example.com\") is True", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 49, "test_prefix_end_lineno": 53, "test_target": "tests/shared/test_auth_utils.py::TestCheckResourceAllowed::test_identical_urls", "ground_truth_oracle": "assert check_resource_allowed(\"https://example.com/path\", \"https://example.com/path\") is True", "ground_truth_oracle_lineno": 51, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def check_resource_allowed(requested_resource: str, configured_resource: str) -> bool:\n \"\"\"Check if a requested resource URL matches a configured resource URL.\n\n A requested resource matches if it has the same scheme, domain, port,\n and its path starts with the configured resource's path. This allows\n hierarchical matching where a token for a parent resource can be used\n for child resources.\n\n Args:\n requested_resource: The resource URL being requested\n configured_resource: The resource URL that has been configured\n\n Returns:\n True if the requested resource matches the configured resource\n \"\"\"\n # Parse both URLs\n requested = urlparse(requested_resource)\n configured = urlparse(configured_resource)\n\n # Compare scheme, host, and port (origin)\n if requested.scheme.lower() != configured.scheme.lower() or requested.netloc.lower() != configured.netloc.lower():\n return False\n\n # Handle cases like requested=/foo and configured=/foo/\n requested_path = requested.path\n configured_path = configured.path\n\n # If requested path is shorter, it cannot be a child\n if len(requested_path) < len(configured_path):\n return False\n\n # Check if the requested path starts with the configured path\n # Ensure both paths end with / for proper comparison\n # This ensures that paths like \"/api123\" don't incorrectly match \"/api\"\n if not requested_path.endswith(\"/\"):\n requested_path += \"/\"\n if not configured_path.endswith(\"/\"):\n configured_path += \"/\"\n\n return requested_path.startswith(configured_path)", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 30, "focal_method_end_lineno": 69} {"index": 223, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_different_schemes", "test_class_name": "TestCheckResourceAllowed", "original_test_prefix": " def test_different_schemes(self):\n \"\"\"Different schemes should not match.\"\"\"\n assert check_resource_allowed(\"https://example.com/path\", \"http://example.com/path\") is False\n assert check_resource_allowed(\"http://example.com/\", \"https://example.com/\") is False", "test_prefix": " def test_different_schemes(self):\n \"\"\"Different schemes should not match.\"\"\"\n assert check_resource_allowed(\"https://example.com/path\", \"http://example.com/path\") is False\n ", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 55, "test_prefix_end_lineno": 58, "test_target": "tests/shared/test_auth_utils.py::TestCheckResourceAllowed::test_different_schemes", "ground_truth_oracle": "assert check_resource_allowed(\"http://example.com/\", \"https://example.com/\") is False", "ground_truth_oracle_lineno": 58, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def check_resource_allowed(requested_resource: str, configured_resource: str) -> bool:\n \"\"\"Check if a requested resource URL matches a configured resource URL.\n\n A requested resource matches if it has the same scheme, domain, port,\n and its path starts with the configured resource's path. This allows\n hierarchical matching where a token for a parent resource can be used\n for child resources.\n\n Args:\n requested_resource: The resource URL being requested\n configured_resource: The resource URL that has been configured\n\n Returns:\n True if the requested resource matches the configured resource\n \"\"\"\n # Parse both URLs\n requested = urlparse(requested_resource)\n configured = urlparse(configured_resource)\n\n # Compare scheme, host, and port (origin)\n if requested.scheme.lower() != configured.scheme.lower() or requested.netloc.lower() != configured.netloc.lower():\n return False\n\n # Handle cases like requested=/foo and configured=/foo/\n requested_path = requested.path\n configured_path = configured.path\n\n # If requested path is shorter, it cannot be a child\n if len(requested_path) < len(configured_path):\n return False\n\n # Check if the requested path starts with the configured path\n # Ensure both paths end with / for proper comparison\n # This ensures that paths like \"/api123\" don't incorrectly match \"/api\"\n if not requested_path.endswith(\"/\"):\n requested_path += \"/\"\n if not configured_path.endswith(\"/\"):\n configured_path += \"/\"\n\n return requested_path.startswith(configured_path)", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 30, "focal_method_end_lineno": 69} {"index": 224, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_different_domains", "test_class_name": "TestCheckResourceAllowed", "original_test_prefix": " def test_different_domains(self):\n \"\"\"Different domains should not match.\"\"\"\n assert check_resource_allowed(\"https://example.com/path\", \"https://example.org/path\") is False\n assert check_resource_allowed(\"https://sub.example.com/\", \"https://example.com/\") is False", "test_prefix": " def test_different_domains(self):\n \"\"\"Different domains should not match.\"\"\"\n assert check_resource_allowed(\"https://example.com/path\", \"https://example.org/path\") is False\n ", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 60, "test_prefix_end_lineno": 63, "test_target": "tests/shared/test_auth_utils.py::TestCheckResourceAllowed::test_different_domains", "ground_truth_oracle": "assert check_resource_allowed(\"https://sub.example.com/\", \"https://example.com/\") is False", "ground_truth_oracle_lineno": 63, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def check_resource_allowed(requested_resource: str, configured_resource: str) -> bool:\n \"\"\"Check if a requested resource URL matches a configured resource URL.\n\n A requested resource matches if it has the same scheme, domain, port,\n and its path starts with the configured resource's path. This allows\n hierarchical matching where a token for a parent resource can be used\n for child resources.\n\n Args:\n requested_resource: The resource URL being requested\n configured_resource: The resource URL that has been configured\n\n Returns:\n True if the requested resource matches the configured resource\n \"\"\"\n # Parse both URLs\n requested = urlparse(requested_resource)\n configured = urlparse(configured_resource)\n\n # Compare scheme, host, and port (origin)\n if requested.scheme.lower() != configured.scheme.lower() or requested.netloc.lower() != configured.netloc.lower():\n return False\n\n # Handle cases like requested=/foo and configured=/foo/\n requested_path = requested.path\n configured_path = configured.path\n\n # If requested path is shorter, it cannot be a child\n if len(requested_path) < len(configured_path):\n return False\n\n # Check if the requested path starts with the configured path\n # Ensure both paths end with / for proper comparison\n # This ensures that paths like \"/api123\" don't incorrectly match \"/api\"\n if not requested_path.endswith(\"/\"):\n requested_path += \"/\"\n if not configured_path.endswith(\"/\"):\n configured_path += \"/\"\n\n return requested_path.startswith(configured_path)", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 30, "focal_method_end_lineno": 69} {"index": 225, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_different_ports", "test_class_name": "TestCheckResourceAllowed", "original_test_prefix": " def test_different_ports(self):\n \"\"\"Different ports should not match.\"\"\"\n assert check_resource_allowed(\"https://example.com:8443/path\", \"https://example.com/path\") is False\n assert check_resource_allowed(\"https://example.com:8080/\", \"https://example.com:8443/\") is False", "test_prefix": " def test_different_ports(self):\n \"\"\"Different ports should not match.\"\"\"\n assert check_resource_allowed(\"https://example.com:8443/path\", \"https://example.com/path\") is False\n ", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 65, "test_prefix_end_lineno": 68, "test_target": "tests/shared/test_auth_utils.py::TestCheckResourceAllowed::test_different_ports", "ground_truth_oracle": "assert check_resource_allowed(\"https://example.com:8080/\", \"https://example.com:8443/\") is False", "ground_truth_oracle_lineno": 68, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def check_resource_allowed(requested_resource: str, configured_resource: str) -> bool:\n \"\"\"Check if a requested resource URL matches a configured resource URL.\n\n A requested resource matches if it has the same scheme, domain, port,\n and its path starts with the configured resource's path. This allows\n hierarchical matching where a token for a parent resource can be used\n for child resources.\n\n Args:\n requested_resource: The resource URL being requested\n configured_resource: The resource URL that has been configured\n\n Returns:\n True if the requested resource matches the configured resource\n \"\"\"\n # Parse both URLs\n requested = urlparse(requested_resource)\n configured = urlparse(configured_resource)\n\n # Compare scheme, host, and port (origin)\n if requested.scheme.lower() != configured.scheme.lower() or requested.netloc.lower() != configured.netloc.lower():\n return False\n\n # Handle cases like requested=/foo and configured=/foo/\n requested_path = requested.path\n configured_path = configured.path\n\n # If requested path is shorter, it cannot be a child\n if len(requested_path) < len(configured_path):\n return False\n\n # Check if the requested path starts with the configured path\n # Ensure both paths end with / for proper comparison\n # This ensures that paths like \"/api123\" don't incorrectly match \"/api\"\n if not requested_path.endswith(\"/\"):\n requested_path += \"/\"\n if not configured_path.endswith(\"/\"):\n configured_path += \"/\"\n\n return requested_path.startswith(configured_path)", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 30, "focal_method_end_lineno": 69} {"index": 226, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_hierarchical_matching", "test_class_name": "TestCheckResourceAllowed", "original_test_prefix": " def test_hierarchical_matching(self):\n \"\"\"Child paths should match parent paths.\"\"\"\n # Parent resource allows child resources\n assert check_resource_allowed(\"https://example.com/api/v1/users\", \"https://example.com/api\") is True\n assert check_resource_allowed(\"https://example.com/api/v1\", \"https://example.com/api\") is True\n assert check_resource_allowed(\"https://example.com/mcp/server\", \"https://example.com/mcp\") is True\n\n # Exact match\n assert check_resource_allowed(\"https://example.com/api\", \"https://example.com/api\") is True\n\n # Parent cannot use child's token\n assert check_resource_allowed(\"https://example.com/api\", \"https://example.com/api/v1\") is False\n assert check_resource_allowed(\"https://example.com/\", \"https://example.com/api\") is False", "test_prefix": " def test_hierarchical_matching(self):\n \"\"\"Child paths should match parent paths.\"\"\"\n # Parent resource allows child resources\n \n assert check_resource_allowed(\"https://example.com/api/v1\", \"https://example.com/api\") is True\n assert check_resource_allowed(\"https://example.com/mcp/server\", \"https://example.com/mcp\") is True\n\n # Exact match\n assert check_resource_allowed(\"https://example.com/api\", \"https://example.com/api\") is True\n\n # Parent cannot use child's token\n assert check_resource_allowed(\"https://example.com/api\", \"https://example.com/api/v1\") is False\n assert check_resource_allowed(\"https://example.com/\", \"https://example.com/api\") is False", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 70, "test_prefix_end_lineno": 82, "test_target": "tests/shared/test_auth_utils.py::TestCheckResourceAllowed::test_hierarchical_matching", "ground_truth_oracle": "assert check_resource_allowed(\"https://example.com/api/v1/users\", \"https://example.com/api\") is True", "ground_truth_oracle_lineno": 73, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def check_resource_allowed(requested_resource: str, configured_resource: str) -> bool:\n \"\"\"Check if a requested resource URL matches a configured resource URL.\n\n A requested resource matches if it has the same scheme, domain, port,\n and its path starts with the configured resource's path. This allows\n hierarchical matching where a token for a parent resource can be used\n for child resources.\n\n Args:\n requested_resource: The resource URL being requested\n configured_resource: The resource URL that has been configured\n\n Returns:\n True if the requested resource matches the configured resource\n \"\"\"\n # Parse both URLs\n requested = urlparse(requested_resource)\n configured = urlparse(configured_resource)\n\n # Compare scheme, host, and port (origin)\n if requested.scheme.lower() != configured.scheme.lower() or requested.netloc.lower() != configured.netloc.lower():\n return False\n\n # Handle cases like requested=/foo and configured=/foo/\n requested_path = requested.path\n configured_path = configured.path\n\n # If requested path is shorter, it cannot be a child\n if len(requested_path) < len(configured_path):\n return False\n\n # Check if the requested path starts with the configured path\n # Ensure both paths end with / for proper comparison\n # This ensures that paths like \"/api123\" don't incorrectly match \"/api\"\n if not requested_path.endswith(\"/\"):\n requested_path += \"/\"\n if not configured_path.endswith(\"/\"):\n configured_path += \"/\"\n\n return requested_path.startswith(configured_path)", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 30, "focal_method_end_lineno": 69} {"index": 227, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_path_boundary_matching", "test_class_name": "TestCheckResourceAllowed", "original_test_prefix": " def test_path_boundary_matching(self):\n \"\"\"Path matching should respect boundaries.\"\"\"\n # Should not match partial path segments\n assert check_resource_allowed(\"https://example.com/apiextra\", \"https://example.com/api\") is False\n assert check_resource_allowed(\"https://example.com/api123\", \"https://example.com/api\") is False\n\n # Should match with trailing slash\n assert check_resource_allowed(\"https://example.com/api/\", \"https://example.com/api\") is True\n assert check_resource_allowed(\"https://example.com/api/v1\", \"https://example.com/api/\") is True", "test_prefix": " def test_path_boundary_matching(self):\n \"\"\"Path matching should respect boundaries.\"\"\"\n # Should not match partial path segments\n assert check_resource_allowed(\"https://example.com/apiextra\", \"https://example.com/api\") is False\n \n\n # Should match with trailing slash\n assert check_resource_allowed(\"https://example.com/api/\", \"https://example.com/api\") is True\n assert check_resource_allowed(\"https://example.com/api/v1\", \"https://example.com/api/\") is True", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 84, "test_prefix_end_lineno": 92, "test_target": "tests/shared/test_auth_utils.py::TestCheckResourceAllowed::test_path_boundary_matching", "ground_truth_oracle": "assert check_resource_allowed(\"https://example.com/api123\", \"https://example.com/api\") is False", "ground_truth_oracle_lineno": 88, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def check_resource_allowed(requested_resource: str, configured_resource: str) -> bool:\n \"\"\"Check if a requested resource URL matches a configured resource URL.\n\n A requested resource matches if it has the same scheme, domain, port,\n and its path starts with the configured resource's path. This allows\n hierarchical matching where a token for a parent resource can be used\n for child resources.\n\n Args:\n requested_resource: The resource URL being requested\n configured_resource: The resource URL that has been configured\n\n Returns:\n True if the requested resource matches the configured resource\n \"\"\"\n # Parse both URLs\n requested = urlparse(requested_resource)\n configured = urlparse(configured_resource)\n\n # Compare scheme, host, and port (origin)\n if requested.scheme.lower() != configured.scheme.lower() or requested.netloc.lower() != configured.netloc.lower():\n return False\n\n # Handle cases like requested=/foo and configured=/foo/\n requested_path = requested.path\n configured_path = configured.path\n\n # If requested path is shorter, it cannot be a child\n if len(requested_path) < len(configured_path):\n return False\n\n # Check if the requested path starts with the configured path\n # Ensure both paths end with / for proper comparison\n # This ensures that paths like \"/api123\" don't incorrectly match \"/api\"\n if not requested_path.endswith(\"/\"):\n requested_path += \"/\"\n if not configured_path.endswith(\"/\"):\n configured_path += \"/\"\n\n return requested_path.startswith(configured_path)", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 30, "focal_method_end_lineno": 69} {"index": 228, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_trailing_slash_handling", "test_class_name": "TestCheckResourceAllowed", "original_test_prefix": " def test_trailing_slash_handling(self):\n \"\"\"Trailing slashes should be handled correctly.\"\"\"\n # With and without trailing slashes\n assert check_resource_allowed(\"https://example.com/api/\", \"https://example.com/api\") is True\n assert check_resource_allowed(\"https://example.com/api\", \"https://example.com/api/\") is False\n assert check_resource_allowed(\"https://example.com/api/v1\", \"https://example.com/api\") is True\n assert check_resource_allowed(\"https://example.com/api/v1\", \"https://example.com/api/\") is True", "test_prefix": " def test_trailing_slash_handling(self):\n \"\"\"Trailing slashes should be handled correctly.\"\"\"\n # With and without trailing slashes\n assert check_resource_allowed(\"https://example.com/api/\", \"https://example.com/api\") is True\n assert check_resource_allowed(\"https://example.com/api\", \"https://example.com/api/\") is False\n assert check_resource_allowed(\"https://example.com/api/v1\", \"https://example.com/api\") is True\n ", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 94, "test_prefix_end_lineno": 100, "test_target": "tests/shared/test_auth_utils.py::TestCheckResourceAllowed::test_trailing_slash_handling", "ground_truth_oracle": "assert check_resource_allowed(\"https://example.com/api/v1\", \"https://example.com/api/\") is True", "ground_truth_oracle_lineno": 100, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def check_resource_allowed(requested_resource: str, configured_resource: str) -> bool:\n \"\"\"Check if a requested resource URL matches a configured resource URL.\n\n A requested resource matches if it has the same scheme, domain, port,\n and its path starts with the configured resource's path. This allows\n hierarchical matching where a token for a parent resource can be used\n for child resources.\n\n Args:\n requested_resource: The resource URL being requested\n configured_resource: The resource URL that has been configured\n\n Returns:\n True if the requested resource matches the configured resource\n \"\"\"\n # Parse both URLs\n requested = urlparse(requested_resource)\n configured = urlparse(configured_resource)\n\n # Compare scheme, host, and port (origin)\n if requested.scheme.lower() != configured.scheme.lower() or requested.netloc.lower() != configured.netloc.lower():\n return False\n\n # Handle cases like requested=/foo and configured=/foo/\n requested_path = requested.path\n configured_path = configured.path\n\n # If requested path is shorter, it cannot be a child\n if len(requested_path) < len(configured_path):\n return False\n\n # Check if the requested path starts with the configured path\n # Ensure both paths end with / for proper comparison\n # This ensures that paths like \"/api123\" don't incorrectly match \"/api\"\n if not requested_path.endswith(\"/\"):\n requested_path += \"/\"\n if not configured_path.endswith(\"/\"):\n configured_path += \"/\"\n\n return requested_path.startswith(configured_path)", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 30, "focal_method_end_lineno": 69} {"index": 229, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_case_insensitive_origin", "test_class_name": "TestCheckResourceAllowed", "original_test_prefix": " def test_case_insensitive_origin(self):\n \"\"\"Origin comparison should be case-insensitive.\"\"\"\n assert check_resource_allowed(\"https://EXAMPLE.COM/path\", \"https://example.com/path\") is True\n assert check_resource_allowed(\"HTTPS://example.com/path\", \"https://example.com/path\") is True\n assert check_resource_allowed(\"https://Example.Com:8080/api\", \"https://example.com:8080/api\") is True", "test_prefix": " def test_case_insensitive_origin(self):\n \"\"\"Origin comparison should be case-insensitive.\"\"\"\n assert check_resource_allowed(\"https://EXAMPLE.COM/path\", \"https://example.com/path\") is True\n \n assert check_resource_allowed(\"https://Example.Com:8080/api\", \"https://example.com:8080/api\") is True", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 102, "test_prefix_end_lineno": 106, "test_target": "tests/shared/test_auth_utils.py::TestCheckResourceAllowed::test_case_insensitive_origin", "ground_truth_oracle": "assert check_resource_allowed(\"HTTPS://example.com/path\", \"https://example.com/path\") is True", "ground_truth_oracle_lineno": 105, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def check_resource_allowed(requested_resource: str, configured_resource: str) -> bool:\n \"\"\"Check if a requested resource URL matches a configured resource URL.\n\n A requested resource matches if it has the same scheme, domain, port,\n and its path starts with the configured resource's path. This allows\n hierarchical matching where a token for a parent resource can be used\n for child resources.\n\n Args:\n requested_resource: The resource URL being requested\n configured_resource: The resource URL that has been configured\n\n Returns:\n True if the requested resource matches the configured resource\n \"\"\"\n # Parse both URLs\n requested = urlparse(requested_resource)\n configured = urlparse(configured_resource)\n\n # Compare scheme, host, and port (origin)\n if requested.scheme.lower() != configured.scheme.lower() or requested.netloc.lower() != configured.netloc.lower():\n return False\n\n # Handle cases like requested=/foo and configured=/foo/\n requested_path = requested.path\n configured_path = configured.path\n\n # If requested path is shorter, it cannot be a child\n if len(requested_path) < len(configured_path):\n return False\n\n # Check if the requested path starts with the configured path\n # Ensure both paths end with / for proper comparison\n # This ensures that paths like \"/api123\" don't incorrectly match \"/api\"\n if not requested_path.endswith(\"/\"):\n requested_path += \"/\"\n if not configured_path.endswith(\"/\"):\n configured_path += \"/\"\n\n return requested_path.startswith(configured_path)", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 30, "focal_method_end_lineno": 69} {"index": 230, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_empty_paths", "test_class_name": "TestCheckResourceAllowed", "original_test_prefix": " def test_empty_paths(self):\n \"\"\"Empty paths should be handled correctly.\"\"\"\n assert check_resource_allowed(\"https://example.com\", \"https://example.com\") is True\n assert check_resource_allowed(\"https://example.com/\", \"https://example.com\") is True\n assert check_resource_allowed(\"https://example.com/api\", \"https://example.com\") is True", "test_prefix": " def test_empty_paths(self):\n \"\"\"Empty paths should be handled correctly.\"\"\"\n assert check_resource_allowed(\"https://example.com\", \"https://example.com\") is True\n \n assert check_resource_allowed(\"https://example.com/api\", \"https://example.com\") is True", "test_prefix_file_path": "tests/shared/test_auth_utils.py", "test_prefix_start_lineno": 108, "test_prefix_end_lineno": 112, "test_target": "tests/shared/test_auth_utils.py::TestCheckResourceAllowed::test_empty_paths", "ground_truth_oracle": "assert check_resource_allowed(\"https://example.com/\", \"https://example.com\") is True", "ground_truth_oracle_lineno": 111, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def check_resource_allowed(requested_resource: str, configured_resource: str) -> bool:\n \"\"\"Check if a requested resource URL matches a configured resource URL.\n\n A requested resource matches if it has the same scheme, domain, port,\n and its path starts with the configured resource's path. This allows\n hierarchical matching where a token for a parent resource can be used\n for child resources.\n\n Args:\n requested_resource: The resource URL being requested\n configured_resource: The resource URL that has been configured\n\n Returns:\n True if the requested resource matches the configured resource\n \"\"\"\n # Parse both URLs\n requested = urlparse(requested_resource)\n configured = urlparse(configured_resource)\n\n # Compare scheme, host, and port (origin)\n if requested.scheme.lower() != configured.scheme.lower() or requested.netloc.lower() != configured.netloc.lower():\n return False\n\n # Handle cases like requested=/foo and configured=/foo/\n requested_path = requested.path\n configured_path = configured.path\n\n # If requested path is shorter, it cannot be a child\n if len(requested_path) < len(configured_path):\n return False\n\n # Check if the requested path starts with the configured path\n # Ensure both paths end with / for proper comparison\n # This ensures that paths like \"/api123\" don't incorrectly match \"/api\"\n if not requested_path.endswith(\"/\"):\n requested_path += \"/\"\n if not configured_path.endswith(\"/\"):\n configured_path += \"/\"\n\n return requested_path.startswith(configured_path)", "focal_method_file_path": "src/mcp/shared/auth_utils.py", "focal_method_start_lineno": 30, "focal_method_end_lineno": 69} {"index": 231, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_in_flight_requests_cleared_after_completion", "test_class_name": "", "original_test_prefix": "@pytest.mark.anyio\nasync def test_in_flight_requests_cleared_after_completion(\n client_connected_to_server: ClientSession,\n):\n \"\"\"Verify that _in_flight is empty after all requests complete.\"\"\"\n # Send a request and wait for response\n response = await client_connected_to_server.send_ping()\n assert isinstance(response, EmptyResult)\n\n # Verify _in_flight is empty\n assert len(client_connected_to_server._in_flight) == 0", "test_prefix": "@pytest.mark.anyio\nasync def test_in_flight_requests_cleared_after_completion(\n client_connected_to_server: ClientSession,\n):\n \"\"\"Verify that _in_flight is empty after all requests complete.\"\"\"\n # Send a request and wait for response\n response = await client_connected_to_server.send_ping()\n assert isinstance(response, EmptyResult)\n\n # Verify _in_flight is empty\n ", "test_prefix_file_path": "tests/shared/test_session.py", "test_prefix_start_lineno": 35, "test_prefix_end_lineno": 45, "test_target": "tests/shared/test_session.py::test_in_flight_requests_cleared_after_completion", "ground_truth_oracle": "assert len(client_connected_to_server._in_flight) == 0", "ground_truth_oracle_lineno": 45, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " async def send_ping(self) -> types.EmptyResult:\n \"\"\"Send a ping request.\"\"\"\n return await self.send_request(\n types.ClientRequest(types.PingRequest()),\n types.EmptyResult,\n )", "focal_method_file_path": "src/mcp/client/session.py", "focal_method_start_lineno": 176, "focal_method_end_lineno": 181} {"index": 232, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_connection_closed", "test_class_name": "", "original_test_prefix": "@pytest.mark.anyio\nasync def test_connection_closed():\n \"\"\"\n Test that pending requests are cancelled when the connection is closed remotely.\n \"\"\"\n\n ev_closed = anyio.Event()\n ev_response = anyio.Event()\n\n async with create_client_server_memory_streams() as (client_streams, server_streams):\n client_read, client_write = client_streams\n server_read, server_write = server_streams\n\n async def make_request(client_session: ClientSession):\n \"\"\"Send a request in a separate task\"\"\"\n nonlocal ev_response\n try:\n # any request will do\n await client_session.initialize()\n pytest.fail(\"Request should have errored\")\n except McpError as e:\n # Expected - request errored\n assert \"Connection closed\" in str(e)\n ev_response.set()\n\n async def mock_server():\n \"\"\"Wait for a request, then close the connection\"\"\"\n nonlocal ev_closed\n # Wait for a request\n await server_read.receive()\n # Close the connection, as if the server exited\n server_write.close()\n server_read.close()\n ev_closed.set()\n\n async with (\n anyio.create_task_group() as tg,\n ClientSession(read_stream=client_read, write_stream=client_write) as client_session,\n ):\n tg.start_soon(make_request, client_session)\n tg.start_soon(mock_server)\n\n with anyio.fail_after(1):\n await ev_closed.wait()\n with anyio.fail_after(1):\n await ev_response.wait()", "test_prefix": "@pytest.mark.anyio\nasync def test_connection_closed():\n \"\"\"\n Test that pending requests are cancelled when the connection is closed remotely.\n \"\"\"\n\n ev_closed = anyio.Event()\n ev_response = anyio.Event()\n\n async with create_client_server_memory_streams() as (client_streams, server_streams):\n client_read, client_write = client_streams\n server_read, server_write = server_streams\n\n async def make_request(client_session: ClientSession):\n \"\"\"Send a request in a separate task\"\"\"\n nonlocal ev_response\n try:\n # any request will do\n await client_session.initialize()\n pytest.fail(\"Request should have errored\")\n except McpError as e:\n # Expected - request errored\n \n ev_response.set()\n\n async def mock_server():\n \"\"\"Wait for a request, then close the connection\"\"\"\n nonlocal ev_closed\n # Wait for a request\n await server_read.receive()\n # Close the connection, as if the server exited\n server_write.close()\n server_read.close()\n ev_closed.set()\n\n async with (\n anyio.create_task_group() as tg,\n ClientSession(read_stream=client_read, write_stream=client_write) as client_session,\n ):\n tg.start_soon(make_request, client_session)\n tg.start_soon(mock_server)\n\n with anyio.fail_after(1):\n await ev_closed.wait()\n with anyio.fail_after(1):\n await ev_response.wait()", "test_prefix_file_path": "tests/shared/test_session.py", "test_prefix_start_lineno": 125, "test_prefix_end_lineno": 170, "test_target": "tests/shared/test_session.py::test_connection_closed", "ground_truth_oracle": "assert \"Connection closed\" in str(e)", "ground_truth_oracle_lineno": 147, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "@asynccontextmanager\nasync def create_client_server_memory_streams() -> AsyncGenerator[tuple[MessageStream, MessageStream], None]:\n \"\"\"\n Creates a pair of bidirectional memory streams for client-server communication.\n\n Returns:\n A tuple of (client_streams, server_streams) where each is a tuple of\n (read_stream, write_stream)\n \"\"\"\n # Create streams for both directions\n server_to_client_send, server_to_client_receive = anyio.create_memory_object_stream[SessionMessage | Exception](1)\n client_to_server_send, client_to_server_receive = anyio.create_memory_object_stream[SessionMessage | Exception](1)\n\n client_streams = (server_to_client_receive, client_to_server_send)\n server_streams = (client_to_server_receive, server_to_client_send)\n\n async with (\n server_to_client_receive,\n client_to_server_send,\n client_to_server_receive,\n server_to_client_send,\n ):\n yield client_streams, server_streams", "focal_method_file_path": "src/mcp/shared/memory.py", "focal_method_start_lineno": 28, "focal_method_end_lineno": 50} {"index": 233, "repo_name": "python-sdk", "github": "https://github.com/modelcontextprotocol/python-sdk.git", "version": "v1.16.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_memory_server_and_client_connection", "test_class_name": "", "original_test_prefix": "@pytest.mark.anyio\nasync def test_memory_server_and_client_connection(\n client_connected_to_server: ClientSession,\n):\n \"\"\"Shows how a client and server can communicate over memory streams.\"\"\"\n response = await client_connected_to_server.send_ping()\n assert isinstance(response, EmptyResult)", "test_prefix": "@pytest.mark.anyio\nasync def test_memory_server_and_client_connection(\n client_connected_to_server: ClientSession,\n):\n \"\"\"Shows how a client and server can communicate over memory streams.\"\"\"\n response = await client_connected_to_server.send_ping()\n ", "test_prefix_file_path": "tests/shared/test_memory.py", "test_prefix_start_lineno": 36, "test_prefix_end_lineno": 42, "test_target": "tests/shared/test_memory.py::test_memory_server_and_client_connection", "ground_truth_oracle": "assert isinstance(response, EmptyResult)", "ground_truth_oracle_lineno": 42, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " async def send_ping(self) -> types.EmptyResult:\n \"\"\"Send a ping request.\"\"\"\n return await self.send_request(\n types.ClientRequest(types.PingRequest()),\n types.EmptyResult,\n )", "focal_method_file_path": "src/mcp/client/session.py", "focal_method_start_lineno": 176, "focal_method_end_lineno": 181} {"index": 234, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_copy", "test_class_name": "TestCaseInsensitiveDict", "original_test_prefix": " def test_copy(self):\n copy = self.case_insensitive_dict.copy()\n assert copy is not self.case_insensitive_dict\n assert copy == self.case_insensitive_dict", "test_prefix": " def test_copy(self):\n copy = self.case_insensitive_dict.copy()\n \n assert copy == self.case_insensitive_dict", "test_prefix_file_path": "tests/test_structures.py", "test_prefix_start_lineno": 37, "test_prefix_end_lineno": 40, "test_target": "tests/test_structures.py::TestCaseInsensitiveDict::test_copy", "ground_truth_oracle": "assert copy is not self.case_insensitive_dict", "ground_truth_oracle_lineno": 39, "test_setup": " @pytest.fixture(autouse=True)\n def setup(self):\n \"\"\"CaseInsensitiveDict instance with \"Accept\" header.\"\"\"\n self.case_insensitive_dict = CaseInsensitiveDict()\n self.case_insensitive_dict[\"Accept\"] = \"application/json\"", "test_setup_file_path": "tests/test_structures.py", "test_setup_start_lineno": 7, "test_setup_end_lineno": 11, "focal_method": " # Copy is required\n def copy(self):\n return CaseInsensitiveDict(self._store.values())", "focal_method_file_path": "src/requests/structures.py", "focal_method_start_lineno": 75, "focal_method_end_lineno": 77} {"index": 235, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get", "test_class_name": "TestLookupDict", "original_test_prefix": " @get_item_parameters\n def test_get(self, key, value):\n assert self.lookup_dict.get(key) == value", "test_prefix": " @get_item_parameters\n def test_get(self, key, value):\n ", "test_prefix_file_path": "tests/test_structures.py", "test_prefix_start_lineno": 76, "test_prefix_end_lineno": 78, "test_target": "tests/test_structures.py::TestLookupDict::test_get", "ground_truth_oracle": "assert self.lookup_dict.get(key) == value", "ground_truth_oracle_lineno": 78, "test_setup": " @pytest.fixture(autouse=True)\n def setup(self):\n \"\"\"LookupDict instance with \"bad_gateway\" attribute.\"\"\"\n self.lookup_dict = LookupDict(\"test\")\n self.lookup_dict.bad_gateway = 502", "test_setup_file_path": "tests/test_structures.py", "test_setup_start_lineno": 55, "test_setup_end_lineno": 59, "focal_method": " def get(self, key, default=None):\n return self.__dict__.get(key, default)", "focal_method_file_path": "src/requests/structures.py", "focal_method_start_lineno": 98, "focal_method_end_lineno": 99} {"index": 236, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_response_chunk_size_type", "test_class_name": "TestRequests", "original_test_prefix": " def test_response_chunk_size_type(self):\n \"\"\"Ensure that chunk_size is passed as None or an integer, otherwise\n raise a TypeError.\n \"\"\"\n r = requests.Response()\n r.raw = io.BytesIO(b\"the content\")\n chunks = r.iter_content(1)\n assert all(len(chunk) == 1 for chunk in chunks)\n\n r = requests.Response()\n r.raw = io.BytesIO(b\"the content\")\n chunks = r.iter_content(None)\n assert list(chunks) == [b\"the content\"]\n\n r = requests.Response()\n r.raw = io.BytesIO(b\"the content\")\n with pytest.raises(TypeError):\n chunks = r.iter_content(\"1024\")", "test_prefix": " def test_response_chunk_size_type(self):\n \"\"\"Ensure that chunk_size is passed as None or an integer, otherwise\n raise a TypeError.\n \"\"\"\n r = requests.Response()\n r.raw = io.BytesIO(b\"the content\")\n chunks = r.iter_content(1)\n assert all(len(chunk) == 1 for chunk in chunks)\n\n r = requests.Response()\n r.raw = io.BytesIO(b\"the content\")\n chunks = r.iter_content(None)\n \n\n r = requests.Response()\n r.raw = io.BytesIO(b\"the content\")\n with pytest.raises(TypeError):\n chunks = r.iter_content(\"1024\")", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1474, "test_prefix_end_lineno": 1491, "test_target": "tests/test_requests.py::TestRequests::test_response_chunk_size_type", "ground_truth_oracle": "assert list(chunks) == [b\"the content\"]", "ground_truth_oracle_lineno": 1486, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def iter_content(self, chunk_size=1, decode_unicode=False):\n \"\"\"Iterates over the response data. When stream=True is set on the\n request, this avoids reading the content at once into memory for\n large responses. The chunk size is the number of bytes it should\n read into memory. This is not necessarily the length of each item\n returned as decoding can take place.\n\n chunk_size must be of type int or None. A value of None will\n function differently depending on the value of `stream`.\n stream=True will read data as it arrives in whatever size the\n chunks are received. If stream=False, data is returned as\n a single chunk.\n\n If decode_unicode is True, content will be decoded using the best\n available encoding based on the response.\n \"\"\"\n\n def generate():\n # Special case for urllib3.\n if hasattr(self.raw, \"stream\"):\n try:\n yield from self.raw.stream(chunk_size, decode_content=True)\n except ProtocolError as e:\n raise ChunkedEncodingError(e)\n except DecodeError as e:\n raise ContentDecodingError(e)\n except ReadTimeoutError as e:\n raise ConnectionError(e)\n except SSLError as e:\n raise RequestsSSLError(e)\n else:\n # Standard file-like object.\n while True:\n chunk = self.raw.read(chunk_size)\n if not chunk:\n break\n yield chunk\n\n self._content_consumed = True\n\n if self._content_consumed and isinstance(self._content, bool):\n raise StreamConsumedError()\n elif chunk_size is not None and not isinstance(chunk_size, int):\n raise TypeError(\n f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n )\n # simulate reading small chunks of the content\n reused_chunks = iter_slices(self._content, chunk_size)\n\n stream_chunks = generate()\n\n chunks = reused_chunks if self._content_consumed else stream_chunks\n\n if decode_unicode:\n chunks = stream_decode_response_unicode(chunks, self)\n\n return chunks", "focal_method_file_path": "src/requests/models.py", "focal_method_start_lineno": 799, "focal_method_end_lineno": 855} {"index": 237, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_chunked_upload_does_not_set_content_length_header", "test_class_name": "TestRequests", "original_test_prefix": " def test_chunked_upload_does_not_set_content_length_header(self, httpbin):\n \"\"\"Ensure that requests with a generator body stream using\n Transfer-Encoding: chunked, not a Content-Length header.\n \"\"\"\n data = (i for i in [b\"a\", b\"b\", b\"c\"])\n url = httpbin(\"post\")\n r = requests.Request(\"POST\", url, data=data)\n prepared_request = r.prepare()\n assert \"Transfer-Encoding\" in prepared_request.headers\n assert \"Content-Length\" not in prepared_request.headers", "test_prefix": " def test_chunked_upload_does_not_set_content_length_header(self, httpbin):\n \"\"\"Ensure that requests with a generator body stream using\n Transfer-Encoding: chunked, not a Content-Length header.\n \"\"\"\n data = (i for i in [b\"a\", b\"b\", b\"c\"])\n url = httpbin(\"post\")\n r = requests.Request(\"POST\", url, data=data)\n prepared_request = r.prepare()\n \n assert \"Content-Length\" not in prepared_request.headers", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 2221, "test_prefix_end_lineno": 2230, "test_target": "tests/test_requests.py::TestRequests::test_chunked_upload_does_not_set_content_length_header", "ground_truth_oracle": "assert \"Transfer-Encoding\" in prepared_request.headers", "ground_truth_oracle_lineno": 2229, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def prepare(self):\n \"\"\"Constructs a :class:`PreparedRequest ` for transmission and returns it.\"\"\"\n p = PreparedRequest()\n p.prepare(\n method=self.method,\n url=self.url,\n headers=self.headers,\n files=self.files,\n data=self.data,\n json=self.json,\n params=self.params,\n auth=self.auth,\n cookies=self.cookies,\n hooks=self.hooks,\n )\n return p", "focal_method_file_path": "src/requests/models.py", "focal_method_start_lineno": 295, "focal_method_end_lineno": 310} {"index": 238, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_response_json_when_content_is_None", "test_class_name": "TestRequests", "original_test_prefix": " def test_response_json_when_content_is_None(self, httpbin):\n r = requests.get(httpbin(\"/status/204\"))\n # Make sure r.content is None\n r.status_code = 0\n r._content = False\n r._content_consumed = False\n\n assert r.content is None\n with pytest.raises(ValueError):\n r.json()", "test_prefix": " def test_response_json_when_content_is_None(self, httpbin):\n r = requests.get(httpbin(\"/status/204\"))\n # Make sure r.content is None\n r.status_code = 0\n r._content = False\n r._content_consumed = False\n\n \n with pytest.raises(ValueError):\n r.json()", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 2176, "test_prefix_end_lineno": 2185, "test_target": "tests/test_requests.py::TestRequests::test_response_json_when_content_is_None", "ground_truth_oracle": "assert r.content is None", "ground_truth_oracle_lineno": 2183, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 239, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_json_param_post_content_type_works", "test_class_name": "TestRequests", "original_test_prefix": " def test_json_param_post_content_type_works(self, httpbin):\n r = requests.post(httpbin(\"post\"), json={\"life\": 42})\n assert r.status_code == 200\n assert \"application/json\" in r.request.headers[\"Content-Type\"]\n assert {\"life\": 42} == r.json()[\"json\"]", "test_prefix": " def test_json_param_post_content_type_works(self, httpbin):\n r = requests.post(httpbin(\"post\"), json={\"life\": 42})\n assert r.status_code == 200\n \n assert {\"life\": 42} == r.json()[\"json\"]", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 2107, "test_prefix_end_lineno": 2111, "test_target": "tests/test_requests.py::TestRequests::test_json_param_post_content_type_works", "ground_truth_oracle": "assert \"application/json\" in r.request.headers[\"Content-Type\"]", "ground_truth_oracle_lineno": 2110, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def post(url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"post\", url, data=data, json=json, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 103, "focal_method_end_lineno": 115} {"index": 240, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_http_301_changes_post_to_get", "test_class_name": "TestRequests", "original_test_prefix": " def test_http_301_changes_post_to_get(self, httpbin):\n r = requests.post(httpbin(\"status\", \"301\"))\n assert r.status_code == 200\n assert r.request.method == \"GET\"\n assert r.history[0].status_code == 301\n assert r.history[0].is_redirect", "test_prefix": " def test_http_301_changes_post_to_get(self, httpbin):\n r = requests.post(httpbin(\"status\", \"301\"))\n assert r.status_code == 200\n assert r.request.method == \"GET\"\n assert r.history[0].status_code == 301\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 267, "test_prefix_end_lineno": 272, "test_target": "tests/test_requests.py::TestRequests::test_http_301_changes_post_to_get", "ground_truth_oracle": "assert r.history[0].is_redirect", "ground_truth_oracle_lineno": 272, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def post(url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"post\", url, data=data, json=json, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 103, "focal_method_end_lineno": 115} {"index": 241, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_proxy_auth", "test_class_name": "TestRequests", "original_test_prefix": " def test_proxy_auth(self):\n adapter = HTTPAdapter()\n headers = adapter.proxy_headers(\"http://user:pass@httpbin.org\")\n assert headers == {\"Proxy-Authorization\": \"Basic dXNlcjpwYXNz\"}", "test_prefix": " def test_proxy_auth(self):\n adapter = HTTPAdapter()\n headers = adapter.proxy_headers(\"http://user:pass@httpbin.org\")\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 2166, "test_prefix_end_lineno": 2169, "test_target": "tests/test_requests.py::TestRequests::test_proxy_auth", "ground_truth_oracle": "assert headers == {\"Proxy-Authorization\": \"Basic dXNlcjpwYXNz\"}", "ground_truth_oracle_lineno": 2169, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def proxy_headers(self, proxy):\n \"\"\"Returns a dictionary of the headers to add to any request sent\n through a proxy. This works with urllib3 magic to ensure that they are\n correctly sent to the proxy, rather than in a tunnelled request if\n CONNECT is being used.\n\n This should not be called from user code, and is only exposed for use\n when subclassing the\n :class:`HTTPAdapter `.\n\n :param proxy: The url of the proxy being used for this request.\n :rtype: dict\n \"\"\"\n headers = {}\n username, password = get_auth_from_url(proxy)\n\n if username:\n headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n return headers", "focal_method_file_path": "src/requests/adapters.py", "focal_method_start_lineno": 569, "focal_method_end_lineno": 588} {"index": 242, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_history_is_always_a_list", "test_class_name": "TestRequests", "original_test_prefix": " def test_history_is_always_a_list(self, httpbin):\n \"\"\"Show that even with redirects, Response.history is always a list.\"\"\"\n resp = requests.get(httpbin(\"get\"))\n assert isinstance(resp.history, list)\n resp = requests.get(httpbin(\"redirect/1\"))\n assert isinstance(resp.history, list)\n assert not isinstance(resp.history, tuple)", "test_prefix": " def test_history_is_always_a_list(self, httpbin):\n \"\"\"Show that even with redirects, Response.history is always a list.\"\"\"\n resp = requests.get(httpbin(\"get\"))\n assert isinstance(resp.history, list)\n resp = requests.get(httpbin(\"redirect/1\"))\n assert isinstance(resp.history, list)\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 478, "test_prefix_end_lineno": 484, "test_target": "tests/test_requests.py::TestRequests::test_history_is_always_a_list", "ground_truth_oracle": "assert not isinstance(resp.history, tuple)", "ground_truth_oracle_lineno": 484, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 243, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_POSTBIN_GET_POST_FILES", "test_class_name": "TestRequests", "original_test_prefix": " def test_POSTBIN_GET_POST_FILES(self, httpbin):\n url = httpbin(\"post\")\n requests.post(url).raise_for_status()\n\n post1 = requests.post(url, data={\"some\": \"data\"})\n assert post1.status_code == 200\n\n with open(\"requirements-dev.txt\") as f:\n post2 = requests.post(url, files={\"some\": f})\n assert post2.status_code == 200\n\n post4 = requests.post(url, data='[{\"some\": \"json\"}]')\n assert post4.status_code == 200\n\n with pytest.raises(ValueError):\n requests.post(url, files=[\"bad file data\"])", "test_prefix": " def test_POSTBIN_GET_POST_FILES(self, httpbin):\n url = httpbin(\"post\")\n requests.post(url).raise_for_status()\n\n post1 = requests.post(url, data={\"some\": \"data\"})\n assert post1.status_code == 200\n\n with open(\"requirements-dev.txt\") as f:\n post2 = requests.post(url, files={\"some\": f})\n \n\n post4 = requests.post(url, data='[{\"some\": \"json\"}]')\n assert post4.status_code == 200\n\n with pytest.raises(ValueError):\n requests.post(url, files=[\"bad file data\"])", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 808, "test_prefix_end_lineno": 823, "test_target": "tests/test_requests.py::TestRequests::test_POSTBIN_GET_POST_FILES", "ground_truth_oracle": "assert post2.status_code == 200", "ground_truth_oracle_lineno": 817, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def post(url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"post\", url, data=data, json=json, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 103, "focal_method_end_lineno": 115} {"index": 244, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_prepare_body_position_non_stream", "test_class_name": "TestRequests", "original_test_prefix": " def test_prepare_body_position_non_stream(self):\n data = b\"the data\"\n prep = requests.Request(\"GET\", \"http://example.com\", data=data).prepare()\n assert prep._body_position is None", "test_prefix": " def test_prepare_body_position_non_stream(self):\n data = b\"the data\"\n prep = requests.Request(\"GET\", \"http://example.com\", data=data).prepare()\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1968, "test_prefix_end_lineno": 1971, "test_target": "tests/test_requests.py::TestRequests::test_prepare_body_position_non_stream", "ground_truth_oracle": "assert prep._body_position is None", "ground_truth_oracle_lineno": 1971, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def prepare(self):\n \"\"\"Constructs a :class:`PreparedRequest ` for transmission and returns it.\"\"\"\n p = PreparedRequest()\n p.prepare(\n method=self.method,\n url=self.url,\n headers=self.headers,\n files=self.files,\n data=self.data,\n json=self.json,\n params=self.params,\n auth=self.auth,\n cookies=self.cookies,\n hooks=self.hooks,\n )\n return p", "focal_method_file_path": "src/requests/models.py", "focal_method_start_lineno": 295, "focal_method_end_lineno": 310} {"index": 245, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_auth_is_stripped_on_http_downgrade", "test_class_name": "TestRequests", "original_test_prefix": " def test_auth_is_stripped_on_http_downgrade(\n self, httpbin, httpbin_secure, httpbin_ca_bundle\n ):\n r = requests.get(\n httpbin_secure(\"redirect-to\"),\n params={\"url\": httpbin(\"get\")},\n auth=(\"user\", \"pass\"),\n verify=httpbin_ca_bundle,\n )\n assert r.history[0].request.headers[\"Authorization\"]\n assert \"Authorization\" not in r.request.headers", "test_prefix": " def test_auth_is_stripped_on_http_downgrade(\n self, httpbin, httpbin_secure, httpbin_ca_bundle\n ):\n r = requests.get(\n httpbin_secure(\"redirect-to\"),\n params={\"url\": httpbin(\"get\")},\n auth=(\"user\", \"pass\"),\n verify=httpbin_ca_bundle,\n )\n \n assert \"Authorization\" not in r.request.headers", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1882, "test_prefix_end_lineno": 1892, "test_target": "tests/test_requests.py::TestRequests::test_auth_is_stripped_on_http_downgrade", "ground_truth_oracle": "assert r.history[0].request.headers[\"Authorization\"]", "ground_truth_oracle_lineno": 1891, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 246, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_DIGEST_HTTP_200_OK_GET", "test_class_name": "TestRequests", "original_test_prefix": " def test_DIGEST_HTTP_200_OK_GET(self, httpbin):\n for authtype in self.digest_auth_algo:\n auth = HTTPDigestAuth(\"user\", \"pass\")\n url = httpbin(\"digest-auth\", \"auth\", \"user\", \"pass\", authtype, \"never\")\n\n r = requests.get(url, auth=auth)\n assert r.status_code == 200\n\n r = requests.get(url)\n assert r.status_code == 401\n print(r.headers[\"WWW-Authenticate\"])\n\n s = requests.session()\n s.auth = HTTPDigestAuth(\"user\", \"pass\")\n r = s.get(url)\n assert r.status_code == 200", "test_prefix": " def test_DIGEST_HTTP_200_OK_GET(self, httpbin):\n for authtype in self.digest_auth_algo:\n auth = HTTPDigestAuth(\"user\", \"pass\")\n url = httpbin(\"digest-auth\", \"auth\", \"user\", \"pass\", authtype, \"never\")\n\n r = requests.get(url, auth=auth)\n \n\n r = requests.get(url)\n assert r.status_code == 401\n print(r.headers[\"WWW-Authenticate\"])\n\n s = requests.session()\n s.auth = HTTPDigestAuth(\"user\", \"pass\")\n r = s.get(url)\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 738, "test_prefix_end_lineno": 753, "test_target": "tests/test_requests.py::TestRequests::test_DIGEST_HTTP_200_OK_GET", "ground_truth_oracle": "assert r.status_code == 200", "ground_truth_oracle_lineno": 744, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 247, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_status_raising", "test_class_name": "TestRequests", "original_test_prefix": " def test_status_raising(self, httpbin):\n r = requests.get(httpbin(\"status\", \"404\"))\n with pytest.raises(requests.exceptions.HTTPError):\n r.raise_for_status()\n\n r = requests.get(httpbin(\"status\", \"500\"))\n assert not r.ok", "test_prefix": " def test_status_raising(self, httpbin):\n r = requests.get(httpbin(\"status\", \"404\"))\n with pytest.raises(requests.exceptions.HTTPError):\n r.raise_for_status()\n\n r = requests.get(httpbin(\"status\", \"500\"))\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 924, "test_prefix_end_lineno": 930, "test_target": "tests/test_requests.py::TestRequests::test_status_raising", "ground_truth_oracle": "assert not r.ok", "ground_truth_oracle_lineno": 930, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 248, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_prepare_request_with_bytestring_url", "test_class_name": "TestRequests", "original_test_prefix": " def test_prepare_request_with_bytestring_url(self):\n req = requests.Request(\"GET\", b\"https://httpbin.org/\")\n s = requests.Session()\n prep = s.prepare_request(req)\n assert prep.url == \"https://httpbin.org/\"", "test_prefix": " def test_prepare_request_with_bytestring_url(self):\n req = requests.Request(\"GET\", b\"https://httpbin.org/\")\n s = requests.Session()\n prep = s.prepare_request(req)\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1222, "test_prefix_end_lineno": 1226, "test_target": "tests/test_requests.py::TestRequests::test_prepare_request_with_bytestring_url", "ground_truth_oracle": "assert prep.url == \"https://httpbin.org/\"", "ground_truth_oracle_lineno": 1226, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def prepare_request(self, request):\n \"\"\"Constructs a :class:`PreparedRequest ` for\n transmission and returns it. The :class:`PreparedRequest` has settings\n merged from the :class:`Request ` instance and those of the\n :class:`Session`.\n\n :param request: :class:`Request` instance to prepare with this\n session's settings.\n :rtype: requests.PreparedRequest\n \"\"\"\n cookies = request.cookies or {}\n\n # Bootstrap CookieJar.\n if not isinstance(cookies, cookielib.CookieJar):\n cookies = cookiejar_from_dict(cookies)\n\n # Merge with session cookies\n merged_cookies = merge_cookies(\n merge_cookies(RequestsCookieJar(), self.cookies), cookies\n )\n\n # Set environment's basic authentication if not explicitly set.\n auth = request.auth\n if self.trust_env and not auth and not self.auth:\n auth = get_netrc_auth(request.url)\n\n p = PreparedRequest()\n p.prepare(\n method=request.method.upper(),\n url=request.url,\n files=request.files,\n data=request.data,\n json=request.json,\n headers=merge_setting(\n request.headers, self.headers, dict_class=CaseInsensitiveDict\n ),\n params=merge_setting(request.params, self.params),\n auth=merge_setting(auth, self.auth),\n cookies=merged_cookies,\n hooks=merge_hooks(request.hooks, self.hooks),\n )\n return p", "focal_method_file_path": "src/requests/sessions.py", "focal_method_start_lineno": 457, "focal_method_end_lineno": 498} {"index": 249, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_http_with_certificate", "test_class_name": "TestRequests", "original_test_prefix": " def test_http_with_certificate(self, httpbin):\n r = requests.get(httpbin(), cert=\".\")\n assert r.status_code == 200", "test_prefix": " def test_http_with_certificate(self, httpbin):\n r = requests.get(httpbin(), cert=\".\")\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1018, "test_prefix_end_lineno": 1020, "test_target": "tests/test_requests.py::TestRequests::test_http_with_certificate", "ground_truth_oracle": "assert r.status_code == 200", "ground_truth_oracle_lineno": 1020, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 250, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_idna_without_version_attribute", "test_class_name": "", "original_test_prefix": "def test_idna_without_version_attribute():\n \"\"\"Older versions of IDNA don't provide a __version__ attribute, verify\n that if we have such a package, we don't blow up.\n \"\"\"\n with mock.patch(\"requests.help.idna\", new=None):\n assert info()[\"idna\"] == {\"version\": \"\"}", "test_prefix": "def test_idna_without_version_attribute():\n \"\"\"Older versions of IDNA don't provide a __version__ attribute, verify\n that if we have such a package, we don't blow up.\n \"\"\"\n with mock.patch(\"requests.help.idna\", new=None):\n ", "test_prefix_file_path": "tests/test_help.py", "test_prefix_start_lineno": 16, "test_prefix_end_lineno": 21, "test_target": "tests/test_help.py::test_idna_without_version_attribute", "ground_truth_oracle": "assert info()[\"idna\"] == {\"version\": \"\"}", "ground_truth_oracle_lineno": 21, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def info():\n \"\"\"Generate information for a bug report.\"\"\"\n try:\n platform_info = {\n \"system\": platform.system(),\n \"release\": platform.release(),\n }\n except OSError:\n platform_info = {\n \"system\": \"Unknown\",\n \"release\": \"Unknown\",\n }\n\n implementation_info = _implementation()\n urllib3_info = {\"version\": urllib3.__version__}\n charset_normalizer_info = {\"version\": None}\n chardet_info = {\"version\": None}\n if charset_normalizer:\n charset_normalizer_info = {\"version\": charset_normalizer.__version__}\n if chardet:\n chardet_info = {\"version\": chardet.__version__}\n\n pyopenssl_info = {\n \"version\": None,\n \"openssl_version\": \"\",\n }\n if OpenSSL:\n pyopenssl_info = {\n \"version\": OpenSSL.__version__,\n \"openssl_version\": f\"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}\",\n }\n cryptography_info = {\n \"version\": getattr(cryptography, \"__version__\", \"\"),\n }\n idna_info = {\n \"version\": getattr(idna, \"__version__\", \"\"),\n }\n\n system_ssl = ssl.OPENSSL_VERSION_NUMBER\n system_ssl_info = {\"version\": f\"{system_ssl:x}\" if system_ssl is not None else \"\"}\n\n return {\n \"platform\": platform_info,\n \"implementation\": implementation_info,\n \"system_ssl\": system_ssl_info,\n \"using_pyopenssl\": pyopenssl is not None,\n \"using_charset_normalizer\": chardet is None,\n \"pyOpenSSL\": pyopenssl_info,\n \"urllib3\": urllib3_info,\n \"chardet\": chardet_info,\n \"charset_normalizer\": charset_normalizer_info,\n \"cryptography\": cryptography_info,\n \"idna\": idna_info,\n \"requests\": {\n \"version\": requests_version,\n },\n }", "focal_method_file_path": "src/requests/help.py", "focal_method_start_lineno": 69, "focal_method_end_lineno": 125} {"index": 251, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_HTTP_200_OK_GET_WITH_PARAMS", "test_class_name": "TestRequests", "original_test_prefix": " def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):\n heads = {\"User-agent\": \"Mozilla/5.0\"}\n\n r = requests.get(httpbin(\"user-agent\"), headers=heads)\n\n assert heads[\"User-agent\"] in r.text\n assert r.status_code == 200", "test_prefix": " def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):\n heads = {\"User-agent\": \"Mozilla/5.0\"}\n\n r = requests.get(httpbin(\"user-agent\"), headers=heads)\n\n assert heads[\"User-agent\"] in r.text\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 358, "test_prefix_end_lineno": 364, "test_target": "tests/test_requests.py::TestRequests::test_HTTP_200_OK_GET_WITH_PARAMS", "ground_truth_oracle": "assert r.status_code == 200", "ground_truth_oracle_lineno": 364, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 252, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_http_302_doesnt_change_head_to_get", "test_class_name": "TestRequests", "original_test_prefix": " def test_http_302_doesnt_change_head_to_get(self, httpbin):\n r = requests.head(httpbin(\"status\", \"302\"), allow_redirects=True)\n assert r.status_code == 200\n assert r.request.method == \"HEAD\"\n assert r.history[0].status_code == 302\n assert r.history[0].is_redirect", "test_prefix": " def test_http_302_doesnt_change_head_to_get(self, httpbin):\n r = requests.head(httpbin(\"status\", \"302\"), allow_redirects=True)\n assert r.status_code == 200\n assert r.request.method == \"HEAD\"\n assert r.history[0].status_code == 302\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 289, "test_prefix_end_lineno": 294, "test_target": "tests/test_requests.py::TestRequests::test_http_302_doesnt_change_head_to_get", "ground_truth_oracle": "assert r.history[0].is_redirect", "ground_truth_oracle_lineno": 294, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def head(url, **kwargs):\n r\"\"\"Sends a HEAD request.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes. If\n `allow_redirects` is not provided, it will be set to `False` (as\n opposed to the default :meth:`request` behavior).\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n kwargs.setdefault(\"allow_redirects\", False)\n return request(\"head\", url, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 88, "focal_method_end_lineno": 100} {"index": 253, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_bad_utf_like_encoding", "test_class_name": "TestGuessJSONUTF", "original_test_prefix": " def test_bad_utf_like_encoding(self):\n assert guess_json_utf(b\"\\x00\\x00\\x00\\x00\") is None", "test_prefix": " def test_bad_utf_like_encoding(self):\n ", "test_prefix_file_path": "tests/test_utils.py", "test_prefix_start_lineno": 413, "test_prefix_end_lineno": 414, "test_target": "tests/test_utils.py::TestGuessJSONUTF::test_bad_utf_like_encoding", "ground_truth_oracle": "assert guess_json_utf(b\"\\x00\\x00\\x00\\x00\") is None", "ground_truth_oracle_lineno": 414, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def guess_json_utf(data):\n \"\"\"\n :rtype: str\n \"\"\"\n # JSON always starts with two ASCII characters, so detection is as\n # easy as counting the nulls and from their location and count\n # determine the encoding. Also detect a BOM, if present.\n sample = data[:4]\n if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):\n return \"utf-32\" # BOM included\n if sample[:3] == codecs.BOM_UTF8:\n return \"utf-8-sig\" # BOM included, MS style (discouraged)\n if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):\n return \"utf-16\" # BOM included\n nullcount = sample.count(_null)\n if nullcount == 0:\n return \"utf-8\"\n if nullcount == 2:\n if sample[::2] == _null2: # 1st and 3rd are null\n return \"utf-16-be\"\n if sample[1::2] == _null2: # 2nd and 4th are null\n return \"utf-16-le\"\n # Did not detect 2 valid UTF-16 ascii-range characters\n if nullcount == 3:\n if sample[:3] == _null3:\n return \"utf-32-be\"\n if sample[1:] == _null3:\n return \"utf-32-le\"\n # Did not detect a valid UTF-32 ascii-range character\n return None", "focal_method_file_path": "src/requests/utils.py", "focal_method_start_lineno": 947, "focal_method_end_lineno": 976} {"index": 254, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_BASICAUTH_TUPLE_HTTP_200_OK_GET", "test_class_name": "TestRequests", "original_test_prefix": " def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):\n auth = (\"user\", \"pass\")\n url = httpbin(\"basic-auth\", \"user\", \"pass\")\n\n r = requests.get(url, auth=auth)\n assert r.status_code == 200\n\n r = requests.get(url)\n assert r.status_code == 401\n\n s = requests.session()\n s.auth = auth\n r = s.get(url)\n assert r.status_code == 200", "test_prefix": " def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):\n auth = (\"user\", \"pass\")\n url = httpbin(\"basic-auth\", \"user\", \"pass\")\n\n r = requests.get(url, auth=auth)\n assert r.status_code == 200\n\n r = requests.get(url)\n \n\n s = requests.session()\n s.auth = auth\n r = s.get(url)\n assert r.status_code == 200", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 529, "test_prefix_end_lineno": 542, "test_target": "tests/test_requests.py::TestRequests::test_BASICAUTH_TUPLE_HTTP_200_OK_GET", "ground_truth_oracle": "assert r.status_code == 401", "ground_truth_oracle_lineno": 537, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 255, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_is_filename", "test_class_name": "TestUnquoteHeaderValue", "original_test_prefix": " def test_is_filename(self):\n assert unquote_header_value('\"\\\\\\\\Comp\\\\Res\"', True) == \"\\\\\\\\Comp\\\\Res\"", "test_prefix": " def test_is_filename(self):\n ", "test_prefix_file_path": "tests/test_utils.py", "test_prefix_start_lineno": 206, "test_prefix_end_lineno": 207, "test_target": "tests/test_utils.py::TestUnquoteHeaderValue::test_is_filename", "ground_truth_oracle": "assert unquote_header_value('\"\\\\\\\\Comp\\\\Res\"', True) == \"\\\\\\\\Comp\\\\Res\"", "ground_truth_oracle_lineno": 207, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "# From mitsuhiko/werkzeug (used with permission).\ndef unquote_header_value(value, is_filename=False):\n r\"\"\"Unquotes a header value. (Reversal of :func:`quote_header_value`).\n This does not use the real unquoting but what browsers are actually\n using for quoting.\n\n :param value: the header value to unquote.\n :rtype: str\n \"\"\"\n if value and value[0] == value[-1] == '\"':\n # this is not the real unquoting, but fixing this so that the\n # RFC is met will result in bugs with internet explorer and\n # probably some other browsers as well. IE for example is\n # uploading files with \"C:\\foo\\bar.txt\" as filename\n value = value[1:-1]\n\n # if this is a filename and the starting characters look like\n # a UNC path, then just return the value without quotes. Using the\n # replace sequence below on a UNC path has the effect of turning\n # the leading double slash into a single slash and then\n # _fix_ie_filename() doesn't work correctly. See #458.\n if not is_filename or value[:2] != \"\\\\\\\\\":\n return value.replace(\"\\\\\\\\\", \"\\\\\").replace('\\\\\"', '\"')\n return value", "focal_method_file_path": "src/requests/utils.py", "focal_method_start_lineno": 431, "focal_method_end_lineno": 454} {"index": 256, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_session_get_adapter_prefix_with_trailing_slash", "test_class_name": "TestRequests", "original_test_prefix": " def test_session_get_adapter_prefix_with_trailing_slash(self):\n # from issue #6935\n prefix = \"https://example.com/\" # trailing slash\n url_matching_prefix = \"https://example.com/some/path\"\n url_not_matching_prefix = \"https://example.com.other.com/some/path\"\n\n s = requests.Session()\n adapter = HTTPAdapter()\n s.mount(prefix, adapter)\n\n assert s.get_adapter(url_matching_prefix) is adapter\n assert s.get_adapter(url_not_matching_prefix) is not adapter", "test_prefix": " def test_session_get_adapter_prefix_with_trailing_slash(self):\n # from issue #6935\n prefix = \"https://example.com/\" # trailing slash\n url_matching_prefix = \"https://example.com/some/path\"\n url_not_matching_prefix = \"https://example.com.other.com/some/path\"\n\n s = requests.Session()\n adapter = HTTPAdapter()\n s.mount(prefix, adapter)\n\n \n assert s.get_adapter(url_not_matching_prefix) is not adapter", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1697, "test_prefix_end_lineno": 1708, "test_target": "tests/test_requests.py::TestRequests::test_session_get_adapter_prefix_with_trailing_slash", "ground_truth_oracle": "assert s.get_adapter(url_matching_prefix) is adapter", "ground_truth_oracle_lineno": 1707, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_adapter(self, url):\n \"\"\"\n Returns the appropriate connection adapter for the given URL.\n\n :rtype: requests.adapters.BaseAdapter\n \"\"\"\n for prefix, adapter in self.adapters.items():\n if url.lower().startswith(prefix.lower()):\n return adapter\n\n # Nothing matches :-/\n raise InvalidSchema(f\"No connection adapters were found for {url!r}\")", "focal_method_file_path": "src/requests/sessions.py", "focal_method_start_lineno": 781, "focal_method_end_lineno": 792} {"index": 257, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_http_error", "test_class_name": "TestRequests", "original_test_prefix": " def test_http_error(self):\n error = requests.exceptions.HTTPError()\n assert not error.response\n response = requests.Response()\n error = requests.exceptions.HTTPError(response=response)\n assert error.response == response\n error = requests.exceptions.HTTPError(\"message\", response=response)\n assert str(error) == \"message\"\n assert error.response == response", "test_prefix": " def test_http_error(self):\n error = requests.exceptions.HTTPError()\n assert not error.response\n response = requests.Response()\n error = requests.exceptions.HTTPError(response=response)\n \n error = requests.exceptions.HTTPError(\"message\", response=response)\n assert str(error) == \"message\"\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1575, "test_prefix_end_lineno": 1583, "test_target": "tests/test_requests.py::TestRequests::test_http_error", "ground_truth_oracle": "assert error.response == response", "ground_truth_oracle_lineno": 1580, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class HTTPError(RequestException):\n \"\"\"An HTTP error occurred.\"\"\"", "focal_method_file_path": "src/requests/exceptions.py", "focal_method_start_lineno": 55, "focal_method_end_lineno": 56} {"index": 258, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_http_303_changes_post_to_get", "test_class_name": "TestRequests", "original_test_prefix": " def test_http_303_changes_post_to_get(self, httpbin):\n r = requests.post(httpbin(\"status\", \"303\"))\n assert r.status_code == 200\n assert r.request.method == \"GET\"\n assert r.history[0].status_code == 303\n assert r.history[0].is_redirect", "test_prefix": " def test_http_303_changes_post_to_get(self, httpbin):\n r = requests.post(httpbin(\"status\", \"303\"))\n assert r.status_code == 200\n \n assert r.history[0].status_code == 303\n assert r.history[0].is_redirect", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 296, "test_prefix_end_lineno": 301, "test_target": "tests/test_requests.py::TestRequests::test_http_303_changes_post_to_get", "ground_truth_oracle": "assert r.request.method == \"GET\"", "ground_truth_oracle_lineno": 299, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def post(url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"post\", url, data=data, json=json, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 103, "focal_method_end_lineno": 115} {"index": 259, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_redirect_rfc1808_to_non_ascii_location", "test_class_name": "", "original_test_prefix": "def test_redirect_rfc1808_to_non_ascii_location():\n path = '\u0161'\n expected_path = b'%C5%A1'\n redirect_request = [] # stores the second request to the server\n\n def redirect_resp_handler(sock):\n consume_socket_content(sock, timeout=0.5)\n location = f'//{host}:{port}/{path}'\n sock.send(\n (\n b'HTTP/1.1 301 Moved Permanently\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: %s\\r\\n'\n b'\\r\\n'\n ) % location.encode('utf8')\n )\n redirect_request.append(consume_socket_content(sock, timeout=0.5))\n sock.send(b'HTTP/1.1 200 OK\\r\\n\\r\\n')\n\n close_server = threading.Event()\n server = Server(redirect_resp_handler, wait_to_close_event=close_server)\n\n with server as (host, port):\n url = f'http://{host}:{port}'\n r = requests.get(url=url, allow_redirects=True)\n assert r.status_code == 200\n assert len(r.history) == 1\n assert r.history[0].status_code == 301\n assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')\n assert r.url == '{}/{}'.format(url, expected_path.decode('ascii'))\n\n close_server.set()", "test_prefix": "def test_redirect_rfc1808_to_non_ascii_location():\n path = '\u0161'\n expected_path = b'%C5%A1'\n redirect_request = [] # stores the second request to the server\n\n def redirect_resp_handler(sock):\n consume_socket_content(sock, timeout=0.5)\n location = f'//{host}:{port}/{path}'\n sock.send(\n (\n b'HTTP/1.1 301 Moved Permanently\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: %s\\r\\n'\n b'\\r\\n'\n ) % location.encode('utf8')\n )\n redirect_request.append(consume_socket_content(sock, timeout=0.5))\n sock.send(b'HTTP/1.1 200 OK\\r\\n\\r\\n')\n\n close_server = threading.Event()\n server = Server(redirect_resp_handler, wait_to_close_event=close_server)\n\n with server as (host, port):\n url = f'http://{host}:{port}'\n r = requests.get(url=url, allow_redirects=True)\n \n assert len(r.history) == 1\n assert r.history[0].status_code == 301\n assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')\n assert r.url == '{}/{}'.format(url, expected_path.decode('ascii'))\n\n close_server.set()", "test_prefix_file_path": "tests/test_lowlevel.py", "test_prefix_start_lineno": 308, "test_prefix_end_lineno": 339, "test_target": "tests/test_lowlevel.py::test_redirect_rfc1808_to_non_ascii_location", "ground_truth_oracle": "assert r.status_code == 200", "ground_truth_oracle_lineno": 333, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 260, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_custom_redirect_mixin", "test_class_name": "TestRequests", "original_test_prefix": " def test_custom_redirect_mixin(self, httpbin):\n \"\"\"Tests a custom mixin to overwrite ``get_redirect_target``.\n\n Ensures a subclassed ``requests.Session`` can handle a certain type of\n malformed redirect responses.\n\n 1. original request receives a proper response: 302 redirect\n 2. following the redirect, a malformed response is given:\n status code = HTTP 200\n location = alternate url\n 3. the custom session catches the edge case and follows the redirect\n \"\"\"\n url_final = httpbin(\"html\")\n querystring_malformed = urlencode({\"location\": url_final})\n url_redirect_malformed = httpbin(\"response-headers?%s\" % querystring_malformed)\n querystring_redirect = urlencode({\"url\": url_redirect_malformed})\n url_redirect = httpbin(\"redirect-to?%s\" % querystring_redirect)\n urls_test = [\n url_redirect,\n url_redirect_malformed,\n url_final,\n ]\n\n class CustomRedirectSession(requests.Session):\n def get_redirect_target(self, resp):\n # default behavior\n if resp.is_redirect:\n return resp.headers[\"location\"]\n # edge case - check to see if 'location' is in headers anyways\n location = resp.headers.get(\"location\")\n if location and (location != resp.url):\n return location\n return None\n\n session = CustomRedirectSession()\n r = session.get(urls_test[0])\n assert len(r.history) == 2\n assert r.status_code == 200\n assert r.history[0].status_code == 302\n assert r.history[0].is_redirect\n assert r.history[1].status_code == 200\n assert not r.history[1].is_redirect\n assert r.url == urls_test[2]", "test_prefix": " def test_custom_redirect_mixin(self, httpbin):\n \"\"\"Tests a custom mixin to overwrite ``get_redirect_target``.\n\n Ensures a subclassed ``requests.Session`` can handle a certain type of\n malformed redirect responses.\n\n 1. original request receives a proper response: 302 redirect\n 2. following the redirect, a malformed response is given:\n status code = HTTP 200\n location = alternate url\n 3. the custom session catches the edge case and follows the redirect\n \"\"\"\n url_final = httpbin(\"html\")\n querystring_malformed = urlencode({\"location\": url_final})\n url_redirect_malformed = httpbin(\"response-headers?%s\" % querystring_malformed)\n querystring_redirect = urlencode({\"url\": url_redirect_malformed})\n url_redirect = httpbin(\"redirect-to?%s\" % querystring_redirect)\n urls_test = [\n url_redirect,\n url_redirect_malformed,\n url_final,\n ]\n\n class CustomRedirectSession(requests.Session):\n def get_redirect_target(self, resp):\n # default behavior\n if resp.is_redirect:\n return resp.headers[\"location\"]\n # edge case - check to see if 'location' is in headers anyways\n location = resp.headers.get(\"location\")\n if location and (location != resp.url):\n return location\n return None\n\n session = CustomRedirectSession()\n r = session.get(urls_test[0])\n assert len(r.history) == 2\n assert r.status_code == 200\n assert r.history[0].status_code == 302\n assert r.history[0].is_redirect\n \n assert not r.history[1].is_redirect\n assert r.url == urls_test[2]", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 2232, "test_prefix_end_lineno": 2274, "test_target": "tests/test_requests.py::TestRequests::test_custom_redirect_mixin", "ground_truth_oracle": "assert r.history[1].status_code == 200", "ground_truth_oracle_lineno": 2272, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get(self, url, **kwargs):\n r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n \"\"\"\n\n kwargs.setdefault(\"allow_redirects\", True)\n return self.request(\"GET\", url, **kwargs)", "focal_method_file_path": "src/requests/sessions.py", "focal_method_start_lineno": 593, "focal_method_end_lineno": 602} {"index": 261, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_works", "test_class_name": "TestGetNetrcAuth", "original_test_prefix": " def test_works(self, tmp_path, monkeypatch):\n netrc_path = tmp_path / \".netrc\"\n monkeypatch.setenv(\"NETRC\", str(netrc_path))\n with open(netrc_path, \"w\") as f:\n f.write(\"machine example.com login aaaa password bbbb\\n\")\n auth = get_netrc_auth(\"http://example.com/thing\")\n assert auth == (\"aaaa\", \"bbbb\")", "test_prefix": " def test_works(self, tmp_path, monkeypatch):\n netrc_path = tmp_path / \".netrc\"\n monkeypatch.setenv(\"NETRC\", str(netrc_path))\n with open(netrc_path, \"w\") as f:\n f.write(\"machine example.com login aaaa password bbbb\\n\")\n auth = get_netrc_auth(\"http://example.com/thing\")\n ", "test_prefix_file_path": "tests/test_utils.py", "test_prefix_start_lineno": 157, "test_prefix_end_lineno": 163, "test_target": "tests/test_utils.py::TestGetNetrcAuth::test_works", "ground_truth_oracle": "assert auth == (\"aaaa\", \"bbbb\")", "ground_truth_oracle_lineno": 163, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_netrc_auth(url, raise_errors=False):\n \"\"\"Returns the Requests tuple auth for a given url from netrc.\"\"\"\n\n netrc_file = os.environ.get(\"NETRC\")\n if netrc_file is not None:\n netrc_locations = (netrc_file,)\n else:\n netrc_locations = (f\"~/{f}\" for f in NETRC_FILES)\n\n try:\n from netrc import NetrcParseError, netrc\n\n netrc_path = None\n\n for f in netrc_locations:\n loc = os.path.expanduser(f)\n if os.path.exists(loc):\n netrc_path = loc\n break\n\n # Abort early if there isn't one.\n if netrc_path is None:\n return\n\n ri = urlparse(url)\n host = ri.hostname\n\n try:\n _netrc = netrc(netrc_path).authenticators(host)\n if _netrc:\n # Return with login / password\n login_i = 0 if _netrc[0] else 1\n return (_netrc[login_i], _netrc[2])\n except (NetrcParseError, OSError):\n # If there was a parsing error or a permissions issue reading the file,\n # we'll just skip netrc auth unless explicitly asked to raise errors.\n if raise_errors:\n raise\n\n # App Engine hackiness.\n except (ImportError, AttributeError):\n pass", "focal_method_file_path": "src/requests/utils.py", "focal_method_start_lineno": 207, "focal_method_end_lineno": 248} {"index": 262, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_set_environ_raises_exception", "test_class_name": "", "original_test_prefix": "def test_set_environ_raises_exception():\n \"\"\"Tests set_environ will raise exceptions in context when the\n value parameter is None.\"\"\"\n with pytest.raises(Exception) as exception:\n with set_environ(\"test1\", None):\n raise Exception(\"Expected exception\")\n\n assert \"Expected exception\" in str(exception.value)", "test_prefix": "def test_set_environ_raises_exception():\n \"\"\"Tests set_environ will raise exceptions in context when the\n value parameter is None.\"\"\"\n with pytest.raises(Exception) as exception:\n with set_environ(\"test1\", None):\n raise Exception(\"Expected exception\")\n\n ", "test_prefix_file_path": "tests/test_utils.py", "test_prefix_start_lineno": 938, "test_prefix_end_lineno": 945, "test_target": "tests/test_utils.py::test_set_environ_raises_exception", "ground_truth_oracle": "assert \"Expected exception\" in str(exception.value)", "ground_truth_oracle_lineno": 945, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "@contextlib.contextmanager\ndef set_environ(env_name, value):\n \"\"\"Set the environment variable 'env_name' to 'value'\n\n Save previous value, yield, and then restore the previous value stored in\n the environment variable 'env_name'.\n\n If 'value' is None, do nothing\"\"\"\n value_changed = value is not None\n if value_changed:\n old_value = os.environ.get(env_name)\n os.environ[env_name] = value\n try:\n yield\n finally:\n if value_changed:\n if old_value is None:\n del os.environ[env_name]\n else:\n os.environ[env_name] = old_value", "focal_method_file_path": "src/requests/utils.py", "focal_method_start_lineno": 733, "focal_method_end_lineno": 752} {"index": 263, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_can_send_file_object_with_non_string_filename", "test_class_name": "TestRequests", "original_test_prefix": " def test_can_send_file_object_with_non_string_filename(self, httpbin):\n f = io.BytesIO()\n f.name = 2\n r = requests.Request(\"POST\", httpbin(\"post\"), files={\"f\": f})\n p = r.prepare()\n\n assert \"multipart/form-data\" in p.headers[\"Content-Type\"]", "test_prefix": " def test_can_send_file_object_with_non_string_filename(self, httpbin):\n f = io.BytesIO()\n f.name = 2\n r = requests.Request(\"POST\", httpbin(\"post\"), files={\"f\": f})\n p = r.prepare()\n\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1855, "test_prefix_end_lineno": 1861, "test_target": "tests/test_requests.py::TestRequests::test_can_send_file_object_with_non_string_filename", "ground_truth_oracle": "assert \"multipart/form-data\" in p.headers[\"Content-Type\"]", "ground_truth_oracle_lineno": 1861, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def prepare(self):\n \"\"\"Constructs a :class:`PreparedRequest ` for transmission and returns it.\"\"\"\n p = PreparedRequest()\n p.prepare(\n method=self.method,\n url=self.url,\n headers=self.headers,\n files=self.files,\n data=self.data,\n json=self.json,\n params=self.params,\n auth=self.auth,\n cookies=self.cookies,\n hooks=self.hooks,\n )\n return p", "focal_method_file_path": "src/requests/models.py", "focal_method_start_lineno": 295, "focal_method_end_lineno": 310} {"index": 264, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_precedence", "test_class_name": "TestContentEncodingDetection", "original_test_prefix": " def test_precedence(self):\n content = \"\"\"\n \n \n \n \"\"\".strip()\n assert get_encodings_from_content(content) == [\"HTML5\", \"HTML4\", \"XML\"]", "test_prefix": " def test_precedence(self):\n content = \"\"\"\n \n \n \n \"\"\".strip()\n ", "test_prefix_file_path": "tests/test_utils.py", "test_prefix_start_lineno": 386, "test_prefix_end_lineno": 392, "test_target": "tests/test_utils.py::TestContentEncodingDetection::test_precedence", "ground_truth_oracle": "assert get_encodings_from_content(content) == [\"HTML5\", \"HTML4\", \"XML\"]", "ground_truth_oracle_lineno": 392, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_encodings_from_content(content):\n \"\"\"Returns encodings from given content string.\n\n :param content: bytestring to extract encodings from.\n \"\"\"\n warnings.warn(\n (\n \"In requests 3.0, get_encodings_from_content will be removed. For \"\n \"more information, please see the discussion on issue #2266. (This\"\n \" warning should only appear once.)\"\n ),\n DeprecationWarning,\n )\n\n charset_re = re.compile(r']', flags=re.I)\n pragma_re = re.compile(r']', flags=re.I)\n xml_re = re.compile(r'^<\\?xml.*?encoding=[\"\\']*(.+?)[\"\\'>]')\n\n return (\n charset_re.findall(content)\n + pragma_re.findall(content)\n + xml_re.findall(content)\n )", "focal_method_file_path": "src/requests/utils.py", "focal_method_start_lineno": 479, "focal_method_end_lineno": 501} {"index": 265, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_content_length_for_string_data_counts_bytes", "test_class_name": "", "original_test_prefix": "@pytest.mark.skipif(\n is_urllib3_1,\n reason=\"urllib3 2.x encodes all strings to utf-8, urllib3 1.x uses latin-1\",\n)\ndef test_content_length_for_string_data_counts_bytes(httpbin):\n data = \"This is a string containing multi-byte UTF-8 \u2603\ufe0f\"\n length = str(len(data.encode(\"utf-8\")))\n req = requests.Request(\"POST\", httpbin(\"post\"), data=data)\n p = req.prepare()\n\n assert p.headers[\"Content-Length\"] == length", "test_prefix": "@pytest.mark.skipif(\n is_urllib3_1,\n reason=\"urllib3 2.x encodes all strings to utf-8, urllib3 1.x uses latin-1\",\n)\ndef test_content_length_for_string_data_counts_bytes(httpbin):\n data = \"This is a string containing multi-byte UTF-8 \u2603\ufe0f\"\n length = str(len(data.encode(\"utf-8\")))\n req = requests.Request(\"POST\", httpbin(\"post\"), data=data)\n p = req.prepare()\n\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 3020, "test_prefix_end_lineno": 3030, "test_target": "tests/test_requests.py::test_content_length_for_string_data_counts_bytes", "ground_truth_oracle": "assert p.headers[\"Content-Length\"] == length", "ground_truth_oracle_lineno": 3030, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def prepare(self):\n \"\"\"Constructs a :class:`PreparedRequest ` for transmission and returns it.\"\"\"\n p = PreparedRequest()\n p.prepare(\n method=self.method,\n url=self.url,\n headers=self.headers,\n files=self.files,\n data=self.data,\n json=self.json,\n params=self.params,\n auth=self.auth,\n cookies=self.cookies,\n hooks=self.hooks,\n )\n return p", "focal_method_file_path": "src/requests/models.py", "focal_method_start_lineno": 295, "focal_method_end_lineno": 310} {"index": 266, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_fragment_update_on_redirect", "test_class_name": "", "original_test_prefix": "def test_fragment_update_on_redirect():\n \"\"\"Verify we only append previous fragment if one doesn't exist on new\n location. If a new fragment is encountered in a Location header, it should\n be added to all subsequent requests.\n \"\"\"\n\n def response_handler(sock):\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 302 FOUND\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: /get#relevant-section\\r\\n\\r\\n'\n )\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 302 FOUND\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: /final-url/\\r\\n\\r\\n'\n )\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 200 OK\\r\\n\\r\\n'\n )\n\n close_server = threading.Event()\n server = Server(response_handler, wait_to_close_event=close_server)\n\n with server as (host, port):\n url = f'http://{host}:{port}/path/to/thing/#view=edit&token=hunter2'\n r = requests.get(url)\n\n assert r.status_code == 200\n assert len(r.history) == 2\n assert r.history[0].request.url == url\n\n # Verify we haven't overwritten the location with our previous fragment.\n assert r.history[1].request.url == f'http://{host}:{port}/get#relevant-section'\n # Verify previous fragment is used and not the original.\n assert r.url == f'http://{host}:{port}/final-url/#relevant-section'\n\n close_server.set()", "test_prefix": "def test_fragment_update_on_redirect():\n \"\"\"Verify we only append previous fragment if one doesn't exist on new\n location. If a new fragment is encountered in a Location header, it should\n be added to all subsequent requests.\n \"\"\"\n\n def response_handler(sock):\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 302 FOUND\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: /get#relevant-section\\r\\n\\r\\n'\n )\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 302 FOUND\\r\\n'\n b'Content-Length: 0\\r\\n'\n b'Location: /final-url/\\r\\n\\r\\n'\n )\n consume_socket_content(sock, timeout=0.5)\n sock.send(\n b'HTTP/1.1 200 OK\\r\\n\\r\\n'\n )\n\n close_server = threading.Event()\n server = Server(response_handler, wait_to_close_event=close_server)\n\n with server as (host, port):\n url = f'http://{host}:{port}/path/to/thing/#view=edit&token=hunter2'\n r = requests.get(url)\n\n assert r.status_code == 200\n assert len(r.history) == 2\n \n\n # Verify we haven't overwritten the location with our previous fragment.\n assert r.history[1].request.url == f'http://{host}:{port}/get#relevant-section'\n # Verify previous fragment is used and not the original.\n assert r.url == f'http://{host}:{port}/final-url/#relevant-section'\n\n close_server.set()", "test_prefix_file_path": "tests/test_lowlevel.py", "test_prefix_start_lineno": 364, "test_prefix_end_lineno": 404, "test_target": "tests/test_lowlevel.py::test_fragment_update_on_redirect", "ground_truth_oracle": "assert r.history[0].request.url == url", "ground_truth_oracle_lineno": 397, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 267, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_zipped_paths_extracted", "test_class_name": "TestExtractZippedPaths", "original_test_prefix": " def test_zipped_paths_extracted(self, tmpdir):\n zipped_py = tmpdir.join(\"test.zip\")\n with zipfile.ZipFile(zipped_py.strpath, \"w\") as f:\n f.write(__file__)\n\n _, name = os.path.splitdrive(__file__)\n zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r\"\\/\"))\n extracted_path = extract_zipped_paths(zipped_path)\n\n assert extracted_path != zipped_path\n assert os.path.exists(extracted_path)\n assert filecmp.cmp(extracted_path, __file__)", "test_prefix": " def test_zipped_paths_extracted(self, tmpdir):\n zipped_py = tmpdir.join(\"test.zip\")\n with zipfile.ZipFile(zipped_py.strpath, \"w\") as f:\n f.write(__file__)\n\n _, name = os.path.splitdrive(__file__)\n zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r\"\\/\"))\n extracted_path = extract_zipped_paths(zipped_path)\n\n assert extracted_path != zipped_path\n \n assert filecmp.cmp(extracted_path, __file__)", "test_prefix_file_path": "tests/test_utils.py", "test_prefix_start_lineno": 345, "test_prefix_end_lineno": 356, "test_target": "tests/test_utils.py::TestExtractZippedPaths::test_zipped_paths_extracted", "ground_truth_oracle": "assert os.path.exists(extracted_path)", "ground_truth_oracle_lineno": 355, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def extract_zipped_paths(path):\n \"\"\"Replace nonexistent paths that look like they refer to a member of a zip\n archive with the location of an extracted copy of the target, or else\n just return the provided path unchanged.\n \"\"\"\n if os.path.exists(path):\n # this is already a valid path, no need to do anything further\n return path\n\n # find the first valid part of the provided path and treat that as a zip archive\n # assume the rest of the path is the name of a member in the archive\n archive, member = os.path.split(path)\n while archive and not os.path.exists(archive):\n archive, prefix = os.path.split(archive)\n if not prefix:\n # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),\n # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users\n break\n member = \"/\".join([prefix, member])\n\n if not zipfile.is_zipfile(archive):\n return path\n\n zip_file = zipfile.ZipFile(archive)\n if member not in zip_file.namelist():\n return path\n\n # we have a valid zip archive and a valid member of that archive\n tmp = tempfile.gettempdir()\n extracted_path = os.path.join(tmp, member.split(\"/\")[-1])\n if not os.path.exists(extracted_path):\n # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition\n with atomic_open(extracted_path) as file_handler:\n file_handler.write(zip_file.read(member))\n return extracted_path", "focal_method_file_path": "src/requests/utils.py", "focal_method_start_lineno": 258, "focal_method_end_lineno": 292} {"index": 268, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_HTTP_200_OK_PUT", "test_class_name": "TestRequests", "original_test_prefix": " def test_HTTP_200_OK_PUT(self, httpbin):\n r = requests.put(httpbin(\"put\"))\n assert r.status_code == 200", "test_prefix": " def test_HTTP_200_OK_PUT(self, httpbin):\n r = requests.put(httpbin(\"put\"))\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 525, "test_prefix_end_lineno": 527, "test_target": "tests/test_requests.py::TestRequests::test_HTTP_200_OK_PUT", "ground_truth_oracle": "assert r.status_code == 200", "ground_truth_oracle_lineno": 527, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def put(url, data=None, **kwargs):\n r\"\"\"Sends a PUT request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"put\", url, data=data, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 118, "focal_method_end_lineno": 130} {"index": 269, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_requests_history_is_saved", "test_class_name": "TestRequests", "original_test_prefix": " def test_requests_history_is_saved(self, httpbin):\n r = requests.get(httpbin(\"redirect/5\"))\n total = r.history[-1].history\n i = 0\n for item in r.history:\n assert item.history == total[0:i]\n i += 1", "test_prefix": " def test_requests_history_is_saved(self, httpbin):\n r = requests.get(httpbin(\"redirect/5\"))\n total = r.history[-1].history\n i = 0\n for item in r.history:\n \n i += 1", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 2099, "test_prefix_end_lineno": 2105, "test_target": "tests/test_requests.py::TestRequests::test_requests_history_is_saved", "ground_truth_oracle": "assert item.history == total[0:i]", "ground_truth_oracle_lineno": 2104, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 270, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_session_hooks_are_used_with_no_request_hooks", "test_class_name": "TestRequests", "original_test_prefix": " def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):\n def hook(*args, **kwargs):\n pass\n\n s = requests.Session()\n s.hooks[\"response\"].append(hook)\n r = requests.Request(\"GET\", httpbin())\n prep = s.prepare_request(r)\n assert prep.hooks[\"response\"] != []\n assert prep.hooks[\"response\"] == [hook]", "test_prefix": " def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):\n def hook(*args, **kwargs):\n pass\n\n s = requests.Session()\n s.hooks[\"response\"].append(hook)\n r = requests.Request(\"GET\", httpbin())\n prep = s.prepare_request(r)\n assert prep.hooks[\"response\"] != []\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1166, "test_prefix_end_lineno": 1175, "test_target": "tests/test_requests.py::TestRequests::test_session_hooks_are_used_with_no_request_hooks", "ground_truth_oracle": "assert prep.hooks[\"response\"] == [hook]", "ground_truth_oracle_lineno": 1175, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def prepare_request(self, request):\n \"\"\"Constructs a :class:`PreparedRequest ` for\n transmission and returns it. The :class:`PreparedRequest` has settings\n merged from the :class:`Request ` instance and those of the\n :class:`Session`.\n\n :param request: :class:`Request` instance to prepare with this\n session's settings.\n :rtype: requests.PreparedRequest\n \"\"\"\n cookies = request.cookies or {}\n\n # Bootstrap CookieJar.\n if not isinstance(cookies, cookielib.CookieJar):\n cookies = cookiejar_from_dict(cookies)\n\n # Merge with session cookies\n merged_cookies = merge_cookies(\n merge_cookies(RequestsCookieJar(), self.cookies), cookies\n )\n\n # Set environment's basic authentication if not explicitly set.\n auth = request.auth\n if self.trust_env and not auth and not self.auth:\n auth = get_netrc_auth(request.url)\n\n p = PreparedRequest()\n p.prepare(\n method=request.method.upper(),\n url=request.url,\n files=request.files,\n data=request.data,\n json=request.json,\n headers=merge_setting(\n request.headers, self.headers, dict_class=CaseInsensitiveDict\n ),\n params=merge_setting(request.params, self.params),\n auth=merge_setting(auth, self.auth),\n cookies=merged_cookies,\n hooks=merge_hooks(request.hooks, self.hooks),\n )\n return p", "focal_method_file_path": "src/requests/sessions.py", "focal_method_start_lineno": 457, "focal_method_end_lineno": 498} {"index": 271, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_http_303_doesnt_change_head_to_get", "test_class_name": "TestRequests", "original_test_prefix": " def test_http_303_doesnt_change_head_to_get(self, httpbin):\n r = requests.head(httpbin(\"status\", \"303\"), allow_redirects=True)\n assert r.status_code == 200\n assert r.request.method == \"HEAD\"\n assert r.history[0].status_code == 303\n assert r.history[0].is_redirect", "test_prefix": " def test_http_303_doesnt_change_head_to_get(self, httpbin):\n r = requests.head(httpbin(\"status\", \"303\"), allow_redirects=True)\n assert r.status_code == 200\n assert r.request.method == \"HEAD\"\n \n assert r.history[0].is_redirect", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 303, "test_prefix_end_lineno": 308, "test_target": "tests/test_requests.py::TestRequests::test_http_303_doesnt_change_head_to_get", "ground_truth_oracle": "assert r.history[0].status_code == 303", "ground_truth_oracle_lineno": 307, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def head(url, **kwargs):\n r\"\"\"Sends a HEAD request.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes. If\n `allow_redirects` is not provided, it will be set to `False` (as\n opposed to the default :meth:`request` behavior).\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n kwargs.setdefault(\"allow_redirects\", False)\n return request(\"head\", url, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 88, "focal_method_end_lineno": 100} {"index": 272, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_cookie_persists_via_api", "test_class_name": "TestRequests", "original_test_prefix": " def test_cookie_persists_via_api(self, httpbin):\n s = requests.session()\n r = s.get(httpbin(\"redirect/1\"), cookies={\"foo\": \"bar\"})\n assert \"foo\" in r.request.headers[\"Cookie\"]\n assert \"foo\" in r.history[0].request.headers[\"Cookie\"]", "test_prefix": " def test_cookie_persists_via_api(self, httpbin):\n s = requests.session()\n r = s.get(httpbin(\"redirect/1\"), cookies={\"foo\": \"bar\"})\n assert \"foo\" in r.request.headers[\"Cookie\"]\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 401, "test_prefix_end_lineno": 405, "test_target": "tests/test_requests.py::TestRequests::test_cookie_persists_via_api", "ground_truth_oracle": "assert \"foo\" in r.history[0].request.headers[\"Cookie\"]", "ground_truth_oracle_lineno": 405, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get(self, url, **kwargs):\n r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n \"\"\"\n\n kwargs.setdefault(\"allow_redirects\", True)\n return self.request(\"GET\", url, **kwargs)", "focal_method_file_path": "src/requests/sessions.py", "focal_method_start_lineno": 593, "focal_method_end_lineno": 602} {"index": 273, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_unicode_method_name", "test_class_name": "TestRequests", "original_test_prefix": " def test_unicode_method_name(self, httpbin):\n with open(__file__, \"rb\") as f:\n files = {\"file\": f}\n r = requests.request(\n method=\"POST\",\n url=httpbin(\"post\"),\n files=files,\n )\n assert r.status_code == 200", "test_prefix": " def test_unicode_method_name(self, httpbin):\n with open(__file__, \"rb\") as f:\n files = {\"file\": f}\n r = requests.request(\n method=\"POST\",\n url=httpbin(\"post\"),\n files=files,\n )\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1114, "test_prefix_end_lineno": 1122, "test_target": "tests/test_requests.py::TestRequests::test_unicode_method_name", "ground_truth_oracle": "assert r.status_code == 200", "ground_truth_oracle_lineno": 1122, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def request(method, url, **kwargs):\n \"\"\"Constructs and sends a :class:`Request `.\n\n :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.\n :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.\n :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.\n ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``\n or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string\n defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers\n to add for the file.\n :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.\n :param timeout: (optional) How many seconds to wait for the server to send data\n before giving up, as a float, or a :ref:`(connect timeout, read\n timeout) ` tuple.\n :type timeout: float or tuple\n :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.\n :type allow_redirects: bool\n :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.\n :param verify: (optional) Either a boolean, in which case it controls whether we verify\n the server's TLS certificate, or a string, in which case it must be a path\n to a CA bundle to use. Defaults to ``True``.\n :param stream: (optional) if ``False``, the response content will be immediately downloaded.\n :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.\n :return: :class:`Response ` object\n :rtype: requests.Response\n\n Usage::\n\n >>> import requests\n >>> req = requests.request('GET', 'https://httpbin.org/get')\n >>> req\n \n \"\"\"\n\n # By using the 'with' statement we are sure the session is closed, thus we\n # avoid leaving sockets open which can trigger a ResourceWarning in some\n # cases, and look like a memory leak in others.\n with sessions.Session() as session:\n return session.request(method=method, url=url, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 14, "focal_method_end_lineno": 59} {"index": 274, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_http_302_changes_post_to_get", "test_class_name": "TestRequests", "original_test_prefix": " def test_http_302_changes_post_to_get(self, httpbin):\n r = requests.post(httpbin(\"status\", \"302\"))\n assert r.status_code == 200\n assert r.request.method == \"GET\"\n assert r.history[0].status_code == 302\n assert r.history[0].is_redirect", "test_prefix": " def test_http_302_changes_post_to_get(self, httpbin):\n r = requests.post(httpbin(\"status\", \"302\"))\n assert r.status_code == 200\n assert r.request.method == \"GET\"\n assert r.history[0].status_code == 302\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 282, "test_prefix_end_lineno": 287, "test_target": "tests/test_requests.py::TestRequests::test_http_302_changes_post_to_get", "ground_truth_oracle": "assert r.history[0].is_redirect", "ground_truth_oracle_lineno": 287, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def post(url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"post\", url, data=data, json=json, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 103, "focal_method_end_lineno": 115} {"index": 275, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_default_hooks", "test_class_name": "", "original_test_prefix": "def test_default_hooks():\n assert hooks.default_hooks() == {\"response\": []}", "test_prefix": "def test_default_hooks():\n ", "test_prefix_file_path": "tests/test_hooks.py", "test_prefix_start_lineno": 21, "test_prefix_end_lineno": 22, "test_target": "tests/test_hooks.py::test_default_hooks", "ground_truth_oracle": "assert hooks.default_hooks() == {\"response\": []}", "ground_truth_oracle_lineno": 22, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def default_hooks():\n return {event: [] for event in HOOKS}", "focal_method_file_path": "src/requests/hooks.py", "focal_method_start_lineno": 15, "focal_method_end_lineno": 16} {"index": 276, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_idna_with_version_attribute", "test_class_name": "", "original_test_prefix": "def test_idna_with_version_attribute():\n \"\"\"Verify we're actually setting idna version when it should be available.\"\"\"\n with mock.patch(\"requests.help.idna\", new=VersionedPackage(\"2.6\")):\n assert info()[\"idna\"] == {\"version\": \"2.6\"}", "test_prefix": "def test_idna_with_version_attribute():\n \"\"\"Verify we're actually setting idna version when it should be available.\"\"\"\n with mock.patch(\"requests.help.idna\", new=VersionedPackage(\"2.6\")):\n ", "test_prefix_file_path": "tests/test_help.py", "test_prefix_start_lineno": 24, "test_prefix_end_lineno": 27, "test_target": "tests/test_help.py::test_idna_with_version_attribute", "ground_truth_oracle": "assert info()[\"idna\"] == {\"version\": \"2.6\"}", "ground_truth_oracle_lineno": 27, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def info():\n \"\"\"Generate information for a bug report.\"\"\"\n try:\n platform_info = {\n \"system\": platform.system(),\n \"release\": platform.release(),\n }\n except OSError:\n platform_info = {\n \"system\": \"Unknown\",\n \"release\": \"Unknown\",\n }\n\n implementation_info = _implementation()\n urllib3_info = {\"version\": urllib3.__version__}\n charset_normalizer_info = {\"version\": None}\n chardet_info = {\"version\": None}\n if charset_normalizer:\n charset_normalizer_info = {\"version\": charset_normalizer.__version__}\n if chardet:\n chardet_info = {\"version\": chardet.__version__}\n\n pyopenssl_info = {\n \"version\": None,\n \"openssl_version\": \"\",\n }\n if OpenSSL:\n pyopenssl_info = {\n \"version\": OpenSSL.__version__,\n \"openssl_version\": f\"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}\",\n }\n cryptography_info = {\n \"version\": getattr(cryptography, \"__version__\", \"\"),\n }\n idna_info = {\n \"version\": getattr(idna, \"__version__\", \"\"),\n }\n\n system_ssl = ssl.OPENSSL_VERSION_NUMBER\n system_ssl_info = {\"version\": f\"{system_ssl:x}\" if system_ssl is not None else \"\"}\n\n return {\n \"platform\": platform_info,\n \"implementation\": implementation_info,\n \"system_ssl\": system_ssl_info,\n \"using_pyopenssl\": pyopenssl is not None,\n \"using_charset_normalizer\": chardet is None,\n \"pyOpenSSL\": pyopenssl_info,\n \"urllib3\": urllib3_info,\n \"chardet\": chardet_info,\n \"charset_normalizer\": charset_normalizer_info,\n \"cryptography\": cryptography_info,\n \"idna\": idna_info,\n \"requests\": {\n \"version\": requests_version,\n },\n }", "focal_method_file_path": "src/requests/help.py", "focal_method_start_lineno": 69, "focal_method_end_lineno": 125} {"index": 277, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_different_encodings_dont_break_post", "test_class_name": "TestRequests", "original_test_prefix": " def test_different_encodings_dont_break_post(self, httpbin):\n with open(__file__, \"rb\") as f:\n r = requests.post(\n httpbin(\"post\"),\n data={\"stuff\": json.dumps({\"a\": 123})},\n params={\"blah\": \"asdf1234\"},\n files={\"file\": (\"test_requests.py\", f)},\n )\n assert r.status_code == 200", "test_prefix": " def test_different_encodings_dont_break_post(self, httpbin):\n with open(__file__, \"rb\") as f:\n r = requests.post(\n httpbin(\"post\"),\n data={\"stuff\": json.dumps({\"a\": 123})},\n params={\"blah\": \"asdf1234\"},\n files={\"file\": (\"test_requests.py\", f)},\n )\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1072, "test_prefix_end_lineno": 1080, "test_target": "tests/test_requests.py::TestRequests::test_different_encodings_dont_break_post", "ground_truth_oracle": "assert r.status_code == 200", "ground_truth_oracle_lineno": 1080, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def post(url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"post\", url, data=data, json=json, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 103, "focal_method_end_lineno": 115} {"index": 278, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_lower_items", "test_class_name": "TestCaseInsensitiveDict", "original_test_prefix": " def test_lower_items(self):\n cid = CaseInsensitiveDict(\n {\n \"Accept\": \"application/json\",\n \"user-Agent\": \"requests\",\n }\n )\n keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())\n lowerkeyset = frozenset([\"accept\", \"user-agent\"])\n assert keyset == lowerkeyset", "test_prefix": " def test_lower_items(self):\n cid = CaseInsensitiveDict(\n {\n \"Accept\": \"application/json\",\n \"user-Agent\": \"requests\",\n }\n )\n keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())\n lowerkeyset = frozenset([\"accept\", \"user-agent\"])\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 2378, "test_prefix_end_lineno": 2387, "test_target": "tests/test_requests.py::TestCaseInsensitiveDict::test_lower_items", "ground_truth_oracle": "assert keyset == lowerkeyset", "ground_truth_oracle_lineno": 2387, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def lower_items(self):\n \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())", "focal_method_file_path": "src/requests/structures.py", "focal_method_start_lineno": 63, "focal_method_end_lineno": 65} {"index": 279, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_uppercase_scheme_redirect", "test_class_name": "TestRequests", "original_test_prefix": " def test_uppercase_scheme_redirect(self, httpbin):\n parts = urlparse(httpbin(\"html\"))\n url = \"HTTP://\" + parts.netloc + parts.path\n r = requests.get(httpbin(\"redirect-to\"), params={\"url\": url})\n assert r.status_code == 200\n assert r.url.lower() == url.lower()", "test_prefix": " def test_uppercase_scheme_redirect(self, httpbin):\n parts = urlparse(httpbin(\"html\"))\n url = \"HTTP://\" + parts.netloc + parts.path\n r = requests.get(httpbin(\"redirect-to\"), params={\"url\": url})\n \n assert r.url.lower() == url.lower()", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1606, "test_prefix_end_lineno": 1611, "test_target": "tests/test_requests.py::TestRequests::test_uppercase_scheme_redirect", "ground_truth_oracle": "assert r.status_code == 200", "ground_truth_oracle_lineno": 1610, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 280, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_invalid_files_input", "test_class_name": "TestRequests", "original_test_prefix": " def test_invalid_files_input(self, httpbin):\n url = httpbin(\"post\")\n post = requests.post(url, files={\"random-file-1\": None, \"random-file-2\": 1})\n assert b'name=\"random-file-1\"' not in post.request.body\n assert b'name=\"random-file-2\"' in post.request.body", "test_prefix": " def test_invalid_files_input(self, httpbin):\n url = httpbin(\"post\")\n post = requests.post(url, files={\"random-file-1\": None, \"random-file-2\": 1})\n \n assert b'name=\"random-file-2\"' in post.request.body", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 825, "test_prefix_end_lineno": 829, "test_target": "tests/test_requests.py::TestRequests::test_invalid_files_input", "ground_truth_oracle": "assert b'name=\"random-file-1\"' not in post.request.body", "ground_truth_oracle_lineno": 828, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def post(url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"post\", url, data=data, json=json, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 103, "focal_method_end_lineno": 115} {"index": 281, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE", "test_class_name": "TestRequests", "original_test_prefix": " def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):\n byte_str = b\"test\"\n r = requests.post(\n httpbin(\"redirect-to\"),\n data=io.BytesIO(byte_str),\n params={\"url\": \"post\", \"status_code\": 307},\n )\n assert r.status_code == 200\n assert r.history[0].status_code == 307\n assert r.history[0].is_redirect\n assert r.json()[\"data\"] == byte_str.decode(\"utf-8\")", "test_prefix": " def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):\n byte_str = b\"test\"\n r = requests.post(\n httpbin(\"redirect-to\"),\n data=io.BytesIO(byte_str),\n params={\"url\": \"post\", \"status_code\": 307},\n )\n assert r.status_code == 200\n \n assert r.history[0].is_redirect\n assert r.json()[\"data\"] == byte_str.decode(\"utf-8\")", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 229, "test_prefix_end_lineno": 239, "test_target": "tests/test_requests.py::TestRequests::test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE", "ground_truth_oracle": "assert r.history[0].status_code == 307", "ground_truth_oracle_lineno": 237, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def post(url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"post\", url, data=data, json=json, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 103, "focal_method_end_lineno": 115} {"index": 282, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_basic_response", "test_class_name": "TestTestServer", "original_test_prefix": " def test_basic_response(self):\n \"\"\"the basic response server returns an empty http response\"\"\"\n with Server.basic_response_server() as (host, port):\n r = requests.get(f\"http://{host}:{port}\")\n assert r.status_code == 200\n assert r.text == \"\"\n assert r.headers[\"Content-Length\"] == \"0\"", "test_prefix": " def test_basic_response(self):\n \"\"\"the basic response server returns an empty http response\"\"\"\n with Server.basic_response_server() as (host, port):\n r = requests.get(f\"http://{host}:{port}\")\n assert r.status_code == 200\n \n assert r.headers[\"Content-Length\"] == \"0\"", "test_prefix_file_path": "tests/test_testserver.py", "test_prefix_start_lineno": 55, "test_prefix_end_lineno": 61, "test_target": "tests/test_testserver.py::TestTestServer::test_basic_response", "ground_truth_oracle": "assert r.text == \"\"", "ground_truth_oracle_lineno": 60, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 283, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_time_elapsed_blank", "test_class_name": "TestRequests", "original_test_prefix": " def test_time_elapsed_blank(self, httpbin):\n r = requests.get(httpbin(\"get\"))\n td = r.elapsed\n total_seconds = (\n td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6\n ) / 10**6\n assert total_seconds > 0.0", "test_prefix": " def test_time_elapsed_blank(self, httpbin):\n r = requests.get(httpbin(\"get\"))\n td = r.elapsed\n total_seconds = (\n td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6\n ) / 10**6\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1409, "test_prefix_end_lineno": 1415, "test_target": "tests/test_requests.py::TestRequests::test_time_elapsed_blank", "ground_truth_oracle": "assert total_seconds > 0.0", "ground_truth_oracle_lineno": 1415, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 284, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_request_ok_set", "test_class_name": "TestRequests", "original_test_prefix": " def test_request_ok_set(self, httpbin):\n r = requests.get(httpbin(\"status\", \"404\"))\n assert not r.ok", "test_prefix": " def test_request_ok_set(self, httpbin):\n r = requests.get(httpbin(\"status\", \"404\"))\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 920, "test_prefix_end_lineno": 922, "test_target": "tests/test_requests.py::TestRequests::test_request_ok_set", "ground_truth_oracle": "assert not r.ok", "ground_truth_oracle_lineno": 922, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 285, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_POSTBIN_GET_POST_FILES_WITH_DATA", "test_class_name": "TestRequests", "original_test_prefix": " def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):\n url = httpbin(\"post\")\n requests.post(url).raise_for_status()\n\n post1 = requests.post(url, data={\"some\": \"data\"})\n assert post1.status_code == 200\n\n with open(\"requirements-dev.txt\") as f:\n post2 = requests.post(url, data={\"some\": \"data\"}, files={\"some\": f})\n assert post2.status_code == 200\n\n post4 = requests.post(url, data='[{\"some\": \"json\"}]')\n assert post4.status_code == 200\n\n with pytest.raises(ValueError):\n requests.post(url, files=[\"bad file data\"])", "test_prefix": " def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):\n url = httpbin(\"post\")\n requests.post(url).raise_for_status()\n\n post1 = requests.post(url, data={\"some\": \"data\"})\n assert post1.status_code == 200\n\n with open(\"requirements-dev.txt\") as f:\n post2 = requests.post(url, data={\"some\": \"data\"}, files={\"some\": f})\n \n\n post4 = requests.post(url, data='[{\"some\": \"json\"}]')\n assert post4.status_code == 200\n\n with pytest.raises(ValueError):\n requests.post(url, files=[\"bad file data\"])", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 872, "test_prefix_end_lineno": 887, "test_target": "tests/test_requests.py::TestRequests::test_POSTBIN_GET_POST_FILES_WITH_DATA", "ground_truth_oracle": "assert post2.status_code == 200", "ground_truth_oracle_lineno": 881, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def post(url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"post\", url, data=data, json=json, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 103, "focal_method_end_lineno": 115} {"index": 286, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_http_301_doesnt_change_head_to_get", "test_class_name": "TestRequests", "original_test_prefix": " def test_http_301_doesnt_change_head_to_get(self, httpbin):\n r = requests.head(httpbin(\"status\", \"301\"), allow_redirects=True)\n print(r.content)\n assert r.status_code == 200\n assert r.request.method == \"HEAD\"\n assert r.history[0].status_code == 301\n assert r.history[0].is_redirect", "test_prefix": " def test_http_301_doesnt_change_head_to_get(self, httpbin):\n r = requests.head(httpbin(\"status\", \"301\"), allow_redirects=True)\n print(r.content)\n \n assert r.request.method == \"HEAD\"\n assert r.history[0].status_code == 301\n assert r.history[0].is_redirect", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 274, "test_prefix_end_lineno": 280, "test_target": "tests/test_requests.py::TestRequests::test_http_301_doesnt_change_head_to_get", "ground_truth_oracle": "assert r.status_code == 200", "ground_truth_oracle_lineno": 277, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def head(url, **kwargs):\n r\"\"\"Sends a HEAD request.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes. If\n `allow_redirects` is not provided, it will be set to `False` (as\n opposed to the default :meth:`request` behavior).\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n kwargs.setdefault(\"allow_redirects\", False)\n return request(\"head\", url, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 88, "focal_method_end_lineno": 100} {"index": 287, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_auth_is_retained_for_redirect_on_host", "test_class_name": "TestRequests", "original_test_prefix": " def test_auth_is_retained_for_redirect_on_host(self, httpbin):\n r = requests.get(httpbin(\"redirect/1\"), auth=(\"user\", \"pass\"))\n h1 = r.history[0].request.headers[\"Authorization\"]\n h2 = r.request.headers[\"Authorization\"]\n\n assert h1 == h2", "test_prefix": " def test_auth_is_retained_for_redirect_on_host(self, httpbin):\n r = requests.get(httpbin(\"redirect/1\"), auth=(\"user\", \"pass\"))\n h1 = r.history[0].request.headers[\"Authorization\"]\n h2 = r.request.headers[\"Authorization\"]\n\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1894, "test_prefix_end_lineno": 1899, "test_target": "tests/test_requests.py::TestRequests::test_auth_is_retained_for_redirect_on_host", "ground_truth_oracle": "assert h1 == h2", "ground_truth_oracle_lineno": 1899, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 288, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_header_with_subclass_types", "test_class_name": "TestRequests", "original_test_prefix": " def test_header_with_subclass_types(self, httpbin):\n \"\"\"If the subclasses does not behave *exactly* like\n the base bytes/str classes, this is not supported.\n This test is for backwards compatibility.\n \"\"\"\n\n class MyString(str):\n pass\n\n class MyBytes(bytes):\n pass\n\n r_str = requests.get(httpbin(\"get\"), headers={MyString(\"x-custom\"): \"myheader\"})\n assert r_str.request.headers[\"x-custom\"] == \"myheader\"\n\n r_bytes = requests.get(\n httpbin(\"get\"), headers={MyBytes(b\"x-custom\"): b\"myheader\"}\n )\n assert r_bytes.request.headers[\"x-custom\"] == b\"myheader\"\n\n r_mixed = requests.get(\n httpbin(\"get\"), headers={MyString(\"x-custom\"): MyBytes(b\"myheader\")}\n )\n assert r_mixed.request.headers[\"x-custom\"] == b\"myheader\"", "test_prefix": " def test_header_with_subclass_types(self, httpbin):\n \"\"\"If the subclasses does not behave *exactly* like\n the base bytes/str classes, this is not supported.\n This test is for backwards compatibility.\n \"\"\"\n\n class MyString(str):\n pass\n\n class MyBytes(bytes):\n pass\n\n r_str = requests.get(httpbin(\"get\"), headers={MyString(\"x-custom\"): \"myheader\"})\n assert r_str.request.headers[\"x-custom\"] == \"myheader\"\n\n r_bytes = requests.get(\n httpbin(\"get\"), headers={MyBytes(b\"x-custom\"): b\"myheader\"}\n )\n assert r_bytes.request.headers[\"x-custom\"] == b\"myheader\"\n\n r_mixed = requests.get(\n httpbin(\"get\"), headers={MyString(\"x-custom\"): MyBytes(b\"myheader\")}\n )\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1822, "test_prefix_end_lineno": 1845, "test_target": "tests/test_requests.py::TestRequests::test_header_with_subclass_types", "ground_truth_oracle": "assert r_mixed.request.headers[\"x-custom\"] == b\"myheader\"", "ground_truth_oracle_lineno": 1845, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 289, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_invalid", "test_class_name": "TestAddressInNetwork", "original_test_prefix": " def test_invalid(self):\n assert not address_in_network(\"172.16.0.1\", \"192.168.1.0/24\")", "test_prefix": " def test_invalid(self):\n ", "test_prefix_file_path": "tests/test_utils.py", "test_prefix_start_lineno": 306, "test_prefix_end_lineno": 307, "test_target": "tests/test_utils.py::TestAddressInNetwork::test_invalid", "ground_truth_oracle": "assert not address_in_network(\"172.16.0.1\", \"192.168.1.0/24\")", "ground_truth_oracle_lineno": 307, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def address_in_network(ip, net):\n \"\"\"This function allows you to check if an IP belongs to a network subnet\n\n Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24\n returns False if ip = 192.168.1.1 and net = 192.168.100.0/24\n\n :rtype: bool\n \"\"\"\n ipaddr = struct.unpack(\"=L\", socket.inet_aton(ip))[0]\n netaddr, bits = net.split(\"/\")\n netmask = struct.unpack(\"=L\", socket.inet_aton(dotted_netmask(int(bits))))[0]\n network = struct.unpack(\"=L\", socket.inet_aton(netaddr))[0] & netmask\n return (ipaddr & netmask) == (network & netmask)", "focal_method_file_path": "src/requests/utils.py", "focal_method_start_lineno": 672, "focal_method_end_lineno": 684} {"index": 290, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_stream_with_auth_does_not_set_transfer_encoding_header", "test_class_name": "TestRequests", "original_test_prefix": " def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):\n \"\"\"Ensure that a byte stream with size > 0 will not set both a Content-Length\n and Transfer-Encoding header.\n \"\"\"\n auth = (\"user\", \"pass\")\n url = httpbin(\"post\")\n file_obj = io.BytesIO(b\"test data\")\n r = requests.Request(\"POST\", url, auth=auth, data=file_obj)\n prepared_request = r.prepare()\n assert \"Transfer-Encoding\" not in prepared_request.headers\n assert \"Content-Length\" in prepared_request.headers", "test_prefix": " def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):\n \"\"\"Ensure that a byte stream with size > 0 will not set both a Content-Length\n and Transfer-Encoding header.\n \"\"\"\n auth = (\"user\", \"pass\")\n url = httpbin(\"post\")\n file_obj = io.BytesIO(b\"test data\")\n r = requests.Request(\"POST\", url, auth=auth, data=file_obj)\n prepared_request = r.prepare()\n \n assert \"Content-Length\" in prepared_request.headers", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 2209, "test_prefix_end_lineno": 2219, "test_target": "tests/test_requests.py::TestRequests::test_stream_with_auth_does_not_set_transfer_encoding_header", "ground_truth_oracle": "assert \"Transfer-Encoding\" not in prepared_request.headers", "ground_truth_oracle_lineno": 2218, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def prepare(self):\n \"\"\"Constructs a :class:`PreparedRequest ` for transmission and returns it.\"\"\"\n p = PreparedRequest()\n p.prepare(\n method=self.method,\n url=self.url,\n headers=self.headers,\n files=self.files,\n data=self.data,\n json=self.json,\n params=self.params,\n auth=self.auth,\n cookies=self.cookies,\n hooks=self.hooks,\n )\n return p", "focal_method_file_path": "src/requests/models.py", "focal_method_start_lineno": 295, "focal_method_end_lineno": 310} {"index": 291, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_HTTP_200_OK_HEAD", "test_class_name": "TestRequests", "original_test_prefix": " def test_HTTP_200_OK_HEAD(self, httpbin):\n r = requests.head(httpbin(\"get\"))\n assert r.status_code == 200", "test_prefix": " def test_HTTP_200_OK_HEAD(self, httpbin):\n r = requests.head(httpbin(\"get\"))\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 521, "test_prefix_end_lineno": 523, "test_target": "tests/test_requests.py::TestRequests::test_HTTP_200_OK_HEAD", "ground_truth_oracle": "assert r.status_code == 200", "ground_truth_oracle_lineno": 523, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def head(url, **kwargs):\n r\"\"\"Sends a HEAD request.\n\n :param url: URL for the new :class:`Request` object.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes. If\n `allow_redirects` is not provided, it will be set to `False` (as\n opposed to the default :meth:`request` behavior).\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n kwargs.setdefault(\"allow_redirects\", False)\n return request(\"head\", url, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 88, "focal_method_end_lineno": 100} {"index": 292, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_max_age_valid_int", "test_class_name": "TestMorselToCookieMaxAge", "original_test_prefix": " def test_max_age_valid_int(self):\n \"\"\"Test case where a valid max age in seconds is passed.\"\"\"\n\n morsel = Morsel()\n morsel[\"max-age\"] = 60\n cookie = morsel_to_cookie(morsel)\n assert isinstance(cookie.expires, int)", "test_prefix": " def test_max_age_valid_int(self):\n \"\"\"Test case where a valid max age in seconds is passed.\"\"\"\n\n morsel = Morsel()\n morsel[\"max-age\"] = 60\n cookie = morsel_to_cookie(morsel)\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 2466, "test_prefix_end_lineno": 2472, "test_target": "tests/test_requests.py::TestMorselToCookieMaxAge::test_max_age_valid_int", "ground_truth_oracle": "assert isinstance(cookie.expires, int)", "ground_truth_oracle_lineno": 2472, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def morsel_to_cookie(morsel):\n \"\"\"Convert a Morsel object into a Cookie containing the one k/v pair.\"\"\"\n\n expires = None\n if morsel[\"max-age\"]:\n try:\n expires = int(time.time() + int(morsel[\"max-age\"]))\n except ValueError:\n raise TypeError(f\"max-age: {morsel['max-age']} must be integer\")\n elif morsel[\"expires\"]:\n time_template = \"%a, %d-%b-%Y %H:%M:%S GMT\"\n expires = calendar.timegm(time.strptime(morsel[\"expires\"], time_template))\n return create_cookie(\n comment=morsel[\"comment\"],\n comment_url=bool(morsel[\"comment\"]),\n discard=False,\n domain=morsel[\"domain\"],\n expires=expires,\n name=morsel.key,\n path=morsel[\"path\"],\n port=None,\n rest={\"HttpOnly\": morsel[\"httponly\"]},\n rfc2109=False,\n secure=bool(morsel[\"secure\"]),\n value=morsel.value,\n version=morsel[\"version\"] or 0,\n )", "focal_method_file_path": "src/requests/cookies.py", "focal_method_start_lineno": 492, "focal_method_end_lineno": 518} {"index": 293, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_none", "test_class_name": "TestContentEncodingDetection", "original_test_prefix": " def test_none(self):\n encodings = get_encodings_from_content(\"\")\n assert not len(encodings)", "test_prefix": " def test_none(self):\n encodings = get_encodings_from_content(\"\")\n ", "test_prefix_file_path": "tests/test_utils.py", "test_prefix_start_lineno": 364, "test_prefix_end_lineno": 366, "test_target": "tests/test_utils.py::TestContentEncodingDetection::test_none", "ground_truth_oracle": "assert not len(encodings)", "ground_truth_oracle_lineno": 366, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_encodings_from_content(content):\n \"\"\"Returns encodings from given content string.\n\n :param content: bytestring to extract encodings from.\n \"\"\"\n warnings.warn(\n (\n \"In requests 3.0, get_encodings_from_content will be removed. For \"\n \"more information, please see the discussion on issue #2266. (This\"\n \" warning should only appear once.)\"\n ),\n DeprecationWarning,\n )\n\n charset_re = re.compile(r']', flags=re.I)\n pragma_re = re.compile(r']', flags=re.I)\n xml_re = re.compile(r'^<\\?xml.*?encoding=[\"\\']*(.+?)[\"\\'>]')\n\n return (\n charset_re.findall(content)\n + pragma_re.findall(content)\n + xml_re.findall(content)\n )", "focal_method_file_path": "src/requests/utils.py", "focal_method_start_lineno": 479, "focal_method_end_lineno": 501} {"index": 294, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_urlencoded_get_query_multivalued_param", "test_class_name": "TestRequests", "original_test_prefix": " def test_urlencoded_get_query_multivalued_param(self, httpbin):\n r = requests.get(httpbin(\"get\"), params={\"test\": [\"foo\", \"baz\"]})\n assert r.status_code == 200\n assert r.url == httpbin(\"get?test=foo&test=baz\")", "test_prefix": " def test_urlencoded_get_query_multivalued_param(self, httpbin):\n r = requests.get(httpbin(\"get\"), params={\"test\": [\"foo\", \"baz\"]})\n \n assert r.url == httpbin(\"get?test=foo&test=baz\")", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1060, "test_prefix_end_lineno": 1063, "test_target": "tests/test_requests.py::TestRequests::test_urlencoded_get_query_multivalued_param", "ground_truth_oracle": "assert r.status_code == 200", "ground_truth_oracle_lineno": 1062, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary, list of tuples or bytes to send\n in the query string for the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"get\", url, params=params, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 62, "focal_method_end_lineno": 73} {"index": 295, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_chunked_upload", "test_class_name": "", "original_test_prefix": "def test_chunked_upload():\n \"\"\"can safely send generators\"\"\"\n close_server = threading.Event()\n server = Server.basic_response_server(wait_to_close_event=close_server)\n data = iter([b\"a\", b\"b\", b\"c\"])\n\n with server as (host, port):\n url = f\"http://{host}:{port}/\"\n r = requests.post(url, data=data, stream=True)\n close_server.set() # release server block\n\n assert r.status_code == 200\n assert r.request.headers[\"Transfer-Encoding\"] == \"chunked\"", "test_prefix": "def test_chunked_upload():\n \"\"\"can safely send generators\"\"\"\n close_server = threading.Event()\n server = Server.basic_response_server(wait_to_close_event=close_server)\n data = iter([b\"a\", b\"b\", b\"c\"])\n\n with server as (host, port):\n url = f\"http://{host}:{port}/\"\n r = requests.post(url, data=data, stream=True)\n close_server.set() # release server block\n\n assert r.status_code == 200\n ", "test_prefix_file_path": "tests/test_lowlevel.py", "test_prefix_start_lineno": 24, "test_prefix_end_lineno": 36, "test_target": "tests/test_lowlevel.py::test_chunked_upload", "ground_truth_oracle": "assert r.request.headers[\"Transfer-Encoding\"] == \"chunked\"", "ground_truth_oracle_lineno": 36, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def post(url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n\n return request(\"post\", url, data=data, json=json, **kwargs)", "focal_method_file_path": "src/requests/api.py", "focal_method_start_lineno": 103, "focal_method_end_lineno": 115} {"index": 296, "repo_name": "requests", "github": "https://github.com/psf/requests.git", "version": "v2.32.5", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\npip install -r requirements-dev.txt\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_form_encoded_post_query_multivalued_element", "test_class_name": "TestRequests", "original_test_prefix": " def test_form_encoded_post_query_multivalued_element(self, httpbin):\n r = requests.Request(\n method=\"POST\", url=httpbin(\"post\"), data=dict(test=[\"foo\", \"baz\"])\n )\n prep = r.prepare()\n assert prep.body == \"test=foo&test=baz\"", "test_prefix": " def test_form_encoded_post_query_multivalued_element(self, httpbin):\n r = requests.Request(\n method=\"POST\", url=httpbin(\"post\"), data=dict(test=[\"foo\", \"baz\"])\n )\n prep = r.prepare()\n ", "test_prefix_file_path": "tests/test_requests.py", "test_prefix_start_lineno": 1065, "test_prefix_end_lineno": 1070, "test_target": "tests/test_requests.py::TestRequests::test_form_encoded_post_query_multivalued_element", "ground_truth_oracle": "assert prep.body == \"test=foo&test=baz\"", "ground_truth_oracle_lineno": 1070, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def prepare(self):\n \"\"\"Constructs a :class:`PreparedRequest ` for transmission and returns it.\"\"\"\n p = PreparedRequest()\n p.prepare(\n method=self.method,\n url=self.url,\n headers=self.headers,\n files=self.files,\n data=self.data,\n json=self.json,\n params=self.params,\n auth=self.auth,\n cookies=self.cookies,\n hooks=self.hooks,\n )\n return p", "focal_method_file_path": "src/requests/models.py", "focal_method_start_lineno": 295, "focal_method_end_lineno": 310} {"index": 297, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ansi_in_pretty_repr", "test_class_name": "", "original_test_prefix": "def test_ansi_in_pretty_repr() -> None:\n class Hello:\n def __repr__(self):\n return \"Hello \\x1b[38;5;239mWorld!\"\n\n pretty = Pretty(Hello())\n\n console = Console(file=io.StringIO(), record=True)\n console.print(pretty)\n result = console.export_text()\n\n assert result == \"Hello World!\\n\"", "test_prefix": "def test_ansi_in_pretty_repr() -> None:\n class Hello:\n def __repr__(self):\n return \"Hello \\x1b[38;5;239mWorld!\"\n\n pretty = Pretty(Hello())\n\n console = Console(file=io.StringIO(), record=True)\n console.print(pretty)\n result = console.export_text()\n\n ", "test_prefix_file_path": "tests/test_pretty.py", "test_prefix_start_lineno": 274, "test_prefix_end_lineno": 285, "test_target": "tests/test_pretty.py::test_ansi_in_pretty_repr", "ground_truth_oracle": "assert result == \"Hello World!\\n\"", "ground_truth_oracle_lineno": 285, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def export_text(self, *, clear: bool = True, styles: bool = False) -> str:\n \"\"\"Generate text from console contents (requires record=True argument in constructor).\n\n Args:\n clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\n styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text.\n Defaults to ``False``.\n\n Returns:\n str: String containing console contents.\n\n \"\"\"\n assert (\n self.record\n ), \"To export console contents set record=True in the constructor or instance\"\n\n with self._record_buffer_lock:\n if styles:\n text = \"\".join(\n (style.render(text) if style else text)\n for text, style, _ in self._record_buffer\n )\n else:\n text = \"\".join(\n segment.text\n for segment in self._record_buffer\n if not segment.control\n )\n if clear:\n del self._record_buffer[:]\n return text", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 2173, "focal_method_end_lineno": 2203} {"index": 298, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_indent", "test_class_name": "", "original_test_prefix": "def test_indent():\n indent_result = Padding.indent(\"test\", 4)\n assert indent_result.top == 0\n assert indent_result.right == 0\n assert indent_result.bottom == 0\n assert indent_result.left == 4", "test_prefix": "def test_indent():\n indent_result = Padding.indent(\"test\", 4)\n assert indent_result.top == 0\n assert indent_result.right == 0\n assert indent_result.bottom == 0\n ", "test_prefix_file_path": "tests/test_padding.py", "test_prefix_start_lineno": 14, "test_prefix_end_lineno": 19, "test_target": "tests/test_padding.py::test_indent", "ground_truth_oracle": "assert indent_result.left == 4", "ground_truth_oracle_lineno": 19, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def indent(cls, renderable: \"RenderableType\", level: int) -> \"Padding\":\n \"\"\"Make padding instance to render an indent.\n\n Args:\n renderable (RenderableType): String or other renderable.\n level (int): Number of characters to indent.\n\n Returns:\n Padding: A Padding instance.\n \"\"\"\n\n return Padding(renderable, pad=(0, 0, 0, level), expand=False)", "focal_method_file_path": "rich/padding.py", "focal_method_start_lineno": 46, "focal_method_end_lineno": 58} {"index": 299, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_read", "test_class_name": "", "original_test_prefix": "def test_read():\n theme = Theme({\"warning\": \"red\"})\n with tempfile.TemporaryDirectory(\"richtheme\") as name:\n filename = os.path.join(name, \"theme.cfg\")\n with open(filename, \"wt\") as write_theme:\n write_theme.write(theme.config)\n load_theme = Theme.read(filename)\n assert theme.styles == load_theme.styles", "test_prefix": "def test_read():\n theme = Theme({\"warning\": \"red\"})\n with tempfile.TemporaryDirectory(\"richtheme\") as name:\n filename = os.path.join(name, \"theme.cfg\")\n with open(filename, \"wt\") as write_theme:\n write_theme.write(theme.config)\n load_theme = Theme.read(filename)\n ", "test_prefix_file_path": "tests/test_theme.py", "test_prefix_start_lineno": 33, "test_prefix_end_lineno": 40, "test_target": "tests/test_theme.py::test_read", "ground_truth_oracle": "assert theme.styles == load_theme.styles", "ground_truth_oracle_lineno": 40, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def read(\n cls, path: str, inherit: bool = True, encoding: Optional[str] = None\n ) -> \"Theme\":\n \"\"\"Read a theme from a path.\n\n Args:\n path (str): Path to a config file readable by Python configparser module.\n inherit (bool, optional): Inherit default styles. Defaults to True.\n encoding (str, optional): Encoding of the config file. Defaults to None.\n\n Returns:\n Theme: A new theme instance.\n \"\"\"\n with open(path, encoding=encoding) as config_file:\n return cls.from_file(config_file, source=path, inherit=inherit)", "focal_method_file_path": "rich/theme.py", "focal_method_start_lineno": 58, "focal_method_end_lineno": 73} {"index": 300, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_chop_cells_mixed_width", "test_class_name": "", "original_test_prefix": "def test_chop_cells_mixed_width():\n \"\"\"Mixed single and double-width characters.\"\"\"\n text = \"\u30421\u308a234\u304c5\u30686\u304678\"\n assert chop_cells(text, 3) == [\"\u30421\", \"\u308a2\", \"34\", \"\u304c5\", \"\u30686\", \"\u30467\", \"8\"]", "test_prefix": "def test_chop_cells_mixed_width():\n \"\"\"Mixed single and double-width characters.\"\"\"\n text = \"\u30421\u308a234\u304c5\u30686\u304678\"\n ", "test_prefix_file_path": "tests/test_cells.py", "test_prefix_start_lineno": 60, "test_prefix_end_lineno": 63, "test_target": "tests/test_cells.py::test_chop_cells_mixed_width", "ground_truth_oracle": "assert chop_cells(text, 3) == [\"\u30421\", \"\u308a2\", \"34\", \"\u304c5\", \"\u30686\", \"\u30467\", \"8\"]", "ground_truth_oracle_lineno": 63, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def chop_cells(\n text: str,\n width: int,\n) -> list[str]:\n \"\"\"Split text into lines such that each line fits within the available (cell) width.\n\n Args:\n text: The text to fold such that it fits in the given width.\n width: The width available (number of cells).\n\n Returns:\n A list of strings such that each string in the list has cell width\n less than or equal to the available width.\n \"\"\"\n _get_character_cell_size = get_character_cell_size\n lines: list[list[str]] = [[]]\n\n append_new_line = lines.append\n append_to_last_line = lines[-1].append\n\n total_width = 0\n\n for character in text:\n cell_width = _get_character_cell_size(character)\n char_doesnt_fit = total_width + cell_width > width\n\n if char_doesnt_fit:\n append_new_line([character])\n append_to_last_line = lines[-1].append\n total_width = cell_width\n else:\n append_to_last_line(character)\n total_width += cell_width\n\n return [\"\".join(line) for line in lines]", "focal_method_file_path": "rich/cells.py", "focal_method_start_lineno": 131, "focal_method_end_lineno": 165} {"index": 301, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_chop_cells_double_width_boundary", "test_class_name": "", "original_test_prefix": "def test_chop_cells_double_width_boundary():\n \"\"\"The available width lies within a double-width character.\"\"\"\n text = \"\u3042\u308a\u304c\u3068\u3046\"\n assert chop_cells(text, 3) == [\"\u3042\", \"\u308a\", \"\u304c\", \"\u3068\", \"\u3046\"]", "test_prefix": "def test_chop_cells_double_width_boundary():\n \"\"\"The available width lies within a double-width character.\"\"\"\n text = \"\u3042\u308a\u304c\u3068\u3046\"\n ", "test_prefix_file_path": "tests/test_cells.py", "test_prefix_start_lineno": 54, "test_prefix_end_lineno": 57, "test_target": "tests/test_cells.py::test_chop_cells_double_width_boundary", "ground_truth_oracle": "assert chop_cells(text, 3) == [\"\u3042\", \"\u308a\", \"\u304c\", \"\u3068\", \"\u3046\"]", "ground_truth_oracle_lineno": 57, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def chop_cells(\n text: str,\n width: int,\n) -> list[str]:\n \"\"\"Split text into lines such that each line fits within the available (cell) width.\n\n Args:\n text: The text to fold such that it fits in the given width.\n width: The width available (number of cells).\n\n Returns:\n A list of strings such that each string in the list has cell width\n less than or equal to the available width.\n \"\"\"\n _get_character_cell_size = get_character_cell_size\n lines: list[list[str]] = [[]]\n\n append_new_line = lines.append\n append_to_last_line = lines[-1].append\n\n total_width = 0\n\n for character in text:\n cell_width = _get_character_cell_size(character)\n char_doesnt_fit = total_width + cell_width > width\n\n if char_doesnt_fit:\n append_new_line([character])\n append_to_last_line = lines[-1].append\n total_width = cell_width\n else:\n append_to_last_line(character)\n total_width += cell_width\n\n return [\"\".join(line) for line in lines]", "focal_method_file_path": "rich/cells.py", "focal_method_start_lineno": 131, "focal_method_end_lineno": 165} {"index": 302, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_reconfigure_console", "test_class_name": "", "original_test_prefix": "def test_reconfigure_console():\n rich.reconfigure(width=100)\n assert rich.get_console().width == 100", "test_prefix": "def test_reconfigure_console():\n rich.reconfigure(width=100)\n ", "test_prefix_file_path": "tests/test_rich_print.py", "test_prefix_start_lineno": 13, "test_prefix_end_lineno": 15, "test_target": "tests/test_rich_print.py::test_reconfigure_console", "ground_truth_oracle": "assert rich.get_console().width == 100", "ground_truth_oracle_lineno": 15, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_console() -> \"Console\":\n \"\"\"Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console,\n and hasn't been explicitly given one.\n\n Returns:\n Console: A console instance.\n \"\"\"\n global _console\n if _console is None:\n from .console import Console\n\n _console = Console()\n\n return _console", "focal_method_file_path": "rich/__init__.py", "focal_method_start_lineno": 23, "focal_method_end_lineno": 36} {"index": 303, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_renderable", "test_class_name": "", "original_test_prefix": "def test_renderable():\n console = Console(\n color_system=None, width=80, legacy_windows=False, get_time=lambda: 0.0\n )\n status = Status(\"foo\", console=console)\n console.begin_capture()\n console.print(status)\n assert console.end_capture() == \"\u280b foo\\n\"", "test_prefix": "def test_renderable():\n console = Console(\n color_system=None, width=80, legacy_windows=False, get_time=lambda: 0.0\n )\n status = Status(\"foo\", console=console)\n console.begin_capture()\n console.print(status)\n ", "test_prefix_file_path": "tests/test_status.py", "test_prefix_start_lineno": 27, "test_prefix_end_lineno": 34, "test_target": "tests/test_status.py::test_renderable", "ground_truth_oracle": "assert console.end_capture() == \"\u280b foo\\n\"", "ground_truth_oracle_lineno": 34, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def end_capture(self) -> str:\n \"\"\"End capture mode and return captured string.\n\n Returns:\n str: Console output.\n \"\"\"\n render_result = self._render_buffer(self._buffer)\n del self._buffer[:]\n self._exit_buffer()\n return render_result", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 876, "focal_method_end_lineno": 885} {"index": 304, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_width_of_none", "test_class_name": "", "original_test_prefix": "def test_width_of_none():\n console = Console()\n constrain = Constrain(Text(\"foo\"), width=None)\n min_width, max_width = constrain.__rich_measure__(\n console, console.options.update_width(80)\n )\n assert min_width == 3\n assert max_width == 3", "test_prefix": "def test_width_of_none():\n console = Console()\n constrain = Constrain(Text(\"foo\"), width=None)\n min_width, max_width = constrain.__rich_measure__(\n console, console.options.update_width(80)\n )\n assert min_width == 3\n ", "test_prefix_file_path": "tests/test_constrain.py", "test_prefix_start_lineno": 6, "test_prefix_end_lineno": 13, "test_target": "tests/test_constrain.py::test_width_of_none", "ground_truth_oracle": "assert max_width == 3", "ground_truth_oracle_lineno": 13, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def __rich_measure__(\n self, console: \"Console\", options: \"ConsoleOptions\"\n ) -> \"Measurement\":\n if self.width is not None:\n options = options.update_width(self.width)\n measurement = Measurement.get(console, options, self.renderable)\n return measurement", "focal_method_file_path": "rich/constrain.py", "focal_method_start_lineno": 31, "focal_method_end_lineno": 37} {"index": 305, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_line_color_none", "test_class_name": "", "original_test_prefix": "def test_get_line_color_none() -> None:\n style = PygmentsSyntaxTheme(\"default\")\n style._background_style = Style(bgcolor=None)\n syntax = Syntax(\n CODE,\n lexer=\"python\",\n line_numbers=True,\n line_range=(2, 10),\n theme=style,\n code_width=60,\n word_wrap=True,\n background_color=\"red\",\n )\n assert syntax._get_line_numbers_color() == Color.default()", "test_prefix": "def test_get_line_color_none() -> None:\n style = PygmentsSyntaxTheme(\"default\")\n style._background_style = Style(bgcolor=None)\n syntax = Syntax(\n CODE,\n lexer=\"python\",\n line_numbers=True,\n line_range=(2, 10),\n theme=style,\n code_width=60,\n word_wrap=True,\n background_color=\"red\",\n )\n ", "test_prefix_file_path": "tests/test_syntax.py", "test_prefix_start_lineno": 172, "test_prefix_end_lineno": 185, "test_target": "tests/test_syntax.py::test_get_line_color_none", "ground_truth_oracle": "assert syntax._get_line_numbers_color() == Color.default()", "ground_truth_oracle_lineno": 185, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def default(cls) -> \"Color\":\n \"\"\"Get a Color instance representing the default color.\n\n Returns:\n Color: Default color.\n \"\"\"\n return cls(name=\"default\", type=ColorType.DEFAULT)", "focal_method_file_path": "rich/color.py", "focal_method_start_lineno": 422, "focal_method_end_lineno": 429} {"index": 306, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_set_cell_size", "test_class_name": "", "original_test_prefix": "def test_set_cell_size():\n assert cells.set_cell_size(\"foo\", 0) == \"\"\n assert cells.set_cell_size(\"f\", 0) == \"\"\n assert cells.set_cell_size(\"\", 0) == \"\"\n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 0) == \"\"\n assert cells.set_cell_size(\"foo\", 2) == \"fo\"\n assert cells.set_cell_size(\"foo\", 3) == \"foo\"\n assert cells.set_cell_size(\"foo\", 4) == \"foo \"\n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 4) == \"\ud83d\ude3d\ud83d\ude3d\"\n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 3) == \"\ud83d\ude3d \"\n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 2) == \"\ud83d\ude3d\"\n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 1) == \" \"\n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 5) == \"\ud83d\ude3d\ud83d\ude3d \"", "test_prefix": "def test_set_cell_size():\n assert cells.set_cell_size(\"foo\", 0) == \"\"\n assert cells.set_cell_size(\"f\", 0) == \"\"\n \n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 0) == \"\"\n assert cells.set_cell_size(\"foo\", 2) == \"fo\"\n assert cells.set_cell_size(\"foo\", 3) == \"foo\"\n assert cells.set_cell_size(\"foo\", 4) == \"foo \"\n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 4) == \"\ud83d\ude3d\ud83d\ude3d\"\n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 3) == \"\ud83d\ude3d \"\n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 2) == \"\ud83d\ude3d\"\n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 1) == \" \"\n assert cells.set_cell_size(\"\ud83d\ude3d\ud83d\ude3d\", 5) == \"\ud83d\ude3d\ud83d\ude3d \"", "test_prefix_file_path": "tests/test_cells.py", "test_prefix_start_lineno": 21, "test_prefix_end_lineno": 33, "test_target": "tests/test_cells.py::test_set_cell_size", "ground_truth_oracle": "assert cells.set_cell_size(\"\", 0) == \"\"", "ground_truth_oracle_lineno": 24, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def set_cell_size(text: str, total: int) -> str:\n \"\"\"Set the length of a string to fit within given number of cells.\"\"\"\n\n if _is_single_cell_widths(text):\n size = len(text)\n if size < total:\n return text + \" \" * (total - size)\n return text[:total]\n\n if total <= 0:\n return \"\"\n cell_size = cell_len(text)\n if cell_size == total:\n return text\n if cell_size < total:\n return text + \" \" * (total - cell_size)\n\n start = 0\n end = len(text)\n\n # Binary search until we find the right size\n while True:\n pos = (start + end) // 2\n before = text[: pos + 1]\n before_len = cell_len(before)\n if before_len == total + 1 and cell_len(before[-1]) == 2:\n return before[:-1] + \" \"\n if before_len == total:\n return before\n if before_len > total:\n end = pos\n else:\n start = pos", "focal_method_file_path": "rich/cells.py", "focal_method_start_lineno": 96, "focal_method_end_lineno": 128} {"index": 307, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_box_substitute_for_same_box", "test_class_name": "", "original_test_prefix": "def test_box_substitute_for_same_box():\n options = ConsoleOptions(\n ConsoleDimensions(80, 25),\n legacy_windows=False,\n min_width=1,\n max_width=100,\n is_terminal=True,\n encoding=\"utf-8\",\n max_height=25,\n )\n\n assert ROUNDED.substitute(options) == ROUNDED\n assert MINIMAL_HEAVY_HEAD.substitute(options) == MINIMAL_HEAVY_HEAD\n assert SIMPLE_HEAVY.substitute(options) == SIMPLE_HEAVY\n assert HEAVY.substitute(options) == HEAVY\n assert HEAVY_EDGE.substitute(options) == HEAVY_EDGE\n assert HEAVY_HEAD.substitute(options) == HEAVY_HEAD", "test_prefix": "def test_box_substitute_for_same_box():\n options = ConsoleOptions(\n ConsoleDimensions(80, 25),\n legacy_windows=False,\n min_width=1,\n max_width=100,\n is_terminal=True,\n encoding=\"utf-8\",\n max_height=25,\n )\n\n assert ROUNDED.substitute(options) == ROUNDED\n assert MINIMAL_HEAVY_HEAD.substitute(options) == MINIMAL_HEAVY_HEAD\n assert SIMPLE_HEAVY.substitute(options) == SIMPLE_HEAVY\n \n assert HEAVY_EDGE.substitute(options) == HEAVY_EDGE\n assert HEAVY_HEAD.substitute(options) == HEAVY_HEAD", "test_prefix_file_path": "tests/test_box.py", "test_prefix_start_lineno": 51, "test_prefix_end_lineno": 67, "test_target": "tests/test_box.py::test_box_substitute_for_same_box", "ground_truth_oracle": "assert HEAVY.substitute(options) == HEAVY", "ground_truth_oracle_lineno": 65, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def substitute(self, options: \"ConsoleOptions\", safe: bool = True) -> \"Box\":\n \"\"\"Substitute this box for another if it won't render due to platform issues.\n\n Args:\n options (ConsoleOptions): Console options used in rendering.\n safe (bool, optional): Substitute this for another Box if there are known problems\n displaying on the platform (currently only relevant on Windows). Default is True.\n\n Returns:\n Box: A different Box or the same Box.\n \"\"\"\n box = self\n if options.legacy_windows and safe:\n box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box)\n if options.ascii_only and not box.ascii:\n box = ASCII\n return box", "focal_method_file_path": "rich/box.py", "focal_method_start_lineno": 67, "focal_method_end_lineno": 83} {"index": 308, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_highlight_words", "test_class_name": "", "original_test_prefix": "def test_highlight_words():\n text = Text(\"Do NOT! touch anything!\")\n words = [\"NOT\", \"!\"]\n count = text.highlight_words(words, \"red\")\n assert count == 3\n assert sorted(text._spans) == [\n Span(3, 6, \"red\"), # NOT\n Span(6, 7, \"red\"), # !\n Span(22, 23, \"red\"), # !\n ]\n\n # regex escape test\n text = Text(\"[o|u]aeiou\")\n words = [\"[a|e|i]\", \"[o|u]\"]\n count = text.highlight_words(words, \"red\")\n assert count == 1\n assert text._spans == [Span(0, 5, \"red\")]\n\n # case sensitive\n text = Text(\"AB Ab aB ab\")\n words = [\"AB\"]\n\n count = text.highlight_words(words, \"red\")\n assert count == 1\n assert text._spans == [Span(0, 2, \"red\")]\n\n text = Text(\"AB Ab aB ab\")\n count = text.highlight_words(words, \"red\", case_sensitive=False)\n assert count == 4", "test_prefix": "def test_highlight_words():\n text = Text(\"Do NOT! touch anything!\")\n words = [\"NOT\", \"!\"]\n count = text.highlight_words(words, \"red\")\n assert count == 3\n assert sorted(text._spans) == [\n Span(3, 6, \"red\"), # NOT\n Span(6, 7, \"red\"), # !\n Span(22, 23, \"red\"), # !\n ]\n\n # regex escape test\n text = Text(\"[o|u]aeiou\")\n words = [\"[a|e|i]\", \"[o|u]\"]\n count = text.highlight_words(words, \"red\")\n assert count == 1\n assert text._spans == [Span(0, 5, \"red\")]\n\n # case sensitive\n text = Text(\"AB Ab aB ab\")\n words = [\"AB\"]\n\n count = text.highlight_words(words, \"red\")\n assert count == 1\n assert text._spans == [Span(0, 2, \"red\")]\n\n text = Text(\"AB Ab aB ab\")\n count = text.highlight_words(words, \"red\", case_sensitive=False)\n ", "test_prefix_file_path": "tests/test_text.py", "test_prefix_start_lineno": 266, "test_prefix_end_lineno": 294, "test_target": "tests/test_text.py::test_highlight_words", "ground_truth_oracle": "assert count == 4", "ground_truth_oracle_lineno": 294, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def highlight_words(\n self,\n words: Iterable[str],\n style: Union[str, Style],\n *,\n case_sensitive: bool = True,\n ) -> int:\n \"\"\"Highlight words with a style.\n\n Args:\n words (Iterable[str]): Words to highlight.\n style (Union[str, Style]): Style to apply.\n case_sensitive (bool, optional): Enable case sensitive matching. Defaults to True.\n\n Returns:\n int: Number of words highlighted.\n \"\"\"\n re_words = \"|\".join(re.escape(word) for word in words)\n add_span = self._spans.append\n count = 0\n _Span = Span\n for match in re.finditer(\n re_words, self.plain, flags=0 if case_sensitive else re.IGNORECASE\n ):\n start, end = match.span(0)\n add_span(_Span(start, end, style))\n count += 1\n return count", "focal_method_file_path": "rich/text.py", "focal_method_start_lineno": 633, "focal_method_end_lineno": 660} {"index": 309, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_no_output_if_progress_is_disabled", "test_class_name": "", "original_test_prefix": "def test_no_output_if_progress_is_disabled() -> None:\n console = Console(\n file=io.StringIO(),\n force_terminal=True,\n width=60,\n color_system=\"truecolor\",\n legacy_windows=False,\n _environ={},\n )\n progress = Progress(\n console=console,\n disable=True,\n )\n test = [\"foo\", \"bar\", \"baz\"]\n expected_values = iter(test)\n with progress:\n for value in progress.track(test, description=\"test\"):\n assert value == next(expected_values)\n result = console.file.getvalue()\n print(repr(result))\n expected = \"\"\n assert result == expected", "test_prefix": "def test_no_output_if_progress_is_disabled() -> None:\n console = Console(\n file=io.StringIO(),\n force_terminal=True,\n width=60,\n color_system=\"truecolor\",\n legacy_windows=False,\n _environ={},\n )\n progress = Progress(\n console=console,\n disable=True,\n )\n test = [\"foo\", \"bar\", \"baz\"]\n expected_values = iter(test)\n with progress:\n for value in progress.track(test, description=\"test\"):\n \n result = console.file.getvalue()\n print(repr(result))\n expected = \"\"\n assert result == expected", "test_prefix_file_path": "tests/test_progress.py", "test_prefix_start_lineno": 544, "test_prefix_end_lineno": 565, "test_target": "tests/test_progress.py::test_no_output_if_progress_is_disabled", "ground_truth_oracle": "assert value == next(expected_values)", "ground_truth_oracle_lineno": 561, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def track(\n self,\n sequence: Iterable[ProgressType],\n total: Optional[float] = None,\n completed: int = 0,\n task_id: Optional[TaskID] = None,\n description: str = \"Working...\",\n update_period: float = 0.1,\n ) -> Iterable[ProgressType]:\n \"\"\"Track progress by iterating over a sequence.\n\n You can also track progress of an iterable, which might require that you additionally specify ``total``.\n\n Args:\n sequence (Iterable[ProgressType]): Values you want to iterate over and track progress.\n total: (float, optional): Total number of steps. Default is len(sequence).\n completed (int, optional): Number of steps completed so far. Defaults to 0.\n task_id: (TaskID): Task to track. Default is new task.\n description: (str, optional): Description of task, if new task is created.\n update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.\n\n Returns:\n Iterable[ProgressType]: An iterable of values taken from the provided sequence.\n \"\"\"\n if total is None:\n total = float(length_hint(sequence)) or None\n\n if task_id is None:\n task_id = self.add_task(description, total=total, completed=completed)\n else:\n self.update(task_id, total=total, completed=completed)\n\n if self.live.auto_refresh:\n with _TrackThread(self, task_id, update_period) as track_thread:\n for value in sequence:\n yield value\n track_thread.completed += 1\n else:\n advance = self.advance\n refresh = self.refresh\n for value in sequence:\n yield value\n advance(task_id, 1)\n refresh()", "focal_method_file_path": "rich/progress.py", "focal_method_start_lineno": 1191, "focal_method_end_lineno": 1234} {"index": 310, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_renderables_empty", "test_class_name": "", "original_test_prefix": "def test_renderables_empty():\n console = Console()\n renderables = Renderables()\n\n result = renderables.__rich_measure__(console, console.options)\n _min, _max = result\n assert _min == 1\n assert _max == 1", "test_prefix": "def test_renderables_empty():\n console = Console()\n renderables = Renderables()\n\n result = renderables.__rich_measure__(console, console.options)\n _min, _max = result\n assert _min == 1\n ", "test_prefix_file_path": "tests/test_containers.py", "test_prefix_start_lineno": 20, "test_prefix_end_lineno": 27, "test_target": "tests/test_containers.py::test_renderables_empty", "ground_truth_oracle": "assert _max == 1", "ground_truth_oracle_lineno": 27, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def __rich_measure__(\n self, console: \"Console\", options: \"ConsoleOptions\"\n ) -> \"Measurement\":\n dimensions = [\n Measurement.get(console, options, renderable)\n for renderable in self._renderables\n ]\n if not dimensions:\n return Measurement(1, 1)\n _min = max(dimension.minimum for dimension in dimensions)\n _max = max(dimension.maximum for dimension in dimensions)\n return Measurement(_min, _max)", "focal_method_file_path": "rich/containers.py", "focal_method_start_lineno": 46, "focal_method_end_lineno": 57} {"index": 311, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_measure", "test_class_name": "", "original_test_prefix": "def test_measure():\n console = Console(width=120)\n bar = Bar(size=100, begin=11, end=62)\n measurement = bar.__rich_measure__(console, console.options)\n assert measurement.minimum == 4\n assert measurement.maximum == 120", "test_prefix": "def test_measure():\n console = Console(width=120)\n bar = Bar(size=100, begin=11, end=62)\n measurement = bar.__rich_measure__(console, console.options)\n assert measurement.minimum == 4\n ", "test_prefix_file_path": "tests/test_block_bar.py", "test_prefix_start_lineno": 32, "test_prefix_end_lineno": 37, "test_target": "tests/test_block_bar.py::test_measure", "ground_truth_oracle": "assert measurement.maximum == 120", "ground_truth_oracle_lineno": 37, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def __rich_measure__(\n self, console: Console, options: ConsoleOptions\n ) -> Measurement:\n return (\n Measurement(self.width, self.width)\n if self.width is not None\n else Measurement(4, options.max_width)\n )", "focal_method_file_path": "rich/bar.py", "focal_method_start_lineno": 86, "focal_method_end_lineno": 93} {"index": 312, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_console_options_update_height", "test_class_name": "", "original_test_prefix": "def test_console_options_update_height() -> None:\n options = ConsoleOptions(\n ConsoleDimensions(80, 25),\n max_height=25,\n legacy_windows=False,\n min_width=10,\n max_width=20,\n is_terminal=False,\n encoding=\"utf-8\",\n )\n assert options.height is None\n render_options = options.update_height(12)\n assert options.height is None\n assert render_options.height == 12\n assert render_options.max_height == 12", "test_prefix": "def test_console_options_update_height() -> None:\n options = ConsoleOptions(\n ConsoleDimensions(80, 25),\n max_height=25,\n legacy_windows=False,\n min_width=10,\n max_width=20,\n is_terminal=False,\n encoding=\"utf-8\",\n )\n assert options.height is None\n render_options = options.update_height(12)\n assert options.height is None\n assert render_options.height == 12\n ", "test_prefix_file_path": "tests/test_console.py", "test_prefix_start_lineno": 106, "test_prefix_end_lineno": 120, "test_target": "tests/test_console.py::test_console_options_update_height", "ground_truth_oracle": "assert render_options.max_height == 12", "ground_truth_oracle_lineno": 120, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def update_height(self, height: int) -> \"ConsoleOptions\":\n \"\"\"Update the height, and return a copy.\n\n Args:\n height (int): New height\n\n Returns:\n ~ConsoleOptions: New Console options instance.\n \"\"\"\n options = self.copy()\n options.max_height = options.height = height\n return options", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 213, "focal_method_end_lineno": 224} {"index": 313, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_fileno_missing", "test_class_name": "", "original_test_prefix": "def test_get_fileno_missing():\n class FileLike:\n pass\n\n assert get_fileno(FileLike()) is None", "test_prefix": "def test_get_fileno_missing():\n class FileLike:\n pass\n\n ", "test_prefix_file_path": "tests/test_getfileno.py", "test_prefix_start_lineno": 12, "test_prefix_end_lineno": 16, "test_target": "tests/test_getfileno.py::test_get_fileno_missing", "ground_truth_oracle": "assert get_fileno(FileLike()) is None", "ground_truth_oracle_lineno": 16, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def get_fileno(file_like: IO[str]) -> int | None:\n \"\"\"Get fileno() from a file, accounting for poorly implemented file-like objects.\n\n Args:\n file_like (IO): A file-like object.\n\n Returns:\n int | None: The result of fileno if available, or None if operation failed.\n \"\"\"\n fileno: Callable[[], int] | None = getattr(file_like, \"fileno\", None)\n if fileno is not None:\n try:\n return fileno()\n except Exception:\n # `fileno` is documented as potentially raising a OSError\n # Alas, from the issues, there are so many poorly implemented file-like objects,\n # that `fileno()` can raise just about anything.\n return None\n return None", "focal_method_file_path": "rich/_fileno.py", "focal_method_start_lineno": 6, "focal_method_end_lineno": 24} {"index": 314, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_pick_bool", "test_class_name": "", "original_test_prefix": "def test_pick_bool():\n assert pick_bool(False) == False\n assert pick_bool(True) == True\n assert pick_bool(None) == False\n assert pick_bool(False, True) == False\n assert pick_bool(None, True) == True\n assert pick_bool(True, None) == True\n assert pick_bool(False, None) == False\n assert pick_bool(None, None) == False\n assert pick_bool(None, None, False, True) == False\n assert pick_bool(None, None, True, False) == True", "test_prefix": "def test_pick_bool():\n assert pick_bool(False) == False\n assert pick_bool(True) == True\n assert pick_bool(None) == False\n assert pick_bool(False, True) == False\n assert pick_bool(None, True) == True\n assert pick_bool(True, None) == True\n \n assert pick_bool(None, None) == False\n assert pick_bool(None, None, False, True) == False\n assert pick_bool(None, None, True, False) == True", "test_prefix_file_path": "tests/test_pick.py", "test_prefix_start_lineno": 4, "test_prefix_end_lineno": 14, "test_target": "tests/test_pick.py::test_pick_bool", "ground_truth_oracle": "assert pick_bool(False, None) == False", "ground_truth_oracle_lineno": 11, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def pick_bool(*values: Optional[bool]) -> bool:\n \"\"\"Pick the first non-none bool or return the last value.\n\n Args:\n *values (bool): Any number of boolean or None values.\n\n Returns:\n bool: First non-none boolean.\n \"\"\"\n assert values, \"1 or more values required\"\n for value in values:\n if value is not None:\n return value\n return bool(value)", "focal_method_file_path": "rich/_pick.py", "focal_method_start_lineno": 4, "focal_method_end_lineno": 17} {"index": 315, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_rich_print_json_no_truncation", "test_class_name": "", "original_test_prefix": "def test_rich_print_json_no_truncation():\n console = rich.get_console()\n with console.capture() as capture:\n rich.print_json(f'[\"{\"x\" * 100}\", {int(2e128)}]', indent=4)\n result = capture.get()\n print(repr(result))\n assert (\"x\" * 100) in result\n assert str(int(2e128)) in result", "test_prefix": "def test_rich_print_json_no_truncation():\n console = rich.get_console()\n with console.capture() as capture:\n rich.print_json(f'[\"{\"x\" * 100}\", {int(2e128)}]', indent=4)\n result = capture.get()\n print(repr(result))\n \n assert str(int(2e128)) in result", "test_prefix_file_path": "tests/test_rich_print.py", "test_prefix_start_lineno": 53, "test_prefix_end_lineno": 60, "test_target": "tests/test_rich_print.py::test_rich_print_json_no_truncation", "ground_truth_oracle": "assert (\"x\" * 100) in result", "ground_truth_oracle_lineno": 59, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get(self) -> str:\n \"\"\"Get the result of the capture.\"\"\"\n if self._result is None:\n raise CaptureError(\n \"Capture result is not available until context manager exits.\"\n )\n return self._result", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 340, "focal_method_end_lineno": 346} {"index": 316, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_shortcuts", "test_class_name": "", "original_test_prefix": "def test_shortcuts():\n assert Align.left(\"foo\").align == \"left\"\n assert Align.left(\"foo\").renderable == \"foo\"\n assert Align.right(\"foo\").align == \"right\"\n assert Align.right(\"foo\").renderable == \"foo\"\n assert Align.center(\"foo\").align == \"center\"\n assert Align.center(\"foo\").renderable == \"foo\"", "test_prefix": "def test_shortcuts():\n assert Align.left(\"foo\").align == \"left\"\n assert Align.left(\"foo\").renderable == \"foo\"\n assert Align.right(\"foo\").align == \"right\"\n assert Align.right(\"foo\").renderable == \"foo\"\n assert Align.center(\"foo\").align == \"center\"\n ", "test_prefix_file_path": "tests/test_align.py", "test_prefix_start_lineno": 130, "test_prefix_end_lineno": 136, "test_target": "tests/test_align.py::test_shortcuts", "ground_truth_oracle": "assert Align.center(\"foo\").renderable == \"foo\"", "ground_truth_oracle_lineno": 136, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def center(\n cls,\n renderable: \"RenderableType\",\n style: Optional[StyleType] = None,\n *,\n vertical: Optional[VerticalAlignMethod] = None,\n pad: bool = True,\n width: Optional[int] = None,\n height: Optional[int] = None,\n ) -> \"Align\":\n \"\"\"Align a renderable to the center.\"\"\"\n return cls(\n renderable,\n \"center\",\n style=style,\n vertical=vertical,\n pad=pad,\n width=width,\n height=height,\n )", "focal_method_file_path": "rich/align.py", "focal_method_start_lineno": 85, "focal_method_end_lineno": 105} {"index": 317, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_escape_backslash_end", "test_class_name": "", "original_test_prefix": "def test_escape_backslash_end():\n # https://github.com/Textualize/rich/issues/2987\n value = \"C:\\\\\"\n assert escape(value) == \"C:\\\\\\\\\"\n\n escaped_tags = f\"[red]{escape(value)}[/red]\"\n assert escaped_tags == \"[red]C:\\\\\\\\[/red]\"\n escaped_text = Text.from_markup(escaped_tags)\n assert escaped_text.plain == \"C:\\\\\"\n assert escaped_text.spans == [Span(0, 3, \"red\")]", "test_prefix": "def test_escape_backslash_end():\n # https://github.com/Textualize/rich/issues/2987\n value = \"C:\\\\\"\n assert escape(value) == \"C:\\\\\\\\\"\n\n escaped_tags = f\"[red]{escape(value)}[/red]\"\n \n escaped_text = Text.from_markup(escaped_tags)\n assert escaped_text.plain == \"C:\\\\\"\n assert escaped_text.spans == [Span(0, 3, \"red\")]", "test_prefix_file_path": "tests/test_markup.py", "test_prefix_start_lineno": 47, "test_prefix_end_lineno": 56, "test_target": "tests/test_markup.py::test_escape_backslash_end", "ground_truth_oracle": "assert escaped_tags == \"[red]C:\\\\\\\\[/red]\"", "ground_truth_oracle_lineno": 53, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def escape(\n markup: str,\n _escape: _EscapeSubMethod = re.compile(r\"(\\\\*)(\\[[a-z#/@][^[]*?])\").sub,\n) -> str:\n \"\"\"Escapes text so that it won't be interpreted as markup.\n\n Args:\n markup (str): Content to be inserted in to markup.\n\n Returns:\n str: Markup with square brackets escaped.\n \"\"\"\n\n def escape_backslashes(match: Match[str]) -> str:\n \"\"\"Called by re.sub replace matches.\"\"\"\n backslashes, text = match.groups()\n return f\"{backslashes}{backslashes}\\\\{text}\"\n\n markup = _escape(escape_backslashes, markup)\n if markup.endswith(\"\\\\\") and not markup.endswith(\"\\\\\\\\\"):\n return markup + \"\\\\\"\n\n return markup", "focal_method_file_path": "rich/markup.py", "focal_method_start_lineno": 48, "focal_method_end_lineno": 70} {"index": 318, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_rich_measure", "test_class_name": "", "original_test_prefix": "def test_rich_measure():\n console = Console(width=80, color_system=None, force_terminal=True)\n spinner = Spinner(\"dots\", \"Foo\")\n min_width, max_width = Measurement.get(console, console.options, spinner)\n assert min_width == 3\n assert max_width == 5", "test_prefix": "def test_rich_measure():\n console = Console(width=80, color_system=None, force_terminal=True)\n spinner = Spinner(\"dots\", \"Foo\")\n min_width, max_width = Measurement.get(console, console.options, spinner)\n \n assert max_width == 5", "test_prefix_file_path": "tests/test_spinner.py", "test_prefix_start_lineno": 61, "test_prefix_end_lineno": 66, "test_target": "tests/test_spinner.py::test_rich_measure", "ground_truth_oracle": "assert min_width == 3", "ground_truth_oracle_lineno": 65, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def get(\n cls, console: \"Console\", options: \"ConsoleOptions\", renderable: \"RenderableType\"\n ) -> \"Measurement\":\n \"\"\"Get a measurement for a renderable.\n\n Args:\n console (~rich.console.Console): Console instance.\n options (~rich.console.ConsoleOptions): Console options.\n renderable (RenderableType): An object that may be rendered with Rich.\n\n Raises:\n errors.NotRenderableError: If the object is not renderable.\n\n Returns:\n Measurement: Measurement object containing range of character widths required to render the object.\n \"\"\"\n _max_width = options.max_width\n if _max_width < 1:\n return Measurement(0, 0)\n if isinstance(renderable, str):\n renderable = console.render_str(\n renderable, markup=options.markup, highlight=False\n )\n renderable = rich_cast(renderable)\n if is_renderable(renderable):\n get_console_width: Optional[\n Callable[[\"Console\", \"ConsoleOptions\"], \"Measurement\"]\n ] = getattr(renderable, \"__rich_measure__\", None)\n if get_console_width is not None:\n render_width = (\n get_console_width(console, options)\n .normalize()\n .with_maximum(_max_width)\n )\n if render_width.maximum < 1:\n return Measurement(0, 0)\n return render_width.normalize()\n else:\n return Measurement(0, _max_width)\n else:\n raise errors.NotRenderableError(\n f\"Unable to get render width for {renderable!r}; \"\n \"a str, Segment, or object with __rich_console__ method is required\"\n )", "focal_method_file_path": "rich/measure.py", "focal_method_start_lineno": 78, "focal_method_end_lineno": 122} {"index": 319, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_replace", "test_class_name": "", "original_test_prefix": "def test_replace():\n assert Emoji.replace(\"my code is :pile_of_poo:\") == \"my code is \ud83d\udca9\"", "test_prefix": "def test_replace():\n ", "test_prefix_file_path": "tests/test_emoji.py", "test_prefix_start_lineno": 18, "test_prefix_end_lineno": 19, "test_target": "tests/test_emoji.py::test_replace", "ground_truth_oracle": "assert Emoji.replace(\"my code is :pile_of_poo:\") == \"my code is \ud83d\udca9\"", "ground_truth_oracle_lineno": 19, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def replace(cls, text: str) -> str:\n \"\"\"Replace emoji markup with corresponding unicode characters.\n\n Args:\n text (str): A string with emojis codes, e.g. \"Hello :smiley:!\"\n\n Returns:\n str: A string with emoji codes replaces with actual emoji.\n \"\"\"\n return _emoji_replace(text)", "focal_method_file_path": "rich/emoji.py", "focal_method_start_lineno": 52, "focal_method_end_lineno": 62} {"index": 320, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_lying_attribute", "test_class_name": "", "original_test_prefix": "def test_lying_attribute() -> None:\n \"\"\"Test getattr doesn't break rich repr protocol\"\"\"\n\n class Foo:\n def __getattr__(self, attr):\n return \"foo\"\n\n foo = Foo()\n result = pretty_repr(foo)\n assert \"Foo\" in result", "test_prefix": "def test_lying_attribute() -> None:\n \"\"\"Test getattr doesn't break rich repr protocol\"\"\"\n\n class Foo:\n def __getattr__(self, attr):\n return \"foo\"\n\n foo = Foo()\n result = pretty_repr(foo)\n ", "test_prefix_file_path": "tests/test_pretty.py", "test_prefix_start_lineno": 696, "test_prefix_end_lineno": 705, "test_target": "tests/test_pretty.py::test_lying_attribute", "ground_truth_oracle": "assert \"Foo\" in result", "ground_truth_oracle_lineno": 705, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def pretty_repr(\n _object: Any,\n *,\n max_width: int = 80,\n indent_size: int = 4,\n max_length: Optional[int] = None,\n max_string: Optional[int] = None,\n max_depth: Optional[int] = None,\n expand_all: bool = False,\n) -> str:\n \"\"\"Prettify repr string by expanding on to new lines to fit within a given width.\n\n Args:\n _object (Any): Object to repr.\n max_width (int, optional): Desired maximum width of repr string. Defaults to 80.\n indent_size (int, optional): Number of spaces to indent. Defaults to 4.\n max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n Defaults to None.\n max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.\n Defaults to None.\n max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.\n Defaults to None.\n expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.\n\n Returns:\n str: A possibly multi-line representation of the object.\n \"\"\"\n\n if _safe_isinstance(_object, Node):\n node = _object\n else:\n node = traverse(\n _object, max_length=max_length, max_string=max_string, max_depth=max_depth\n )\n repr_str: str = node.render(\n max_width=max_width, indent_size=indent_size, expand_all=expand_all\n )\n return repr_str", "focal_method_file_path": "rich/pretty.py", "focal_method_start_lineno": 878, "focal_method_end_lineno": 915} {"index": 321, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_fit", "test_class_name": "", "original_test_prefix": "def test_fit():\n text = Text(\"Hello\\nWorld\")\n lines = text.fit(3)\n assert str(lines[0]) == \"Hel\"\n assert str(lines[1]) == \"Wor\"", "test_prefix": "def test_fit():\n text = Text(\"Hello\\nWorld\")\n lines = text.fit(3)\n assert str(lines[0]) == \"Hel\"\n ", "test_prefix_file_path": "tests/test_text.py", "test_prefix_start_lineno": 644, "test_prefix_end_lineno": 648, "test_target": "tests/test_text.py::test_fit", "ground_truth_oracle": "assert str(lines[1]) == \"Wor\"", "ground_truth_oracle_lineno": 648, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def fit(self, width: int) -> Lines:\n \"\"\"Fit the text in to given width by chopping in to lines.\n\n Args:\n width (int): Maximum characters in a line.\n\n Returns:\n Lines: Lines container.\n \"\"\"\n lines: Lines = Lines()\n append = lines.append\n for line in self.split():\n line.set_length(width)\n append(line)\n return lines", "focal_method_file_path": "rich/text.py", "focal_method_start_lineno": 1250, "focal_method_end_lineno": 1264} {"index": 322, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_wrap_long_words_justify_left", "test_class_name": "", "original_test_prefix": "def test_wrap_long_words_justify_left():\n text = Text(\"X 123456789\", justify=\"left\")\n lines = text.wrap(Console(), 4)\n\n assert len(lines) == 4\n assert lines[0] == Text(\"X \")\n assert lines[1] == Text(\"1234\")\n assert lines[2] == Text(\"5678\")\n assert lines[3] == Text(\"9 \")", "test_prefix": "def test_wrap_long_words_justify_left():\n text = Text(\"X 123456789\", justify=\"left\")\n lines = text.wrap(Console(), 4)\n\n \n assert lines[0] == Text(\"X \")\n assert lines[1] == Text(\"1234\")\n assert lines[2] == Text(\"5678\")\n assert lines[3] == Text(\"9 \")", "test_prefix_file_path": "tests/test_text.py", "test_prefix_start_lineno": 608, "test_prefix_end_lineno": 616, "test_target": "tests/test_text.py::test_wrap_long_words_justify_left", "ground_truth_oracle": "assert len(lines) == 4", "ground_truth_oracle_lineno": 612, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def wrap(\n self,\n console: \"Console\",\n width: int,\n *,\n justify: Optional[\"JustifyMethod\"] = None,\n overflow: Optional[\"OverflowMethod\"] = None,\n tab_size: int = 8,\n no_wrap: Optional[bool] = None,\n ) -> Lines:\n \"\"\"Word wrap the text.\n\n Args:\n console (Console): Console instance.\n width (int): Number of cells available per line.\n justify (str, optional): Justify method: \"default\", \"left\", \"center\", \"full\", \"right\". Defaults to \"default\".\n overflow (str, optional): Overflow method: \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n tab_size (int, optional): Default tab size. Defaults to 8.\n no_wrap (bool, optional): Disable wrapping, Defaults to False.\n\n Returns:\n Lines: Number of lines.\n \"\"\"\n wrap_justify = justify or self.justify or DEFAULT_JUSTIFY\n wrap_overflow = overflow or self.overflow or DEFAULT_OVERFLOW\n\n no_wrap = pick_bool(no_wrap, self.no_wrap, False) or overflow == \"ignore\"\n\n lines = Lines()\n for line in self.split(allow_blank=True):\n if \"\\t\" in line:\n line.expand_tabs(tab_size)\n if no_wrap:\n new_lines = Lines([line])\n else:\n offsets = divide_line(str(line), width, fold=wrap_overflow == \"fold\")\n new_lines = line.divide(offsets)\n for line in new_lines:\n line.rstrip_end(width)\n if wrap_justify:\n new_lines.justify(\n console, width, justify=wrap_justify, overflow=wrap_overflow\n )\n for line in new_lines:\n line.truncate(width, overflow=wrap_overflow)\n lines.extend(new_lines)\n return lines", "focal_method_file_path": "rich/text.py", "focal_method_start_lineno": 1202, "focal_method_end_lineno": 1248} {"index": 323, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_ansi_codes", "test_class_name": "", "original_test_prefix": "def test_get_ansi_codes() -> None:\n assert Color.parse(\"default\").get_ansi_codes() == (\"39\",)\n assert Color.parse(\"default\").get_ansi_codes(False) == (\"49\",)\n assert Color.parse(\"red\").get_ansi_codes() == (\"31\",)\n assert Color.parse(\"red\").get_ansi_codes(False) == (\"41\",)\n assert Color.parse(\"color(1)\").get_ansi_codes() == (\"31\",)\n assert Color.parse(\"color(1)\").get_ansi_codes(False) == (\"41\",)\n assert Color.parse(\"#ff0000\").get_ansi_codes() == (\"38\", \"2\", \"255\", \"0\", \"0\")\n assert Color.parse(\"#ff0000\").get_ansi_codes(False) == (\"48\", \"2\", \"255\", \"0\", \"0\")", "test_prefix": "def test_get_ansi_codes() -> None:\n assert Color.parse(\"default\").get_ansi_codes() == (\"39\",)\n assert Color.parse(\"default\").get_ansi_codes(False) == (\"49\",)\n assert Color.parse(\"red\").get_ansi_codes() == (\"31\",)\n assert Color.parse(\"red\").get_ansi_codes(False) == (\"41\",)\n assert Color.parse(\"color(1)\").get_ansi_codes() == (\"31\",)\n assert Color.parse(\"color(1)\").get_ansi_codes(False) == (\"41\",)\n \n assert Color.parse(\"#ff0000\").get_ansi_codes(False) == (\"48\", \"2\", \"255\", \"0\", \"0\")", "test_prefix_file_path": "tests/test_color.py", "test_prefix_start_lineno": 115, "test_prefix_end_lineno": 123, "test_target": "tests/test_color.py::test_get_ansi_codes", "ground_truth_oracle": "assert Color.parse(\"#ff0000\").get_ansi_codes() == (\"38\", \"2\", \"255\", \"0\", \"0\")", "ground_truth_oracle_lineno": 122, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @lru_cache(maxsize=1024)\n def get_ansi_codes(self, foreground: bool = True) -> Tuple[str, ...]:\n \"\"\"Get the ANSI escape codes for this color.\"\"\"\n _type = self.type\n if _type == ColorType.DEFAULT:\n return (\"39\" if foreground else \"49\",)\n\n elif _type == ColorType.WINDOWS:\n number = self.number\n assert number is not None\n fore, back = (30, 40) if number < 8 else (82, 92)\n return (str(fore + number if foreground else back + number),)\n\n elif _type == ColorType.STANDARD:\n number = self.number\n assert number is not None\n fore, back = (30, 40) if number < 8 else (82, 92)\n return (str(fore + number if foreground else back + number),)\n\n elif _type == ColorType.EIGHT_BIT:\n assert self.number is not None\n return (\"38\" if foreground else \"48\", \"5\", str(self.number))\n\n else: # self.standard == ColorStandard.TRUECOLOR:\n assert self.triplet is not None\n red, green, blue = self.triplet\n return (\"38\" if foreground else \"48\", \"2\", str(red), str(green), str(blue))", "focal_method_file_path": "rich/color.py", "focal_method_start_lineno": 484, "focal_method_end_lineno": 510} {"index": 324, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_empty_repr", "test_class_name": "", "original_test_prefix": "def test_empty_repr() -> None:\n class Foo:\n def __repr__(self):\n return \"\"\n\n assert pretty_repr(Foo()) == \"\"", "test_prefix": "def test_empty_repr() -> None:\n class Foo:\n def __repr__(self):\n return \"\"\n\n ", "test_prefix_file_path": "tests/test_pretty.py", "test_prefix_start_lineno": 609, "test_prefix_end_lineno": 614, "test_target": "tests/test_pretty.py::test_empty_repr", "ground_truth_oracle": "assert pretty_repr(Foo()) == \"\"", "ground_truth_oracle_lineno": 614, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def pretty_repr(\n _object: Any,\n *,\n max_width: int = 80,\n indent_size: int = 4,\n max_length: Optional[int] = None,\n max_string: Optional[int] = None,\n max_depth: Optional[int] = None,\n expand_all: bool = False,\n) -> str:\n \"\"\"Prettify repr string by expanding on to new lines to fit within a given width.\n\n Args:\n _object (Any): Object to repr.\n max_width (int, optional): Desired maximum width of repr string. Defaults to 80.\n indent_size (int, optional): Number of spaces to indent. Defaults to 4.\n max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n Defaults to None.\n max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.\n Defaults to None.\n max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.\n Defaults to None.\n expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.\n\n Returns:\n str: A possibly multi-line representation of the object.\n \"\"\"\n\n if _safe_isinstance(_object, Node):\n node = _object\n else:\n node = traverse(\n _object, max_length=max_length, max_string=max_string, max_depth=max_depth\n )\n repr_str: str = node.render(\n max_width=max_width, indent_size=indent_size, expand_all=expand_all\n )\n return repr_str", "focal_method_file_path": "rich/pretty.py", "focal_method_start_lineno": 878, "focal_method_end_lineno": 915} {"index": 325, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_from_meta", "test_class_name": "", "original_test_prefix": "def test_from_meta():\n style = Style.from_meta({\"foo\": \"bar\"})\n assert style.color is None\n assert style.bold is None", "test_prefix": "def test_from_meta():\n style = Style.from_meta({\"foo\": \"bar\"})\n \n assert style.bold is None", "test_prefix_file_path": "tests/test_style.py", "test_prefix_start_lineno": 223, "test_prefix_end_lineno": 226, "test_target": "tests/test_style.py::test_from_meta", "ground_truth_oracle": "assert style.color is None", "ground_truth_oracle_lineno": 225, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def from_meta(cls, meta: Optional[Dict[str, Any]]) -> \"Style\":\n \"\"\"Create a new style with meta data.\n\n Returns:\n meta (Optional[Dict[str, Any]]): A dictionary of meta data. Defaults to None.\n \"\"\"\n style: Style = cls.__new__(Style)\n style._ansi = None\n style._style_definition = None\n style._color = None\n style._bgcolor = None\n style._set_attributes = 0\n style._attributes = 0\n style._link = None\n style._meta = dumps(meta)\n style._link_id = f\"{randint(0, 999999)}{hash(style._meta)}\"\n style._hash = None\n style._null = not (meta)\n return style", "focal_method_file_path": "rich/style.py", "focal_method_start_lineno": 232, "focal_method_end_lineno": 251} {"index": 326, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_render_group", "test_class_name": "", "original_test_prefix": "def test_render_group() -> None:\n @group(fit=False)\n def renderable():\n yield \"one\"\n yield \"two\"\n yield \"three\" # <- largest width of 5\n yield \"four\"\n\n renderables = [renderable() for _ in range(4)]\n console = Console(width=42)\n min_width, _ = measure_renderables(console, console.options, renderables)\n assert min_width == 42", "test_prefix": "def test_render_group() -> None:\n @group(fit=False)\n def renderable():\n yield \"one\"\n yield \"two\"\n yield \"three\" # <- largest width of 5\n yield \"four\"\n\n renderables = [renderable() for _ in range(4)]\n console = Console(width=42)\n min_width, _ = measure_renderables(console, console.options, renderables)\n ", "test_prefix_file_path": "tests/test_console.py", "test_prefix_start_lineno": 651, "test_prefix_end_lineno": 662, "test_target": "tests/test_console.py::test_render_group", "ground_truth_oracle": "assert min_width == 42", "ground_truth_oracle_lineno": 662, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def measure_renderables(\n console: \"Console\",\n options: \"ConsoleOptions\",\n renderables: Sequence[\"RenderableType\"],\n) -> \"Measurement\":\n \"\"\"Get a measurement that would fit a number of renderables.\n\n Args:\n console (~rich.console.Console): Console instance.\n options (~rich.console.ConsoleOptions): Console options.\n renderables (Iterable[RenderableType]): One or more renderable objects.\n\n Returns:\n Measurement: Measurement object containing range of character widths required to\n contain all given renderables.\n \"\"\"\n if not renderables:\n return Measurement(0, 0)\n get_measurement = Measurement.get\n measurements = [\n get_measurement(console, options, renderable) for renderable in renderables\n ]\n measured_width = Measurement(\n max(measurements, key=itemgetter(0)).minimum,\n max(measurements, key=itemgetter(1)).maximum,\n )\n return measured_width", "focal_method_file_path": "rich/measure.py", "focal_method_start_lineno": 125, "focal_method_end_lineno": 151} {"index": 327, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_node", "test_class_name": "", "original_test_prefix": "def test_node() -> None:\n node = Node(\"abc\")\n assert pretty_repr(node) == \"abc: \"", "test_prefix": "def test_node() -> None:\n node = Node(\"abc\")\n ", "test_prefix_file_path": "tests/test_pretty.py", "test_prefix_start_lineno": 536, "test_prefix_end_lineno": 538, "test_target": "tests/test_pretty.py::test_node", "ground_truth_oracle": "assert pretty_repr(node) == \"abc: \"", "ground_truth_oracle_lineno": 538, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def pretty_repr(\n _object: Any,\n *,\n max_width: int = 80,\n indent_size: int = 4,\n max_length: Optional[int] = None,\n max_string: Optional[int] = None,\n max_depth: Optional[int] = None,\n expand_all: bool = False,\n) -> str:\n \"\"\"Prettify repr string by expanding on to new lines to fit within a given width.\n\n Args:\n _object (Any): Object to repr.\n max_width (int, optional): Desired maximum width of repr string. Defaults to 80.\n indent_size (int, optional): Number of spaces to indent. Defaults to 4.\n max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n Defaults to None.\n max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.\n Defaults to None.\n max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.\n Defaults to None.\n expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.\n\n Returns:\n str: A possibly multi-line representation of the object.\n \"\"\"\n\n if _safe_isinstance(_object, Node):\n node = _object\n else:\n node = traverse(\n _object, max_length=max_length, max_string=max_string, max_depth=max_depth\n )\n repr_str: str = node.render(\n max_width=max_width, indent_size=indent_size, expand_all=expand_all\n )\n return repr_str", "focal_method_file_path": "rich/pretty.py", "focal_method_start_lineno": 878, "focal_method_end_lineno": 915} {"index": 328, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_strip_control_codes", "test_class_name": "", "original_test_prefix": "def test_strip_control_codes():\n assert strip_control_codes(\"\") == \"\"\n assert strip_control_codes(\"foo\\rbar\") == \"foobar\"\n assert strip_control_codes(\"Fear is the mind killer\") == \"Fear is the mind killer\"", "test_prefix": "def test_strip_control_codes():\n \n assert strip_control_codes(\"foo\\rbar\") == \"foobar\"\n assert strip_control_codes(\"Fear is the mind killer\") == \"Fear is the mind killer\"", "test_prefix_file_path": "tests/test_control.py", "test_prefix_start_lineno": 10, "test_prefix_end_lineno": 13, "test_target": "tests/test_control.py::test_strip_control_codes", "ground_truth_oracle": "assert strip_control_codes(\"\") == \"\"", "ground_truth_oracle_lineno": 11, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def strip_control_codes(\n text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE\n) -> str:\n \"\"\"Remove control codes from text.\n\n Args:\n text (str): A string possibly contain control codes.\n\n Returns:\n str: String with control codes removed.\n \"\"\"\n return text.translate(_translate_table)", "focal_method_file_path": "rich/control.py", "focal_method_start_lineno": 181, "focal_method_end_lineno": 192} {"index": 329, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_pprint_max_values", "test_class_name": "", "original_test_prefix": "def test_pprint_max_values() -> None:\n console = Console(color_system=None)\n console.begin_capture()\n pprint([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], console=console, max_length=2)\n assert console.end_capture() == \"[1, 2, ... +8]\\n\"", "test_prefix": "def test_pprint_max_values() -> None:\n console = Console(color_system=None)\n console.begin_capture()\n pprint([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], console=console, max_length=2)\n ", "test_prefix_file_path": "tests/test_pretty.py", "test_prefix_start_lineno": 564, "test_prefix_end_lineno": 568, "test_target": "tests/test_pretty.py::test_pprint_max_values", "ground_truth_oracle": "assert console.end_capture() == \"[1, 2, ... +8]\\n\"", "ground_truth_oracle_lineno": 568, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def end_capture(self) -> str:\n \"\"\"End capture mode and return captured string.\n\n Returns:\n str: Console output.\n \"\"\"\n render_result = self._render_buffer(self._buffer)\n del self._buffer[:]\n self._exit_buffer()\n return render_result", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 876, "focal_method_end_lineno": 885} {"index": 330, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ratio_distribute", "test_class_name": "", "original_test_prefix": "def test_ratio_distribute():\n assert ratio_distribute(10, [1]) == [10]\n assert ratio_distribute(10, [1, 1]) == [5, 5]\n assert ratio_distribute(12, [1, 3]) == [3, 9]\n assert ratio_distribute(0, [1, 3]) == [0, 0]\n assert ratio_distribute(0, [1, 3], [1, 1]) == [1, 1]\n assert ratio_distribute(10, [1, 0]) == [10, 0]", "test_prefix": "def test_ratio_distribute():\n assert ratio_distribute(10, [1]) == [10]\n assert ratio_distribute(10, [1, 1]) == [5, 5]\n assert ratio_distribute(12, [1, 3]) == [3, 9]\n assert ratio_distribute(0, [1, 3]) == [0, 0]\n \n assert ratio_distribute(10, [1, 0]) == [10, 0]", "test_prefix_file_path": "tests/test_tools.py", "test_prefix_start_lineno": 32, "test_prefix_end_lineno": 38, "test_target": "tests/test_tools.py::test_ratio_distribute", "ground_truth_oracle": "assert ratio_distribute(0, [1, 3], [1, 1]) == [1, 1]", "ground_truth_oracle_lineno": 37, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def ratio_distribute(\n total: int, ratios: List[int], minimums: Optional[List[int]] = None\n) -> List[int]:\n \"\"\"Distribute an integer total in to parts based on ratios.\n\n Args:\n total (int): The total to divide.\n ratios (List[int]): A list of integer ratios.\n minimums (List[int]): List of minimum values for each slot.\n\n Returns:\n List[int]: A list of integers guaranteed to sum to total.\n \"\"\"\n if minimums:\n ratios = [ratio if _min else 0 for ratio, _min in zip(ratios, minimums)]\n total_ratio = sum(ratios)\n assert total_ratio > 0, \"Sum of ratios must be > 0\"\n\n total_remaining = total\n distributed_total: List[int] = []\n append = distributed_total.append\n if minimums is None:\n _minimums = [0] * len(ratios)\n else:\n _minimums = minimums\n for ratio, minimum in zip(ratios, _minimums):\n if total_ratio > 0:\n distributed = max(minimum, ceil(ratio * total_remaining / total_ratio))\n else:\n distributed = total_remaining\n append(distributed)\n total_ratio -= ratio\n total_remaining -= distributed\n return distributed_total", "focal_method_file_path": "rich/_ratio.py", "focal_method_start_lineno": 107, "focal_method_end_lineno": 140} {"index": 331, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_eq", "test_class_name": "", "original_test_prefix": "def test_eq():\n assert Text(\"foo\") == Text(\"foo\")\n assert Text(\"foo\") != Text(\"bar\")\n assert Text(\"foo\").__eq__(1) == NotImplemented", "test_prefix": "def test_eq():\n assert Text(\"foo\") == Text(\"foo\")\n assert Text(\"foo\") != Text(\"bar\")\n ", "test_prefix_file_path": "tests/test_text.py", "test_prefix_start_lineno": 63, "test_prefix_end_lineno": 66, "test_target": "tests/test_text.py::test_eq", "ground_truth_oracle": "assert Text(\"foo\").__eq__(1) == NotImplemented", "ground_truth_oracle_lineno": 66, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def __eq__(self, other: object) -> bool:\n if not isinstance(other, Text):\n return NotImplemented\n return self.plain == other.plain and self._spans == other._spans", "focal_method_file_path": "rich/text.py", "focal_method_start_lineno": 186, "focal_method_end_lineno": 189} {"index": 332, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_box_substitute_for_different_box_ascii_encoding", "test_class_name": "", "original_test_prefix": "def test_box_substitute_for_different_box_ascii_encoding():\n options = ConsoleOptions(\n ConsoleDimensions(80, 25),\n legacy_windows=True,\n min_width=1,\n max_width=100,\n is_terminal=True,\n encoding=\"ascii\",\n max_height=25,\n )\n\n assert ROUNDED.substitute(options) == ASCII\n assert MINIMAL_HEAVY_HEAD.substitute(options) == ASCII\n assert SIMPLE_HEAVY.substitute(options) == ASCII\n assert HEAVY.substitute(options) == ASCII\n assert HEAVY_EDGE.substitute(options) == ASCII\n assert HEAVY_HEAD.substitute(options) == ASCII", "test_prefix": "def test_box_substitute_for_different_box_ascii_encoding():\n options = ConsoleOptions(\n ConsoleDimensions(80, 25),\n legacy_windows=True,\n min_width=1,\n max_width=100,\n is_terminal=True,\n encoding=\"ascii\",\n max_height=25,\n )\n\n assert ROUNDED.substitute(options) == ASCII\n \n assert SIMPLE_HEAVY.substitute(options) == ASCII\n assert HEAVY.substitute(options) == ASCII\n assert HEAVY_EDGE.substitute(options) == ASCII\n assert HEAVY_HEAD.substitute(options) == ASCII", "test_prefix_file_path": "tests/test_box.py", "test_prefix_start_lineno": 89, "test_prefix_end_lineno": 105, "test_target": "tests/test_box.py::test_box_substitute_for_different_box_ascii_encoding", "ground_truth_oracle": "assert MINIMAL_HEAVY_HEAD.substitute(options) == ASCII", "ground_truth_oracle_lineno": 101, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def substitute(self, options: \"ConsoleOptions\", safe: bool = True) -> \"Box\":\n \"\"\"Substitute this box for another if it won't render due to platform issues.\n\n Args:\n options (ConsoleOptions): Console options used in rendering.\n safe (bool, optional): Substitute this for another Box if there are known problems\n displaying on the platform (currently only relevant on Windows). Default is True.\n\n Returns:\n Box: A different Box or the same Box.\n \"\"\"\n box = self\n if options.legacy_windows and safe:\n box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box)\n if options.ascii_only and not box.ascii:\n box = ASCII\n return box", "focal_method_file_path": "rich/box.py", "focal_method_start_lineno": 67, "focal_method_end_lineno": 83} {"index": 333, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_renderable_column", "test_class_name": "", "original_test_prefix": "def test_renderable_column():\n column = RenderableColumn(\"foo\")\n task = Task(1, \"test\", 100, 20, _get_time=lambda: 1.0)\n assert column.render(task) == \"foo\"", "test_prefix": "def test_renderable_column():\n column = RenderableColumn(\"foo\")\n task = Task(1, \"test\", 100, 20, _get_time=lambda: 1.0)\n ", "test_prefix_file_path": "tests/test_progress.py", "test_prefix_start_lineno": 123, "test_prefix_end_lineno": 126, "test_target": "tests/test_progress.py::test_renderable_column", "ground_truth_oracle": "assert column.render(task) == \"foo\"", "ground_truth_oracle_lineno": 126, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def render(self, task: \"Task\") -> RenderableType:\n return self.renderable", "focal_method_file_path": "rich/progress.py", "focal_method_start_lineno": 562, "focal_method_end_lineno": 563} {"index": 334, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_pager", "test_class_name": "", "original_test_prefix": "def test_pager() -> None:\n console = Console(_environ={})\n\n pager_content: Optional[str] = None\n\n def mock_pager(content: str) -> None:\n nonlocal pager_content\n pager_content = content\n\n pager = SystemPager()\n pager._pager = mock_pager\n\n with console.pager(pager):\n console.print(\"[bold]Hello World\")\n assert pager_content == \"Hello World\\n\"\n\n with console.pager(pager, styles=True, links=False):\n console.print(\"[bold link https:/example.org]Hello World\")\n\n assert pager_content == \"Hello World\\n\"", "test_prefix": "def test_pager() -> None:\n console = Console(_environ={})\n\n pager_content: Optional[str] = None\n\n def mock_pager(content: str) -> None:\n nonlocal pager_content\n pager_content = content\n\n pager = SystemPager()\n pager._pager = mock_pager\n\n with console.pager(pager):\n console.print(\"[bold]Hello World\")\n \n\n with console.pager(pager, styles=True, links=False):\n console.print(\"[bold link https:/example.org]Hello World\")\n\n ", "test_prefix_file_path": "tests/test_console.py", "test_prefix_start_lineno": 622, "test_prefix_end_lineno": 641, "test_target": "tests/test_console.py::test_pager", "ground_truth_oracle": "assert pager_content == \"Hello World\\n\"", "ground_truth_oracle_lineno": 636, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def pager(\n self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False\n ) -> PagerContext:\n \"\"\"A context manager to display anything printed within a \"pager\". The pager application\n is defined by the system and will typically support at least pressing a key to scroll.\n\n Args:\n pager (Pager, optional): A pager object, or None to use :class:`~rich.pager.SystemPager`. Defaults to None.\n styles (bool, optional): Show styles in pager. Defaults to False.\n links (bool, optional): Show links in pager. Defaults to False.\n\n Example:\n >>> from rich.console import Console\n >>> from rich.__main__ import make_test_card\n >>> console = Console()\n >>> with console.pager():\n console.print(make_test_card())\n\n Returns:\n PagerContext: A context manager.\n \"\"\"\n return PagerContext(self, pager=pager, styles=styles, links=links)", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 1119, "focal_method_end_lineno": 1140} {"index": 335, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_prompt_str_default", "test_class_name": "", "original_test_prefix": "def test_prompt_str_default():\n INPUT = \"\"\n console = Console(file=io.StringIO())\n name = Prompt.ask(\n \"what is your name\",\n console=console,\n default=\"Will\",\n stream=io.StringIO(INPUT),\n )\n assert name == \"Will\"\n expected = \"what is your name (Will): \"\n output = console.file.getvalue()\n print(repr(output))\n assert output == expected", "test_prefix": "def test_prompt_str_default():\n INPUT = \"\"\n console = Console(file=io.StringIO())\n name = Prompt.ask(\n \"what is your name\",\n console=console,\n default=\"Will\",\n stream=io.StringIO(INPUT),\n )\n \n expected = \"what is your name (Will): \"\n output = console.file.getvalue()\n print(repr(output))\n assert output == expected", "test_prefix_file_path": "tests/test_prompt.py", "test_prefix_start_lineno": 42, "test_prefix_end_lineno": 55, "test_target": "tests/test_prompt.py::test_prompt_str_default", "ground_truth_oracle": "assert name == \"Will\"", "ground_truth_oracle_lineno": 51, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n @overload\n def ask(\n cls,\n prompt: TextType = \"\",\n *,\n console: Optional[Console] = None,\n password: bool = False,\n choices: Optional[List[str]] = None,\n case_sensitive: bool = True,\n show_default: bool = True,\n show_choices: bool = True,\n default: DefaultType,\n stream: Optional[TextIO] = None,\n ) -> Union[DefaultType, PromptType]:\n ...", "focal_method_file_path": "rich/prompt.py", "focal_method_start_lineno": 78, "focal_method_end_lineno": 93} {"index": 336, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_track_thread", "test_class_name": "", "original_test_prefix": "def test_track_thread() -> None:\n progress = Progress()\n task_id = progress.add_task(\"foo\")\n track_thread = _TrackThread(progress, task_id, 0.1)\n assert track_thread.completed == 0\n from time import sleep\n\n with track_thread:\n track_thread.completed = 1\n sleep(0.3)\n assert progress.tasks[task_id].completed >= 1\n track_thread.completed += 1", "test_prefix": "def test_track_thread() -> None:\n progress = Progress()\n task_id = progress.add_task(\"foo\")\n track_thread = _TrackThread(progress, task_id, 0.1)\n assert track_thread.completed == 0\n from time import sleep\n\n with track_thread:\n track_thread.completed = 1\n sleep(0.3)\n \n track_thread.completed += 1", "test_prefix_file_path": "tests/test_progress.py", "test_prefix_start_lineno": 451, "test_prefix_end_lineno": 462, "test_target": "tests/test_progress.py::test_track_thread", "ground_truth_oracle": "assert progress.tasks[task_id].completed >= 1", "ground_truth_oracle_lineno": 461, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class _TrackThread(Thread):\n \"\"\"A thread to periodically update progress.\"\"\"\n\n def __init__(self, progress: \"Progress\", task_id: \"TaskID\", update_period: float):\n self.progress = progress\n self.task_id = task_id\n self.update_period = update_period\n self.done = Event()\n\n self.completed = 0\n super().__init__(daemon=True)\n\n def run(self) -> None:\n task_id = self.task_id\n advance = self.progress.advance\n update_period = self.update_period\n last_completed = 0\n wait = self.done.wait\n while not wait(update_period) and self.progress.live.is_started:\n completed = self.completed\n if last_completed != completed:\n advance(task_id, completed - last_completed)\n last_completed = completed\n\n self.progress.update(self.task_id, completed=self.completed, refresh=True)\n\n def __enter__(self) -> \"_TrackThread\":\n self.start()\n return self\n\n def __exit__(\n self,\n exc_type: Optional[Type[BaseException]],\n exc_val: Optional[BaseException],\n exc_tb: Optional[TracebackType],\n ) -> None:\n self.done.set()\n self.join()", "focal_method_file_path": "rich/progress.py", "focal_method_start_lineno": 64, "focal_method_end_lineno": 101} {"index": 337, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ipy_display_hook__multiple_special_reprs", "test_class_name": "", "original_test_prefix": "def test_ipy_display_hook__multiple_special_reprs() -> None:\n \"\"\"\n The case where there are multiple IPython special _repr_*_\n methods on the object, and one of them returns None but another\n one does not.\n \"\"\"\n console = Console(file=io.StringIO(), force_jupyter=True)\n\n class Thing:\n def __repr__(self):\n return \"A Thing\"\n\n def _repr_latex_(self):\n return None\n\n def _repr_html_(self):\n return \"hello\"\n\n result = _ipy_display_hook(Thing(), console=console)\n assert result == \"A Thing\"", "test_prefix": "def test_ipy_display_hook__multiple_special_reprs() -> None:\n \"\"\"\n The case where there are multiple IPython special _repr_*_\n methods on the object, and one of them returns None but another\n one does not.\n \"\"\"\n console = Console(file=io.StringIO(), force_jupyter=True)\n\n class Thing:\n def __repr__(self):\n return \"A Thing\"\n\n def _repr_latex_(self):\n return None\n\n def _repr_html_(self):\n return \"hello\"\n\n result = _ipy_display_hook(Thing(), console=console)\n ", "test_prefix_file_path": "tests/test_pretty.py", "test_prefix_start_lineno": 79, "test_prefix_end_lineno": 98, "test_target": "tests/test_pretty.py::test_ipy_display_hook__multiple_special_reprs", "ground_truth_oracle": "assert result == \"A Thing\"", "ground_truth_oracle_lineno": 98, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _ipy_display_hook(\n value: Any,\n console: Optional[\"Console\"] = None,\n overflow: \"OverflowMethod\" = \"ignore\",\n crop: bool = False,\n indent_guides: bool = False,\n max_length: Optional[int] = None,\n max_string: Optional[int] = None,\n max_depth: Optional[int] = None,\n expand_all: bool = False,\n) -> Union[str, None]:\n # needed here to prevent circular import:\n from .console import ConsoleRenderable\n\n # always skip rich generated jupyter renderables or None values\n if _safe_isinstance(value, JupyterRenderable) or value is None:\n return None\n\n console = console or get_console()\n\n with console.capture() as capture:\n # certain renderables should start on a new line\n if _safe_isinstance(value, ConsoleRenderable):\n console.line()\n console.print(\n (\n value\n if _safe_isinstance(value, RichRenderable)\n else Pretty(\n value,\n overflow=overflow,\n indent_guides=indent_guides,\n max_length=max_length,\n max_string=max_string,\n max_depth=max_depth,\n expand_all=expand_all,\n margin=12,\n )\n ),\n crop=crop,\n new_line_start=True,\n end=\"\",\n )\n # strip trailing newline, not usually part of a text repr\n # I'm not sure if this should be prevented at a lower level\n return capture.get().rstrip(\"\\n\")", "focal_method_file_path": "rich/pretty.py", "focal_method_start_lineno": 113, "focal_method_end_lineno": 158} {"index": 338, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_parse_rgb_hex", "test_class_name": "", "original_test_prefix": "def test_parse_rgb_hex() -> None:\n assert parse_rgb_hex(\"aabbcc\") == ColorTriplet(0xAA, 0xBB, 0xCC)", "test_prefix": "def test_parse_rgb_hex() -> None:\n ", "test_prefix_file_path": "tests/test_color.py", "test_prefix_start_lineno": 180, "test_prefix_end_lineno": 181, "test_target": "tests/test_color.py::test_parse_rgb_hex", "ground_truth_oracle": "assert parse_rgb_hex(\"aabbcc\") == ColorTriplet(0xAA, 0xBB, 0xCC)", "ground_truth_oracle_lineno": 181, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class ColorTriplet(NamedTuple):\n \"\"\"The red, green, and blue components of a color.\"\"\"\n\n red: int\n \"\"\"Red component in 0 to 255 range.\"\"\"\n green: int\n \"\"\"Green component in 0 to 255 range.\"\"\"\n blue: int\n \"\"\"Blue component in 0 to 255 range.\"\"\"\n\n @property\n def hex(self) -> str:\n \"\"\"get the color triplet in CSS style.\"\"\"\n red, green, blue = self\n return f\"#{red:02x}{green:02x}{blue:02x}\"\n\n @property\n def rgb(self) -> str:\n \"\"\"The color in RGB format.\n\n Returns:\n str: An rgb color, e.g. ``\"rgb(100,23,255)\"``.\n \"\"\"\n red, green, blue = self\n return f\"rgb({red},{green},{blue})\"\n\n @property\n def normalized(self) -> Tuple[float, float, float]:\n \"\"\"Convert components into floats between 0 and 1.\n\n Returns:\n Tuple[float, float, float]: A tuple of three normalized colour components.\n \"\"\"\n red, green, blue = self\n return red / 255.0, green / 255.0, blue / 255.0", "focal_method_file_path": "rich/color_triplet.py", "focal_method_start_lineno": 4, "focal_method_end_lineno": 38} {"index": 339, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_copy", "test_class_name": "", "original_test_prefix": "def test_copy():\n style = Style(color=\"red\", bgcolor=\"black\", italic=True)\n assert style == style.copy()\n assert style is not style.copy()", "test_prefix": "def test_copy():\n style = Style(color=\"red\", bgcolor=\"black\", italic=True)\n assert style == style.copy()\n ", "test_prefix_file_path": "tests/test_style.py", "test_prefix_start_lineno": 150, "test_prefix_end_lineno": 153, "test_target": "tests/test_style.py::test_copy", "ground_truth_oracle": "assert style is not style.copy()", "ground_truth_oracle_lineno": 153, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def copy(self) -> \"Style\":\n \"\"\"Get a copy of this style.\n\n Returns:\n Style: A new Style instance with identical attributes.\n \"\"\"\n if self._null:\n return NULL_STYLE\n style: Style = self.__new__(Style)\n style._ansi = self._ansi\n style._style_definition = self._style_definition\n style._color = self._color\n style._bgcolor = self._bgcolor\n style._attributes = self._attributes\n style._set_attributes = self._set_attributes\n style._link = self._link\n style._link_id = f\"{randint(0, 999999)}\" if self._link else \"\"\n style._hash = self._hash\n style._null = False\n style._meta = self._meta\n return style", "focal_method_file_path": "rich/style.py", "focal_method_start_lineno": 622, "focal_method_end_lineno": 642} {"index": 340, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_input_password", "test_class_name": "", "original_test_prefix": "def test_input_password(monkeypatch, capsys) -> None:\n def fake_input(prompt, stream=None):\n console.file.write(prompt)\n return \"bar\"\n\n import rich.console\n\n monkeypatch.setattr(rich.console, \"getpass\", fake_input)\n console = Console()\n user_input = console.input(prompt=\"foo:\", password=True)\n assert capsys.readouterr().out == \"foo:\"\n assert user_input == \"bar\"", "test_prefix": "def test_input_password(monkeypatch, capsys) -> None:\n def fake_input(prompt, stream=None):\n console.file.write(prompt)\n return \"bar\"\n\n import rich.console\n\n monkeypatch.setattr(rich.console, \"getpass\", fake_input)\n console = Console()\n user_input = console.input(prompt=\"foo:\", password=True)\n assert capsys.readouterr().out == \"foo:\"\n ", "test_prefix_file_path": "tests/test_console.py", "test_prefix_start_lineno": 398, "test_prefix_end_lineno": 409, "test_target": "tests/test_console.py::test_input_password", "ground_truth_oracle": "assert user_input == \"bar\"", "ground_truth_oracle_lineno": 409, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def input(\n self,\n prompt: TextType = \"\",\n *,\n markup: bool = True,\n emoji: bool = True,\n password: bool = False,\n stream: Optional[TextIO] = None,\n ) -> str:\n \"\"\"Displays a prompt and waits for input from the user. The prompt may contain color / style.\n\n It works in the same way as Python's builtin :func:`input` function and provides elaborate line editing and history features if Python's builtin :mod:`readline` module is previously loaded.\n\n Args:\n prompt (Union[str, Text]): Text to render in the prompt.\n markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True.\n emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.\n password: (bool, optional): Hide typed text. Defaults to False.\n stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.\n\n Returns:\n str: Text read from stdin.\n \"\"\"\n if prompt:\n self.print(prompt, markup=markup, emoji=emoji, end=\"\")\n if password:\n result = getpass(\"\", stream=stream)\n else:\n if stream:\n result = stream.readline()\n else:\n result = input()\n return result", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 2139, "focal_method_end_lineno": 2171} {"index": 341, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_array", "test_class_name": "", "original_test_prefix": "def test_array() -> None:\n test_array = array(\"I\", [1, 2, 3])\n result = pretty_repr(test_array)\n assert result == \"array('I', [1, 2, 3])\"", "test_prefix": "def test_array() -> None:\n test_array = array(\"I\", [1, 2, 3])\n result = pretty_repr(test_array)\n ", "test_prefix_file_path": "tests/test_pretty.py", "test_prefix_start_lineno": 526, "test_prefix_end_lineno": 529, "test_target": "tests/test_pretty.py::test_array", "ground_truth_oracle": "assert result == \"array('I', [1, 2, 3])\"", "ground_truth_oracle_lineno": 529, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def pretty_repr(\n _object: Any,\n *,\n max_width: int = 80,\n indent_size: int = 4,\n max_length: Optional[int] = None,\n max_string: Optional[int] = None,\n max_depth: Optional[int] = None,\n expand_all: bool = False,\n) -> str:\n \"\"\"Prettify repr string by expanding on to new lines to fit within a given width.\n\n Args:\n _object (Any): Object to repr.\n max_width (int, optional): Desired maximum width of repr string. Defaults to 80.\n indent_size (int, optional): Number of spaces to indent. Defaults to 4.\n max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n Defaults to None.\n max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.\n Defaults to None.\n max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.\n Defaults to None.\n expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.\n\n Returns:\n str: A possibly multi-line representation of the object.\n \"\"\"\n\n if _safe_isinstance(_object, Node):\n node = _object\n else:\n node = traverse(\n _object, max_length=max_length, max_string=max_string, max_depth=max_depth\n )\n repr_str: str = node.render(\n max_width=max_width, indent_size=indent_size, expand_all=expand_all\n )\n return repr_str", "focal_method_file_path": "rich/pretty.py", "focal_method_start_lineno": 878, "focal_method_end_lineno": 915} {"index": 342, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_rich_cast", "test_class_name": "", "original_test_prefix": "def test_rich_cast():\n table = STANDARD_PALETTE.__rich__()\n assert isinstance(table, Table)\n assert table.row_count == 16", "test_prefix": "def test_rich_cast():\n table = STANDARD_PALETTE.__rich__()\n \n assert table.row_count == 16", "test_prefix_file_path": "tests/test_palette.py", "test_prefix_start_lineno": 5, "test_prefix_end_lineno": 8, "test_target": "tests/test_palette.py::test_rich_cast", "ground_truth_oracle": "assert isinstance(table, Table)", "ground_truth_oracle_lineno": 7, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def __rich__(self) -> \"Table\":\n from rich.color import Color\n from rich.style import Style\n from rich.text import Text\n from rich.table import Table\n\n table = Table(\n \"index\",\n \"RGB\",\n \"Color\",\n title=\"Palette\",\n caption=f\"{len(self._colors)} colors\",\n highlight=True,\n caption_justify=\"right\",\n )\n for index, color in enumerate(self._colors):\n table.add_row(\n str(index),\n repr(color),\n Text(\" \" * 16, style=Style(bgcolor=Color.from_rgb(*color))),\n )\n return table", "focal_method_file_path": "rich/palette.py", "focal_method_start_lineno": 20, "focal_method_end_lineno": 41} {"index": 343, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_no_columns", "test_class_name": "", "original_test_prefix": "def test_no_columns():\n console = Console(color_system=None)\n console.begin_capture()\n console.print(Table())\n output = console.end_capture()\n print(repr(output))\n assert output == \"\\n\"", "test_prefix": "def test_no_columns():\n console = Console(color_system=None)\n console.begin_capture()\n console.print(Table())\n output = console.end_capture()\n print(repr(output))\n ", "test_prefix_file_path": "tests/test_table.py", "test_prefix_start_lineno": 143, "test_prefix_end_lineno": 149, "test_target": "tests/test_table.py::test_no_columns", "ground_truth_oracle": "assert output == \"\\n\"", "ground_truth_oracle_lineno": 149, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def end_capture(self) -> str:\n \"\"\"End capture mode and return captured string.\n\n Returns:\n str: Console output.\n \"\"\"\n render_result = self._render_buffer(self._buffer)\n del self._buffer[:]\n self._exit_buffer()\n return render_result", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 876, "focal_method_end_lineno": 885} {"index": 344, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_measure", "test_class_name": "", "original_test_prefix": "def test_measure():\n console = Console(width=120)\n bar = ProgressBar()\n measurement = bar.__rich_measure__(console, console.options)\n assert measurement.minimum == 4\n assert measurement.maximum == 120", "test_prefix": "def test_measure():\n console = Console(width=120)\n bar = ProgressBar()\n measurement = bar.__rich_measure__(console, console.options)\n assert measurement.minimum == 4\n ", "test_prefix_file_path": "tests/test_bar.py", "test_prefix_start_lineno": 42, "test_prefix_end_lineno": 47, "test_target": "tests/test_bar.py::test_measure", "ground_truth_oracle": "assert measurement.maximum == 120", "ground_truth_oracle_lineno": 47, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def __rich_measure__(\n self, console: Console, options: ConsoleOptions\n ) -> Measurement:\n return (\n Measurement(self.width, self.width)\n if self.width is not None\n else Measurement(4, options.max_width)\n )", "focal_method_file_path": "rich/progress_bar.py", "focal_method_start_lineno": 200, "focal_method_end_lineno": 207} {"index": 345, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ipy_display_hook__repr_html", "test_class_name": "", "original_test_prefix": "def test_ipy_display_hook__repr_html() -> None:\n console = Console(file=io.StringIO(), force_jupyter=True)\n\n class Thing:\n def _repr_html_(self):\n return \"hello\"\n\n console.begin_capture()\n _ipy_display_hook(Thing(), console=console)\n\n # Rendering delegated to notebook because _repr_html_ method exists\n assert console.end_capture() == \"\"", "test_prefix": "def test_ipy_display_hook__repr_html() -> None:\n console = Console(file=io.StringIO(), force_jupyter=True)\n\n class Thing:\n def _repr_html_(self):\n return \"hello\"\n\n console.begin_capture()\n _ipy_display_hook(Thing(), console=console)\n\n # Rendering delegated to notebook because _repr_html_ method exists\n ", "test_prefix_file_path": "tests/test_pretty.py", "test_prefix_start_lineno": 65, "test_prefix_end_lineno": 76, "test_target": "tests/test_pretty.py::test_ipy_display_hook__repr_html", "ground_truth_oracle": "assert console.end_capture() == \"\"", "ground_truth_oracle_lineno": 76, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def end_capture(self) -> str:\n \"\"\"End capture mode and return captured string.\n\n Returns:\n str: Console output.\n \"\"\"\n render_result = self._render_buffer(self._buffer)\n del self._buffer[:]\n self._exit_buffer()\n return render_result", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 876, "focal_method_end_lineno": 885} {"index": 346, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_print_json_data_with_default", "test_class_name": "", "original_test_prefix": "def test_print_json_data_with_default():\n date = datetime.date(2021, 1, 1)\n json = JSON.from_data({\"date\": date}, default=lambda d: d.isoformat())\n assert str(json.text) == '{\\n \"date\": \"2021-01-01\"\\n}'", "test_prefix": "def test_print_json_data_with_default():\n date = datetime.date(2021, 1, 1)\n json = JSON.from_data({\"date\": date}, default=lambda d: d.isoformat())\n ", "test_prefix_file_path": "tests/test_json.py", "test_prefix_start_lineno": 5, "test_prefix_end_lineno": 8, "test_target": "tests/test_json.py::test_print_json_data_with_default", "ground_truth_oracle": "assert str(json.text) == '{\\n \"date\": \"2021-01-01\"\\n}'", "ground_truth_oracle_lineno": 8, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def from_data(\n cls,\n data: Any,\n indent: Union[None, int, str] = 2,\n highlight: bool = True,\n skip_keys: bool = False,\n ensure_ascii: bool = False,\n check_circular: bool = True,\n allow_nan: bool = True,\n default: Optional[Callable[[Any], Any]] = None,\n sort_keys: bool = False,\n ) -> \"JSON\":\n \"\"\"Encodes a JSON object from arbitrary data.\n\n Args:\n data (Any): An object that may be encoded in to JSON\n indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.\n highlight (bool, optional): Enable highlighting. Defaults to True.\n default (Callable, optional): Optional callable which will be called for objects that cannot be serialized. Defaults to None.\n skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.\n ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.\n check_circular (bool, optional): Check for circular references. Defaults to True.\n allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.\n default (Callable, optional): A callable that converts values that can not be encoded\n in to something that can be JSON encoded. Defaults to None.\n sort_keys (bool, optional): Sort dictionary keys. Defaults to False.\n\n Returns:\n JSON: New JSON object from the given data.\n \"\"\"\n json_instance: \"JSON\" = cls.__new__(cls)\n json = dumps(\n data,\n indent=indent,\n skipkeys=skip_keys,\n ensure_ascii=ensure_ascii,\n check_circular=check_circular,\n allow_nan=allow_nan,\n default=default,\n sort_keys=sort_keys,\n )\n highlighter = JSONHighlighter() if highlight else NullHighlighter()\n json_instance.text = highlighter(json)\n json_instance.text.no_wrap = True\n json_instance.text.overflow = None\n return json_instance", "focal_method_file_path": "rich/json.py", "focal_method_start_lineno": 53, "focal_method_end_lineno": 99} {"index": 347, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_loop_first", "test_class_name": "", "original_test_prefix": "def test_loop_first():\n assert list(loop_first([])) == []\n iterable = loop_first([\"apples\", \"oranges\", \"pears\", \"lemons\"])\n assert next(iterable) == (True, \"apples\")\n assert next(iterable) == (False, \"oranges\")\n assert next(iterable) == (False, \"pears\")\n assert next(iterable) == (False, \"lemons\")", "test_prefix": "def test_loop_first():\n assert list(loop_first([])) == []\n iterable = loop_first([\"apples\", \"oranges\", \"pears\", \"lemons\"])\n assert next(iterable) == (True, \"apples\")\n \n assert next(iterable) == (False, \"pears\")\n assert next(iterable) == (False, \"lemons\")", "test_prefix_file_path": "tests/test_tools.py", "test_prefix_start_lineno": 5, "test_prefix_end_lineno": 11, "test_target": "tests/test_tools.py::test_loop_first", "ground_truth_oracle": "assert next(iterable) == (False, \"oranges\")", "ground_truth_oracle_lineno": 9, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n \"\"\"Iterate and generate a tuple with a flag for first value.\"\"\"\n iter_values = iter(values)\n try:\n value = next(iter_values)\n except StopIteration:\n return\n yield True, value\n for value in iter_values:\n yield False, value", "focal_method_file_path": "rich/_loop.py", "focal_method_start_lineno": 6, "focal_method_end_lineno": 15} {"index": 348, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_copy", "test_class_name": "", "original_test_prefix": "def test_copy():\n text = Text()\n text.append(\"Hello\", \"bold\")\n text.append(\" \")\n text.append(\"World\", \"italic\")\n test_copy = text.copy()\n assert text == test_copy\n assert text is not test_copy", "test_prefix": "def test_copy():\n text = Text()\n text.append(\"Hello\", \"bold\")\n text.append(\" \")\n text.append(\"World\", \"italic\")\n test_copy = text.copy()\n assert text == test_copy\n ", "test_prefix_file_path": "tests/test_text.py", "test_prefix_start_lineno": 119, "test_prefix_end_lineno": 126, "test_target": "tests/test_text.py::test_copy", "ground_truth_oracle": "assert text is not test_copy", "ground_truth_oracle_lineno": 126, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def copy(self) -> \"Text\":\n \"\"\"Return a copy of this instance.\"\"\"\n copy_self = Text(\n self.plain,\n style=self.style,\n justify=self.justify,\n overflow=self.overflow,\n no_wrap=self.no_wrap,\n end=self.end,\n tab_size=self.tab_size,\n )\n copy_self._spans[:] = self._spans\n return copy_self", "focal_method_file_path": "rich/text.py", "focal_method_start_lineno": 443, "focal_method_end_lineno": 455} {"index": 349, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_style_for_token", "test_class_name": "", "original_test_prefix": "def test_get_style_for_token() -> None:\n # from pygments.style import Style as PygmentsStyle\n # pygments_style = PygmentsStyle()\n from pygments.style import Token\n\n style = PygmentsSyntaxTheme(\"default\")\n style_dict = {Token.Text: Style(color=None)}\n style._style_cache = style_dict\n syntax = Syntax(\n CODE,\n lexer=\"python\",\n line_numbers=True,\n line_range=(2, 10),\n theme=style,\n code_width=60,\n word_wrap=True,\n background_color=\"red\",\n )\n assert syntax._get_line_numbers_color() == Color.default()", "test_prefix": "def test_get_style_for_token() -> None:\n # from pygments.style import Style as PygmentsStyle\n # pygments_style = PygmentsStyle()\n from pygments.style import Token\n\n style = PygmentsSyntaxTheme(\"default\")\n style_dict = {Token.Text: Style(color=None)}\n style._style_cache = style_dict\n syntax = Syntax(\n CODE,\n lexer=\"python\",\n line_numbers=True,\n line_range=(2, 10),\n theme=style,\n code_width=60,\n word_wrap=True,\n background_color=\"red\",\n )\n ", "test_prefix_file_path": "tests/test_syntax.py", "test_prefix_start_lineno": 212, "test_prefix_end_lineno": 230, "test_target": "tests/test_syntax.py::test_get_style_for_token", "ground_truth_oracle": "assert syntax._get_line_numbers_color() == Color.default()", "ground_truth_oracle_lineno": 230, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def default(cls) -> \"Color\":\n \"\"\"Get a Color instance representing the default color.\n\n Returns:\n Color: Default color.\n \"\"\"\n return cls(name=\"default\", type=ColorType.DEFAULT)", "focal_method_file_path": "rich/color.py", "focal_method_start_lineno": 422, "focal_method_end_lineno": 429} {"index": 350, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_download_progress_uses_binary_units", "test_class_name": "", "original_test_prefix": "def test_download_progress_uses_binary_units() -> None:\n column = DownloadColumn(binary_units=True)\n test_task = Task(1, \"test\", 1024, 512, _get_time=lambda: 1.0)\n rendered_progress = str(column.render(test_task))\n expected = \"0.5/1.0 KiB\"\n assert rendered_progress == expected", "test_prefix": "def test_download_progress_uses_binary_units() -> None:\n column = DownloadColumn(binary_units=True)\n test_task = Task(1, \"test\", 1024, 512, _get_time=lambda: 1.0)\n rendered_progress = str(column.render(test_task))\n expected = \"0.5/1.0 KiB\"\n ", "test_prefix_file_path": "tests/test_progress.py", "test_prefix_start_lineno": 160, "test_prefix_end_lineno": 165, "test_target": "tests/test_progress.py::test_download_progress_uses_binary_units", "ground_truth_oracle": "assert rendered_progress == expected", "ground_truth_oracle_lineno": 165, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def render(self, task: \"Task\") -> Text:\n \"\"\"Calculate common unit for completed and total.\"\"\"\n completed = int(task.completed)\n\n unit_and_suffix_calculation_base = (\n int(task.total) if task.total is not None else completed\n )\n if self.binary_units:\n unit, suffix = filesize.pick_unit_and_suffix(\n unit_and_suffix_calculation_base,\n [\"bytes\", \"KiB\", \"MiB\", \"GiB\", \"TiB\", \"PiB\", \"EiB\", \"ZiB\", \"YiB\"],\n 1024,\n )\n else:\n unit, suffix = filesize.pick_unit_and_suffix(\n unit_and_suffix_calculation_base,\n [\"bytes\", \"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"],\n 1000,\n )\n precision = 0 if unit == 1 else 1\n\n completed_ratio = completed / unit\n completed_str = f\"{completed_ratio:,.{precision}f}\"\n\n if task.total is not None:\n total = int(task.total)\n total_ratio = total / unit\n total_str = f\"{total_ratio:,.{precision}f}\"\n else:\n total_str = \"?\"\n\n download_status = f\"{completed_str}/{total_str} {suffix}\"\n download_text = Text(download_status, style=\"progress.download\")\n return download_text", "focal_method_file_path": "rich/progress.py", "focal_method_start_lineno": 878, "focal_method_end_lineno": 911} {"index": 351, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_traditional", "test_class_name": "", "original_test_prefix": "def test_traditional():\n assert filesize.decimal(0) == \"0 bytes\"\n assert filesize.decimal(1) == \"1 byte\"\n assert filesize.decimal(2) == \"2 bytes\"\n assert filesize.decimal(1000) == \"1.0 kB\"\n assert filesize.decimal(1.5 * 1000 * 1000) == \"1.5 MB\"\n assert filesize.decimal(0, precision=2) == \"0 bytes\"\n assert filesize.decimal(1111, precision=0) == \"1 kB\"\n assert filesize.decimal(1111, precision=1) == \"1.1 kB\"\n assert filesize.decimal(1111, precision=2) == \"1.11 kB\"\n assert filesize.decimal(1111, separator=\"\") == \"1.1kB\"", "test_prefix": "def test_traditional():\n \n assert filesize.decimal(1) == \"1 byte\"\n assert filesize.decimal(2) == \"2 bytes\"\n assert filesize.decimal(1000) == \"1.0 kB\"\n assert filesize.decimal(1.5 * 1000 * 1000) == \"1.5 MB\"\n assert filesize.decimal(0, precision=2) == \"0 bytes\"\n assert filesize.decimal(1111, precision=0) == \"1 kB\"\n assert filesize.decimal(1111, precision=1) == \"1.1 kB\"\n assert filesize.decimal(1111, precision=2) == \"1.11 kB\"\n assert filesize.decimal(1111, separator=\"\") == \"1.1kB\"", "test_prefix_file_path": "tests/test_filesize.py", "test_prefix_start_lineno": 4, "test_prefix_end_lineno": 14, "test_target": "tests/test_filesize.py::test_traditional", "ground_truth_oracle": "assert filesize.decimal(0) == \"0 bytes\"", "ground_truth_oracle_lineno": 5, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def decimal(\n size: int,\n *,\n precision: Optional[int] = 1,\n separator: Optional[str] = \" \",\n) -> str:\n \"\"\"Convert a filesize in to a string (powers of 1000, SI prefixes).\n\n In this convention, ``1000 B = 1 kB``.\n\n This is typically the format used to advertise the storage\n capacity of USB flash drives and the like (*256 MB* meaning\n actually a storage capacity of more than *256 000 000 B*),\n or used by **Mac OS X** since v10.6 to report file sizes.\n\n Arguments:\n int (size): A file size.\n int (precision): The number of decimal places to include (default = 1).\n str (separator): The string to separate the value from the units (default = \" \").\n\n Returns:\n `str`: A string containing a abbreviated file size and units.\n\n Example:\n >>> filesize.decimal(30000)\n '30.0 kB'\n >>> filesize.decimal(30000, precision=2, separator=\"\")\n '30.00kB'\n\n \"\"\"\n return _to_str(\n size,\n (\"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"),\n 1000,\n precision=precision,\n separator=separator,\n )", "focal_method_file_path": "rich/filesize.py", "focal_method_start_lineno": 52, "focal_method_end_lineno": 88} {"index": 352, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_markup_property", "test_class_name": "", "original_test_prefix": "def test_markup_property():\n assert Text(\"\").markup == \"\"\n assert Text(\"foo\").markup == \"foo\"\n assert Text(\"foo\", style=\"bold\").markup == \"[bold]foo[/bold]\"\n assert Text.from_markup(\"foo [red]bar[/red]\").markup == \"foo [red]bar[/red]\"\n assert (\n Text.from_markup(\"foo [red]bar[/red]\", style=\"bold\").markup\n == \"[bold]foo [red]bar[/red][/bold]\"\n )\n assert (\n Text.from_markup(\"[bold]foo [italic]bar[/bold] baz[/italic]\").markup\n == \"[bold]foo [italic]bar[/bold] baz[/italic]\"\n )\n assert Text(\"[bold]foo\").markup == \"\\\\[bold]foo\"", "test_prefix": "def test_markup_property():\n assert Text(\"\").markup == \"\"\n assert Text(\"foo\").markup == \"foo\"\n assert Text(\"foo\", style=\"bold\").markup == \"[bold]foo[/bold]\"\n \n assert (\n Text.from_markup(\"foo [red]bar[/red]\", style=\"bold\").markup\n == \"[bold]foo [red]bar[/red][/bold]\"\n )\n assert (\n Text.from_markup(\"[bold]foo [italic]bar[/bold] baz[/italic]\").markup\n == \"[bold]foo [italic]bar[/bold] baz[/italic]\"\n )\n assert Text(\"[bold]foo\").markup == \"\\\\[bold]foo\"", "test_prefix_file_path": "tests/test_text.py", "test_prefix_start_lineno": 1012, "test_prefix_end_lineno": 1025, "test_target": "tests/test_text.py::test_markup_property", "ground_truth_oracle": "assert Text.from_markup(\"foo [red]bar[/red]\").markup == \"foo [red]bar[/red]\"", "ground_truth_oracle_lineno": 1016, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def from_markup(\n cls,\n text: str,\n *,\n style: Union[str, Style] = \"\",\n emoji: bool = True,\n emoji_variant: Optional[EmojiVariant] = None,\n justify: Optional[\"JustifyMethod\"] = None,\n overflow: Optional[\"OverflowMethod\"] = None,\n end: str = \"\\n\",\n ) -> \"Text\":\n \"\"\"Create Text instance from markup.\n\n Args:\n text (str): A string containing console markup.\n style (Union[str, Style], optional): Base style for text. Defaults to \"\".\n emoji (bool, optional): Also render emoji code. Defaults to True.\n emoji_variant (str, optional): Optional emoji variant, either \"text\" or \"emoji\". Defaults to None.\n justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n end (str, optional): Character to end text with. Defaults to \"\\\\\\\\n\".\n\n Returns:\n Text: A Text instance with markup rendered.\n \"\"\"\n from .markup import render\n\n rendered_text = render(text, style, emoji=emoji, emoji_variant=emoji_variant)\n rendered_text.justify = justify\n rendered_text.overflow = overflow\n rendered_text.end = end\n return rendered_text", "focal_method_file_path": "rich/text.py", "focal_method_start_lineno": 259, "focal_method_end_lineno": 291} {"index": 353, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_loop_last", "test_class_name": "", "original_test_prefix": "def test_loop_last():\n assert list(loop_last([])) == []\n iterable = loop_last([\"apples\", \"oranges\", \"pears\", \"lemons\"])\n assert next(iterable) == (False, \"apples\")\n assert next(iterable) == (False, \"oranges\")\n assert next(iterable) == (False, \"pears\")\n assert next(iterable) == (True, \"lemons\")", "test_prefix": "def test_loop_last():\n assert list(loop_last([])) == []\n iterable = loop_last([\"apples\", \"oranges\", \"pears\", \"lemons\"])\n assert next(iterable) == (False, \"apples\")\n assert next(iterable) == (False, \"oranges\")\n \n assert next(iterable) == (True, \"lemons\")", "test_prefix_file_path": "tests/test_tools.py", "test_prefix_start_lineno": 14, "test_prefix_end_lineno": 20, "test_target": "tests/test_tools.py::test_loop_last", "ground_truth_oracle": "assert next(iterable) == (False, \"pears\")", "ground_truth_oracle_lineno": 19, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n \"\"\"Iterate and generate a tuple with a flag for last value.\"\"\"\n iter_values = iter(values)\n try:\n previous_value = next(iter_values)\n except StopIteration:\n return\n for value in iter_values:\n yield False, previous_value\n previous_value = value\n yield True, previous_value", "focal_method_file_path": "rich/_loop.py", "focal_method_start_lineno": 18, "focal_method_end_lineno": 28} {"index": 354, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_guess_lexer", "test_class_name": "", "original_test_prefix": "def test_guess_lexer():\n assert Traceback._guess_lexer(\"foo.py\", \"code\") == \"python\"\n code_python = \"#! usr/bin/env python\\nimport this\"\n assert Traceback._guess_lexer(\"foo\", code_python) == \"python\"\n assert Traceback._guess_lexer(\"foo\", \"foo\\nbnar\") == \"text\"", "test_prefix": "def test_guess_lexer():\n \n code_python = \"#! usr/bin/env python\\nimport this\"\n assert Traceback._guess_lexer(\"foo\", code_python) == \"python\"\n assert Traceback._guess_lexer(\"foo\", \"foo\\nbnar\") == \"text\"", "test_prefix_file_path": "tests/test_traceback.py", "test_prefix_start_lineno": 251, "test_prefix_end_lineno": 255, "test_target": "tests/test_traceback.py::test_guess_lexer", "ground_truth_oracle": "assert Traceback._guess_lexer(\"foo.py\", \"code\") == \"python\"", "ground_truth_oracle_lineno": 252, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def _guess_lexer(cls, filename: str, code: str) -> str:\n ext = os.path.splitext(filename)[-1]\n if not ext:\n # No extension, look at first line to see if it is a hashbang\n # Note, this is an educated guess and not a guarantee\n # If it fails, the only downside is that the code is highlighted strangely\n new_line_index = code.index(\"\\n\")\n first_line = code[:new_line_index] if new_line_index != -1 else code\n if first_line.startswith(\"#!\") and \"python\" in first_line.lower():\n return \"python\"\n try:\n return cls.LEXERS.get(ext) or guess_lexer_for_filename(filename, code).name\n except ClassNotFound:\n return \"text\"", "focal_method_file_path": "rich/traceback.py", "focal_method_start_lineno": 728, "focal_method_end_lineno": 742} {"index": 355, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_extend_style", "test_class_name": "", "original_test_prefix": "def test_extend_style():\n text = Text.from_markup(\"[red]foo[/red] [bold]bar\")\n text.extend_style(0)\n\n assert text.plain == \"foo bar\"\n assert text.spans == [Span(0, 3, \"red\"), Span(4, 7, \"bold\")]\n\n text.extend_style(-1)\n assert text.plain == \"foo bar\"\n assert text.spans == [Span(0, 3, \"red\"), Span(4, 7, \"bold\")]\n\n text.extend_style(2)\n assert text.plain == \"foo bar \"\n assert text.spans == [Span(0, 3, \"red\"), Span(4, 9, \"bold\")]", "test_prefix": "def test_extend_style():\n text = Text.from_markup(\"[red]foo[/red] [bold]bar\")\n text.extend_style(0)\n\n \n assert text.spans == [Span(0, 3, \"red\"), Span(4, 7, \"bold\")]\n\n text.extend_style(-1)\n \n assert text.spans == [Span(0, 3, \"red\"), Span(4, 7, \"bold\")]\n\n text.extend_style(2)\n assert text.plain == \"foo bar \"\n assert text.spans == [Span(0, 3, \"red\"), Span(4, 9, \"bold\")]", "test_prefix_file_path": "tests/test_text.py", "test_prefix_start_lineno": 1028, "test_prefix_end_lineno": 1041, "test_target": "tests/test_text.py::test_extend_style", "ground_truth_oracle": "assert text.plain == \"foo bar\"", "ground_truth_oracle_lineno": 1036, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def from_markup(\n cls,\n text: str,\n *,\n style: Union[str, Style] = \"\",\n emoji: bool = True,\n emoji_variant: Optional[EmojiVariant] = None,\n justify: Optional[\"JustifyMethod\"] = None,\n overflow: Optional[\"OverflowMethod\"] = None,\n end: str = \"\\n\",\n ) -> \"Text\":\n \"\"\"Create Text instance from markup.\n\n Args:\n text (str): A string containing console markup.\n style (Union[str, Style], optional): Base style for text. Defaults to \"\".\n emoji (bool, optional): Also render emoji code. Defaults to True.\n emoji_variant (str, optional): Optional emoji variant, either \"text\" or \"emoji\". Defaults to None.\n justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n end (str, optional): Character to end text with. Defaults to \"\\\\\\\\n\".\n\n Returns:\n Text: A Text instance with markup rendered.\n \"\"\"\n from .markup import render\n\n rendered_text = render(text, style, emoji=emoji, emoji_variant=emoji_variant)\n rendered_text.justify = justify\n rendered_text.overflow = overflow\n rendered_text.end = end\n return rendered_text", "focal_method_file_path": "rich/text.py", "focal_method_start_lineno": 259, "focal_method_end_lineno": 291} {"index": 356, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_is_alt_screen", "test_class_name": "", "original_test_prefix": "def test_is_alt_screen() -> None:\n console = Console(force_terminal=True)\n if console.legacy_windows:\n return\n assert not console.is_alt_screen\n with console.screen():\n assert console.is_alt_screen\n assert not console.is_alt_screen", "test_prefix": "def test_is_alt_screen() -> None:\n console = Console(force_terminal=True)\n if console.legacy_windows:\n return\n \n with console.screen():\n assert console.is_alt_screen\n ", "test_prefix_file_path": "tests/test_console.py", "test_prefix_start_lineno": 785, "test_prefix_end_lineno": 792, "test_target": "tests/test_console.py::test_is_alt_screen", "ground_truth_oracle": "assert not console.is_alt_screen", "ground_truth_oracle_lineno": 792, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def screen(\n self, hide_cursor: bool = True, style: Optional[StyleType] = None\n ) -> \"ScreenContext\":\n \"\"\"Context manager to enable and disable 'alternative screen' mode.\n\n Args:\n hide_cursor (bool, optional): Also hide the cursor. Defaults to False.\n style (Style, optional): Optional style for screen. Defaults to None.\n\n Returns:\n ~ScreenContext: Context which enables alternate screen on enter, and disables it on exit.\n \"\"\"\n return ScreenContext(self, hide_cursor=hide_cursor, style=style or \"\")", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 1269, "focal_method_end_lineno": 1281} {"index": 357, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_section", "test_class_name": "", "original_test_prefix": "def test_section():\n table = Table(\"foo\")\n table.add_section() # Null-op\n table.add_row(\"row1\")\n table.add_row(\"row2\", end_section=True)\n table.add_row(\"row3\")\n table.add_row(\"row4\")\n table.add_section()\n table.add_row(\"row5\")\n table.add_section() # Null-op\n\n console = Console(\n width=80,\n force_terminal=True,\n color_system=\"truecolor\",\n legacy_windows=False,\n record=True,\n )\n console.print(table)\n output = console.export_text()\n print(repr(output))\n expected = \"\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\u2503 foo \u2503\\n\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\u2502 row1 \u2502\\n\u2502 row2 \u2502\\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\u2502 row3 \u2502\\n\u2502 row4 \u2502\\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\u2502 row5 \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\"\n\n assert output == expected", "test_prefix": "def test_section():\n table = Table(\"foo\")\n table.add_section() # Null-op\n table.add_row(\"row1\")\n table.add_row(\"row2\", end_section=True)\n table.add_row(\"row3\")\n table.add_row(\"row4\")\n table.add_section()\n table.add_row(\"row5\")\n table.add_section() # Null-op\n\n console = Console(\n width=80,\n force_terminal=True,\n color_system=\"truecolor\",\n legacy_windows=False,\n record=True,\n )\n console.print(table)\n output = console.export_text()\n print(repr(output))\n expected = \"\u250f\u2501\u2501\u2501\u2501\u2501\u2501\u2513\\n\u2503 foo \u2503\\n\u2521\u2501\u2501\u2501\u2501\u2501\u2501\u2529\\n\u2502 row1 \u2502\\n\u2502 row2 \u2502\\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\u2502 row3 \u2502\\n\u2502 row4 \u2502\\n\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2524\\n\u2502 row5 \u2502\\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2518\\n\"\n\n ", "test_prefix_file_path": "tests/test_table.py", "test_prefix_start_lineno": 212, "test_prefix_end_lineno": 235, "test_target": "tests/test_table.py::test_section", "ground_truth_oracle": "assert output == expected", "ground_truth_oracle_lineno": 235, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def export_text(self, *, clear: bool = True, styles: bool = False) -> str:\n \"\"\"Generate text from console contents (requires record=True argument in constructor).\n\n Args:\n clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\n styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text.\n Defaults to ``False``.\n\n Returns:\n str: String containing console contents.\n\n \"\"\"\n assert (\n self.record\n ), \"To export console contents set record=True in the constructor or instance\"\n\n with self._record_buffer_lock:\n if styles:\n text = \"\".join(\n (style.render(text) if style else text)\n for text, style, _ in self._record_buffer\n )\n else:\n text = \"\".join(\n segment.text\n for segment in self._record_buffer\n if not segment.control\n )\n if clear:\n del self._record_buffer[:]\n return text", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 2173, "focal_method_end_lineno": 2203} {"index": 358, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ipy_display_hook__no_special_repr_methods", "test_class_name": "", "original_test_prefix": "def test_ipy_display_hook__no_special_repr_methods() -> None:\n console = Console(file=io.StringIO(), force_jupyter=True)\n\n class Thing:\n def __repr__(self) -> str:\n return \"hello\"\n\n result = _ipy_display_hook(Thing(), console=console)\n # should be repr as-is\n assert result == \"hello\"", "test_prefix": "def test_ipy_display_hook__no_special_repr_methods() -> None:\n console = Console(file=io.StringIO(), force_jupyter=True)\n\n class Thing:\n def __repr__(self) -> str:\n return \"hello\"\n\n result = _ipy_display_hook(Thing(), console=console)\n # should be repr as-is\n ", "test_prefix_file_path": "tests/test_pretty.py", "test_prefix_start_lineno": 101, "test_prefix_end_lineno": 110, "test_target": "tests/test_pretty.py::test_ipy_display_hook__no_special_repr_methods", "ground_truth_oracle": "assert result == \"hello\"", "ground_truth_oracle_lineno": 110, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _ipy_display_hook(\n value: Any,\n console: Optional[\"Console\"] = None,\n overflow: \"OverflowMethod\" = \"ignore\",\n crop: bool = False,\n indent_guides: bool = False,\n max_length: Optional[int] = None,\n max_string: Optional[int] = None,\n max_depth: Optional[int] = None,\n expand_all: bool = False,\n) -> Union[str, None]:\n # needed here to prevent circular import:\n from .console import ConsoleRenderable\n\n # always skip rich generated jupyter renderables or None values\n if _safe_isinstance(value, JupyterRenderable) or value is None:\n return None\n\n console = console or get_console()\n\n with console.capture() as capture:\n # certain renderables should start on a new line\n if _safe_isinstance(value, ConsoleRenderable):\n console.line()\n console.print(\n (\n value\n if _safe_isinstance(value, RichRenderable)\n else Pretty(\n value,\n overflow=overflow,\n indent_guides=indent_guides,\n max_length=max_length,\n max_string=max_string,\n max_depth=max_depth,\n expand_all=expand_all,\n margin=12,\n )\n ),\n crop=crop,\n new_line_start=True,\n end=\"\",\n )\n # strip trailing newline, not usually part of a text repr\n # I'm not sure if this should be prevented at a lower level\n return capture.get().rstrip(\"\\n\")", "focal_method_file_path": "rich/pretty.py", "focal_method_start_lineno": 113, "focal_method_end_lineno": 158} {"index": 359, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ansi_theme", "test_class_name": "", "original_test_prefix": "def test_ansi_theme() -> None:\n style = Style(color=\"red\")\n theme = ANSISyntaxTheme({(\"foo\", \"bar\"): style})\n assert theme.get_style_for_token((\"foo\", \"bar\", \"baz\")) == style\n assert theme.get_background_style() == Style()", "test_prefix": "def test_ansi_theme() -> None:\n style = Style(color=\"red\")\n theme = ANSISyntaxTheme({(\"foo\", \"bar\"): style})\n \n assert theme.get_background_style() == Style()", "test_prefix_file_path": "tests/test_syntax.py", "test_prefix_start_lineno": 305, "test_prefix_end_lineno": 309, "test_target": "tests/test_syntax.py::test_ansi_theme", "ground_truth_oracle": "assert theme.get_style_for_token((\"foo\", \"bar\", \"baz\")) == style", "ground_truth_oracle_lineno": 308, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_style_for_token(self, token_type: TokenType) -> Style:\n \"\"\"Look up style in the style map.\"\"\"\n try:\n return self._style_cache[token_type]\n except KeyError:\n # Styles form a hierarchy\n # We need to go from most to least specific\n # e.g. (\"foo\", \"bar\", \"baz\") to (\"foo\", \"bar\") to (\"foo\",)\n get_style = self.style_map.get\n token = tuple(token_type)\n style = self._missing_style\n while token:\n _style = get_style(token)\n if _style is not None:\n style = _style\n break\n token = token[:-1]\n self._style_cache[token_type] = style\n return style", "focal_method_file_path": "rich/syntax.py", "focal_method_start_lineno": 189, "focal_method_end_lineno": 207} {"index": 360, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_task_progress_column_speed", "test_class_name": "", "original_test_prefix": "def test_task_progress_column_speed() -> None:\n speed_text = TaskProgressColumn.render_speed(None)\n assert speed_text.plain == \"\"\n\n speed_text = TaskProgressColumn.render_speed(5)\n assert speed_text.plain == \"5.0 it/s\"\n\n speed_text = TaskProgressColumn.render_speed(5000)\n assert speed_text.plain == \"5.0\u00d710\u00b3 it/s\"\n\n speed_text = TaskProgressColumn.render_speed(8888888)\n assert speed_text.plain == \"8.9\u00d710\u2076 it/s\"", "test_prefix": "def test_task_progress_column_speed() -> None:\n speed_text = TaskProgressColumn.render_speed(None)\n assert speed_text.plain == \"\"\n\n speed_text = TaskProgressColumn.render_speed(5)\n assert speed_text.plain == \"5.0 it/s\"\n\n speed_text = TaskProgressColumn.render_speed(5000)\n assert speed_text.plain == \"5.0\u00d710\u00b3 it/s\"\n\n speed_text = TaskProgressColumn.render_speed(8888888)\n ", "test_prefix_file_path": "tests/test_progress.py", "test_prefix_start_lineno": 649, "test_prefix_end_lineno": 660, "test_target": "tests/test_progress.py::test_task_progress_column_speed", "ground_truth_oracle": "assert speed_text.plain == \"8.9\u00d710\u2076 it/s\"", "ground_truth_oracle_lineno": 660, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def render_speed(cls, speed: Optional[float]) -> Text:\n \"\"\"Render the speed in iterations per second.\n\n Args:\n task (Task): A Task object.\n\n Returns:\n Text: Text object containing the task speed.\n \"\"\"\n if speed is None:\n return Text(\"\", style=\"progress.percentage\")\n unit, suffix = filesize.pick_unit_and_suffix(\n int(speed),\n [\"\", \"\u00d710\u00b3\", \"\u00d710\u2076\", \"\u00d710\u2079\", \"\u00d710\u00b9\u00b2\"],\n 1000,\n )\n data_speed = speed / unit\n return Text(f\"{data_speed:.1f}{suffix} it/s\", style=\"progress.percentage\")", "focal_method_file_path": "rich/progress.py", "focal_method_start_lineno": 736, "focal_method_end_lineno": 754} {"index": 361, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_rich_console", "test_class_name": "", "original_test_prefix": "def test_rich_console():\n renderable = \"test renderable\"\n style = Style(color=\"red\")\n options = ConsoleOptions(\n ConsoleDimensions(80, 25),\n max_height=25,\n legacy_windows=False,\n min_width=10,\n max_width=20,\n is_terminal=False,\n encoding=\"utf-8\",\n )\n\n expected_outputs = [\n Segment(renderable, style=style),\n Segment(\" \" * (20 - len(renderable)), style=style),\n Segment(\"\\n\", style=None),\n ]\n padding_generator = Padding(renderable, style=style).__rich_console__(\n Console(), options\n )\n for output, expected in zip(padding_generator, expected_outputs):\n assert output == expected", "test_prefix": "def test_rich_console():\n renderable = \"test renderable\"\n style = Style(color=\"red\")\n options = ConsoleOptions(\n ConsoleDimensions(80, 25),\n max_height=25,\n legacy_windows=False,\n min_width=10,\n max_width=20,\n is_terminal=False,\n encoding=\"utf-8\",\n )\n\n expected_outputs = [\n Segment(renderable, style=style),\n Segment(\" \" * (20 - len(renderable)), style=style),\n Segment(\"\\n\", style=None),\n ]\n padding_generator = Padding(renderable, style=style).__rich_console__(\n Console(), options\n )\n for output, expected in zip(padding_generator, expected_outputs):\n ", "test_prefix_file_path": "tests/test_padding.py", "test_prefix_start_lineno": 38, "test_prefix_end_lineno": 60, "test_target": "tests/test_padding.py::test_rich_console", "ground_truth_oracle": "assert output == expected", "ground_truth_oracle_lineno": 60, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def __rich_console__(\n self, console: \"Console\", options: \"ConsoleOptions\"\n ) -> \"RenderResult\":\n style = console.get_style(self.style)\n if self.expand:\n width = options.max_width\n else:\n width = min(\n Measurement.get(console, options, self.renderable).maximum\n + self.left\n + self.right,\n options.max_width,\n )\n render_options = options.update_width(width - self.left - self.right)\n if render_options.height is not None:\n render_options = render_options.update_height(\n height=render_options.height - self.top - self.bottom\n )\n lines = console.render_lines(\n self.renderable, render_options, style=style, pad=True\n )\n _Segment = Segment\n\n left = _Segment(\" \" * self.left, style) if self.left else None\n right = (\n [_Segment(f'{\" \" * self.right}', style), _Segment.line()]\n if self.right\n else [_Segment.line()]\n )\n blank_line: Optional[List[Segment]] = None\n if self.top:\n blank_line = [_Segment(f'{\" \" * width}\\n', style)]\n yield from blank_line * self.top\n if left:\n for line in lines:\n yield left\n yield from line\n yield from right\n else:\n for line in lines:\n yield from line\n yield from right\n if self.bottom:\n blank_line = blank_line or [_Segment(f'{\" \" * width}\\n', style)]\n yield from blank_line * self.bottom", "focal_method_file_path": "rich/padding.py", "focal_method_start_lineno": 79, "focal_method_end_lineno": 123} {"index": 362, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_repr", "test_class_name": "", "original_test_prefix": "def test_repr() -> None:\n assert repr(Color.parse(\"red\")) == \"Color('red', ColorType.STANDARD, number=1)\"", "test_prefix": "def test_repr() -> None:\n ", "test_prefix_file_path": "tests/test_color.py", "test_prefix_start_lineno": 20, "test_prefix_end_lineno": 21, "test_target": "tests/test_color.py::test_repr", "ground_truth_oracle": "assert repr(Color.parse(\"red\")) == \"Color('red', ColorType.STANDARD, number=1)\"", "ground_truth_oracle_lineno": 21, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n @lru_cache(maxsize=1024)\n def parse(cls, color: str) -> \"Color\":\n \"\"\"Parse a color definition.\"\"\"\n original_color = color\n color = color.lower().strip()\n\n if color == \"default\":\n return cls(color, type=ColorType.DEFAULT)\n\n color_number = ANSI_COLOR_NAMES.get(color)\n if color_number is not None:\n return cls(\n color,\n type=(ColorType.STANDARD if color_number < 16 else ColorType.EIGHT_BIT),\n number=color_number,\n )\n\n color_match = RE_COLOR.match(color)\n if color_match is None:\n raise ColorParseError(f\"{original_color!r} is not a valid color\")\n\n color_24, color_8, color_rgb = color_match.groups()\n if color_24:\n triplet = ColorTriplet(\n int(color_24[0:2], 16), int(color_24[2:4], 16), int(color_24[4:6], 16)\n )\n return cls(color, ColorType.TRUECOLOR, triplet=triplet)\n\n elif color_8:\n number = int(color_8)\n if number > 255:\n raise ColorParseError(f\"color number must be <= 255 in {color!r}\")\n return cls(\n color,\n type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT),\n number=number,\n )\n\n else: # color_rgb:\n components = color_rgb.split(\",\")\n if len(components) != 3:\n raise ColorParseError(\n f\"expected three components in {original_color!r}\"\n )\n red, green, blue = components\n triplet = ColorTriplet(int(red), int(green), int(blue))\n if not all(component <= 255 for component in triplet):\n raise ColorParseError(\n f\"color components must be <= 255 in {original_color!r}\"\n )\n return cls(color, ColorType.TRUECOLOR, triplet=triplet)", "focal_method_file_path": "rich/color.py", "focal_method_start_lineno": 431, "focal_method_end_lineno": 482} {"index": 363, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_render_simple", "test_class_name": "", "original_test_prefix": "def test_render_simple():\n console = Console(width=80)\n console.begin_capture()\n console.print(Text(\"foo\"))\n result = console.end_capture()\n assert result == \"foo\\n\"", "test_prefix": "def test_render_simple():\n console = Console(width=80)\n console.begin_capture()\n console.print(Text(\"foo\"))\n result = console.end_capture()\n ", "test_prefix_file_path": "tests/test_text.py", "test_prefix_start_lineno": 670, "test_prefix_end_lineno": 675, "test_target": "tests/test_text.py::test_render_simple", "ground_truth_oracle": "assert result == \"foo\\n\"", "ground_truth_oracle_lineno": 675, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def end_capture(self) -> str:\n \"\"\"End capture mode and return captured string.\n\n Returns:\n str: Console output.\n \"\"\"\n render_result = self._render_buffer(self._buffer)\n del self._buffer[:]\n self._exit_buffer()\n return render_result", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 876, "focal_method_end_lineno": 885} {"index": 364, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_box_substitute_for_different_box_legacy_windows", "test_class_name": "", "original_test_prefix": "def test_box_substitute_for_different_box_legacy_windows():\n options = ConsoleOptions(\n ConsoleDimensions(80, 25),\n legacy_windows=True,\n min_width=1,\n max_width=100,\n is_terminal=True,\n encoding=\"utf-8\",\n max_height=25,\n )\n\n assert ROUNDED.substitute(options) == SQUARE\n assert MINIMAL_HEAVY_HEAD.substitute(options) == MINIMAL\n assert SIMPLE_HEAVY.substitute(options) == SIMPLE\n assert HEAVY.substitute(options) == SQUARE\n assert HEAVY_EDGE.substitute(options) == SQUARE\n assert HEAVY_HEAD.substitute(options) == SQUARE", "test_prefix": "def test_box_substitute_for_different_box_legacy_windows():\n options = ConsoleOptions(\n ConsoleDimensions(80, 25),\n legacy_windows=True,\n min_width=1,\n max_width=100,\n is_terminal=True,\n encoding=\"utf-8\",\n max_height=25,\n )\n\n \n assert MINIMAL_HEAVY_HEAD.substitute(options) == MINIMAL\n assert SIMPLE_HEAVY.substitute(options) == SIMPLE\n assert HEAVY.substitute(options) == SQUARE\n assert HEAVY_EDGE.substitute(options) == SQUARE\n assert HEAVY_HEAD.substitute(options) == SQUARE", "test_prefix_file_path": "tests/test_box.py", "test_prefix_start_lineno": 70, "test_prefix_end_lineno": 86, "test_target": "tests/test_box.py::test_box_substitute_for_different_box_legacy_windows", "ground_truth_oracle": "assert ROUNDED.substitute(options) == SQUARE", "ground_truth_oracle_lineno": 81, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def substitute(self, options: \"ConsoleOptions\", safe: bool = True) -> \"Box\":\n \"\"\"Substitute this box for another if it won't render due to platform issues.\n\n Args:\n options (ConsoleOptions): Console options used in rendering.\n safe (bool, optional): Substitute this for another Box if there are known problems\n displaying on the platform (currently only relevant on Windows). Default is True.\n\n Returns:\n Box: A different Box or the same Box.\n \"\"\"\n box = self\n if options.legacy_windows and safe:\n box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box)\n if options.ascii_only and not box.ascii:\n box = ASCII\n return box", "focal_method_file_path": "rich/box.py", "focal_method_start_lineno": 67, "focal_method_end_lineno": 83} {"index": 365, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_null_file", "test_class_name": "", "original_test_prefix": "def test_null_file():\n file = NullFile()\n with file:\n assert file.write(\"abc\") == 0\n assert file.close() is None\n assert not file.isatty()\n assert file.read() == \"\"\n assert not file.readable()\n assert file.readline() == \"\"\n assert file.readlines() == []\n assert file.seek(0, 0) == 0\n assert not file.seekable()\n assert file.tell() == 0\n assert file.truncate() == 0\n assert file.writable() == False\n assert file.writelines([\"\"]) is None\n assert next(file) == \"\"\n assert next(iter(file)) == \"\"\n assert file.fileno() == -1\n assert file.flush() is None", "test_prefix": "def test_null_file():\n file = NullFile()\n with file:\n assert file.write(\"abc\") == 0\n assert file.close() is None\n \n assert file.read() == \"\"\n assert not file.readable()\n assert file.readline() == \"\"\n assert file.readlines() == []\n assert file.seek(0, 0) == 0\n assert not file.seekable()\n assert file.tell() == 0\n assert file.truncate() == 0\n assert file.writable() == False\n assert file.writelines([\"\"]) is None\n assert next(file) == \"\"\n assert next(iter(file)) == \"\"\n assert file.fileno() == -1\n assert file.flush() is None", "test_prefix_file_path": "tests/test_null_file.py", "test_prefix_start_lineno": 4, "test_prefix_end_lineno": 23, "test_target": "tests/test_null_file.py::test_null_file", "ground_truth_oracle": "assert not file.isatty()", "ground_truth_oracle_lineno": 9, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def isatty(self) -> bool:\n return False", "focal_method_file_path": "rich/_null_file.py", "focal_method_start_lineno": 9, "focal_method_end_lineno": 10} {"index": 366, "repo_name": "rich", "github": "https://github.com/Textualize/rich.git", "version": "v14.2.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_wrap_cjk_mixed", "test_class_name": "", "original_test_prefix": "def test_wrap_cjk_mixed():\n \"\"\"Regression test covering https://github.com/Textualize/rich/issues/3176 and\n https://github.com/Textualize/textual/issues/3567 - double width characters could\n result in text going missing when wrapping.\"\"\"\n text = Text(\"123\u3042\u308a\u304c\u3068\u3046\u3054\u3056\u3044\u307e\u3057\u305f\")\n console = Console(width=20) # let's ensure the width passed to wrap() wins.\n\n wrapped_lines = text.wrap(console, width=8)\n with console.capture() as capture:\n console.print(wrapped_lines)\n\n assert capture.get() == \"123\u3042\u308a\\n\u304c\u3068\u3046\u3054\\n\u3056\u3044\u307e\u3057\\n\u305f\\n\"", "test_prefix": "def test_wrap_cjk_mixed():\n \"\"\"Regression test covering https://github.com/Textualize/rich/issues/3176 and\n https://github.com/Textualize/textual/issues/3567 - double width characters could\n result in text going missing when wrapping.\"\"\"\n text = Text(\"123\u3042\u308a\u304c\u3068\u3046\u3054\u3056\u3044\u307e\u3057\u305f\")\n console = Console(width=20) # let's ensure the width passed to wrap() wins.\n\n wrapped_lines = text.wrap(console, width=8)\n with console.capture() as capture:\n console.print(wrapped_lines)\n\n ", "test_prefix_file_path": "tests/test_text.py", "test_prefix_start_lineno": 505, "test_prefix_end_lineno": 516, "test_target": "tests/test_text.py::test_wrap_cjk_mixed", "ground_truth_oracle": "assert capture.get() == \"123\u3042\u308a\\n\u304c\u3068\u3046\u3054\\n\u3056\u3044\u307e\u3057\\n\u305f\\n\"", "ground_truth_oracle_lineno": 516, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get(self) -> str:\n \"\"\"Get the result of the capture.\"\"\"\n if self._result is None:\n raise CaptureError(\n \"Capture result is not available until context manager exits.\"\n )\n return self._result", "focal_method_file_path": "rich/console.py", "focal_method_start_lineno": 340, "focal_method_end_lineno": 346} {"index": 367, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_Failure_description_priorities_parameter_only", "test_class_name": "", "original_test_prefix": "def test_Failure_description_priorities_parameter_only():\n number_validator = Number(failure_description=\"ABC\")\n non_number_value = \"x\"\n result = number_validator.validate(non_number_value)\n # The inline value takes priority over the describe_failure.\n assert result.failures[0].description == \"ABC\"", "test_prefix": "def test_Failure_description_priorities_parameter_only():\n number_validator = Number(failure_description=\"ABC\")\n non_number_value = \"x\"\n result = number_validator.validate(non_number_value)\n # The inline value takes priority over the describe_failure.\n ", "test_prefix_file_path": "tests/test_validation.py", "test_prefix_start_lineno": 56, "test_prefix_end_lineno": 61, "test_target": "tests/test_validation.py::test_Failure_description_priorities_parameter_only", "ground_truth_oracle": "assert result.failures[0].description == \"ABC\"", "ground_truth_oracle_lineno": 61, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def validate(self, value: str) -> ValidationResult:\n \"\"\"Ensure that `value` is a valid number, optionally within a range.\n\n Args:\n value: The value to validate.\n\n Returns:\n The result of the validation.\n \"\"\"\n try:\n float_value = float(value)\n except ValueError:\n return ValidationResult.failure([Number.NotANumber(self, value)])\n\n if math.isnan(float_value) or math.isinf(float_value):\n return ValidationResult.failure([Number.NotANumber(self, value)])\n\n if not self._validate_range(float_value):\n return ValidationResult.failure(\n [Number.NotInRange(self, value)],\n )\n return self.success()", "focal_method_file_path": "src/textual/validation.py", "focal_method_start_lineno": 289, "focal_method_end_lineno": 310} {"index": 368, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_compositor_scroll_placements", "test_class_name": "", "original_test_prefix": "async def test_compositor_scroll_placements():\n \"\"\"Regression test for https://github.com/Textualize/textual/issues/5249\n The Static should remain visible.\n \"\"\"\n\n class ScrollApp(App):\n CSS = \"\"\"\n Screen {\n overflow: scroll;\n }\n Container {\n width: 200vw;\n }\n #hello {\n width: 20;\n height: 10;\n offset: 50 10;\n background: blue;\n color: white;\n }\n \"\"\"\n\n def compose(self) -> ComposeResult:\n with Container():\n yield Static(\"Hello\", id=\"hello\")\n\n def on_mount(self) -> None:\n self.screen.scroll_to(20, 0, animate=False)\n\n app = ScrollApp()\n async with app.run_test() as pilot:\n await pilot.pause()\n static = app.query_one(\"#hello\")\n widgets = app.screen._compositor.visible_widgets\n # The static wasn't scrolled out of view, and should be visible\n # This wasn't the case <= v0.86.1\n assert static in widgets", "test_prefix": "async def test_compositor_scroll_placements():\n \"\"\"Regression test for https://github.com/Textualize/textual/issues/5249\n The Static should remain visible.\n \"\"\"\n\n class ScrollApp(App):\n CSS = \"\"\"\n Screen {\n overflow: scroll;\n }\n Container {\n width: 200vw;\n }\n #hello {\n width: 20;\n height: 10;\n offset: 50 10;\n background: blue;\n color: white;\n }\n \"\"\"\n\n def compose(self) -> ComposeResult:\n with Container():\n yield Static(\"Hello\", id=\"hello\")\n\n def on_mount(self) -> None:\n self.screen.scroll_to(20, 0, animate=False)\n\n app = ScrollApp()\n async with app.run_test() as pilot:\n await pilot.pause()\n static = app.query_one(\"#hello\")\n widgets = app.screen._compositor.visible_widgets\n # The static wasn't scrolled out of view, and should be visible\n # This wasn't the case <= v0.86.1\n ", "test_prefix_file_path": "tests/test_compositor.py", "test_prefix_start_lineno": 6, "test_prefix_end_lineno": 42, "test_target": "tests/test_compositor.py::test_compositor_scroll_placements", "ground_truth_oracle": "assert static in widgets", "ground_truth_oracle_lineno": 42, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 369, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_default_timeout", "test_class_name": "", "original_test_prefix": "def test_default_timeout() -> None:\n \"\"\"The default timeout should be as expected.\"\"\"\n assert Notification(\"test\").timeout == Notification.timeout", "test_prefix": "def test_default_timeout() -> None:\n \"\"\"The default timeout should be as expected.\"\"\"\n ", "test_prefix_file_path": "tests/notifications/test_notification.py", "test_prefix_start_lineno": 23, "test_prefix_end_lineno": 25, "test_target": "tests/notifications/test_notification.py::test_default_timeout", "ground_truth_oracle": "assert Notification(\"test\").timeout == Notification.timeout", "ground_truth_oracle_lineno": 25, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "@dataclass\nclass Notification:\n \"\"\"Holds the details of a notification.\"\"\"\n\n message: str\n \"\"\"The message for the notification.\"\"\"\n\n title: str = \"\"\n \"\"\"The title for the notification.\"\"\"\n\n severity: SeverityLevel = \"information\"\n \"\"\"The severity level for the notification.\"\"\"\n\n timeout: float = 5\n \"\"\"The timeout (in seconds) for the notification.\"\"\"\n\n markup: bool = False\n \"\"\"Render the notification message as content markup?\"\"\"\n\n raised_at: float = field(default_factory=time)\n \"\"\"The time when the notification was raised (in Unix time).\"\"\"\n\n identity: str = field(default_factory=lambda: str(uuid4()))\n \"\"\"The unique identity of the notification.\"\"\"\n\n @property\n def time_left(self) -> float:\n \"\"\"The time left until this notification expires\"\"\"\n return (self.raised_at + self.timeout) - time()\n\n @property\n def has_expired(self) -> bool:\n \"\"\"Has the notification expired?\"\"\"\n return self.time_left <= 0\n\n def __rich_repr__(self) -> Result:\n yield \"message\", self.message\n yield \"title\", self.title, \"\"\n yield \"severity\", self.severity\n yield \"raised_it\", self.raised_at\n yield \"identity\", self.identity\n yield \"time_left\", self.time_left\n yield \"has_expired\", self.has_expired", "focal_method_file_path": "src/textual/notifications.py", "focal_method_start_lineno": 26, "focal_method_end_lineno": 68} {"index": 370, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_stylesheet_apply_doesnt_override_defaults", "test_class_name": "", "original_test_prefix": "def test_stylesheet_apply_doesnt_override_defaults():\n css = \"#id {color: red;}\"\n stylesheet = _make_user_stylesheet(css)\n node = DOMNode(id=\"id\")\n stylesheet.apply(node)\n\n assert node.styles.margin == Spacing.all(0)\n assert node.styles.box_sizing == \"border-box\"", "test_prefix": "def test_stylesheet_apply_doesnt_override_defaults():\n css = \"#id {color: red;}\"\n stylesheet = _make_user_stylesheet(css)\n node = DOMNode(id=\"id\")\n stylesheet.apply(node)\n\n \n assert node.styles.box_sizing == \"border-box\"", "test_prefix_file_path": "tests/css/test_stylesheet.py", "test_prefix_start_lineno": 30, "test_prefix_end_lineno": 37, "test_target": "tests/css/test_stylesheet.py::test_stylesheet_apply_doesnt_override_defaults", "ground_truth_oracle": "assert node.styles.margin == Spacing.all(0)", "ground_truth_oracle_lineno": 36, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def all(cls, amount: int) -> Spacing:\n \"\"\"Construct a Spacing with a given amount of spacing on all edges.\n\n Args:\n amount: The magnitude of spacing to apply to all edges.\n\n Returns:\n `Spacing(amount, amount, amount, amount)`\n \"\"\"\n return Spacing(amount, amount, amount, amount)", "focal_method_file_path": "src/textual/geometry.py", "focal_method_start_lineno": 1270, "focal_method_end_lineno": 1280} {"index": 371, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_progress_bar_animates_on_basic", "test_class_name": "", "original_test_prefix": "async def test_progress_bar_animates_on_basic() -> None:\n \"\"\"An indeterminate progress bar is not fully highlighted when animating.\"\"\"\n app = ProgressBarApp()\n app.animation_level = \"basic\"\n\n async with app.run_test():\n bar_renderable = app.query_one(Bar).render()\n start, end = bar_renderable.highlight_range\n assert start != 0 or end != app.query_one(Bar).size.width", "test_prefix": "async def test_progress_bar_animates_on_basic() -> None:\n \"\"\"An indeterminate progress bar is not fully highlighted when animating.\"\"\"\n app = ProgressBarApp()\n app.animation_level = \"basic\"\n\n async with app.run_test():\n bar_renderable = app.query_one(Bar).render()\n start, end = bar_renderable.highlight_range\n ", "test_prefix_file_path": "tests/animations/test_progress_bar_animation.py", "test_prefix_start_lineno": 27, "test_prefix_end_lineno": 35, "test_target": "tests/animations/test_progress_bar_animation.py::test_progress_bar_animates_on_basic", "ground_truth_oracle": "assert start != 0 or end != app.query_one(Bar).size.width", "ground_truth_oracle_lineno": 35, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 372, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_regions_to_ranges_disjoint_regions_different_lines", "test_class_name": "", "original_test_prefix": "def test_regions_to_ranges_disjoint_regions_different_lines():\n regions = [Region(0, 0, 2, 1), Region(2, 2, 2, 1)]\n assert list(Compositor._regions_to_spans(regions)) == [(0, 0, 2), (2, 2, 4)]", "test_prefix": "def test_regions_to_ranges_disjoint_regions_different_lines():\n regions = [Region(0, 0, 2, 1), Region(2, 2, 2, 1)]\n ", "test_prefix_file_path": "tests/test_compositor_regions_to_spans.py", "test_prefix_start_lineno": 35, "test_prefix_end_lineno": 37, "test_target": "tests/test_compositor_regions_to_spans.py::test_regions_to_ranges_disjoint_regions_different_lines", "ground_truth_oracle": "assert list(Compositor._regions_to_spans(regions)) == [(0, 0, 2), (2, 2, 4)]", "ground_truth_oracle_lineno": 37, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def _regions_to_spans(\n cls, regions: Iterable[Region]\n ) -> Iterable[tuple[int, int, int]]:\n \"\"\"Converts the regions to horizontal spans. Spans will be combined if they overlap\n or are contiguous to produce optimal non-overlapping spans.\n\n Args:\n regions: An iterable of Regions.\n\n Returns:\n Yields tuples of (Y, X1, X2).\n \"\"\"\n inline_ranges: dict[int, list[tuple[int, int]]] = {}\n setdefault = inline_ranges.setdefault\n for region_x, region_y, width, height in regions:\n span = (region_x, region_x + width)\n for y in range(region_y, region_y + height):\n setdefault(y, []).append(span)\n\n slice_remaining = slice(1, None)\n for y, ranges in sorted(inline_ranges.items()):\n if len(ranges) == 1:\n # Special case of 1 span\n yield (y, *ranges[0])\n else:\n ranges.sort()\n x1, x2 = ranges[0]\n for next_x1, next_x2 in ranges[slice_remaining]:\n if next_x1 <= x2:\n if next_x2 > x2:\n x2 = next_x2\n else:\n yield (y, x1, x2)\n x1 = next_x1\n x2 = next_x2\n yield (y, x1, x2)", "focal_method_file_path": "src/textual/_compositor.py", "focal_method_start_lineno": 322, "focal_method_end_lineno": 358} {"index": 373, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_cell_coordinate_returns_coordinate", "test_class_name": "", "original_test_prefix": "async def test_get_cell_coordinate_returns_coordinate():\n app = DataTableApp()\n async with app.run_test():\n table = app.query_one(DataTable)\n table.add_column(\"Column1\", key=\"C1\")\n table.add_column(\"Column2\", key=\"C2\")\n table.add_column(\"Column3\", key=\"C3\")\n table.add_row(\"ValR1C1\", \"ValR1C2\", \"ValR1C3\", key=\"R1\")\n table.add_row(\"ValR2C1\", \"ValR2C2\", \"ValR2C3\", key=\"R2\")\n table.add_row(\"ValR3C1\", \"ValR3C2\", \"ValR3C3\", key=\"R3\")\n\n assert table.get_cell_coordinate(\"R1\", \"C1\") == Coordinate(0, 0)\n assert table.get_cell_coordinate(\"R2\", \"C2\") == Coordinate(1, 1)\n assert table.get_cell_coordinate(\"R1\", \"C3\") == Coordinate(0, 2)\n assert table.get_cell_coordinate(\"R3\", \"C1\") == Coordinate(2, 0)\n assert table.get_cell_coordinate(\"R3\", \"C2\") == Coordinate(2, 1)", "test_prefix": "async def test_get_cell_coordinate_returns_coordinate():\n app = DataTableApp()\n async with app.run_test():\n table = app.query_one(DataTable)\n table.add_column(\"Column1\", key=\"C1\")\n table.add_column(\"Column2\", key=\"C2\")\n table.add_column(\"Column3\", key=\"C3\")\n table.add_row(\"ValR1C1\", \"ValR1C2\", \"ValR1C3\", key=\"R1\")\n table.add_row(\"ValR2C1\", \"ValR2C2\", \"ValR2C3\", key=\"R2\")\n table.add_row(\"ValR3C1\", \"ValR3C2\", \"ValR3C3\", key=\"R3\")\n\n assert table.get_cell_coordinate(\"R1\", \"C1\") == Coordinate(0, 0)\n assert table.get_cell_coordinate(\"R2\", \"C2\") == Coordinate(1, 1)\n assert table.get_cell_coordinate(\"R1\", \"C3\") == Coordinate(0, 2)\n \n assert table.get_cell_coordinate(\"R3\", \"C2\") == Coordinate(2, 1)", "test_prefix_file_path": "tests/test_data_table.py", "test_prefix_start_lineno": 473, "test_prefix_end_lineno": 488, "test_target": "tests/test_data_table.py::test_get_cell_coordinate_returns_coordinate", "ground_truth_oracle": "assert table.get_cell_coordinate(\"R3\", \"C1\") == Coordinate(2, 0)", "ground_truth_oracle_lineno": 487, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class Coordinate(NamedTuple):\n \"\"\"An object representing a row/column coordinate within a grid.\"\"\"\n\n row: int\n \"\"\"The row of the coordinate within a grid.\"\"\"\n\n column: int\n \"\"\"The column of the coordinate within a grid.\"\"\"\n\n def left(self) -> Coordinate:\n \"\"\"Get the coordinate to the left.\n\n Returns:\n The coordinate to the left.\n \"\"\"\n row, column = self\n return Coordinate(row, column - 1)\n\n def right(self) -> Coordinate:\n \"\"\"Get the coordinate to the right.\n\n Returns:\n The coordinate to the right.\n \"\"\"\n row, column = self\n return Coordinate(row, column + 1)\n\n def up(self) -> Coordinate:\n \"\"\"Get the coordinate above.\n\n Returns:\n The coordinate above.\n \"\"\"\n row, column = self\n return Coordinate(row - 1, column)\n\n def down(self) -> Coordinate:\n \"\"\"Get the coordinate below.\n\n Returns:\n The coordinate below.\n \"\"\"\n row, column = self\n return Coordinate(row + 1, column)", "focal_method_file_path": "src/textual/coordinate.py", "focal_method_start_lineno": 10, "focal_method_end_lineno": 53} {"index": 374, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_style_animations_via_transition_are_disabled_on_none", "test_class_name": "", "original_test_prefix": "async def test_style_animations_via_transition_are_disabled_on_none() -> None:\n app = LabelWithTransitionsApp()\n app.animation_level = \"none\"\n\n async with app.run_test():\n label = app.query_one(Label)\n # Sanity check.\n assert label.styles.background == Color.parse(\"red\")\n animator = app.animator\n # Free time at 0 before triggering the animation.\n animator._get_time = lambda *_: 0\n label.add_class(\"blue-bg\")\n assert len(animator._animations) > 0 # Sanity check.\n # Freeze time after the animation start and before animation end.\n animator._get_time = lambda *_: 0.01\n animator()\n # The animation should have completed.\n assert label.styles.background == Color.parse(\"blue\")", "test_prefix": "async def test_style_animations_via_transition_are_disabled_on_none() -> None:\n app = LabelWithTransitionsApp()\n app.animation_level = \"none\"\n\n async with app.run_test():\n label = app.query_one(Label)\n # Sanity check.\n assert label.styles.background == Color.parse(\"red\")\n animator = app.animator\n # Free time at 0 before triggering the animation.\n animator._get_time = lambda *_: 0\n label.add_class(\"blue-bg\")\n \n # Freeze time after the animation start and before animation end.\n animator._get_time = lambda *_: 0.01\n animator()\n # The animation should have completed.\n assert label.styles.background == Color.parse(\"blue\")", "test_prefix_file_path": "tests/animations/test_disabling_animations.py", "test_prefix_start_lineno": 146, "test_prefix_end_lineno": 163, "test_target": "tests/animations/test_disabling_animations.py::test_style_animations_via_transition_are_disabled_on_none", "ground_truth_oracle": "assert len(animator._animations) > 0 # Sanity check.", "ground_truth_oracle_lineno": 158, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 375, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_discard_regression", "test_class_name": "", "original_test_prefix": "def test_discard_regression():\n \"\"\"Regression test for https://github.com/Textualize/textual/issues/3537\"\"\"\n\n cache = LRUCache(maxsize=3)\n cache[1] = \"foo\"\n cache[2] = \"bar\"\n cache[3] = \"baz\"\n cache[4] = \"egg\"\n\n assert cache.keys() == {2, 3, 4}\n\n cache.discard(2)\n assert cache.keys() == {3, 4}\n\n cache[5] = \"bob\"\n assert cache.keys() == {3, 4, 5}\n\n cache.discard(5)\n assert cache.keys() == {3, 4}\n\n cache.discard(4)\n cache.discard(3)\n\n assert cache.keys() == set()", "test_prefix": "def test_discard_regression():\n \"\"\"Regression test for https://github.com/Textualize/textual/issues/3537\"\"\"\n\n cache = LRUCache(maxsize=3)\n cache[1] = \"foo\"\n cache[2] = \"bar\"\n cache[3] = \"baz\"\n cache[4] = \"egg\"\n\n assert cache.keys() == {2, 3, 4}\n\n cache.discard(2)\n \n\n cache[5] = \"bob\"\n assert cache.keys() == {3, 4, 5}\n\n cache.discard(5)\n \n\n cache.discard(4)\n cache.discard(3)\n\n assert cache.keys() == set()", "test_prefix_file_path": "tests/test_cache.py", "test_prefix_start_lineno": 264, "test_prefix_end_lineno": 287, "test_target": "tests/test_cache.py::test_discard_regression", "ground_truth_oracle": "assert cache.keys() == {3, 4}", "ground_truth_oracle_lineno": 282, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def keys(self) -> KeysView[CacheKey]:\n \"\"\"Get cache keys.\"\"\"\n # Mostly for tests\n return self._cache.keys()", "focal_method_file_path": "src/textual/cache.py", "focal_method_start_lineno": 94, "focal_method_end_lineno": 97} {"index": 376, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_copy", "test_class_name": "", "original_test_prefix": "async def test_copy():\n \"\"\"Check that copy places text in the clipboard.\"\"\"\n app = InputApp()\n async with app.run_test() as pilot:\n input = app.query_one(Input)\n await pilot.click(input)\n await pilot.press(*\"Hello, World\")\n await pilot.press(\"left\", \"shift+left\", \"shift+left\")\n await pilot.press(\"ctrl+c\")\n assert input.value == \"Hello, World\"\n assert app.clipboard == \"rl\"", "test_prefix": "async def test_copy():\n \"\"\"Check that copy places text in the clipboard.\"\"\"\n app = InputApp()\n async with app.run_test() as pilot:\n input = app.query_one(Input)\n await pilot.click(input)\n await pilot.press(*\"Hello, World\")\n await pilot.press(\"left\", \"shift+left\", \"shift+left\")\n await pilot.press(\"ctrl+c\")\n \n assert app.clipboard == \"rl\"", "test_prefix_file_path": "tests/input/test_cut_copy_paste.py", "test_prefix_start_lineno": 23, "test_prefix_end_lineno": 33, "test_target": "tests/input/test_cut_copy_paste.py::test_copy", "ground_truth_oracle": "assert input.value == \"Hello, World\"", "ground_truth_oracle_lineno": 32, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 377, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_radioset_inner_navigation_post_build", "test_class_name": "", "original_test_prefix": "async def test_radioset_inner_navigation_post_build():\n class EmptyRadioSetApp(App[None]):\n def compose(self) -> ComposeResult:\n yield RadioSet()\n\n def on_mount(self) -> None:\n # This isn't encouraged; but neither is it currently prohibited;\n # so let's test.\n for n in range(5):\n self.query_one(RadioSet).mount(RadioButton(id=f\"rb{n}\"))\n\n async with EmptyRadioSetApp().run_test() as pilot:\n assert pilot.app.query_one(RadioSet)._selected is None\n await pilot.press(\"up\")\n assert pilot.app.query_one(RadioSet)._selected == 4", "test_prefix": "async def test_radioset_inner_navigation_post_build():\n class EmptyRadioSetApp(App[None]):\n def compose(self) -> ComposeResult:\n yield RadioSet()\n\n def on_mount(self) -> None:\n # This isn't encouraged; but neither is it currently prohibited;\n # so let's test.\n for n in range(5):\n self.query_one(RadioSet).mount(RadioButton(id=f\"rb{n}\"))\n\n async with EmptyRadioSetApp().run_test() as pilot:\n assert pilot.app.query_one(RadioSet)._selected is None\n await pilot.press(\"up\")\n ", "test_prefix_file_path": "tests/toggles/test_radioset.py", "test_prefix_start_lineno": 99, "test_prefix_end_lineno": 113, "test_target": "tests/toggles/test_radioset.py::test_radioset_inner_navigation_post_build", "ground_truth_oracle": "assert pilot.app.query_one(RadioSet)._selected == 4", "ground_truth_oracle_lineno": 113, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 378, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_query_error", "test_class_name": "", "original_test_prefix": "async def test_query_error():\n class QueryApp(App):\n def compose(self) -> ComposeResult:\n yield Input(id=\"foo\")\n\n app = QueryApp()\n async with app.run_test():\n with pytest.raises(WrongType):\n # Asking for a Label, but the widget is an Input\n app.query_one(\"#foo\", Label)\n\n # Widget is an Input so this works\n foo = app.query_one(\"#foo\", Input)\n assert isinstance(foo, Input)", "test_prefix": "async def test_query_error():\n class QueryApp(App):\n def compose(self) -> ComposeResult:\n yield Input(id=\"foo\")\n\n app = QueryApp()\n async with app.run_test():\n with pytest.raises(WrongType):\n # Asking for a Label, but the widget is an Input\n app.query_one(\"#foo\", Label)\n\n # Widget is an Input so this works\n foo = app.query_one(\"#foo\", Input)\n ", "test_prefix_file_path": "tests/test_query.py", "test_prefix_start_lineno": 369, "test_prefix_end_lineno": 382, "test_target": "tests/test_query.py::test_query_error", "ground_truth_oracle": "assert isinstance(foo, Input)", "ground_truth_oracle_lineno": 382, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 379, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_input_left_word_from_home", "test_class_name": "", "original_test_prefix": "async def test_input_left_word_from_home() -> None:\n \"\"\"Going left one word from the start should do nothing.\"\"\"\n async with InputTester().run_test() as pilot:\n for input in pilot.app.query(Input):\n input.cursor_position = 0\n input.action_cursor_left_word()\n assert input.cursor_position == 0", "test_prefix": "async def test_input_left_word_from_home() -> None:\n \"\"\"Going left one word from the start should do nothing.\"\"\"\n async with InputTester().run_test() as pilot:\n for input in pilot.app.query(Input):\n input.cursor_position = 0\n input.action_cursor_left_word()\n ", "test_prefix_file_path": "tests/input/test_input_key_movement_actions.py", "test_prefix_start_lineno": 78, "test_prefix_end_lineno": 84, "test_target": "tests/input/test_input_key_movement_actions.py::test_input_left_word_from_home", "ground_truth_oracle": "assert input.cursor_position == 0", "ground_truth_oracle_lineno": 84, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query(self, selector: str | None = None) -> DOMQuery[Widget]: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1370, "focal_method_end_lineno": 1371} {"index": 380, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_cursor_selection_right", "test_class_name": "", "original_test_prefix": "async def test_cursor_selection_right(app: TextAreaApp):\n \"\"\"When you press shift+right the selection is updated correctly.\"\"\"\n async with app.run_test() as pilot:\n text_area = app.query_one(TextArea)\n await pilot.press(*[\"shift+right\"] * 3)\n assert text_area.selection == Selection((0, 0), (0, 3))", "test_prefix": "async def test_cursor_selection_right(app: TextAreaApp):\n \"\"\"When you press shift+right the selection is updated correctly.\"\"\"\n async with app.run_test() as pilot:\n text_area = app.query_one(TextArea)\n await pilot.press(*[\"shift+right\"] * 3)\n ", "test_prefix_file_path": "tests/text_area/test_selection_bindings.py", "test_prefix_start_lineno": 76, "test_prefix_end_lineno": 81, "test_target": "tests/text_area/test_selection_bindings.py::test_cursor_selection_right", "ground_truth_oracle": "assert text_area.selection == Selection((0, 0), (0, 3))", "ground_truth_oracle_lineno": 81, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class Selection(NamedTuple):\n \"\"\"A range of characters within a document from a start point to the end point.\n The location of the cursor is always considered to be the `end` point of the selection.\n The selection is inclusive of the minimum point and exclusive of the maximum point.\n \"\"\"\n\n start: Location = (0, 0)\n \"\"\"The start location of the selection.\n\n If you were to click and drag a selection inside a text-editor, this is where you *started* dragging.\n \"\"\"\n end: Location = (0, 0)\n \"\"\"The end location of the selection.\n\n If you were to click and drag a selection inside a text-editor, this is where you *finished* dragging.\n \"\"\"\n\n @classmethod\n def cursor(cls, location: Location) -> \"Selection\":\n \"\"\"Create a Selection with the same start and end point - a \"cursor\".\n\n Args:\n location: The location to create the zero-width Selection.\n \"\"\"\n return cls(location, location)\n\n @property\n def is_empty(self) -> bool:\n \"\"\"Return True if the selection has 0 width, i.e. it's just a cursor.\"\"\"\n start, end = self\n return start == end\n\n def contains_line(self, y: int) -> bool:\n \"\"\"Check if the given line is within the selection.\"\"\"\n top, bottom = sorted((self.start[0], self.end[0]))\n return y >= top and y <= bottom", "focal_method_file_path": "src/textual/document/_document.py", "focal_method_start_lineno": 438, "focal_method_end_lineno": 473} {"index": 381, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_focus_next_wrap_around", "test_class_name": "", "original_test_prefix": "async def test_focus_next_wrap_around():\n \"\"\"Ensure focusing the next widget wraps around the focus chain.\"\"\"\n app = FocusTestApp()\n async with app.run_test():\n screen = app.screen\n\n screen.set_focus(screen.query_one(\"#child\"))\n assert screen.focused.id == \"child\"\n\n assert screen.focus_next().id == \"foo\"", "test_prefix": "async def test_focus_next_wrap_around():\n \"\"\"Ensure focusing the next widget wraps around the focus chain.\"\"\"\n app = FocusTestApp()\n async with app.run_test():\n screen = app.screen\n\n screen.set_focus(screen.query_one(\"#child\"))\n assert screen.focused.id == \"child\"\n\n ", "test_prefix_file_path": "tests/test_focus.py", "test_prefix_start_lineno": 111, "test_prefix_end_lineno": 120, "test_target": "tests/test_focus.py::test_focus_next_wrap_around", "ground_truth_oracle": "assert screen.focus_next().id == \"foo\"", "ground_truth_oracle_lineno": 120, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def focus_next(self, selector: str | type[QueryType] = \"*\") -> Widget | None:\n \"\"\"Focus the next widget, optionally filtered by a CSS selector.\n\n If no widget is currently focused, this will focus the first focusable widget.\n If no focusable widget matches the given CSS selector, focus is set to `None`.\n\n Args:\n selector: CSS selector to filter\n what nodes can be focused.\n\n Returns:\n Newly focused widget, or None for no focus. If the return\n is not `None`, then it is guaranteed that the widget returned matches\n the CSS selectors given in the argument.\n \"\"\"\n return self._move_focus(1, selector)", "focal_method_file_path": "src/textual/screen.py", "focal_method_start_lineno": 846, "focal_method_end_lineno": 861} {"index": 382, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_tabbed_content_switch_via_code", "test_class_name": "", "original_test_prefix": "async def test_tabbed_content_switch_via_code():\n \"\"\"Check tab navigation via code.\"\"\"\n\n class TabbedApp(App):\n def compose(self) -> ComposeResult:\n with TabbedContent():\n with TabPane(\"foo\", id=\"foo\"):\n yield Label(\"Foo\", id=\"foo-label\")\n with TabPane(\"bar\", id=\"bar\"):\n yield Label(\"Bar\", id=\"bar-label\")\n with TabPane(\"baz\", id=\"baz\"):\n yield Label(\"Baz\", id=\"baz-label\")\n\n app = TabbedApp()\n async with app.run_test() as pilot:\n tabbed_content = app.query_one(TabbedContent)\n\n # Check first tab\n assert tabbed_content.active == \"foo\"\n assert app.query_one(\"#foo-label\").region\n assert not app.query_one(\"#bar-label\").region\n assert not app.query_one(\"#baz-label\").region\n\n # Click second tab\n tabbed_content.active = \"bar\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n assert app.query_one(\"#bar-label\").region\n assert not app.query_one(\"#baz-label\").region\n\n # Click third tab\n tabbed_content.active = \"baz\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n assert not app.query_one(\"#bar-label\").region\n assert app.query_one(\"#baz-label\").region\n\n # Check fail with non existent tab\n with pytest.raises(ValueError):\n tabbed_content.active = \"X\"", "test_prefix": "async def test_tabbed_content_switch_via_code():\n \"\"\"Check tab navigation via code.\"\"\"\n\n class TabbedApp(App):\n def compose(self) -> ComposeResult:\n with TabbedContent():\n with TabPane(\"foo\", id=\"foo\"):\n yield Label(\"Foo\", id=\"foo-label\")\n with TabPane(\"bar\", id=\"bar\"):\n yield Label(\"Bar\", id=\"bar-label\")\n with TabPane(\"baz\", id=\"baz\"):\n yield Label(\"Baz\", id=\"baz-label\")\n\n app = TabbedApp()\n async with app.run_test() as pilot:\n tabbed_content = app.query_one(TabbedContent)\n\n # Check first tab\n assert tabbed_content.active == \"foo\"\n assert app.query_one(\"#foo-label\").region\n \n assert not app.query_one(\"#baz-label\").region\n\n # Click second tab\n tabbed_content.active = \"bar\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n assert app.query_one(\"#bar-label\").region\n assert not app.query_one(\"#baz-label\").region\n\n # Click third tab\n tabbed_content.active = \"baz\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n \n assert app.query_one(\"#baz-label\").region\n\n # Check fail with non existent tab\n with pytest.raises(ValueError):\n tabbed_content.active = \"X\"", "test_prefix_file_path": "tests/test_tabbed_content.py", "test_prefix_start_lineno": 70, "test_prefix_end_lineno": 109, "test_target": "tests/test_tabbed_content.py::test_tabbed_content_switch_via_code", "ground_truth_oracle": "assert not app.query_one(\"#bar-label\").region", "ground_truth_oracle_lineno": 90, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 383, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_cursor_selection_right_to_previous_line", "test_class_name": "", "original_test_prefix": "async def test_cursor_selection_right_to_previous_line(app: TextAreaApp):\n \"\"\"When you press shift+right resulting in the cursor moving to the next line,\n the selection is updated correctly.\"\"\"\n async with app.run_test() as pilot:\n text_area = app.query_one(TextArea)\n text_area.selection = Selection.cursor((0, 15))\n await pilot.press(*[\"shift+right\"] * 4)\n assert text_area.selection == Selection((0, 15), (1, 2))", "test_prefix": "async def test_cursor_selection_right_to_previous_line(app: TextAreaApp):\n \"\"\"When you press shift+right resulting in the cursor moving to the next line,\n the selection is updated correctly.\"\"\"\n async with app.run_test() as pilot:\n text_area = app.query_one(TextArea)\n text_area.selection = Selection.cursor((0, 15))\n await pilot.press(*[\"shift+right\"] * 4)\n ", "test_prefix_file_path": "tests/text_area/test_selection_bindings.py", "test_prefix_start_lineno": 84, "test_prefix_end_lineno": 91, "test_target": "tests/text_area/test_selection_bindings.py::test_cursor_selection_right_to_previous_line", "ground_truth_oracle": "assert text_area.selection == Selection((0, 15), (1, 2))", "ground_truth_oracle_lineno": 91, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class Selection(NamedTuple):\n \"\"\"A range of characters within a document from a start point to the end point.\n The location of the cursor is always considered to be the `end` point of the selection.\n The selection is inclusive of the minimum point and exclusive of the maximum point.\n \"\"\"\n\n start: Location = (0, 0)\n \"\"\"The start location of the selection.\n\n If you were to click and drag a selection inside a text-editor, this is where you *started* dragging.\n \"\"\"\n end: Location = (0, 0)\n \"\"\"The end location of the selection.\n\n If you were to click and drag a selection inside a text-editor, this is where you *finished* dragging.\n \"\"\"\n\n @classmethod\n def cursor(cls, location: Location) -> \"Selection\":\n \"\"\"Create a Selection with the same start and end point - a \"cursor\".\n\n Args:\n location: The location to create the zero-width Selection.\n \"\"\"\n return cls(location, location)\n\n @property\n def is_empty(self) -> bool:\n \"\"\"Return True if the selection has 0 width, i.e. it's just a cursor.\"\"\"\n start, end = self\n return start == end\n\n def contains_line(self, y: int) -> bool:\n \"\"\"Check if the given line is within the selection.\"\"\"\n top, bottom = sorted((self.start[0], self.end[0]))\n return y >= top and y <= bottom", "focal_method_file_path": "src/textual/document/_document.py", "focal_method_start_lineno": 438, "focal_method_end_lineno": 473} {"index": 384, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_add_tabs_later", "test_class_name": "", "original_test_prefix": "async def test_add_tabs_later():\n \"\"\"It should be possible to add tabs later on in the app's cycle.\"\"\"\n\n class TabsApp(App[None]):\n def compose(self) -> ComposeResult:\n yield Tabs()\n\n async with TabsApp().run_test() as pilot:\n tabs = pilot.app.query_one(Tabs)\n assert tabs.tab_count == 0\n assert tabs.active_tab is None\n await tabs.add_tab(\"John\")\n assert tabs.tab_count == 1\n assert tabs.active_tab is not None\n assert tabs.active_tab.id == \"tab-1\"\n await tabs.add_tab(\"Aeryn\")\n assert tabs.tab_count == 2\n assert tabs.active_tab is not None\n assert tabs.active_tab.id == \"tab-1\"", "test_prefix": "async def test_add_tabs_later():\n \"\"\"It should be possible to add tabs later on in the app's cycle.\"\"\"\n\n class TabsApp(App[None]):\n def compose(self) -> ComposeResult:\n yield Tabs()\n\n async with TabsApp().run_test() as pilot:\n tabs = pilot.app.query_one(Tabs)\n assert tabs.tab_count == 0\n assert tabs.active_tab is None\n await tabs.add_tab(\"John\")\n assert tabs.tab_count == 1\n \n assert tabs.active_tab.id == \"tab-1\"\n await tabs.add_tab(\"Aeryn\")\n assert tabs.tab_count == 2\n \n assert tabs.active_tab.id == \"tab-1\"", "test_prefix_file_path": "tests/test_tabs.py", "test_prefix_start_lineno": 69, "test_prefix_end_lineno": 87, "test_target": "tests/test_tabs.py::test_add_tabs_later", "ground_truth_oracle": "assert tabs.active_tab is not None", "ground_truth_oracle_lineno": 82, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 385, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_wrap_around_selector", "test_class_name": "", "original_test_prefix": "async def test_wrap_around_selector():\n \"\"\"Ensure moving focus in both directions wraps around the focus chain.\"\"\"\n app = FocusTestApp()\n async with app.run_test():\n screen = app.screen\n\n screen.set_focus(screen.query_one(\"#foo\"))\n assert screen.focused.id == \"foo\"\n\n assert screen.focus_previous(\"#Paul\").id == \"Paul\"\n assert screen.focus_next(\"#foo\").id == \"foo\"", "test_prefix": "async def test_wrap_around_selector():\n \"\"\"Ensure moving focus in both directions wraps around the focus chain.\"\"\"\n app = FocusTestApp()\n async with app.run_test():\n screen = app.screen\n\n screen.set_focus(screen.query_one(\"#foo\"))\n assert screen.focused.id == \"foo\"\n\n assert screen.focus_previous(\"#Paul\").id == \"Paul\"\n ", "test_prefix_file_path": "tests/test_focus.py", "test_prefix_start_lineno": 135, "test_prefix_end_lineno": 145, "test_target": "tests/test_focus.py::test_wrap_around_selector", "ground_truth_oracle": "assert screen.focus_next(\"#foo\").id == \"foo\"", "ground_truth_oracle_lineno": 145, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def focus_next(self, selector: str | type[QueryType] = \"*\") -> Widget | None:\n \"\"\"Focus the next widget, optionally filtered by a CSS selector.\n\n If no widget is currently focused, this will focus the first focusable widget.\n If no focusable widget matches the given CSS selector, focus is set to `None`.\n\n Args:\n selector: CSS selector to filter\n what nodes can be focused.\n\n Returns:\n Newly focused widget, or None for no focus. If the return\n is not `None`, then it is guaranteed that the widget returned matches\n the CSS selectors given in the argument.\n \"\"\"\n return self._move_focus(1, selector)", "focal_method_file_path": "src/textual/screen.py", "focal_method_start_lineno": 846, "focal_method_end_lineno": 861} {"index": 386, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_creating_disabled_tree", "test_class_name": "", "original_test_prefix": "async def test_creating_disabled_tree():\n \"\"\"Mounting a disabled `Tree` should result in the base `Widget`\n having a `disabled` property equal to `True`\"\"\"\n app = TreeApp(disabled=True)\n async with app.run_test() as pilot:\n tree = app.query_one(Tree)\n assert not tree.focusable\n assert tree.disabled\n assert tree.cursor_line == 0\n await pilot.click(\"#test-tree\")\n await pilot.pause()\n await pilot.press(\"down\")\n await pilot.pause()\n assert tree.cursor_line == 0", "test_prefix": "async def test_creating_disabled_tree():\n \"\"\"Mounting a disabled `Tree` should result in the base `Widget`\n having a `disabled` property equal to `True`\"\"\"\n app = TreeApp(disabled=True)\n async with app.run_test() as pilot:\n tree = app.query_one(Tree)\n assert not tree.focusable\n assert tree.disabled\n \n await pilot.click(\"#test-tree\")\n await pilot.pause()\n await pilot.press(\"down\")\n await pilot.pause()\n ", "test_prefix_file_path": "tests/tree/test_tree_availability.py", "test_prefix_start_lineno": 56, "test_prefix_end_lineno": 69, "test_target": "tests/tree/test_tree_availability.py::test_creating_disabled_tree", "ground_truth_oracle": "assert tree.cursor_line == 0", "ground_truth_oracle_lineno": 69, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 387, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_update_cell_at_coordinate_exists", "test_class_name": "", "original_test_prefix": "async def test_update_cell_at_coordinate_exists():\n app = DataTableApp()\n async with app.run_test():\n table = app.query_one(DataTable)\n column_0, column_1 = table.add_columns(\"A\", \"B\")\n row_0, *_ = table.add_rows(ROWS)\n\n table.update_cell_at(Coordinate(0, 1), \"newvalue\")\n assert table.get_cell(row_0, column_1) == \"newvalue\"", "test_prefix": "async def test_update_cell_at_coordinate_exists():\n app = DataTableApp()\n async with app.run_test():\n table = app.query_one(DataTable)\n column_0, column_1 = table.add_columns(\"A\", \"B\")\n row_0, *_ = table.add_rows(ROWS)\n\n table.update_cell_at(Coordinate(0, 1), \"newvalue\")\n ", "test_prefix_file_path": "tests/test_data_table.py", "test_prefix_start_lineno": 716, "test_prefix_end_lineno": 724, "test_target": "tests/test_data_table.py::test_update_cell_at_coordinate_exists", "ground_truth_oracle": "assert table.get_cell(row_0, column_1) == \"newvalue\"", "ground_truth_oracle_lineno": 724, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_cell(self, row_key: RowKey | str, column_key: ColumnKey | str) -> CellType:\n \"\"\"Given a row key and column key, return the value of the corresponding cell.\n\n Args:\n row_key: The row key of the cell.\n column_key: The column key of the cell.\n\n Returns:\n The value of the cell identified by the row and column keys.\n \"\"\"\n try:\n cell_value = self._data[row_key][column_key]\n except KeyError:\n raise CellDoesNotExist(\n f\"No cell exists for row_key={row_key!r}, column_key={column_key!r}.\"\n )\n return cell_value", "focal_method_file_path": "src/textual/widgets/_data_table.py", "focal_method_start_lineno": 931, "focal_method_end_lineno": 947} {"index": 388, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_enter_selects_an_item", "test_class_name": "", "original_test_prefix": "async def test_enter_selects_an_item() -> None:\n \"\"\"Typing in a search value then pressing enter should dismiss the command palette.\"\"\"\n async with CommandPaletteApp().run_test() as pilot:\n assert CommandPalette.is_open(pilot.app)\n assert pilot.app.screen.query_one(CommandList).visible is False\n await pilot.press(\"a\")\n assert pilot.app.screen.query_one(CommandList).visible is True\n assert pilot.app.screen.query_one(CommandList).highlighted == 0\n await pilot.press(\"enter\")\n assert not CommandPalette.is_open(pilot.app)\n assert not pilot.app.screen.query(CommandList)", "test_prefix": "async def test_enter_selects_an_item() -> None:\n \"\"\"Typing in a search value then pressing enter should dismiss the command palette.\"\"\"\n async with CommandPaletteApp().run_test() as pilot:\n assert CommandPalette.is_open(pilot.app)\n assert pilot.app.screen.query_one(CommandList).visible is False\n await pilot.press(\"a\")\n assert pilot.app.screen.query_one(CommandList).visible is True\n assert pilot.app.screen.query_one(CommandList).highlighted == 0\n await pilot.press(\"enter\")\n assert not CommandPalette.is_open(pilot.app)\n ", "test_prefix_file_path": "tests/command_palette/test_interaction.py", "test_prefix_start_lineno": 43, "test_prefix_end_lineno": 53, "test_target": "tests/command_palette/test_interaction.py::test_enter_selects_an_item", "ground_truth_oracle": "assert not pilot.app.screen.query(CommandList)", "ground_truth_oracle_lineno": 53, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query(self, selector: str | None = None) -> DOMQuery[Widget]: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1370, "focal_method_end_lineno": 1371} {"index": 389, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_screen_with_expected_type", "test_class_name": "", "original_test_prefix": "async def test_get_screen_with_expected_type():\n \"\"\"Test get_screen with expected type works\"\"\"\n\n class BadScreen(Screen[None]):\n pass\n\n class MyScreen(Screen[None]):\n def compose(self):\n yield Label()\n yield Button()\n\n class MyApp(App[None]):\n SCREENS = {\"my_screen\": MyScreen}\n\n def on_mount(self):\n self.push_screen(\"my_screen\")\n\n app = MyApp()\n async with app.run_test():\n screen = app.get_screen(\"my_screen\")\n # Should be fine\n assert isinstance(screen, MyScreen)\n\n screen = app.get_screen(\"my_screen\", MyScreen)\n # Should be fine\n assert isinstance(screen, MyScreen)\n\n # TypeError because my_screen is not a BadScreen\n with pytest.raises(TypeError):\n screen = app.get_screen(\"my_screen\", BadScreen)", "test_prefix": "async def test_get_screen_with_expected_type():\n \"\"\"Test get_screen with expected type works\"\"\"\n\n class BadScreen(Screen[None]):\n pass\n\n class MyScreen(Screen[None]):\n def compose(self):\n yield Label()\n yield Button()\n\n class MyApp(App[None]):\n SCREENS = {\"my_screen\": MyScreen}\n\n def on_mount(self):\n self.push_screen(\"my_screen\")\n\n app = MyApp()\n async with app.run_test():\n screen = app.get_screen(\"my_screen\")\n # Should be fine\n \n\n screen = app.get_screen(\"my_screen\", MyScreen)\n # Should be fine\n \n\n # TypeError because my_screen is not a BadScreen\n with pytest.raises(TypeError):\n screen = app.get_screen(\"my_screen\", BadScreen)", "test_prefix_file_path": "tests/test_screens.py", "test_prefix_start_lineno": 613, "test_prefix_end_lineno": 642, "test_target": "tests/test_screens.py::test_get_screen_with_expected_type", "ground_truth_oracle": "assert isinstance(screen, MyScreen)", "ground_truth_oracle_lineno": 638, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def get_screen(self, screen: ScreenType) -> ScreenType: ...", "focal_method_file_path": "src/textual/app.py", "focal_method_start_lineno": 2629, "focal_method_end_lineno": 2630} {"index": 390, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_after_add", "test_class_name": "", "original_test_prefix": "async def test_get_after_add() -> None:\n \"\"\"It should be possible to get an option by ID after adding.\"\"\"\n async with OptionListApp().run_test() as pilot:\n option_list = pilot.app.query_one(OptionList)\n option_list.add_option(Option(\"0\", id=\"0\"))\n assert option_list.get_option(\"0\").id == \"0\"", "test_prefix": "async def test_get_after_add() -> None:\n \"\"\"It should be possible to get an option by ID after adding.\"\"\"\n async with OptionListApp().run_test() as pilot:\n option_list = pilot.app.query_one(OptionList)\n option_list.add_option(Option(\"0\", id=\"0\"))\n ", "test_prefix_file_path": "tests/option_list/test_option_list_id_stability.py", "test_prefix_start_lineno": 17, "test_prefix_end_lineno": 22, "test_target": "tests/option_list/test_option_list_id_stability.py::test_get_after_add", "ground_truth_oracle": "assert option_list.get_option(\"0\").id == \"0\"", "ground_truth_oracle_lineno": 22, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_option(self, option_id: str) -> Option:\n \"\"\"Get the option with the given ID.\n\n Args:\n option_id: The ID of the option to get.\n\n Returns:\n The option with the ID.\n\n Raises:\n OptionDoesNotExist: If no option has the given ID.\n \"\"\"\n try:\n return self._id_to_option[option_id]\n except KeyError:\n raise OptionDoesNotExist(\n f\"There is no option with an ID of {option_id!r}\"\n ) from None", "focal_method_file_path": "src/textual/widgets/_option_list.py", "focal_method_start_lineno": 429, "focal_method_end_lineno": 446} {"index": 391, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_lazy_reveal", "test_class_name": "", "original_test_prefix": "async def test_lazy_reveal():\n app = RevealApp()\n async with app.run_test() as pilot:\n # No #foo on initial mount\n\n # Only first child should be available initially\n assert app.query_one(\"#foo\").display\n # Next two aren't mounted yet\n assert not app.query(\"#baz\")\n\n # All children should be visible after a pause\n await pilot.pause()\n for n in range(3):\n await pilot.pause(1 / 60)\n await pilot.pause()\n\n assert app.query_one(\"#foo\").display\n assert app.query_one(\"#bar\").display\n assert app.query_one(\"#baz\").display", "test_prefix": "async def test_lazy_reveal():\n app = RevealApp()\n async with app.run_test() as pilot:\n # No #foo on initial mount\n\n # Only first child should be available initially\n \n # Next two aren't mounted yet\n assert not app.query(\"#baz\")\n\n # All children should be visible after a pause\n await pilot.pause()\n for n in range(3):\n await pilot.pause(1 / 60)\n await pilot.pause()\n\n \n assert app.query_one(\"#bar\").display\n assert app.query_one(\"#baz\").display", "test_prefix_file_path": "tests/test_lazy.py", "test_prefix_start_lineno": 37, "test_prefix_end_lineno": 55, "test_target": "tests/test_lazy.py::test_lazy_reveal", "ground_truth_oracle": "assert app.query_one(\"#foo\").display", "ground_truth_oracle_lineno": 43, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 392, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_widget_remove_children_with_string_selector", "test_class_name": "", "original_test_prefix": "async def test_widget_remove_children_with_string_selector():\n app = ExampleApp()\n async with app.run_test():\n container = app.query_one(Vertical)\n\n # 6 labels in total, with 5 of them inside the container.\n assert len(app.query(Label)) == 6\n assert len(container.children) == 5\n\n await app.screen.remove_children(\"Label\")\n\n # Only the Screen > Label widget is gone, everything else remains.\n assert len(app.query(Button)) == 1\n assert len(app.query(Vertical)) == 1\n assert len(app.query(Label)) == 5", "test_prefix": "async def test_widget_remove_children_with_string_selector():\n app = ExampleApp()\n async with app.run_test():\n container = app.query_one(Vertical)\n\n # 6 labels in total, with 5 of them inside the container.\n \n assert len(container.children) == 5\n\n await app.screen.remove_children(\"Label\")\n\n # Only the Screen > Label widget is gone, everything else remains.\n assert len(app.query(Button)) == 1\n assert len(app.query(Vertical)) == 1\n assert len(app.query(Label)) == 5", "test_prefix_file_path": "tests/test_widget_removing.py", "test_prefix_start_lineno": 160, "test_prefix_end_lineno": 174, "test_target": "tests/test_widget_removing.py::test_widget_remove_children_with_string_selector", "ground_truth_oracle": "assert len(app.query(Label)) == 6", "ground_truth_oracle_lineno": 166, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query(self, selector: str | None = None) -> DOMQuery[Widget]: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1370, "focal_method_end_lineno": 1371} {"index": 393, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_move_up_from_nowhere", "test_class_name": "", "original_test_prefix": "async def test_move_up_from_nowhere() -> None:\n \"\"\"The highlight should settle on the last item when moving up from `None`.\"\"\"\n async with OptionListApp().run_test() as pilot:\n await pilot.press(\"tab\", \"up\")\n assert pilot.app.query_one(OptionList).highlighted == 5", "test_prefix": "async def test_move_up_from_nowhere() -> None:\n \"\"\"The highlight should settle on the last item when moving up from `None`.\"\"\"\n async with OptionListApp().run_test() as pilot:\n await pilot.press(\"tab\", \"up\")\n ", "test_prefix_file_path": "tests/option_list/test_option_list_movement.py", "test_prefix_start_lineno": 68, "test_prefix_end_lineno": 72, "test_target": "tests/option_list/test_option_list_movement.py::test_move_up_from_nowhere", "ground_truth_oracle": "assert pilot.app.query_one(OptionList).highlighted == 5", "ground_truth_oracle_lineno": 72, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 394, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_password_delete_left_word_from_end", "test_class_name": "", "original_test_prefix": "async def test_password_delete_left_word_from_end() -> None:\n \"\"\"Deleting word left from end of a password input should delete everything.\"\"\"\n async with InputTester().run_test() as pilot:\n for input in pilot.app.query(Input):\n input.password = True\n input.action_delete_left_word()\n assert input.cursor_position == 0\n assert input.value == \"\"", "test_prefix": "async def test_password_delete_left_word_from_end() -> None:\n \"\"\"Deleting word left from end of a password input should delete everything.\"\"\"\n async with InputTester().run_test() as pilot:\n for input in pilot.app.query(Input):\n input.password = True\n input.action_delete_left_word()\n \n assert input.value == \"\"", "test_prefix_file_path": "tests/input/test_input_key_modification_actions.py", "test_prefix_start_lineno": 78, "test_prefix_end_lineno": 85, "test_target": "tests/input/test_input_key_modification_actions.py::test_password_delete_left_word_from_end", "ground_truth_oracle": "assert input.cursor_position == 0", "ground_truth_oracle_lineno": 84, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query(self, selector: str | None = None) -> DOMQuery[Widget]: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1370, "focal_method_end_lineno": 1371} {"index": 395, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_just_app_alpha_binding", "test_class_name": "", "original_test_prefix": "async def test_just_app_alpha_binding() -> None:\n \"\"\"An app with a single binding should have just the one binding.\"\"\"\n async with AlphaBinding().run_test() as pilot:\n assert sorted(pilot.app._bindings.key_to_bindings.keys()) == sorted(\n [\"ctrl+c\", \"ctrl+p\", \"ctrl+q\", \"a\"]\n )\n assert pilot.app._bindings.get_bindings_for_key(\"ctrl+q\")[0].priority is True\n assert pilot.app._bindings.get_bindings_for_key(\"a\")[0].priority is True", "test_prefix": "async def test_just_app_alpha_binding() -> None:\n \"\"\"An app with a single binding should have just the one binding.\"\"\"\n async with AlphaBinding().run_test() as pilot:\n assert sorted(pilot.app._bindings.key_to_bindings.keys()) == sorted(\n [\"ctrl+c\", \"ctrl+p\", \"ctrl+q\", \"a\"]\n )\n \n assert pilot.app._bindings.get_bindings_for_key(\"a\")[0].priority is True", "test_prefix_file_path": "tests/test_binding_inheritance.py", "test_prefix_start_lineno": 65, "test_prefix_end_lineno": 72, "test_target": "tests/test_binding_inheritance.py::test_just_app_alpha_binding", "ground_truth_oracle": "assert pilot.app._bindings.get_bindings_for_key(\"ctrl+q\")[0].priority is True", "ground_truth_oracle_lineno": 71, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_bindings_for_key(self, key: str) -> list[Binding]:\n \"\"\"Get a list of bindings for a given key.\n\n Args:\n key: Key to look up.\n\n Raises:\n NoBinding: If the binding does not exist.\n\n Returns:\n A list of bindings associated with the key.\n \"\"\"\n try:\n return self.key_to_bindings[key]\n except KeyError:\n raise NoBinding(f\"No binding for {key}\") from None", "focal_method_file_path": "src/textual/binding.py", "focal_method_start_lineno": 378, "focal_method_end_lineno": 393} {"index": 396, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_delete_left_start", "test_class_name": "", "original_test_prefix": "async def test_delete_left_start():\n app = TextAreaApp()\n async with app.run_test() as pilot:\n text_area = app.query_one(TextArea)\n text_area.load_text(\"Hello, world!\")\n await pilot.press(\"backspace\")\n assert text_area.text == \"Hello, world!\"\n assert text_area.selection == Selection.cursor((0, 0))", "test_prefix": "async def test_delete_left_start():\n app = TextAreaApp()\n async with app.run_test() as pilot:\n text_area = app.query_one(TextArea)\n text_area.load_text(\"Hello, world!\")\n await pilot.press(\"backspace\")\n \n assert text_area.selection == Selection.cursor((0, 0))", "test_prefix_file_path": "tests/text_area/test_edit_via_bindings.py", "test_prefix_start_lineno": 95, "test_prefix_end_lineno": 102, "test_target": "tests/text_area/test_edit_via_bindings.py::test_delete_left_start", "ground_truth_oracle": "assert text_area.text == \"Hello, world!\"", "ground_truth_oracle_lineno": 101, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 397, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_directory_tree_reloading_preserves_state", "test_class_name": "", "original_test_prefix": "async def test_directory_tree_reloading_preserves_state(tmp_path: Path) -> None:\n \"\"\"Regression test for https://github.com/Textualize/textual/issues/4122.\n\n Ensures `clear_node` does clear the node specified.\n \"\"\"\n ROOT = \"root\"\n structure = [\n ROOT,\n \"root/file1.txt\",\n \"root/file2.txt\",\n ]\n\n for path in structure:\n if path.endswith(\".txt\"):\n (tmp_path / path).touch()\n else:\n (tmp_path / path).mkdir()\n\n app = DirectoryTreeApp(tmp_path / ROOT)\n async with app.run_test() as pilot:\n directory_tree = app.query_one(DirectoryTree)\n directory_tree.clear_node(directory_tree.root)\n await pilot.pause()\n assert not directory_tree.root.children", "test_prefix": "async def test_directory_tree_reloading_preserves_state(tmp_path: Path) -> None:\n \"\"\"Regression test for https://github.com/Textualize/textual/issues/4122.\n\n Ensures `clear_node` does clear the node specified.\n \"\"\"\n ROOT = \"root\"\n structure = [\n ROOT,\n \"root/file1.txt\",\n \"root/file2.txt\",\n ]\n\n for path in structure:\n if path.endswith(\".txt\"):\n (tmp_path / path).touch()\n else:\n (tmp_path / path).mkdir()\n\n app = DirectoryTreeApp(tmp_path / ROOT)\n async with app.run_test() as pilot:\n directory_tree = app.query_one(DirectoryTree)\n directory_tree.clear_node(directory_tree.root)\n await pilot.pause()\n ", "test_prefix_file_path": "tests/tree/test_directory_tree.py", "test_prefix_start_lineno": 180, "test_prefix_end_lineno": 203, "test_target": "tests/tree/test_directory_tree.py::test_directory_tree_reloading_preserves_state", "ground_truth_oracle": "assert not directory_tree.root.children", "ground_truth_oracle_lineno": 203, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 398, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_password_input_left_word_from_end", "test_class_name": "", "original_test_prefix": "async def test_password_input_left_word_from_end() -> None:\n \"\"\"Going left one word from the end in a password field should land at home.\"\"\"\n async with InputTester().run_test() as pilot:\n for input in pilot.app.query(Input):\n input.action_end()\n input.password = True\n input.action_cursor_left_word()\n assert input.cursor_position == 0", "test_prefix": "async def test_password_input_left_word_from_end() -> None:\n \"\"\"Going left one word from the end in a password field should land at home.\"\"\"\n async with InputTester().run_test() as pilot:\n for input in pilot.app.query(Input):\n input.action_end()\n input.password = True\n input.action_cursor_left_word()\n ", "test_prefix_file_path": "tests/input/test_input_key_movement_actions.py", "test_prefix_start_lineno": 103, "test_prefix_end_lineno": 110, "test_target": "tests/input/test_input_key_movement_actions.py::test_password_input_left_word_from_end", "ground_truth_oracle": "assert input.cursor_position == 0", "ground_truth_oracle_lineno": 110, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query(self, selector: str | None = None) -> DOMQuery[Widget]: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1370, "focal_method_end_lineno": 1371} {"index": 399, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_pseudo_classes_work_in_nested_css", "test_class_name": "", "original_test_prefix": "async def test_pseudo_classes_work_in_nested_css() -> None:\n \"\"\"Makes sure pseudo-classes are correctly understood in nested TCSS.\n\n Regression test for https://github.com/Textualize/textual/issues/4039.\n \"\"\"\n\n app = PseudoClassesInNestedApp()\n green = Color.parse(\"green\")\n red = Color.parse(\"red\")\n async with app.run_test() as pilot:\n assert app.query_one(\"#one\").styles.background == green\n assert app.query_one(\"#two\").styles.background == green\n assert app.query_one(\"#five\").styles.background == red\n assert app.query_one(\"#six\").styles.background == red\n\n assert app.query_one(\"#three\").styles.background == red\n assert app.query_one(\"#four\").styles.background == red\n assert app.query_one(\"#seven\").styles.background == red\n assert app.query_one(\"#eight\").styles.background == red\n\n await pilot.hover(\"#eight\")\n\n assert app.query_one(\"#three\").styles.background == red\n assert app.query_one(\"#four\").styles.background == red\n assert app.query_one(\"#seven\").styles.background == red\n assert app.query_one(\"#eight\").styles.background == green", "test_prefix": "async def test_pseudo_classes_work_in_nested_css() -> None:\n \"\"\"Makes sure pseudo-classes are correctly understood in nested TCSS.\n\n Regression test for https://github.com/Textualize/textual/issues/4039.\n \"\"\"\n\n app = PseudoClassesInNestedApp()\n green = Color.parse(\"green\")\n red = Color.parse(\"red\")\n async with app.run_test() as pilot:\n assert app.query_one(\"#one\").styles.background == green\n assert app.query_one(\"#two\").styles.background == green\n assert app.query_one(\"#five\").styles.background == red\n assert app.query_one(\"#six\").styles.background == red\n\n assert app.query_one(\"#three\").styles.background == red\n \n assert app.query_one(\"#seven\").styles.background == red\n assert app.query_one(\"#eight\").styles.background == red\n\n await pilot.hover(\"#eight\")\n\n assert app.query_one(\"#three\").styles.background == red\n \n assert app.query_one(\"#seven\").styles.background == red\n assert app.query_one(\"#eight\").styles.background == green", "test_prefix_file_path": "tests/css/test_nested_css.py", "test_prefix_start_lineno": 160, "test_prefix_end_lineno": 185, "test_target": "tests/css/test_nested_css.py::test_pseudo_classes_work_in_nested_css", "ground_truth_oracle": "assert app.query_one(\"#four\").styles.background == red", "ground_truth_oracle_lineno": 176, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 400, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_tabbed_content_switch_via_ui", "test_class_name": "", "original_test_prefix": "async def test_tabbed_content_switch_via_ui():\n \"\"\"Check tab navigation via the user interface.\"\"\"\n\n class TabbedApp(App):\n def compose(self) -> ComposeResult:\n with TabbedContent():\n with TabPane(\"foo\", id=\"foo\"):\n yield Label(\"Foo\", id=\"foo-label\")\n with TabPane(\"bar\", id=\"bar\"):\n yield Label(\"Bar\", id=\"bar-label\")\n with TabPane(\"baz\", id=\"baz\"):\n yield Label(\"Baz\", id=\"baz-label\")\n\n app = TabbedApp()\n async with app.run_test() as pilot:\n tabbed_content = app.query_one(TabbedContent)\n # Check first tab\n assert tabbed_content.active == \"foo\"\n assert tabbed_content.active_pane.id == \"foo\"\n await pilot.pause()\n assert app.query_one(\"#foo-label\").region\n assert not app.query_one(\"#bar-label\").region\n assert not app.query_one(\"#baz-label\").region\n\n # Click second tab\n await pilot.click(f\"Tab#{ContentTab.add_prefix('bar')}\")\n assert tabbed_content.active == \"bar\"\n assert tabbed_content.active_pane.id == \"bar\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n assert app.query_one(\"#bar-label\").region\n assert not app.query_one(\"#baz-label\").region\n\n # Click third tab\n await pilot.click(f\"Tab#{ContentTab.add_prefix('baz')}\")\n assert tabbed_content.active == \"baz\"\n assert tabbed_content.active_pane.id == \"baz\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n assert not app.query_one(\"#bar-label\").region\n assert app.query_one(\"#baz-label\").region\n\n # Press left\n await pilot.press(\"left\")\n assert tabbed_content.active == \"bar\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n assert app.query_one(\"#bar-label\").region\n assert not app.query_one(\"#baz-label\").region\n\n # Press right\n await pilot.press(\"right\")\n assert tabbed_content.active == \"baz\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n assert not app.query_one(\"#bar-label\").region\n assert app.query_one(\"#baz-label\").region", "test_prefix": "async def test_tabbed_content_switch_via_ui():\n \"\"\"Check tab navigation via the user interface.\"\"\"\n\n class TabbedApp(App):\n def compose(self) -> ComposeResult:\n with TabbedContent():\n with TabPane(\"foo\", id=\"foo\"):\n yield Label(\"Foo\", id=\"foo-label\")\n with TabPane(\"bar\", id=\"bar\"):\n yield Label(\"Bar\", id=\"bar-label\")\n with TabPane(\"baz\", id=\"baz\"):\n yield Label(\"Baz\", id=\"baz-label\")\n\n app = TabbedApp()\n async with app.run_test() as pilot:\n tabbed_content = app.query_one(TabbedContent)\n # Check first tab\n assert tabbed_content.active == \"foo\"\n \n await pilot.pause()\n assert app.query_one(\"#foo-label\").region\n assert not app.query_one(\"#bar-label\").region\n assert not app.query_one(\"#baz-label\").region\n\n # Click second tab\n await pilot.click(f\"Tab#{ContentTab.add_prefix('bar')}\")\n assert tabbed_content.active == \"bar\"\n assert tabbed_content.active_pane.id == \"bar\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n assert app.query_one(\"#bar-label\").region\n assert not app.query_one(\"#baz-label\").region\n\n # Click third tab\n await pilot.click(f\"Tab#{ContentTab.add_prefix('baz')}\")\n assert tabbed_content.active == \"baz\"\n assert tabbed_content.active_pane.id == \"baz\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n assert not app.query_one(\"#bar-label\").region\n assert app.query_one(\"#baz-label\").region\n\n # Press left\n await pilot.press(\"left\")\n assert tabbed_content.active == \"bar\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n assert app.query_one(\"#bar-label\").region\n assert not app.query_one(\"#baz-label\").region\n\n # Press right\n await pilot.press(\"right\")\n assert tabbed_content.active == \"baz\"\n await pilot.pause()\n assert not app.query_one(\"#foo-label\").region\n assert not app.query_one(\"#bar-label\").region\n assert app.query_one(\"#baz-label\").region", "test_prefix_file_path": "tests/test_tabbed_content.py", "test_prefix_start_lineno": 11, "test_prefix_end_lineno": 67, "test_target": "tests/test_tabbed_content.py::test_tabbed_content_switch_via_ui", "ground_truth_oracle": "assert tabbed_content.active_pane.id == \"foo\"", "ground_truth_oracle_lineno": 29, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 401, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_tree_reset_with_label_and_data", "test_class_name": "", "original_test_prefix": "async def test_tree_reset_with_label_and_data() -> None:\n \"\"\"Resetting a tree with a label and data have that label and data used.\"\"\"\n async with TreeClearApp().run_test() as pilot:\n tree = pilot.app.query_one(VerseTree)\n assert len(tree.root.children) > 1\n pilot.app.query_one(VerseTree).reset(label=\"Jiangyin\", data=VersePlanet())\n assert len(tree.root.children) == 0\n assert str(tree.root.label) == \"Jiangyin\"\n assert isinstance(tree.root.data, VersePlanet)", "test_prefix": "async def test_tree_reset_with_label_and_data() -> None:\n \"\"\"Resetting a tree with a label and data have that label and data used.\"\"\"\n async with TreeClearApp().run_test() as pilot:\n tree = pilot.app.query_one(VerseTree)\n \n pilot.app.query_one(VerseTree).reset(label=\"Jiangyin\", data=VersePlanet())\n assert len(tree.root.children) == 0\n assert str(tree.root.label) == \"Jiangyin\"\n assert isinstance(tree.root.data, VersePlanet)", "test_prefix_file_path": "tests/tree/test_tree_clearing.py", "test_prefix_start_lineno": 68, "test_prefix_end_lineno": 76, "test_target": "tests/tree/test_tree_clearing.py::test_tree_reset_with_label_and_data", "ground_truth_oracle": "assert len(tree.root.children) > 1", "ground_truth_oracle_lineno": 72, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 402, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_input_left_from_end", "test_class_name": "", "original_test_prefix": "async def test_input_left_from_end() -> None:\n \"\"\"Going left from the end should go back one place, where possible.\"\"\"\n async with InputTester().run_test() as pilot:\n for input in pilot.app.query(Input):\n input.action_end()\n input.action_cursor_left()\n assert input.cursor_position == (len(input.value) - 1 if input.value else 0)", "test_prefix": "async def test_input_left_from_end() -> None:\n \"\"\"Going left from the end should go back one place, where possible.\"\"\"\n async with InputTester().run_test() as pilot:\n for input in pilot.app.query(Input):\n input.action_end()\n input.action_cursor_left()\n ", "test_prefix_file_path": "tests/input/test_input_key_movement_actions.py", "test_prefix_start_lineno": 69, "test_prefix_end_lineno": 75, "test_target": "tests/input/test_input_key_movement_actions.py::test_input_left_from_end", "ground_truth_oracle": "assert input.cursor_position == (len(input.value) - 1 if input.value else 0)", "ground_truth_oracle_lineno": 75, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query(self, selector: str | None = None) -> DOMQuery[Widget]: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1370, "focal_method_end_lineno": 1371} {"index": 403, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_add_tab_before_and_after", "test_class_name": "", "original_test_prefix": "async def test_add_tab_before_and_after():\n \"\"\"Attempting to add a tab before and after another is an error.\"\"\"\n\n class TabsApp(App[None]):\n def compose(self) -> ComposeResult:\n yield Tabs(\"Pilot\")\n\n async with TabsApp().run_test() as pilot:\n tabs = pilot.app.query_one(Tabs)\n assert tabs.tab_count == 1\n assert tabs.active_tab is not None\n assert tabs.active_tab.id == \"tab-1\"\n assert tabs.active == \"tab-1\"\n with pytest.raises(Tabs.TabError):\n tabs.add_tab(\"John\", before=\"tab-1\", after=\"tab-1\")", "test_prefix": "async def test_add_tab_before_and_after():\n \"\"\"Attempting to add a tab before and after another is an error.\"\"\"\n\n class TabsApp(App[None]):\n def compose(self) -> ComposeResult:\n yield Tabs(\"Pilot\")\n\n async with TabsApp().run_test() as pilot:\n tabs = pilot.app.query_one(Tabs)\n assert tabs.tab_count == 1\n assert tabs.active_tab is not None\n \n assert tabs.active == \"tab-1\"\n with pytest.raises(Tabs.TabError):\n tabs.add_tab(\"John\", before=\"tab-1\", after=\"tab-1\")", "test_prefix_file_path": "tests/test_tabs.py", "test_prefix_start_lineno": 194, "test_prefix_end_lineno": 208, "test_target": "tests/test_tabs.py::test_add_tab_before_and_after", "ground_truth_oracle": "assert tabs.active_tab.id == \"tab-1\"", "ground_truth_oracle_lineno": 205, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 404, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_styled", "test_class_name": "", "original_test_prefix": "def test_styled():\n text = Content.styled(\"Hello\", \"red\")\n assert text.plain == \"Hello\"\n assert len(text) == 5\n assert text.cell_length == 5\n assert text._spans == [Span(0, 5, \"red\")]", "test_prefix": "def test_styled():\n text = Content.styled(\"Hello\", \"red\")\n \n assert len(text) == 5\n assert text.cell_length == 5\n assert text._spans == [Span(0, 5, \"red\")]", "test_prefix_file_path": "tests/test_content.py", "test_prefix_start_lineno": 58, "test_prefix_end_lineno": 63, "test_target": "tests/test_content.py::test_styled", "ground_truth_oracle": "assert text.plain == \"Hello\"", "ground_truth_oracle_lineno": 60, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def styled(\n cls,\n text: str,\n style: Style | str = \"\",\n cell_length: int | None = None,\n ) -> Content:\n \"\"\"Create a Content instance from text and an optional style.\n\n Args:\n text: String content.\n style: Desired style.\n cell_length: Cell length of text if known, otherwise `None`.\n\n Returns:\n New Content instance.\n \"\"\"\n if not text:\n return Content(\"\")\n new_content = cls(text, [Span(0, len(text), style)] if style else None)\n return new_content", "focal_method_file_path": "src/textual/content.py", "focal_method_start_lineno": 318, "focal_method_end_lineno": 338} {"index": 405, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_cut", "test_class_name": "", "original_test_prefix": "async def test_cut():\n \"\"\"Check that cut removes text and places it in the clipboard.\"\"\"\n app = InputApp()\n async with app.run_test() as pilot:\n input = app.query_one(Input)\n await pilot.click(input)\n await pilot.press(*\"Hello, World\")\n await pilot.press(\"left\", \"shift+left\", \"shift+left\")\n await pilot.press(\"ctrl+x\")\n assert input.value == \"Hello, Wod\"\n assert app.clipboard == \"rl\"", "test_prefix": "async def test_cut():\n \"\"\"Check that cut removes text and places it in the clipboard.\"\"\"\n app = InputApp()\n async with app.run_test() as pilot:\n input = app.query_one(Input)\n await pilot.click(input)\n await pilot.press(*\"Hello, World\")\n await pilot.press(\"left\", \"shift+left\", \"shift+left\")\n await pilot.press(\"ctrl+x\")\n assert input.value == \"Hello, Wod\"\n ", "test_prefix_file_path": "tests/input/test_cut_copy_paste.py", "test_prefix_start_lineno": 10, "test_prefix_end_lineno": 20, "test_target": "tests/input/test_cut_copy_paste.py::test_cut", "ground_truth_oracle": "assert app.clipboard == \"rl\"", "ground_truth_oracle_lineno": 20, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 406, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_app_getter", "test_class_name": "", "original_test_prefix": "async def test_app_getter() -> None:\n\n class MyApp(App):\n def compose(self) -> ComposeResult:\n my_widget = MyWidget()\n my_widget.app\n yield my_widget\n\n class MyWidget(Widget):\n app = getters.app(MyApp)\n\n app = MyApp()\n async with app.run_test():\n assert isinstance(app.query_one(MyWidget).app, MyApp)", "test_prefix": "async def test_app_getter() -> None:\n\n class MyApp(App):\n def compose(self) -> ComposeResult:\n my_widget = MyWidget()\n my_widget.app\n yield my_widget\n\n class MyWidget(Widget):\n app = getters.app(MyApp)\n\n app = MyApp()\n async with app.run_test():\n ", "test_prefix_file_path": "tests/test_getters.py", "test_prefix_start_lineno": 48, "test_prefix_end_lineno": 61, "test_target": "tests/test_getters.py::test_app_getter", "ground_truth_oracle": "assert isinstance(app.query_one(MyWidget).app, MyApp)", "ground_truth_oracle_lineno": 61, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 407, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_clear_tabs", "test_class_name": "", "original_test_prefix": "async def test_clear_tabs():\n \"\"\"It should be possible to clear all tabs.\"\"\"\n\n class TabsApp(App[None]):\n def compose(self) -> ComposeResult:\n yield Tabs(\"John\", \"Aeryn\", \"Moya\", \"Pilot\")\n\n async with TabsApp().run_test() as pilot:\n tabs = pilot.app.query_one(Tabs)\n assert tabs.tab_count == 4\n assert tabs.active_tab is not None\n assert tabs.active_tab.id == \"tab-1\"\n await tabs.clear()\n assert tabs.tab_count == 0\n assert tabs.active_tab is None", "test_prefix": "async def test_clear_tabs():\n \"\"\"It should be possible to clear all tabs.\"\"\"\n\n class TabsApp(App[None]):\n def compose(self) -> ComposeResult:\n yield Tabs(\"John\", \"Aeryn\", \"Moya\", \"Pilot\")\n\n async with TabsApp().run_test() as pilot:\n tabs = pilot.app.query_one(Tabs)\n assert tabs.tab_count == 4\n \n assert tabs.active_tab.id == \"tab-1\"\n await tabs.clear()\n assert tabs.tab_count == 0\n assert tabs.active_tab is None", "test_prefix_file_path": "tests/test_tabs.py", "test_prefix_start_lineno": 283, "test_prefix_end_lineno": 297, "test_target": "tests/test_tabs.py::test_clear_tabs", "ground_truth_oracle": "assert tabs.active_tab is not None", "ground_truth_oracle_lineno": 293, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 408, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_tree_reset_with_label", "test_class_name": "", "original_test_prefix": "async def test_tree_reset_with_label() -> None:\n \"\"\"Resetting a tree with a new label should use the new label and set the data to None.\"\"\"\n async with TreeClearApp().run_test() as pilot:\n tree = pilot.app.query_one(VerseTree)\n assert len(tree.root.children) > 1\n pilot.app.query_one(VerseTree).reset(label=\"Jiangyin\")\n assert len(tree.root.children) == 0\n assert str(tree.root.label) == \"Jiangyin\"\n assert tree.root.data is None", "test_prefix": "async def test_tree_reset_with_label() -> None:\n \"\"\"Resetting a tree with a new label should use the new label and set the data to None.\"\"\"\n async with TreeClearApp().run_test() as pilot:\n tree = pilot.app.query_one(VerseTree)\n assert len(tree.root.children) > 1\n pilot.app.query_one(VerseTree).reset(label=\"Jiangyin\")\n assert len(tree.root.children) == 0\n assert str(tree.root.label) == \"Jiangyin\"\n ", "test_prefix_file_path": "tests/tree/test_tree_clearing.py", "test_prefix_start_lineno": 57, "test_prefix_end_lineno": 65, "test_target": "tests/tree/test_tree_clearing.py::test_tree_reset_with_label", "ground_truth_oracle": "assert tree.root.data is None", "ground_truth_oracle_lineno": 65, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 409, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_boosted_matches", "test_class_name": "", "original_test_prefix": "def test_boosted_matches():\n \"\"\"Check first word matchers rank higher.\"\"\"\n matcher = Matcher(\"ss\")\n\n # First word matchers should score higher\n assert matcher.match(\"Save Screenshot\") > matcher.match(\"Show Keys abcde\")", "test_prefix": "def test_boosted_matches():\n \"\"\"Check first word matchers rank higher.\"\"\"\n matcher = Matcher(\"ss\")\n\n # First word matchers should score higher\n ", "test_prefix_file_path": "tests/test_fuzzy.py", "test_prefix_start_lineno": 18, "test_prefix_end_lineno": 23, "test_target": "tests/test_fuzzy.py::test_boosted_matches", "ground_truth_oracle": "assert matcher.match(\"Save Screenshot\") > matcher.match(\"Show Keys abcde\")", "ground_truth_oracle_lineno": 23, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def match(self, candidate: str) -> float:\n \"\"\"Match the candidate against the query.\n\n Args:\n candidate: Candidate string to match against the query.\n\n Returns:\n Strength of the match from 0 to 1.\n \"\"\"\n return self.fuzzy_search.match(self.query, candidate)[0]", "focal_method_file_path": "src/textual/fuzzy.py", "focal_method_start_lineno": 192, "focal_method_end_lineno": 201} {"index": 410, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_input_selected_text", "test_class_name": "", "original_test_prefix": "async def test_input_selected_text():\n async with InputApp().run_test() as pilot:\n input_widget = pilot.app.query_one(Input)\n input_widget.value = \"Hello, world!\"\n input_widget.selection = Selection(0, 4)\n assert input_widget.selected_text == \"Hell\"\n\n # Reverse selection\n input_widget.selection = Selection(4, 0)\n assert input_widget.selected_text == \"Hell\"\n\n # Empty selection\n input_widget.selection = Selection(4, 4)\n assert input_widget.selected_text == \"\"", "test_prefix": "async def test_input_selected_text():\n async with InputApp().run_test() as pilot:\n input_widget = pilot.app.query_one(Input)\n input_widget.value = \"Hello, world!\"\n input_widget.selection = Selection(0, 4)\n assert input_widget.selected_text == \"Hell\"\n\n # Reverse selection\n input_widget.selection = Selection(4, 0)\n assert input_widget.selected_text == \"Hell\"\n\n # Empty selection\n input_widget.selection = Selection(4, 4)\n ", "test_prefix_file_path": "tests/input/test_input_properties.py", "test_prefix_start_lineno": 67, "test_prefix_end_lineno": 80, "test_target": "tests/input/test_input_properties.py::test_input_selected_text", "ground_truth_oracle": "assert input_widget.selected_text == \"\"", "ground_truth_oracle_lineno": 80, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class Selection(NamedTuple):\n \"\"\"A range of selected text within the Input.\n\n Text can be selected by clicking and dragging the mouse, or by pressing\n shift+arrow keys.\n\n Attributes:\n start: The start index of the selection.\n end: The end index of the selection.\n \"\"\"\n\n start: int\n end: int\n\n @classmethod\n def cursor(cls, cursor_position: int) -> Selection:\n \"\"\"Create a selection from a cursor position.\"\"\"\n return cls(cursor_position, cursor_position)\n\n @property\n def is_empty(self) -> bool:\n \"\"\"Return True if the selection is empty.\"\"\"\n return self.start == self.end", "focal_method_file_path": "src/textual/widgets/_input.py", "focal_method_start_lineno": 46, "focal_method_end_lineno": 68} {"index": 411, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_delete_left_word_from_home", "test_class_name": "", "original_test_prefix": "async def test_delete_left_word_from_home() -> None:\n \"\"\"Deleting word left from home should do nothing.\"\"\"\n async with InputTester().run_test() as pilot:\n for input in pilot.app.query(Input):\n input.cursor_position = 0\n input.action_delete_left_word()\n assert input.cursor_position == 0\n assert input.value == TEST_INPUTS[input.id]", "test_prefix": "async def test_delete_left_word_from_home() -> None:\n \"\"\"Deleting word left from home should do nothing.\"\"\"\n async with InputTester().run_test() as pilot:\n for input in pilot.app.query(Input):\n input.cursor_position = 0\n input.action_delete_left_word()\n assert input.cursor_position == 0\n ", "test_prefix_file_path": "tests/input/test_input_key_modification_actions.py", "test_prefix_start_lineno": 44, "test_prefix_end_lineno": 51, "test_target": "tests/input/test_input_key_modification_actions.py::test_delete_left_word_from_home", "ground_truth_oracle": "assert input.value == TEST_INPUTS[input.id]", "ground_truth_oracle_lineno": 51, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query(self, selector: str | None = None) -> DOMQuery[Widget]: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1370, "focal_method_end_lineno": 1371} {"index": 412, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_column_at", "test_class_name": "", "original_test_prefix": "async def test_get_column_at():\n app = DataTableApp()\n async with app.run_test():\n table = app.query_one(DataTable)\n table.add_columns(\"A\", \"B\")\n table.add_rows(ROWS)\n\n first_column = list(table.get_column_at(0))\n assert first_column == [ROWS[0][0], ROWS[1][0], ROWS[2][0]]\n\n second_column = list(table.get_column_at(1))\n assert second_column == [ROWS[0][1], ROWS[1][1], ROWS[2][1]]", "test_prefix": "async def test_get_column_at():\n app = DataTableApp()\n async with app.run_test():\n table = app.query_one(DataTable)\n table.add_columns(\"A\", \"B\")\n table.add_rows(ROWS)\n\n first_column = list(table.get_column_at(0))\n assert first_column == [ROWS[0][0], ROWS[1][0], ROWS[2][0]]\n\n second_column = list(table.get_column_at(1))\n ", "test_prefix_file_path": "tests/test_data_table.py", "test_prefix_start_lineno": 634, "test_prefix_end_lineno": 645, "test_target": "tests/test_data_table.py::test_get_column_at", "ground_truth_oracle": "assert second_column == [ROWS[0][1], ROWS[1][1], ROWS[2][1]]", "ground_truth_oracle_lineno": 645, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_column_at(self, column_index: int) -> Iterable[CellType]:\n \"\"\"Get the values from the column at a given index.\n\n Args:\n column_index: The index of the column.\n\n Returns:\n A generator which yields the cells in the column.\n\n Raises:\n ColumnDoesNotExist: If there is no column with the given index.\n \"\"\"\n if not self.is_valid_column_index(column_index):\n raise ColumnDoesNotExist(f\"Column index {column_index!r} is not valid.\")\n\n column_key = self._column_locations.get_key(column_index)\n yield from self.get_column(column_key)", "focal_method_file_path": "src/textual/widgets/_data_table.py", "focal_method_start_lineno": 1065, "focal_method_end_lineno": 1081} {"index": 413, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_add_later", "test_class_name": "", "original_test_prefix": "async def test_add_later() -> None:\n \"\"\"It should be possible to add more items to a list.\"\"\"\n async with OptionListApp().run_test() as pilot:\n option_list = pilot.app.query_one(OptionList)\n assert option_list.option_count == 5\n option_list.add_option(\"more\")\n assert option_list.option_count == 6\n option_list.add_option()\n assert option_list.option_count == 6\n option_list.add_option(Option(\"even more\"))\n assert option_list.option_count == 7\n option_list.add_options(\n [Option(\"more still\"), \"Yet more options\", \"so many options!\"]\n )\n assert option_list.option_count == 10\n option_list.add_option(None)\n assert option_list.option_count == 10\n option_list.add_options([])\n assert option_list.option_count == 10", "test_prefix": "async def test_add_later() -> None:\n \"\"\"It should be possible to add more items to a list.\"\"\"\n async with OptionListApp().run_test() as pilot:\n option_list = pilot.app.query_one(OptionList)\n assert option_list.option_count == 5\n option_list.add_option(\"more\")\n \n option_list.add_option()\n \n option_list.add_option(Option(\"even more\"))\n assert option_list.option_count == 7\n option_list.add_options(\n [Option(\"more still\"), \"Yet more options\", \"so many options!\"]\n )\n assert option_list.option_count == 10\n option_list.add_option(None)\n assert option_list.option_count == 10\n option_list.add_options([])\n assert option_list.option_count == 10", "test_prefix_file_path": "tests/option_list/test_option_list_create.py", "test_prefix_start_lineno": 93, "test_prefix_end_lineno": 111, "test_target": "tests/option_list/test_option_list_create.py::test_add_later", "ground_truth_oracle": "assert option_list.option_count == 6", "ground_truth_oracle_lineno": 101, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 414, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_cell_returns_value_at_cell", "test_class_name": "", "original_test_prefix": "async def test_get_cell_returns_value_at_cell():\n app = DataTableApp()\n async with app.run_test():\n table = app.query_one(DataTable)\n table.add_column(\"Column1\", key=\"C1\")\n table.add_row(\"TargetValue\", key=\"R1\")\n assert table.get_cell(\"R1\", \"C1\") == \"TargetValue\"", "test_prefix": "async def test_get_cell_returns_value_at_cell():\n app = DataTableApp()\n async with app.run_test():\n table = app.query_one(DataTable)\n table.add_column(\"Column1\", key=\"C1\")\n table.add_row(\"TargetValue\", key=\"R1\")\n ", "test_prefix_file_path": "tests/test_data_table.py", "test_prefix_start_lineno": 444, "test_prefix_end_lineno": 450, "test_target": "tests/test_data_table.py::test_get_cell_returns_value_at_cell", "ground_truth_oracle": "assert table.get_cell(\"R1\", \"C1\") == \"TargetValue\"", "ground_truth_oracle_lineno": 450, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_cell(self, row_key: RowKey | str, column_key: ColumnKey | str) -> CellType:\n \"\"\"Given a row key and column key, return the value of the corresponding cell.\n\n Args:\n row_key: The row key of the cell.\n column_key: The column key of the cell.\n\n Returns:\n The value of the cell identified by the row and column keys.\n \"\"\"\n try:\n cell_value = self._data[row_key][column_key]\n except KeyError:\n raise CellDoesNotExist(\n f\"No cell exists for row_key={row_key!r}, column_key={column_key!r}.\"\n )\n return cell_value", "focal_method_file_path": "src/textual/widgets/_data_table.py", "focal_method_start_lineno": 931, "focal_method_end_lineno": 947} {"index": 415, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_down_arrow_selects_an_item", "test_class_name": "", "original_test_prefix": "async def test_down_arrow_selects_an_item() -> None:\n \"\"\"Typing in a search value then pressing down should select a command.\"\"\"\n async with CommandPaletteApp().run_test() as pilot:\n assert CommandPalette.is_open(pilot.app)\n assert pilot.app.screen.query_one(CommandList).visible is False\n await pilot.press(\"a\")\n assert pilot.app.screen.query_one(CommandList).visible is True\n assert pilot.app.screen.query_one(CommandList).highlighted == 0\n await pilot.press(\"down\")\n assert pilot.app.screen.query_one(CommandList).highlighted == 1", "test_prefix": "async def test_down_arrow_selects_an_item() -> None:\n \"\"\"Typing in a search value then pressing down should select a command.\"\"\"\n async with CommandPaletteApp().run_test() as pilot:\n assert CommandPalette.is_open(pilot.app)\n assert pilot.app.screen.query_one(CommandList).visible is False\n await pilot.press(\"a\")\n assert pilot.app.screen.query_one(CommandList).visible is True\n \n await pilot.press(\"down\")\n assert pilot.app.screen.query_one(CommandList).highlighted == 1", "test_prefix_file_path": "tests/command_palette/test_interaction.py", "test_prefix_start_lineno": 31, "test_prefix_end_lineno": 40, "test_target": "tests/command_palette/test_interaction.py::test_down_arrow_selects_an_item", "ground_truth_oracle": "assert pilot.app.screen.query_one(CommandList).highlighted == 0", "ground_truth_oracle_lineno": 38, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 416, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_text_setter", "test_class_name": "", "original_test_prefix": "async def test_text_setter():\n app = TextAreaApp()\n async with app.run_test():\n text_area = app.query_one(TextArea)\n new_text = \"hello\\nworld\\n\"\n text_area.text = new_text\n assert text_area.text == new_text", "test_prefix": "async def test_text_setter():\n app = TextAreaApp()\n async with app.run_test():\n text_area = app.query_one(TextArea)\n new_text = \"hello\\nworld\\n\"\n text_area.text = new_text\n ", "test_prefix_file_path": "tests/text_area/test_edit_via_api.py", "test_prefix_start_lineno": 547, "test_prefix_end_lineno": 553, "test_target": "tests/text_area/test_edit_via_api.py::test_text_setter", "ground_truth_oracle": "assert text_area.text == new_text", "ground_truth_oracle_lineno": 553, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 417, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_app_loop_run_after_asyncio_run", "test_class_name": "", "original_test_prefix": "def test_app_loop_run_after_asyncio_run() -> None:\n \"\"\"Test that App.run runs after asyncio.run has run.\"\"\"\n\n class MyApp(App[int]):\n def on_mount(self) -> None:\n self.exit(42)\n\n async def amain():\n pass\n\n asyncio.run(amain())\n\n app = MyApp()\n result = app.run()\n assert result == 42", "test_prefix": "def test_app_loop_run_after_asyncio_run() -> None:\n \"\"\"Test that App.run runs after asyncio.run has run.\"\"\"\n\n class MyApp(App[int]):\n def on_mount(self) -> None:\n self.exit(42)\n\n async def amain():\n pass\n\n asyncio.run(amain())\n\n app = MyApp()\n result = app.run()\n ", "test_prefix_file_path": "tests/test_app.py", "test_prefix_start_lineno": 374, "test_prefix_end_lineno": 388, "test_target": "tests/test_app.py::test_app_loop_run_after_asyncio_run", "ground_truth_oracle": "assert result == 42", "ground_truth_oracle_lineno": 388, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def run(\n self,\n *,\n headless: bool = False,\n inline: bool = False,\n inline_no_clear: bool = False,\n mouse: bool = True,\n size: tuple[int, int] | None = None,\n auto_pilot: AutopilotCallbackType | None = None,\n loop: AbstractEventLoop | None = None,\n ) -> ReturnType | None:\n \"\"\"Run the app.\n\n Args:\n headless: Run in headless mode (no output).\n inline: Run the app inline (under the prompt).\n inline_no_clear: Don't clear the app output when exiting an inline app.\n mouse: Enable mouse support.\n size: Force terminal size to `(WIDTH, HEIGHT)`,\n or None to auto-detect.\n auto_pilot: An auto pilot coroutine.\n loop: Asyncio loop instance, or `None` to use default.\n Returns:\n App return value.\n \"\"\"\n\n async def run_app() -> ReturnType | None:\n \"\"\"Run the app.\"\"\"\n return await self.run_async(\n headless=headless,\n inline=inline,\n inline_no_clear=inline_no_clear,\n mouse=mouse,\n size=size,\n auto_pilot=auto_pilot,\n )\n\n if loop is None:\n if _ASYNCIO_GET_EVENT_LOOP_IS_DEPRECATED:\n # N.B. This does work with Python<3.10, but global Locks, Events, etc\n # eagerly bind the event loop, and result in Future bound to wrong\n # loop errors.\n return asyncio.run(run_app())\n try:\n global_loop = asyncio.get_event_loop()\n except RuntimeError:\n # the global event loop may have been destroyed by someone running\n # asyncio.run(), or asyncio.set_event_loop(None), in which case\n # we need to use asyncio.run() also. (We run this outside the\n # context of an exception handler)\n pass\n else:\n return global_loop.run_until_complete(run_app())\n return asyncio.run(run_app())\n return loop.run_until_complete(run_app())", "focal_method_file_path": "src/textual/app.py", "focal_method_start_lineno": 2209, "focal_method_end_lineno": 2263} {"index": 418, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_environ_port", "test_class_name": "", "original_test_prefix": "def test_environ_port(monkeypatch):\n \"\"\"Valid ports are between 0 and 65536.\"\"\"\n monkeypatch.setenv(\"PORT\", \"-1\")\n assert _get_environ_port(\"PORT\", 80) == 80\n monkeypatch.setenv(\"PORT\", \"0\")\n assert _get_environ_port(\"PORT\", 80) == 0\n monkeypatch.setenv(\"PORT\", \"65536\")\n assert _get_environ_port(\"PORT\", 80) == 80", "test_prefix": "def test_environ_port(monkeypatch):\n \"\"\"Valid ports are between 0 and 65536.\"\"\"\n monkeypatch.setenv(\"PORT\", \"-1\")\n assert _get_environ_port(\"PORT\", 80) == 80\n monkeypatch.setenv(\"PORT\", \"0\")\n \n monkeypatch.setenv(\"PORT\", \"65536\")\n assert _get_environ_port(\"PORT\", 80) == 80", "test_prefix_file_path": "tests/test_constants.py", "test_prefix_start_lineno": 24, "test_prefix_end_lineno": 31, "test_target": "tests/test_constants.py::test_environ_port", "ground_truth_oracle": "assert _get_environ_port(\"PORT\", 80) == 0", "ground_truth_oracle_lineno": 29, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _get_environ_port(name: str, default: int) -> int:\n \"\"\"Get a port no. from an environment variable.\n\n Note that there is no 'minimum' here, as ports are more like names than a scalar value.\n\n Args:\n name: Name of environment variable.\n default: The value to use if the value is not set, or set to something other\n than a valid port.\n\n Returns:\n An integer port number.\n\n \"\"\"\n try:\n value = int(os.environ[name])\n except KeyError:\n return default\n except ValueError:\n return default\n if value < 0 or value > 65535:\n return default\n return value", "focal_method_file_path": "src/textual/constants.py", "focal_method_start_lineno": 58, "focal_method_end_lineno": 80} {"index": 419, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_schedule_reverse_animations", "test_class_name": "", "original_test_prefix": "async def test_schedule_reverse_animations() -> None:\n \"\"\"Test that you can schedule reverse animations.\n\n Regression test for #1372 https://github.com/Textualize/textual/issues/1372\n \"\"\"\n\n app = AnimApp()\n\n async with app.run_test() as pilot:\n static = app.query_one(Static)\n styles = static.styles\n\n # Starting point.\n styles.background = \"black\"\n assert styles.background.rgb == (0, 0, 0)\n\n # First, make sure we can go from black to white and back, step by step.\n styles.animate(\"background\", \"white\", delay=0.01, duration=0.01)\n await pilot.wait_for_scheduled_animations()\n assert styles.background.rgb == (255, 255, 255)\n\n styles.animate(\"background\", \"black\", delay=0.01, duration=0.01)\n await pilot.wait_for_scheduled_animations()\n assert styles.background.rgb == (0, 0, 0)\n\n # Now, the actual test is to make sure we go back to black if scheduling both at once.\n styles.animate(\"background\", \"white\", delay=0.025, duration=0.05)\n # While the black -> white animation runs, start the white -> black animation.\n styles.animate(\"background\", \"black\", delay=0.05, duration=0.01)\n await pilot.wait_for_scheduled_animations()\n assert styles.background.rgb == (0, 0, 0)", "test_prefix": "async def test_schedule_reverse_animations() -> None:\n \"\"\"Test that you can schedule reverse animations.\n\n Regression test for #1372 https://github.com/Textualize/textual/issues/1372\n \"\"\"\n\n app = AnimApp()\n\n async with app.run_test() as pilot:\n static = app.query_one(Static)\n styles = static.styles\n\n # Starting point.\n styles.background = \"black\"\n assert styles.background.rgb == (0, 0, 0)\n\n # First, make sure we can go from black to white and back, step by step.\n styles.animate(\"background\", \"white\", delay=0.01, duration=0.01)\n await pilot.wait_for_scheduled_animations()\n \n\n styles.animate(\"background\", \"black\", delay=0.01, duration=0.01)\n await pilot.wait_for_scheduled_animations()\n assert styles.background.rgb == (0, 0, 0)\n\n # Now, the actual test is to make sure we go back to black if scheduling both at once.\n styles.animate(\"background\", \"white\", delay=0.025, duration=0.05)\n # While the black -> white animation runs, start the white -> black animation.\n styles.animate(\"background\", \"black\", delay=0.05, duration=0.01)\n await pilot.wait_for_scheduled_animations()\n assert styles.background.rgb == (0, 0, 0)", "test_prefix_file_path": "tests/test_animation.py", "test_prefix_start_lineno": 130, "test_prefix_end_lineno": 160, "test_target": "tests/test_animation.py::test_schedule_reverse_animations", "ground_truth_oracle": "assert styles.background.rgb == (255, 255, 255)", "ground_truth_oracle_lineno": 149, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 420, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_timeout", "test_class_name": "", "original_test_prefix": "def test_timeout() -> None:\n \"\"\"Notifications should timeout from the list.\"\"\"\n tester = Notifications()\n for n in range(100):\n tester.add(Notification(\"test\", timeout=(0.5 if bool(n % 2) else 60)))\n assert len(tester) == 100\n sleep(0.6)\n assert len(tester) == 50", "test_prefix": "def test_timeout() -> None:\n \"\"\"Notifications should timeout from the list.\"\"\"\n tester = Notifications()\n for n in range(100):\n tester.add(Notification(\"test\", timeout=(0.5 if bool(n % 2) else 60)))\n assert len(tester) == 100\n sleep(0.6)\n ", "test_prefix_file_path": "tests/notifications/test_notifications.py", "test_prefix_start_lineno": 21, "test_prefix_end_lineno": 28, "test_target": "tests/notifications/test_notifications.py::test_timeout", "ground_truth_oracle": "assert len(tester) == 50", "ground_truth_oracle_lineno": 28, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class Notifications:\n \"\"\"Class for managing a collection of notifications.\"\"\"\n\n def __init__(self) -> None:\n \"\"\"Initialise the notification collection.\"\"\"\n self._notifications: dict[str, Notification] = {}\n\n def _reap(self) -> Self:\n \"\"\"Remove any expired notifications from the notification collection.\"\"\"\n for notification in list(self._notifications.values()):\n if notification.has_expired:\n del self._notifications[notification.identity]\n return self\n\n def add(self, notification: Notification) -> Self:\n \"\"\"Add the given notification to the collection of managed notifications.\n\n Args:\n notification: The notification to add.\n\n Returns:\n Self.\n \"\"\"\n self._reap()._notifications[notification.identity] = notification\n return self\n\n def clear(self) -> Self:\n \"\"\"Clear all the notifications.\"\"\"\n self._notifications.clear()\n return self\n\n def __len__(self) -> int:\n \"\"\"The number of notifications.\"\"\"\n return len(self._reap()._notifications)\n\n def __iter__(self) -> Iterator[Notification]:\n return iter(self._reap()._notifications.values())\n\n def __contains__(self, notification: Notification) -> bool:\n return notification.identity in self._notifications\n\n def __delitem__(self, notification: Notification) -> None:\n try:\n del self._reap()._notifications[notification.identity]\n except KeyError:\n # An attempt to remove a notification we don't know about is a\n # no-op. What matters here is that the notification is forgotten\n # about, and it looks like a caller has tried to be\n # belt-and-braces. We're fine with this.\n pass", "focal_method_file_path": "src/textual/notifications.py", "focal_method_start_lineno": 71, "focal_method_end_lineno": 120} {"index": 421, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_on_blur_triggers_validation", "test_class_name": "", "original_test_prefix": "async def test_on_blur_triggers_validation():\n app = InputApp()\n async with app.run_test() as pilot:\n input = app.query_one(Input)\n input.focus()\n input.value = \"3\"\n input.remove_class(\"-valid\")\n app.set_focus(None)\n await pilot.pause()\n assert input.has_class(\"-valid\")", "test_prefix": "async def test_on_blur_triggers_validation():\n app = InputApp()\n async with app.run_test() as pilot:\n input = app.query_one(Input)\n input.focus()\n input.value = \"3\"\n input.remove_class(\"-valid\")\n app.set_focus(None)\n await pilot.pause()\n ", "test_prefix_file_path": "tests/input/test_input_validation.py", "test_prefix_start_lineno": 87, "test_prefix_end_lineno": 96, "test_target": "tests/input/test_input_validation.py::test_on_blur_triggers_validation", "ground_truth_oracle": "assert input.has_class(\"-valid\")", "ground_truth_oracle_lineno": 96, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 422, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_overflow_importance", "test_class_name": "", "original_test_prefix": "async def test_overflow_importance():\n \"\"\"Overflow without direction should support !important\"\"\"\n async with StyleApp().run_test() as pilot:\n assert pilot.app.query_one(Container).styles.overflow_x == \"hidden\"\n assert pilot.app.query_one(Container).styles.overflow_y == \"hidden\"", "test_prefix": "async def test_overflow_importance():\n \"\"\"Overflow without direction should support !important\"\"\"\n async with StyleApp().run_test() as pilot:\n \n assert pilot.app.query_one(Container).styles.overflow_y == \"hidden\"", "test_prefix_file_path": "tests/test_style_importance.py", "test_prefix_start_lineno": 81, "test_prefix_end_lineno": 85, "test_target": "tests/test_style_importance.py::test_overflow_importance", "ground_truth_oracle": "assert pilot.app.query_one(Container).styles.overflow_x == \"hidden\"", "ground_truth_oracle_lineno": 84, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 423, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_disabled_log_no_attribute_error", "test_class_name": "", "original_test_prefix": "async def test_disabled_log_no_attribute_error() -> None:\n \"\"\"Ensure that initializing the log with disabled=True does not\n raise an AttributeError.\n Regression test for https://github.com/Textualize/textual/issues/5028\n \"\"\"\n\n class DisabledLogApp(App):\n def compose(self) -> ComposeResult:\n yield Log(disabled=True)\n\n async with DisabledLogApp().run_test() as pilot:\n # If no exception is raised, the test will pass\n log = pilot.app.query_one(Log)\n assert log.disabled == True", "test_prefix": "async def test_disabled_log_no_attribute_error() -> None:\n \"\"\"Ensure that initializing the log with disabled=True does not\n raise an AttributeError.\n Regression test for https://github.com/Textualize/textual/issues/5028\n \"\"\"\n\n class DisabledLogApp(App):\n def compose(self) -> ComposeResult:\n yield Log(disabled=True)\n\n async with DisabledLogApp().run_test() as pilot:\n # If no exception is raised, the test will pass\n log = pilot.app.query_one(Log)\n ", "test_prefix_file_path": "tests/test_log.py", "test_prefix_start_lineno": 12, "test_prefix_end_lineno": 25, "test_target": "tests/test_log.py::test_disabled_log_no_attribute_error", "ground_truth_oracle": "assert log.disabled == True", "ground_truth_oracle_lineno": 25, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 424, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_replace_option_prompt_with_valid_index", "test_class_name": "", "original_test_prefix": "async def test_replace_option_prompt_with_valid_index() -> None:\n \"\"\"It should be possible to replace the prompt of an option index that does exist.\"\"\"\n async with OptionListApp().run_test() as pilot:\n option_list = pilot.app.query_one(OptionList).replace_option_prompt_at_index(1, \"new-prompt\")\n assert option_list.get_option_at_index(1).prompt == \"new-prompt\"", "test_prefix": "async def test_replace_option_prompt_with_valid_index() -> None:\n \"\"\"It should be possible to replace the prompt of an option index that does exist.\"\"\"\n async with OptionListApp().run_test() as pilot:\n option_list = pilot.app.query_one(OptionList).replace_option_prompt_at_index(1, \"new-prompt\")\n ", "test_prefix_file_path": "tests/option_list/test_option_prompt_replacement.py", "test_prefix_start_lineno": 41, "test_prefix_end_lineno": 45, "test_target": "tests/option_list/test_option_prompt_replacement.py::test_replace_option_prompt_with_valid_index", "ground_truth_oracle": "assert option_list.get_option_at_index(1).prompt == \"new-prompt\"", "ground_truth_oracle_lineno": 45, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_option_at_index(self, index: int) -> Option:\n \"\"\"Get the option at the given index.\n\n Args:\n index: The index of the option to get.\n\n Returns:\n The option at that index.\n\n Raises:\n OptionDoesNotExist: If there is no option with the given index.\n \"\"\"\n try:\n return self._options[index]\n except IndexError:\n raise OptionDoesNotExist(\n f\"There is no option with an index of {index}\"\n ) from None", "focal_method_file_path": "src/textual/widgets/_option_list.py", "focal_method_start_lineno": 463, "focal_method_end_lineno": 480} {"index": 425, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_universal_selector_doesnt_select_self", "test_class_name": "", "original_test_prefix": "async def test_universal_selector_doesnt_select_self():\n class ExampleApp(App):\n def compose(self) -> ComposeResult:\n yield Container(\n Widget(\n Widget(),\n Widget(\n Widget(),\n ),\n ),\n Widget(),\n id=\"root-container\",\n )\n\n app = ExampleApp()\n async with app.run_test():\n container = app.query_one(\"#root-container\", Container)\n query = container.query(\"*\")\n results = list(query.results())\n assert len(results) == 5\n assert not any(node.id == \"root-container\" for node in results)", "test_prefix": "async def test_universal_selector_doesnt_select_self():\n class ExampleApp(App):\n def compose(self) -> ComposeResult:\n yield Container(\n Widget(\n Widget(),\n Widget(\n Widget(),\n ),\n ),\n Widget(),\n id=\"root-container\",\n )\n\n app = ExampleApp()\n async with app.run_test():\n container = app.query_one(\"#root-container\", Container)\n query = container.query(\"*\")\n results = list(query.results())\n assert len(results) == 5\n ", "test_prefix_file_path": "tests/test_query.py", "test_prefix_start_lineno": 241, "test_prefix_end_lineno": 261, "test_target": "tests/test_query.py::test_universal_selector_doesnt_select_self", "ground_truth_oracle": "assert not any(node.id == \"root-container\" for node in results)", "ground_truth_oracle_lineno": 261, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def results(self) -> Iterator[QueryType]: ...", "focal_method_file_path": "src/textual/css/query.py", "focal_method_start_lineno": 333, "focal_method_end_lineno": 334} {"index": 426, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_overflow_change_updates_virtual_size_appropriately", "test_class_name": "", "original_test_prefix": "async def test_overflow_change_updates_virtual_size_appropriately():\n class MyApp(App):\n def compose(self):\n yield VerticalScroll()\n\n app = MyApp()\n\n async with app.run_test() as pilot:\n vertical = app.query_one(VerticalScroll)\n\n height = vertical.virtual_size.height\n\n vertical.styles.overflow_x = \"scroll\"\n await pilot.pause() # Let changes propagate.\n assert vertical.virtual_size.height < height\n\n vertical.styles.overflow_x = \"hidden\"\n await pilot.pause()\n assert vertical.virtual_size.height == height\n\n width = vertical.virtual_size.width\n\n vertical.styles.overflow_y = \"scroll\"\n await pilot.pause()\n assert vertical.virtual_size.width < width\n\n vertical.styles.overflow_y = \"hidden\"\n await pilot.pause()\n assert vertical.virtual_size.width == width", "test_prefix": "async def test_overflow_change_updates_virtual_size_appropriately():\n class MyApp(App):\n def compose(self):\n yield VerticalScroll()\n\n app = MyApp()\n\n async with app.run_test() as pilot:\n vertical = app.query_one(VerticalScroll)\n\n height = vertical.virtual_size.height\n\n vertical.styles.overflow_x = \"scroll\"\n await pilot.pause() # Let changes propagate.\n assert vertical.virtual_size.height < height\n\n vertical.styles.overflow_x = \"hidden\"\n await pilot.pause()\n \n\n width = vertical.virtual_size.width\n\n vertical.styles.overflow_y = \"scroll\"\n await pilot.pause()\n assert vertical.virtual_size.width < width\n\n vertical.styles.overflow_y = \"hidden\"\n await pilot.pause()\n assert vertical.virtual_size.width == width", "test_prefix_file_path": "tests/test_overflow_change.py", "test_prefix_start_lineno": 7, "test_prefix_end_lineno": 35, "test_target": "tests/test_overflow_change.py::test_overflow_change_updates_virtual_size_appropriately", "ground_truth_oracle": "assert vertical.virtual_size.height == height", "ground_truth_oracle_lineno": 25, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 427, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_softbreak_split_links_rendered_correctly", "test_class_name": "", "original_test_prefix": "async def test_softbreak_split_links_rendered_correctly() -> None:\n \"\"\"Test for https://github.com/Textualize/textual/issues/2805\"\"\"\n\n document = \"\"\"\\\nMy site [has\nthis\nURL](https://example.com)\\\n\"\"\"\n async with MarkdownApp(document).run_test() as pilot:\n markdown = pilot.app.query_one(Markdown)\n paragraph = markdown.children[0]\n assert isinstance(paragraph, MD.MarkdownParagraph)\n assert paragraph._content.plain == \"My site has this URL\"\n print(paragraph._content.spans)\n\n expected_spans = [\n Span(8, 20, Style.from_meta({\"@click\": \"link('https://example.com')\"})),\n ]\n print(expected_spans)\n\n assert paragraph._content.spans == expected_spans", "test_prefix": "async def test_softbreak_split_links_rendered_correctly() -> None:\n \"\"\"Test for https://github.com/Textualize/textual/issues/2805\"\"\"\n\n document = \"\"\"\\\nMy site [has\nthis\nURL](https://example.com)\\\n\"\"\"\n async with MarkdownApp(document).run_test() as pilot:\n markdown = pilot.app.query_one(Markdown)\n paragraph = markdown.children[0]\n assert isinstance(paragraph, MD.MarkdownParagraph)\n \n print(paragraph._content.spans)\n\n expected_spans = [\n Span(8, 20, Style.from_meta({\"@click\": \"link('https://example.com')\"})),\n ]\n print(expected_spans)\n\n assert paragraph._content.spans == expected_spans", "test_prefix_file_path": "tests/test_markdown.py", "test_prefix_start_lineno": 99, "test_prefix_end_lineno": 119, "test_target": "tests/test_markdown.py::test_softbreak_split_links_rendered_correctly", "ground_truth_oracle": "assert paragraph._content.plain == \"My site has this URL\"", "ground_truth_oracle_lineno": 111, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 428, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_delete_word_left_to_start_of_line", "test_class_name": "", "original_test_prefix": "async def test_delete_word_left_to_start_of_line():\n \"\"\"If no word boundary found when we 'delete word left', then\n the deletion happens to the start of the line.\"\"\"\n app = TextAreaApp()\n async with app.run_test() as pilot:\n text_area = app.query_one(TextArea)\n text_area.load_text(\"0123\\n 456789\")\n text_area.selection = Selection.cursor((1, 3))\n\n await pilot.press(\"ctrl+w\")\n\n assert text_area.text == \"0123\\n456789\"\n assert text_area.selection == Selection.cursor((1, 0))", "test_prefix": "async def test_delete_word_left_to_start_of_line():\n \"\"\"If no word boundary found when we 'delete word left', then\n the deletion happens to the start of the line.\"\"\"\n app = TextAreaApp()\n async with app.run_test() as pilot:\n text_area = app.query_one(TextArea)\n text_area.load_text(\"0123\\n 456789\")\n text_area.selection = Selection.cursor((1, 3))\n\n await pilot.press(\"ctrl+w\")\n\n \n assert text_area.selection == Selection.cursor((1, 0))", "test_prefix_file_path": "tests/text_area/test_edit_via_bindings.py", "test_prefix_start_lineno": 394, "test_prefix_end_lineno": 406, "test_target": "tests/text_area/test_edit_via_bindings.py::test_delete_word_left_to_start_of_line", "ground_truth_oracle": "assert text_area.text == \"0123\\n456789\"", "ground_truth_oracle_lineno": 405, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def cursor(cls, location: Location) -> \"Selection\":\n \"\"\"Create a Selection with the same start and end point - a \"cursor\".\n\n Args:\n location: The location to create the zero-width Selection.\n \"\"\"\n return cls(location, location)", "focal_method_file_path": "src/textual/document/_document.py", "focal_method_start_lineno": 455, "focal_method_end_lineno": 462} {"index": 429, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_tree_node_toggle_all", "test_class_name": "", "original_test_prefix": "async def test_tree_node_toggle_all() -> None:\n \"\"\"Toggling all on a node should toggle all child nodes too.\"\"\"\n async with TreeApp().run_test() as pilot:\n assert pilot.app.query_one(Tree).root.is_expanded is False\n check_node = pilot.app.query_one(Tree).root.children[0]\n while check_node.children:\n assert any(child.is_expanded for child in check_node.children) is False\n check_node = check_node.children[0]\n pilot.app.query_one(Tree).root.toggle_all()\n assert pilot.app.query_one(Tree).root.is_expanded is True\n check_node = pilot.app.query_one(Tree).root.children[0]\n while check_node.children:\n assert check_node.children[0].is_expanded is True\n assert any(child.is_expanded for child in check_node.children[1:]) is False\n check_node = check_node.children[0]\n pilot.app.query_one(Tree).root.toggle_all()\n assert pilot.app.query_one(Tree).root.is_expanded is False\n check_node = pilot.app.query_one(Tree).root.children[0]\n while check_node.children:\n assert any(child.is_expanded for child in check_node.children) is False\n check_node = check_node.children[0]", "test_prefix": "async def test_tree_node_toggle_all() -> None:\n \"\"\"Toggling all on a node should toggle all child nodes too.\"\"\"\n async with TreeApp().run_test() as pilot:\n \n check_node = pilot.app.query_one(Tree).root.children[0]\n while check_node.children:\n assert any(child.is_expanded for child in check_node.children) is False\n check_node = check_node.children[0]\n pilot.app.query_one(Tree).root.toggle_all()\n assert pilot.app.query_one(Tree).root.is_expanded is True\n check_node = pilot.app.query_one(Tree).root.children[0]\n while check_node.children:\n assert check_node.children[0].is_expanded is True\n assert any(child.is_expanded for child in check_node.children[1:]) is False\n check_node = check_node.children[0]\n pilot.app.query_one(Tree).root.toggle_all()\n \n check_node = pilot.app.query_one(Tree).root.children[0]\n while check_node.children:\n assert any(child.is_expanded for child in check_node.children) is False\n check_node = check_node.children[0]", "test_prefix_file_path": "tests/tree/test_tree_expand_etc.py", "test_prefix_start_lineno": 86, "test_prefix_end_lineno": 106, "test_target": "tests/tree/test_tree_expand_etc.py::test_tree_node_toggle_all", "ground_truth_oracle": "assert pilot.app.query_one(Tree).root.is_expanded is False", "ground_truth_oracle_lineno": 89, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 430, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_clear", "test_class_name": "", "original_test_prefix": "def test_clear() -> None:\n \"\"\"It should be possible to clear all notifications.\"\"\"\n tester = Notifications()\n for _ in range(100):\n tester.add(Notification(\"test\", timeout=120))\n assert len(tester) == 100\n tester.clear()\n assert len(tester) == 0", "test_prefix": "def test_clear() -> None:\n \"\"\"It should be possible to clear all notifications.\"\"\"\n tester = Notifications()\n for _ in range(100):\n tester.add(Notification(\"test\", timeout=120))\n \n tester.clear()\n assert len(tester) == 0", "test_prefix_file_path": "tests/notifications/test_notifications.py", "test_prefix_start_lineno": 71, "test_prefix_end_lineno": 78, "test_target": "tests/notifications/test_notifications.py::test_clear", "ground_truth_oracle": "assert len(tester) == 100", "ground_truth_oracle_lineno": 76, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class Notifications:\n \"\"\"Class for managing a collection of notifications.\"\"\"\n\n def __init__(self) -> None:\n \"\"\"Initialise the notification collection.\"\"\"\n self._notifications: dict[str, Notification] = {}\n\n def _reap(self) -> Self:\n \"\"\"Remove any expired notifications from the notification collection.\"\"\"\n for notification in list(self._notifications.values()):\n if notification.has_expired:\n del self._notifications[notification.identity]\n return self\n\n def add(self, notification: Notification) -> Self:\n \"\"\"Add the given notification to the collection of managed notifications.\n\n Args:\n notification: The notification to add.\n\n Returns:\n Self.\n \"\"\"\n self._reap()._notifications[notification.identity] = notification\n return self\n\n def clear(self) -> Self:\n \"\"\"Clear all the notifications.\"\"\"\n self._notifications.clear()\n return self\n\n def __len__(self) -> int:\n \"\"\"The number of notifications.\"\"\"\n return len(self._reap()._notifications)\n\n def __iter__(self) -> Iterator[Notification]:\n return iter(self._reap()._notifications.values())\n\n def __contains__(self, notification: Notification) -> bool:\n return notification.identity in self._notifications\n\n def __delitem__(self, notification: Notification) -> None:\n try:\n del self._reap()._notifications[notification.identity]\n except KeyError:\n # An attempt to remove a notification we don't know about is a\n # no-op. What matters here is that the notification is forgotten\n # about, and it looks like a caller has tried to be\n # belt-and-braces. We're fine with this.\n pass", "focal_method_file_path": "src/textual/notifications.py", "focal_method_start_lineno": 71, "focal_method_end_lineno": 120} {"index": 431, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_disabled_tab_is_not_activated_by_clicking_underline", "test_class_name": "", "original_test_prefix": "async def test_disabled_tab_is_not_activated_by_clicking_underline():\n \"\"\"Regression test for https://github.com/Textualize/textual/issues/4701\"\"\"\n\n class DisabledTabApp(App):\n def compose(self) -> ComposeResult:\n yield Tabs(\n Tab(\"Enabled\", id=\"enabled\"),\n Tab(\"Disabled\", id=\"disabled\", disabled=True),\n )\n\n app = DisabledTabApp()\n async with app.run_test() as pilot:\n # Click the underline beneath the disabled tab\n await pilot.click(Tabs, offset=(14, 2))\n tabs = pilot.app.query_one(Tabs)\n assert tabs.active_tab is not None\n assert tabs.active_tab.id == \"enabled\"", "test_prefix": "async def test_disabled_tab_is_not_activated_by_clicking_underline():\n \"\"\"Regression test for https://github.com/Textualize/textual/issues/4701\"\"\"\n\n class DisabledTabApp(App):\n def compose(self) -> ComposeResult:\n yield Tabs(\n Tab(\"Enabled\", id=\"enabled\"),\n Tab(\"Disabled\", id=\"disabled\", disabled=True),\n )\n\n app = DisabledTabApp()\n async with app.run_test() as pilot:\n # Click the underline beneath the disabled tab\n await pilot.click(Tabs, offset=(14, 2))\n tabs = pilot.app.query_one(Tabs)\n \n assert tabs.active_tab.id == \"enabled\"", "test_prefix_file_path": "tests/test_tabs.py", "test_prefix_start_lineno": 496, "test_prefix_end_lineno": 512, "test_target": "tests/test_tabs.py::test_disabled_tab_is_not_activated_by_clicking_underline", "ground_truth_oracle": "assert tabs.active_tab is not None", "ground_truth_oracle_lineno": 511, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 432, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_focus_next_and_previous_with_type_selector", "test_class_name": "", "original_test_prefix": "async def test_focus_next_and_previous_with_type_selector():\n \"\"\"Move focus with a selector that matches the currently focused node.\"\"\"\n app = FocusTestApp()\n async with app.run_test():\n screen = app.screen\n\n screen.set_focus(screen.query_one(\"#Paul\"))\n assert screen.focused.id == \"Paul\"\n\n assert screen.focus_next(Focusable).id == \"baz\"\n assert screen.focus_next(Focusable).id == \"child\"\n\n assert screen.focus_previous(Focusable).id == \"baz\"\n assert screen.focus_previous(Focusable).id == \"Paul\"\n assert screen.focus_previous(Focusable).id == \"container1\"\n assert screen.focus_previous(Focusable).id == \"foo\"", "test_prefix": "async def test_focus_next_and_previous_with_type_selector():\n \"\"\"Move focus with a selector that matches the currently focused node.\"\"\"\n app = FocusTestApp()\n async with app.run_test():\n screen = app.screen\n\n screen.set_focus(screen.query_one(\"#Paul\"))\n assert screen.focused.id == \"Paul\"\n\n assert screen.focus_next(Focusable).id == \"baz\"\n assert screen.focus_next(Focusable).id == \"child\"\n\n assert screen.focus_previous(Focusable).id == \"baz\"\n assert screen.focus_previous(Focusable).id == \"Paul\"\n \n assert screen.focus_previous(Focusable).id == \"foo\"", "test_prefix_file_path": "tests/test_focus.py", "test_prefix_start_lineno": 168, "test_prefix_end_lineno": 183, "test_target": "tests/test_focus.py::test_focus_next_and_previous_with_type_selector", "ground_truth_oracle": "assert screen.focus_previous(Focusable).id == \"container1\"", "ground_truth_oracle_lineno": 182, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def focus_previous(self, selector: str | type[QueryType] = \"*\") -> Widget | None:\n \"\"\"Focus the previous widget, optionally filtered by a CSS selector.\n\n If no widget is currently focused, this will focus the first focusable widget.\n If no focusable widget matches the given CSS selector, focus is set to `None`.\n\n Args:\n selector: CSS selector to filter\n what nodes can be focused.\n\n Returns:\n Newly focused widget, or None for no focus. If the return\n is not `None`, then it is guaranteed that the widget returned matches\n the CSS selectors given in the argument.\n \"\"\"\n return self._move_focus(-1, selector)", "focal_method_file_path": "src/textual/screen.py", "focal_method_start_lineno": 863, "focal_method_end_lineno": 878} {"index": 433, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_set_current_to_unknown_id", "test_class_name": "", "original_test_prefix": "async def test_set_current_to_unknown_id() -> None:\n \"\"\"Test attempting to switch to an unknown widget ID.\"\"\"\n async with SwitcherApp().run_test() as pilot:\n assert pilot.app.query_one(ContentSwitcher).current is None\n assert all(\n not child.display for child in pilot.app.query_one(ContentSwitcher).children\n )\n with pytest.raises(NoMatches):\n pilot.app.query_one(ContentSwitcher).current = \"does-not-exist\"", "test_prefix": "async def test_set_current_to_unknown_id() -> None:\n \"\"\"Test attempting to switch to an unknown widget ID.\"\"\"\n async with SwitcherApp().run_test() as pilot:\n \n assert all(\n not child.display for child in pilot.app.query_one(ContentSwitcher).children\n )\n with pytest.raises(NoMatches):\n pilot.app.query_one(ContentSwitcher).current = \"does-not-exist\"", "test_prefix_file_path": "tests/test_content_switcher.py", "test_prefix_start_lineno": 101, "test_prefix_end_lineno": 109, "test_target": "tests/test_content_switcher.py::test_set_current_to_unknown_id", "ground_truth_oracle": "assert pilot.app.query_one(ContentSwitcher).current is None", "ground_truth_oracle_lineno": 104, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 434, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_get_tree_node_by_id", "test_class_name": "", "original_test_prefix": "def test_get_tree_node_by_id() -> None:\n \"\"\"It should be possible to get a TreeNode by its ID.\"\"\"\n tree = Tree[None](\"Anakin\")\n child = tree.root.add(\"Leia\")\n grandchild = child.add(\"Ben\")\n assert tree.get_node_by_id(tree.root.id).id == tree.root.id\n assert tree.get_node_by_id(child.id).id == child.id\n assert tree.get_node_by_id(grandchild.id).id == grandchild.id\n with pytest.raises(UnknownNodeID):\n tree.get_node_by_id(cast(NodeID, grandchild.id + 1000))", "test_prefix": "def test_get_tree_node_by_id() -> None:\n \"\"\"It should be possible to get a TreeNode by its ID.\"\"\"\n tree = Tree[None](\"Anakin\")\n child = tree.root.add(\"Leia\")\n grandchild = child.add(\"Ben\")\n \n assert tree.get_node_by_id(child.id).id == child.id\n assert tree.get_node_by_id(grandchild.id).id == grandchild.id\n with pytest.raises(UnknownNodeID):\n tree.get_node_by_id(cast(NodeID, grandchild.id + 1000))", "test_prefix_file_path": "tests/tree/test_tree_get_node_by_id.py", "test_prefix_start_lineno": 9, "test_prefix_end_lineno": 18, "test_target": "tests/tree/test_tree_get_node_by_id.py::test_get_tree_node_by_id", "ground_truth_oracle": "assert tree.get_node_by_id(tree.root.id).id == tree.root.id", "ground_truth_oracle_lineno": 14, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_node_by_id(self, node_id: NodeID) -> TreeNode[TreeDataType]:\n \"\"\"Get a tree node by its ID.\n\n Args:\n node_id: The ID of the node to get.\n\n Returns:\n The node associated with that ID.\n\n Raises:\n UnknownNodeID: Raised if the `TreeNode` ID is unknown.\n \"\"\"\n try:\n return self._tree_nodes[node_id]\n except KeyError:\n raise UnknownNodeID(f\"Unknown NodeID ({node_id}) in tree\") from None", "focal_method_file_path": "src/textual/widgets/_tree.py", "focal_method_start_lineno": 1032, "focal_method_end_lineno": 1047} {"index": 435, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_click_by_widget", "test_class_name": "", "original_test_prefix": "async def test_click_by_widget():\n \"\"\"Test that click accept a Widget instance.\"\"\"\n pressed = False\n\n class TestApp(CenteredButtonApp):\n def on_button_pressed(self):\n nonlocal pressed\n pressed = True\n\n app = TestApp()\n async with app.run_test() as pilot:\n button = app.query_one(Button)\n assert not pressed\n await pilot.click(button)\n assert pressed", "test_prefix": "async def test_click_by_widget():\n \"\"\"Test that click accept a Widget instance.\"\"\"\n pressed = False\n\n class TestApp(CenteredButtonApp):\n def on_button_pressed(self):\n nonlocal pressed\n pressed = True\n\n app = TestApp()\n async with app.run_test() as pilot:\n button = app.query_one(Button)\n assert not pressed\n await pilot.click(button)\n ", "test_prefix_file_path": "tests/test_pilot.py", "test_prefix_start_lineno": 414, "test_prefix_end_lineno": 428, "test_target": "tests/test_pilot.py::test_click_by_widget", "ground_truth_oracle": "assert pressed", "ground_truth_oracle_lineno": 428, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 436, "repo_name": "textual", "github": "https://github.com/Textualize/textual.git", "version": "v6.2.1", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nhash -r\npoetry env use python\npoetry install --with dev\npip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_tree_simple_clear", "test_class_name": "", "original_test_prefix": "async def test_tree_simple_clear() -> None:\n \"\"\"Clearing a tree should keep the old root label and data.\"\"\"\n async with TreeClearApp().run_test() as pilot:\n tree = pilot.app.query_one(VerseTree)\n assert len(tree.root.children) > 1\n pilot.app.query_one(VerseTree).clear()\n assert len(tree.root.children) == 0\n assert str(tree.root.label) == \"White Sun\"\n assert isinstance(tree.root.data, VerseStar)", "test_prefix": "async def test_tree_simple_clear() -> None:\n \"\"\"Clearing a tree should keep the old root label and data.\"\"\"\n async with TreeClearApp().run_test() as pilot:\n tree = pilot.app.query_one(VerseTree)\n \n pilot.app.query_one(VerseTree).clear()\n assert len(tree.root.children) == 0\n assert str(tree.root.label) == \"White Sun\"\n assert isinstance(tree.root.data, VerseStar)", "test_prefix_file_path": "tests/tree/test_tree_clearing.py", "test_prefix_start_lineno": 46, "test_prefix_end_lineno": 54, "test_target": "tests/tree/test_tree_clearing.py::test_tree_simple_clear", "ground_truth_oracle": "assert len(tree.root.children) > 1", "ground_truth_oracle_lineno": 50, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @overload\n def query_one(self, selector: str) -> Widget: ...", "focal_method_file_path": "src/textual/dom.py", "focal_method_start_lineno": 1430, "focal_method_end_lineno": 1431} {"index": 437, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_items", "test_class_name": "TestHTTPHeaderDict", "original_test_prefix": " def test_items(self, d: HTTPHeaderDict) -> None:\n items = d.items()\n assert len(items) == 2\n assert list(items) == [\n (\"Cookie\", \"foo\"),\n (\"Cookie\", \"bar\"),\n ]\n assert (\"Cookie\", \"foo\") in items\n assert (\"Cookie\", \"bar\") in items\n assert (\"X-Some-Header\", \"foo\") not in items\n assert (\"Cookie\", \"not_present\") not in items\n assert (\"Cookie\", 1) not in items # type: ignore[comparison-overlap]\n assert \"Cookie\" not in items # type: ignore[comparison-overlap]", "test_prefix": " def test_items(self, d: HTTPHeaderDict) -> None:\n items = d.items()\n assert len(items) == 2\n assert list(items) == [\n (\"Cookie\", \"foo\"),\n (\"Cookie\", \"bar\"),\n ]\n assert (\"Cookie\", \"foo\") in items\n assert (\"Cookie\", \"bar\") in items\n assert (\"X-Some-Header\", \"foo\") not in items\n assert (\"Cookie\", \"not_present\") not in items\n \n assert \"Cookie\" not in items # type: ignore[comparison-overlap]", "test_prefix_file_path": "test/test_collections.py", "test_prefix_start_lineno": 369, "test_prefix_end_lineno": 381, "test_target": "test/test_collections.py::TestHTTPHeaderDict::test_items", "ground_truth_oracle": "assert (\"Cookie\", 1) not in items # type: ignore[comparison-overlap]", "ground_truth_oracle_lineno": 380, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def items(self) -> HTTPHeaderDictItemView: # type: ignore[override]\n return HTTPHeaderDictItemView(self)", "focal_method_file_path": "src/urllib3/_collections.py", "focal_method_start_lineno": 444, "focal_method_end_lineno": 445} {"index": 438, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_retry_total_none", "test_class_name": "TestRetry", "original_test_prefix": " def test_retry_total_none(self) -> None:\n \"\"\"if Total is none, connect error should take precedence\"\"\"\n error = ConnectTimeoutError()\n retry = Retry(connect=2, total=None)\n retry = retry.increment(error=error)\n retry = retry.increment(error=error)\n with pytest.raises(MaxRetryError) as e:\n retry.increment(error=error)\n assert e.value.reason == error\n\n timeout_error = ReadTimeoutError(DUMMY_POOL, \"/\", \"read timed out\")\n retry = Retry(connect=2, total=None)\n retry = retry.increment(method=\"GET\", error=timeout_error)\n retry = retry.increment(method=\"GET\", error=timeout_error)\n retry = retry.increment(method=\"GET\", error=timeout_error)\n assert not retry.is_exhausted()", "test_prefix": " def test_retry_total_none(self) -> None:\n \"\"\"if Total is none, connect error should take precedence\"\"\"\n error = ConnectTimeoutError()\n retry = Retry(connect=2, total=None)\n retry = retry.increment(error=error)\n retry = retry.increment(error=error)\n with pytest.raises(MaxRetryError) as e:\n retry.increment(error=error)\n assert e.value.reason == error\n\n timeout_error = ReadTimeoutError(DUMMY_POOL, \"/\", \"read timed out\")\n retry = Retry(connect=2, total=None)\n retry = retry.increment(method=\"GET\", error=timeout_error)\n retry = retry.increment(method=\"GET\", error=timeout_error)\n retry = retry.increment(method=\"GET\", error=timeout_error)\n ", "test_prefix_file_path": "test/test_retry.py", "test_prefix_start_lineno": 64, "test_prefix_end_lineno": 79, "test_target": "test/test_retry.py::TestRetry::test_retry_total_none", "ground_truth_oracle": "assert not retry.is_exhausted()", "ground_truth_oracle_lineno": 79, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def is_exhausted(self) -> bool:\n \"\"\"Are we out of retries?\"\"\"\n retry_counts = [\n x\n for x in (\n self.total,\n self.connect,\n self.read,\n self.redirect,\n self.status,\n self.other,\n )\n if x\n ]\n if not retry_counts:\n return False\n\n return min(retry_counts) < 0", "focal_method_file_path": "src/urllib3/util/retry.py", "focal_method_start_lineno": 409, "focal_method_end_lineno": 426} {"index": 439, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_getlist", "test_class_name": "TestHTTPHeaderDict", "original_test_prefix": " def test_getlist(self, d: HTTPHeaderDict) -> None:\n assert d.getlist(\"cookie\") == [\"foo\", \"bar\"]\n assert d.getlist(\"Cookie\") == [\"foo\", \"bar\"]\n assert d.getlist(\"b\") == []\n d.add(\"b\", \"asdf\")\n assert d.getlist(\"b\") == [\"asdf\"]", "test_prefix": " def test_getlist(self, d: HTTPHeaderDict) -> None:\n assert d.getlist(\"cookie\") == [\"foo\", \"bar\"]\n assert d.getlist(\"Cookie\") == [\"foo\", \"bar\"]\n \n d.add(\"b\", \"asdf\")\n assert d.getlist(\"b\") == [\"asdf\"]", "test_prefix_file_path": "test/test_collections.py", "test_prefix_start_lineno": 314, "test_prefix_end_lineno": 319, "test_target": "test/test_collections.py::TestHTTPHeaderDict::test_getlist", "ground_truth_oracle": "assert d.getlist(\"b\") == []", "ground_truth_oracle_lineno": 317, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @typing.overload\n def getlist(self, key: str) -> list[str]: ...", "focal_method_file_path": "src/urllib3/_collections.py", "focal_method_start_lineno": 368, "focal_method_end_lineno": 369} {"index": 440, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_render_parts", "test_class_name": "TestRequestField", "original_test_prefix": " def test_render_parts(self) -> None:\n field = RequestField(\"somename\", \"data\")\n parts = field._render_parts({\"name\": \"value\", \"filename\": \"value\"})\n assert 'name=\"value\"' in parts\n assert 'filename=\"value\"' in parts\n parts = field._render_parts([(\"name\", \"value\"), (\"filename\", \"value\")])\n assert parts == 'name=\"value\"; filename=\"value\"'", "test_prefix": " def test_render_parts(self) -> None:\n field = RequestField(\"somename\", \"data\")\n parts = field._render_parts({\"name\": \"value\", \"filename\": \"value\"})\n assert 'name=\"value\"' in parts\n assert 'filename=\"value\"' in parts\n parts = field._render_parts([(\"name\", \"value\"), (\"filename\", \"value\")])\n ", "test_prefix_file_path": "test/test_fields.py", "test_prefix_start_lineno": 60, "test_prefix_end_lineno": 66, "test_target": "test/test_fields.py::TestRequestField::test_render_parts", "ground_truth_oracle": "assert parts == 'name=\"value\"; filename=\"value\"'", "ground_truth_oracle_lineno": 66, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def _render_parts(\n self,\n header_parts: (\n dict[str, _TYPE_FIELD_VALUE | None]\n | typing.Sequence[tuple[str, _TYPE_FIELD_VALUE | None]]\n ),\n ) -> str:\n \"\"\"\n Helper function to format and quote a single header.\n\n Useful for single headers that are composed of multiple items. E.g.,\n 'Content-Disposition' fields.\n\n :param header_parts:\n A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format\n as `k1=\"v1\"; k2=\"v2\"; ...`.\n \"\"\"\n iterable: typing.Iterable[tuple[str, _TYPE_FIELD_VALUE | None]]\n\n parts = []\n if isinstance(header_parts, dict):\n iterable = header_parts.items()\n else:\n iterable = header_parts\n\n for name, value in iterable:\n if value is not None:\n parts.append(self._render_part(name, value))\n\n return \"; \".join(parts)", "focal_method_file_path": "src/urllib3/fields.py", "focal_method_start_lineno": 260, "focal_method_end_lineno": 289} {"index": 441, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_override_pool_kwargs_url", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_override_pool_kwargs_url(self) -> None:\n \"\"\"Assert overriding pool kwargs works with connection_from_url.\"\"\"\n p = PoolManager()\n pool_kwargs = {\"retries\": 100, \"block\": True}\n\n default_pool = p.connection_from_url(\"http://example.com/\")\n override_pool = p.connection_from_url(\n \"http://example.com/\", pool_kwargs=pool_kwargs\n )\n\n assert retry.Retry.DEFAULT == default_pool.retries\n assert not default_pool.block\n\n assert 100 == override_pool.retries\n assert override_pool.block", "test_prefix": " def test_override_pool_kwargs_url(self) -> None:\n \"\"\"Assert overriding pool kwargs works with connection_from_url.\"\"\"\n p = PoolManager()\n pool_kwargs = {\"retries\": 100, \"block\": True}\n\n default_pool = p.connection_from_url(\"http://example.com/\")\n override_pool = p.connection_from_url(\n \"http://example.com/\", pool_kwargs=pool_kwargs\n )\n\n \n assert not default_pool.block\n\n assert 100 == override_pool.retries\n assert override_pool.block", "test_prefix_file_path": "test/test_poolmanager.py", "test_prefix_start_lineno": 331, "test_prefix_end_lineno": 345, "test_target": "test/test_poolmanager.py::TestPoolManager::test_override_pool_kwargs_url", "ground_truth_oracle": "assert retry.Retry.DEFAULT == default_pool.retries", "ground_truth_oracle_lineno": 341, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def connection_from_url(\n self, url: str, pool_kwargs: dict[str, typing.Any] | None = None\n ) -> HTTPConnectionPool:\n \"\"\"\n Similar to :func:`urllib3.connectionpool.connection_from_url`.\n\n If ``pool_kwargs`` is not provided and a new pool needs to be\n constructed, ``self.connection_pool_kw`` is used to initialize\n the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``\n is provided, it is used instead. Note that if a new pool does not\n need to be created for the request, the provided ``pool_kwargs`` are\n not used.\n \"\"\"\n u = parse_url(url)\n return self.connection_from_host(\n u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs\n )", "focal_method_file_path": "src/urllib3/poolmanager.py", "focal_method_start_lineno": 372, "focal_method_end_lineno": 388} {"index": 442, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_pool_manager_no_url_absolute_form", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_pool_manager_no_url_absolute_form(self) -> None:\n \"\"\"Valides we won't send a request with absolute form without a proxy\"\"\"\n p = PoolManager()\n assert p._proxy_requires_url_absolute_form(Url(\"http://example.com\")) is False\n assert p._proxy_requires_url_absolute_form(Url(\"https://example.com\")) is False", "test_prefix": " def test_pool_manager_no_url_absolute_form(self) -> None:\n \"\"\"Valides we won't send a request with absolute form without a proxy\"\"\"\n p = PoolManager()\n \n assert p._proxy_requires_url_absolute_form(Url(\"https://example.com\")) is False", "test_prefix_file_path": "test/test_poolmanager.py", "test_prefix_start_lineno": 407, "test_prefix_end_lineno": 411, "test_target": "test/test_poolmanager.py::TestPoolManager::test_pool_manager_no_url_absolute_form", "ground_truth_oracle": "assert p._proxy_requires_url_absolute_form(Url(\"http://example.com\")) is False", "ground_truth_oracle_lineno": 410, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def _proxy_requires_url_absolute_form(self, parsed_url: Url) -> bool:\n \"\"\"\n Indicates if the proxy requires the complete destination URL in the\n request. Normally this is only needed when not using an HTTP CONNECT\n tunnel.\n \"\"\"\n if self.proxy is None:\n return False\n\n return not connection_requires_http_tunnel(\n self.proxy, self.proxy_config, parsed_url.scheme\n )", "focal_method_file_path": "src/urllib3/poolmanager.py", "focal_method_start_lineno": 412, "focal_method_end_lineno": 423} {"index": 443, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_stream_keepalive", "test_class_name": "TestConnectionPool", "original_test_prefix": " def test_stream_keepalive(self) -> None:\n x = 2\n\n with HTTPConnectionPool(self.host, self.port) as pool:\n for _ in range(x):\n response = pool.request(\n \"GET\",\n \"/chunked\",\n headers={\"Connection\": \"keep-alive\"},\n preload_content=False,\n retries=False,\n )\n for chunk in response.stream():\n assert chunk == b\"123\"\n\n assert pool.num_connections == 1\n assert pool.num_requests == x", "test_prefix": " def test_stream_keepalive(self) -> None:\n x = 2\n\n with HTTPConnectionPool(self.host, self.port) as pool:\n for _ in range(x):\n response = pool.request(\n \"GET\",\n \"/chunked\",\n headers={\"Connection\": \"keep-alive\"},\n preload_content=False,\n retries=False,\n )\n for chunk in response.stream():\n assert chunk == b\"123\"\n\n assert pool.num_connections == 1\n ", "test_prefix_file_path": "test/with_dummyserver/test_connectionpool.py", "test_prefix_start_lineno": 839, "test_prefix_end_lineno": 855, "test_target": "test/with_dummyserver/test_connectionpool.py::TestConnectionPool::test_stream_keepalive", "ground_truth_oracle": "assert pool.num_requests == x", "ground_truth_oracle_lineno": 855, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def stream(\n self, amt: int | None = 2**16, decode_content: bool | None = None\n ) -> typing.Iterator[bytes]:\n raise NotImplementedError()", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 436, "focal_method_end_lineno": 439} {"index": 444, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_dnsname_to_stdlib_simple", "test_class_name": "TestPyOpenSSLHelpers", "original_test_prefix": " def test_dnsname_to_stdlib_simple(self) -> None:\n \"\"\"\n We can convert a dnsname to a native string when the domain is simple.\n \"\"\"\n name = \"\u0909\u0926\u093e\u0939\u0930\u0923.\u092a\u0930\u0940\u0915\"\n expected_result = \"xn--p1b6ci4b4b3a.xn--11b5bs8d\"\n\n assert _dnsname_to_stdlib(name) == expected_result", "test_prefix": " def test_dnsname_to_stdlib_simple(self) -> None:\n \"\"\"\n We can convert a dnsname to a native string when the domain is simple.\n \"\"\"\n name = \"\u0909\u0926\u093e\u0939\u0930\u0923.\u092a\u0930\u0940\u0915\"\n expected_result = \"xn--p1b6ci4b4b3a.xn--11b5bs8d\"\n\n ", "test_prefix_file_path": "test/contrib/test_pyopenssl.py", "test_prefix_start_lineno": 63, "test_prefix_end_lineno": 70, "test_target": "test/contrib/test_pyopenssl.py::TestPyOpenSSLHelpers::test_dnsname_to_stdlib_simple", "ground_truth_oracle": "assert _dnsname_to_stdlib(name) == expected_result", "ground_truth_oracle_lineno": 70, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _dnsname_to_stdlib(name: str) -> str | None:\n \"\"\"\n Converts a dNSName SubjectAlternativeName field to the form used by the\n standard library on the given Python version.\n\n Cryptography produces a dNSName as a unicode string that was idna-decoded\n from ASCII bytes. We need to idna-encode that string to get it back, and\n then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib\n uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).\n\n If the name cannot be idna-encoded then we return None signalling that\n the name given should be skipped.\n \"\"\"\n\n def idna_encode(name: str) -> bytes | None:\n \"\"\"\n Borrowed wholesale from the Python Cryptography Project. It turns out\n that we can't just safely call `idna.encode`: it can explode for\n wildcard names. This avoids that problem.\n \"\"\"\n import idna\n\n try:\n for prefix in [\"*.\", \".\"]:\n if name.startswith(prefix):\n name = name[len(prefix) :]\n return prefix.encode(\"ascii\") + idna.encode(name)\n return idna.encode(name)\n except idna.core.IDNAError:\n return None\n\n # Don't send IPv6 addresses through the IDNA encoder.\n if \":\" in name:\n return name\n\n encoded_name = idna_encode(name)\n if encoded_name is None:\n return None\n return encoded_name.decode(\"utf-8\")", "focal_method_file_path": "src/urllib3/contrib/pyopenssl.py", "focal_method_start_lineno": 185, "focal_method_end_lineno": 223} {"index": 445, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_merge_pool_kwargs_invalid_key", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_merge_pool_kwargs_invalid_key(self) -> None:\n \"\"\"Assert removing invalid keys with _merge_pool_kwargs doesn't break\"\"\"\n p = PoolManager(retries=100)\n merged = p._merge_pool_kwargs({\"invalid_key\": None})\n assert p.connection_pool_kw == merged", "test_prefix": " def test_merge_pool_kwargs_invalid_key(self) -> None:\n \"\"\"Assert removing invalid keys with _merge_pool_kwargs doesn't break\"\"\"\n p = PoolManager(retries=100)\n merged = p._merge_pool_kwargs({\"invalid_key\": None})\n ", "test_prefix_file_path": "test/test_poolmanager.py", "test_prefix_start_lineno": 401, "test_prefix_end_lineno": 405, "test_target": "test/test_poolmanager.py::TestPoolManager::test_merge_pool_kwargs_invalid_key", "ground_truth_oracle": "assert p.connection_pool_kw == merged", "ground_truth_oracle_lineno": 405, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def _merge_pool_kwargs(\n self, override: dict[str, typing.Any] | None\n ) -> dict[str, typing.Any]:\n \"\"\"\n Merge a dictionary of override values for self.connection_pool_kw.\n\n This does not modify self.connection_pool_kw and returns a new dict.\n Any keys in the override dictionary with a value of ``None`` are\n removed from the merged dictionary.\n \"\"\"\n base_pool_kwargs = self.connection_pool_kw.copy()\n if override:\n for key, value in override.items():\n if value is None:\n try:\n del base_pool_kwargs[key]\n except KeyError:\n pass\n else:\n base_pool_kwargs[key] = value\n return base_pool_kwargs", "focal_method_file_path": "src/urllib3/poolmanager.py", "focal_method_start_lineno": 390, "focal_method_end_lineno": 410} {"index": 446, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ca_certs_default_cert_required", "test_class_name": "TestConnectionPool", "original_test_prefix": " def test_ca_certs_default_cert_required(self) -> None:\n with connection_from_url(\"https://google.com:80\", ca_certs=DEFAULT_CA) as pool:\n conn = pool._get_conn()\n assert conn.cert_reqs == ssl.CERT_REQUIRED # type: ignore[attr-defined]", "test_prefix": " def test_ca_certs_default_cert_required(self) -> None:\n with connection_from_url(\"https://google.com:80\", ca_certs=DEFAULT_CA) as pool:\n conn = pool._get_conn()\n ", "test_prefix_file_path": "test/test_connectionpool.py", "test_prefix_start_lineno": 461, "test_prefix_end_lineno": 464, "test_target": "test/test_connectionpool.py::TestConnectionPool::test_ca_certs_default_cert_required", "ground_truth_oracle": "assert conn.cert_reqs == ssl.CERT_REQUIRED # type: ignore[attr-defined]", "ground_truth_oracle_lineno": 464, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection:\n \"\"\"\n Get a connection. Will return a pooled connection if one is available.\n\n If no connections are available and :prop:`.block` is ``False``, then a\n fresh connection is returned.\n\n :param timeout:\n Seconds to wait before giving up and raising\n :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and\n :prop:`.block` is ``True``.\n \"\"\"\n conn = None\n\n if self.pool is None:\n raise ClosedPoolError(self, \"Pool is closed.\")\n\n try:\n conn = self.pool.get(block=self.block, timeout=timeout)\n\n except AttributeError: # self.pool is None\n raise ClosedPoolError(self, \"Pool is closed.\") from None # Defensive:\n\n except queue.Empty:\n if self.block:\n raise EmptyPoolError(\n self,\n \"Pool is empty and a new connection can't be opened due to blocking mode.\",\n ) from None\n pass # Oh well, we'll create a new connection then\n\n # If this is a persistent connection, check if it got disconnected\n if conn and is_connection_dropped(conn):\n log.debug(\"Resetting dropped connection: %s\", self.host)\n conn.close()\n\n return conn or self._new_conn()", "focal_method_file_path": "src/urllib3/connectionpool.py", "focal_method_start_lineno": 256, "focal_method_end_lineno": 292} {"index": 447, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_textplain", "test_class_name": "TestMultipartEncoding", "original_test_prefix": " def test_textplain(self) -> None:\n fields = [(\"k\", (\"somefile.txt\", b\"v\"))]\n\n encoded, content_type = encode_multipart_formdata(fields, boundary=BOUNDARY)\n expected = (\n b\"--\" + BOUNDARY_BYTES + b\"\\r\\n\"\n b'Content-Disposition: form-data; name=\"k\"; filename=\"somefile.txt\"\\r\\n'\n b\"Content-Type: text/plain\\r\\n\"\n b\"\\r\\n\"\n b\"v\\r\\n\"\n b\"--\" + BOUNDARY_BYTES + b\"--\\r\\n\"\n )\n\n assert encoded == expected\n\n assert content_type == \"multipart/form-data; boundary=\" + str(BOUNDARY)", "test_prefix": " def test_textplain(self) -> None:\n fields = [(\"k\", (\"somefile.txt\", b\"v\"))]\n\n encoded, content_type = encode_multipart_formdata(fields, boundary=BOUNDARY)\n expected = (\n b\"--\" + BOUNDARY_BYTES + b\"\\r\\n\"\n b'Content-Disposition: form-data; name=\"k\"; filename=\"somefile.txt\"\\r\\n'\n b\"Content-Type: text/plain\\r\\n\"\n b\"\\r\\n\"\n b\"v\\r\\n\"\n b\"--\" + BOUNDARY_BYTES + b\"--\\r\\n\"\n )\n\n assert encoded == expected\n\n ", "test_prefix_file_path": "test/test_filepost.py", "test_prefix_start_lineno": 63, "test_prefix_end_lineno": 78, "test_target": "test/test_filepost.py::TestMultipartEncoding::test_textplain", "ground_truth_oracle": "assert content_type == \"multipart/form-data; boundary=\" + str(BOUNDARY)", "ground_truth_oracle_lineno": 78, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def encode_multipart_formdata(\n fields: _TYPE_FIELDS, boundary: str | None = None\n) -> tuple[bytes, str]:\n \"\"\"\n Encode a dictionary of ``fields`` using the multipart/form-data MIME format.\n\n :param fields:\n Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).\n Values are processed by :func:`urllib3.fields.RequestField.from_tuples`.\n\n :param boundary:\n If not specified, then a random boundary will be generated using\n :func:`urllib3.filepost.choose_boundary`.\n \"\"\"\n body = BytesIO()\n if boundary is None:\n boundary = choose_boundary()\n\n for field in iter_field_objects(fields):\n body.write(f\"--{boundary}\\r\\n\".encode(\"latin-1\"))\n\n writer(body).write(field.render_headers())\n data = field.data\n\n if isinstance(data, int):\n data = str(data) # Backwards compatibility\n\n if isinstance(data, str):\n writer(body).write(data)\n else:\n body.write(data)\n\n body.write(b\"\\r\\n\")\n\n body.write(f\"--{boundary}--\\r\\n\".encode(\"latin-1\"))\n\n content_type = f\"multipart/form-data; boundary={boundary}\"\n\n return body.getvalue(), content_type", "focal_method_file_path": "src/urllib3/filepost.py", "focal_method_start_lineno": 51, "focal_method_end_lineno": 89} {"index": 448, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_https_connection_from_url_case_insensitive", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_https_connection_from_url_case_insensitive(self) -> None:\n \"\"\"Assert scheme case is ignored when pooling HTTPS connections.\"\"\"\n p = PoolManager()\n pool = p.connection_from_url(\"https://example.com/\")\n other_pool = p.connection_from_url(\"HTTPS://EXAMPLE.COM/\")\n\n assert 1 == len(p.pools)\n assert pool is other_pool\n assert all(isinstance(key, PoolKey) for key in p.pools.keys())", "test_prefix": " def test_https_connection_from_url_case_insensitive(self) -> None:\n \"\"\"Assert scheme case is ignored when pooling HTTPS connections.\"\"\"\n p = PoolManager()\n pool = p.connection_from_url(\"https://example.com/\")\n other_pool = p.connection_from_url(\"HTTPS://EXAMPLE.COM/\")\n\n assert 1 == len(p.pools)\n assert pool is other_pool\n ", "test_prefix_file_path": "test/test_poolmanager.py", "test_prefix_start_lineno": 188, "test_prefix_end_lineno": 196, "test_target": "test/test_poolmanager.py::TestPoolManager::test_https_connection_from_url_case_insensitive", "ground_truth_oracle": "assert all(isinstance(key, PoolKey) for key in p.pools.keys())", "ground_truth_oracle_lineno": 196, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def keys(self) -> set[_KT]: # type: ignore[override]\n with self.lock:\n return set(self._container.keys())", "focal_method_file_path": "src/urllib3/_collections.py", "focal_method_start_lineno": 151, "focal_method_end_lineno": 153} {"index": 449, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_geturl_retries", "test_class_name": "TestResponse", "original_test_prefix": " def test_geturl_retries(self) -> None:\n fp = BytesIO(b\"\")\n resp = HTTPResponse(fp, request_url=\"http://example.com\")\n request_histories = (\n RequestHistory(\n method=\"GET\",\n url=\"http://example.com\",\n error=None,\n status=301,\n redirect_location=\"https://example.com/\",\n ),\n RequestHistory(\n method=\"GET\",\n url=\"https://example.com/\",\n error=None,\n status=301,\n redirect_location=\"https://www.example.com\",\n ),\n )\n retry = Retry(history=request_histories)\n resp = HTTPResponse(fp, retries=retry)\n assert resp.geturl() == \"https://www.example.com\"", "test_prefix": " def test_geturl_retries(self) -> None:\n fp = BytesIO(b\"\")\n resp = HTTPResponse(fp, request_url=\"http://example.com\")\n request_histories = (\n RequestHistory(\n method=\"GET\",\n url=\"http://example.com\",\n error=None,\n status=301,\n redirect_location=\"https://example.com/\",\n ),\n RequestHistory(\n method=\"GET\",\n url=\"https://example.com/\",\n error=None,\n status=301,\n redirect_location=\"https://www.example.com\",\n ),\n )\n retry = Retry(history=request_histories)\n resp = HTTPResponse(fp, retries=retry)\n ", "test_prefix_file_path": "test/test_response.py", "test_prefix_start_lineno": 1456, "test_prefix_end_lineno": 1477, "test_target": "test/test_response.py::TestResponse::test_geturl_retries", "ground_truth_oracle": "assert resp.geturl() == \"https://www.example.com\"", "ground_truth_oracle_lineno": 1477, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def geturl(self) -> str | None:\n return self.url", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 565, "focal_method_end_lineno": 566} {"index": 450, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_add_comma_separated_multiheader", "test_class_name": "TestHTTPHeaderDict", "original_test_prefix": " def test_add_comma_separated_multiheader(self, d: HTTPHeaderDict) -> None:\n d.add(\"bar\", \"foo\")\n # The bytes value gets converted to str. The API is typed for str only,\n # but the implementation continues supports bytes.\n d.add(b\"BAR\", \"bar\") # type: ignore[arg-type]\n d.add(\"Bar\", \"asdf\")\n assert d.getlist(\"bar\") == [\"foo\", \"bar\", \"asdf\"]\n assert d[\"bar\"] == \"foo, bar, asdf\"", "test_prefix": " def test_add_comma_separated_multiheader(self, d: HTTPHeaderDict) -> None:\n d.add(\"bar\", \"foo\")\n # The bytes value gets converted to str. The API is typed for str only,\n # but the implementation continues supports bytes.\n d.add(b\"BAR\", \"bar\") # type: ignore[arg-type]\n d.add(\"Bar\", \"asdf\")\n \n assert d[\"bar\"] == \"foo, bar, asdf\"", "test_prefix_file_path": "test/test_collections.py", "test_prefix_start_lineno": 238, "test_prefix_end_lineno": 245, "test_target": "test/test_collections.py::TestHTTPHeaderDict::test_add_comma_separated_multiheader", "ground_truth_oracle": "assert d.getlist(\"bar\") == [\"foo\", \"bar\", \"asdf\"]", "ground_truth_oracle_lineno": 244, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @typing.overload\n def getlist(self, key: str) -> list[str]: ...", "focal_method_file_path": "src/urllib3/_collections.py", "focal_method_start_lineno": 368, "focal_method_end_lineno": 369} {"index": 451, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_connection_state_properties", "test_class_name": "", "original_test_prefix": "def test_connection_state_properties(pool: HTTPConnectionPool) -> None:\n conn = pool._get_conn()\n\n assert conn.is_closed is True\n assert conn.is_connected is False\n assert conn.has_connected_to_proxy is False\n assert conn.is_verified is False\n assert conn.proxy_is_verified is None\n\n conn.connect()\n\n assert conn.is_closed is False\n assert conn.is_connected is True\n assert conn.has_connected_to_proxy is False\n assert conn.is_verified is False\n assert conn.proxy_is_verified is None\n\n conn.request(\"GET\", \"/\")\n resp = conn.getresponse()\n assert resp.status == 200\n\n conn.close()\n\n assert conn.is_closed is True\n assert conn.is_connected is False\n assert conn.has_connected_to_proxy is False\n assert conn.is_verified is False\n assert conn.proxy_is_verified is None", "test_prefix": "def test_connection_state_properties(pool: HTTPConnectionPool) -> None:\n conn = pool._get_conn()\n\n \n assert conn.is_connected is False\n assert conn.has_connected_to_proxy is False\n assert conn.is_verified is False\n assert conn.proxy_is_verified is None\n\n conn.connect()\n\n assert conn.is_closed is False\n assert conn.is_connected is True\n assert conn.has_connected_to_proxy is False\n assert conn.is_verified is False\n assert conn.proxy_is_verified is None\n\n conn.request(\"GET\", \"/\")\n resp = conn.getresponse()\n assert resp.status == 200\n\n conn.close()\n\n \n assert conn.is_connected is False\n assert conn.has_connected_to_proxy is False\n assert conn.is_verified is False\n assert conn.proxy_is_verified is None", "test_prefix_file_path": "test/with_dummyserver/test_connection.py", "test_prefix_start_lineno": 80, "test_prefix_end_lineno": 107, "test_target": "test/with_dummyserver/test_connection.py::test_connection_state_properties", "ground_truth_oracle": "assert conn.is_closed is True", "ground_truth_oracle_lineno": 103, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def getresponse(self) -> BaseHTTPResponse: ...", "focal_method_file_path": "src/urllib3/_base_connection.py", "focal_method_start_lineno": 93, "focal_method_end_lineno": 93} {"index": 452, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_303_redirect_makes_request_lose_body", "test_class_name": "TestConnectionPool", "original_test_prefix": " def test_303_redirect_makes_request_lose_body(self) -> None:\n with HTTPConnectionPool(self.host, self.port) as pool:\n response = pool.request(\n \"POST\",\n \"/redirect\",\n fields={\"target\": \"/headers_and_params\", \"status\": \"303 See Other\"},\n )\n data = response.json()\n assert data[\"params\"] == {}\n assert \"Content-Type\" not in HTTPHeaderDict(data[\"headers\"])", "test_prefix": " def test_303_redirect_makes_request_lose_body(self) -> None:\n with HTTPConnectionPool(self.host, self.port) as pool:\n response = pool.request(\n \"POST\",\n \"/redirect\",\n fields={\"target\": \"/headers_and_params\", \"status\": \"303 See Other\"},\n )\n data = response.json()\n \n assert \"Content-Type\" not in HTTPHeaderDict(data[\"headers\"])", "test_prefix_file_path": "test/with_dummyserver/test_connectionpool.py", "test_prefix_start_lineno": 511, "test_prefix_end_lineno": 520, "test_target": "test/with_dummyserver/test_connectionpool.py::TestConnectionPool::test_303_redirect_makes_request_lose_body", "ground_truth_oracle": "assert data[\"params\"] == {}", "ground_truth_oracle_lineno": 519, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def json(self) -> typing.Any:\n \"\"\"\n Deserializes the body of the HTTP response as a Python object.\n\n The body of the HTTP response must be encoded using UTF-8, as per\n `RFC 8529 Section 8.1 `_.\n\n To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to\n your custom decoder instead.\n\n If the body of the HTTP response is not decodable to UTF-8, a\n `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a\n valid JSON document, a `json.JSONDecodeError` will be raised.\n\n Read more :ref:`here `.\n\n :returns: The body of the HTTP response as a Python object.\n \"\"\"\n data = self.data.decode(\"utf-8\")\n return _json.loads(data)", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 392, "focal_method_end_lineno": 411} {"index": 453, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_read1_with_illegal_mix_decode_toggle", "test_class_name": "TestResponse", "original_test_prefix": " def test_read1_with_illegal_mix_decode_toggle(self) -> None:\n data = zlib.compress(b\"foo\")\n\n fp = BytesIO(data)\n\n resp = HTTPResponse(\n fp, headers={\"content-encoding\": \"deflate\"}, preload_content=False\n )\n\n assert resp.read1(1) == b\"f\"\n\n with pytest.raises(\n RuntimeError,\n match=(\n r\"Calling read1\\(decode_content=False\\) is not supported after \"\n r\"read1\\(decode_content=True\\) was called\"\n ),\n ):\n resp.read1(1, decode_content=False)\n\n with pytest.raises(\n RuntimeError,\n match=(\n r\"Calling read1\\(decode_content=False\\) is not supported after \"\n r\"read1\\(decode_content=True\\) was called\"\n ),\n ):\n resp.read1(decode_content=False)", "test_prefix": " def test_read1_with_illegal_mix_decode_toggle(self) -> None:\n data = zlib.compress(b\"foo\")\n\n fp = BytesIO(data)\n\n resp = HTTPResponse(\n fp, headers={\"content-encoding\": \"deflate\"}, preload_content=False\n )\n\n \n\n with pytest.raises(\n RuntimeError,\n match=(\n r\"Calling read1\\(decode_content=False\\) is not supported after \"\n r\"read1\\(decode_content=True\\) was called\"\n ),\n ):\n resp.read1(1, decode_content=False)\n\n with pytest.raises(\n RuntimeError,\n match=(\n r\"Calling read1\\(decode_content=False\\) is not supported after \"\n r\"read1\\(decode_content=True\\) was called\"\n ),\n ):\n resp.read1(decode_content=False)", "test_prefix_file_path": "test/test_response.py", "test_prefix_start_lineno": 875, "test_prefix_end_lineno": 902, "test_target": "test/test_response.py::TestResponse::test_read1_with_illegal_mix_decode_toggle", "ground_truth_oracle": "assert resp.read1(1) == b\"f\"", "ground_truth_oracle_lineno": 884, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def read1(\n self,\n amt: int | None = None,\n decode_content: bool | None = None,\n ) -> bytes:\n \"\"\"\n Similar to ``http.client.HTTPResponse.read1`` and documented\n in :meth:`io.BufferedReader.read1`, but with an additional parameter:\n ``decode_content``.\n\n :param amt:\n How much of the content to read.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n \"\"\"\n if decode_content is None:\n decode_content = self.decode_content\n if amt and amt < 0:\n # Negative numbers and `None` should be treated the same.\n amt = None\n # try and respond without going to the network\n if self._has_decoded_content:\n if not decode_content:\n raise RuntimeError(\n \"Calling read1(decode_content=False) is not supported after \"\n \"read1(decode_content=True) was called.\"\n )\n if len(self._decoded_buffer) > 0:\n if amt is None:\n return self._decoded_buffer.get_all()\n return self._decoded_buffer.get(amt)\n if amt == 0:\n return b\"\"\n\n # FIXME, this method's type doesn't say returning None is possible\n data = self._raw_read(amt, read1=True)\n if not decode_content or data is None:\n return data\n\n self._init_decoder()\n while True:\n flush_decoder = not data\n decoded_data = self._decode(data, decode_content, flush_decoder)\n self._decoded_buffer.put(decoded_data)\n if decoded_data or flush_decoder:\n break\n data = self._raw_read(8192, read1=True)\n\n if amt is None:\n return self._decoded_buffer.get_all()\n return self._decoded_buffer.get(amt)", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 1015, "focal_method_end_lineno": 1067} {"index": 454, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_has_ipv6_enabled_but_fails", "test_class_name": "TestUtil", "original_test_prefix": " def test_has_ipv6_enabled_but_fails(self) -> None:\n with patch(\"socket.has_ipv6\", True):\n with patch(\"socket.socket\") as mock:\n instance = mock.return_value\n instance.bind = Mock(side_effect=Exception(\"No IPv6 here!\"))\n assert not _has_ipv6(\"::1\")", "test_prefix": " def test_has_ipv6_enabled_but_fails(self) -> None:\n with patch(\"socket.has_ipv6\", True):\n with patch(\"socket.socket\") as mock:\n instance = mock.return_value\n instance.bind = Mock(side_effect=Exception(\"No IPv6 here!\"))\n ", "test_prefix_file_path": "test/test_util.py", "test_prefix_start_lineno": 780, "test_prefix_end_lineno": 785, "test_target": "test/test_util.py::TestUtil::test_has_ipv6_enabled_but_fails", "ground_truth_oracle": "assert not _has_ipv6(\"::1\")", "ground_truth_oracle_lineno": 785, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _has_ipv6(host: str) -> bool:\n \"\"\"Returns True if the system can bind an IPv6 address.\"\"\"\n sock = None\n has_ipv6 = False\n\n if socket.has_ipv6:\n # has_ipv6 returns true if cPython was compiled with IPv6 support.\n # It does not tell us if the system has IPv6 support enabled. To\n # determine that we must bind to an IPv6 address.\n # https://github.com/urllib3/urllib3/pull/611\n # https://bugs.python.org/issue658327\n try:\n sock = socket.socket(socket.AF_INET6)\n sock.bind((host, 0))\n has_ipv6 = True\n except Exception:\n pass\n\n if sock:\n sock.close()\n return has_ipv6", "focal_method_file_path": "src/urllib3/util/connection.py", "focal_method_start_lineno": 114, "focal_method_end_lineno": 134} {"index": 455, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_mock_httpresponse_stream", "test_class_name": "TestResponse", "original_test_prefix": " def test_mock_httpresponse_stream(self) -> None:\n # Mock out a HTTP Request that does enough to make it through urllib3's\n # read() and close() calls, and also exhausts and underlying file\n # object.\n class MockHTTPRequest:\n def __init__(self) -> None:\n self.fp: BytesIO | None = None\n\n def read(self, amt: int) -> bytes:\n assert self.fp is not None\n data = self.fp.read(amt)\n if not data:\n self.fp = None\n\n return data\n\n def read1(self, amt: int) -> bytes:\n return self.read(1)\n\n def close(self) -> None:\n self.fp = None\n\n bio = BytesIO(b\"foo\")\n fp = MockHTTPRequest()\n fp.fp = bio\n resp = HTTPResponse(fp, preload_content=False) # type: ignore[arg-type]\n stream = resp.stream(2)\n\n assert next(stream) == b\"fo\"\n assert next(stream) == b\"o\"\n with pytest.raises(StopIteration):\n next(stream)", "test_prefix": " def test_mock_httpresponse_stream(self) -> None:\n # Mock out a HTTP Request that does enough to make it through urllib3's\n # read() and close() calls, and also exhausts and underlying file\n # object.\n class MockHTTPRequest:\n def __init__(self) -> None:\n self.fp: BytesIO | None = None\n\n def read(self, amt: int) -> bytes:\n assert self.fp is not None\n data = self.fp.read(amt)\n if not data:\n self.fp = None\n\n return data\n\n def read1(self, amt: int) -> bytes:\n return self.read(1)\n\n def close(self) -> None:\n self.fp = None\n\n bio = BytesIO(b\"foo\")\n fp = MockHTTPRequest()\n fp.fp = bio\n resp = HTTPResponse(fp, preload_content=False) # type: ignore[arg-type]\n stream = resp.stream(2)\n\n assert next(stream) == b\"fo\"\n \n with pytest.raises(StopIteration):\n next(stream)", "test_prefix_file_path": "test/test_response.py", "test_prefix_start_lineno": 1201, "test_prefix_end_lineno": 1232, "test_target": "test/test_response.py::TestResponse::test_mock_httpresponse_stream", "ground_truth_oracle": "assert next(stream) == b\"o\"", "ground_truth_oracle_lineno": 1230, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def stream(\n self, amt: int | None = 2**16, decode_content: bool | None = None\n ) -> typing.Generator[bytes]:\n \"\"\"\n A generator wrapper for the read() method. A call will block until\n ``amt`` bytes have been read from the connection or until the\n connection is closed.\n\n :param amt:\n How much of the content to read. The generator will return up to\n much data per iteration, but may return less. This is particularly\n likely when using compressed data. However, the empty string will\n never be returned.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n \"\"\"\n if self.chunked and self.supports_chunked_reads():\n yield from self.read_chunked(amt, decode_content=decode_content)\n else:\n while not is_fp_closed(self._fp) or len(self._decoded_buffer) > 0:\n data = self.read(amt=amt, decode_content=decode_content)\n\n if data:\n yield data", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 1069, "focal_method_end_lineno": 1094} {"index": 456, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_stream_none_unchunked_response_does_not_hang", "test_class_name": "TestStream", "original_test_prefix": " def test_stream_none_unchunked_response_does_not_hang(self) -> None:\n done_event = Event()\n\n def socket_handler(listener: socket.socket) -> None:\n sock = listener.accept()[0]\n\n buf = b\"\"\n while not buf.endswith(b\"\\r\\n\\r\\n\"):\n buf += sock.recv(65536)\n\n sock.send(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 12\\r\\n\"\n b\"Content-type: text/plain\\r\\n\"\n b\"\\r\\n\"\n b\"hello, world\"\n )\n done_event.wait(5)\n sock.close()\n\n self._start_server(socket_handler)\n with HTTPConnectionPool(self.host, self.port, retries=False) as pool:\n r = pool.request(\"GET\", \"/\", timeout=LONG_TIMEOUT, preload_content=False)\n\n # Stream should read to the end.\n assert [b\"hello, world\"] == list(r.stream(None))\n\n done_event.set()", "test_prefix": " def test_stream_none_unchunked_response_does_not_hang(self) -> None:\n done_event = Event()\n\n def socket_handler(listener: socket.socket) -> None:\n sock = listener.accept()[0]\n\n buf = b\"\"\n while not buf.endswith(b\"\\r\\n\\r\\n\"):\n buf += sock.recv(65536)\n\n sock.send(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 12\\r\\n\"\n b\"Content-type: text/plain\\r\\n\"\n b\"\\r\\n\"\n b\"hello, world\"\n )\n done_event.wait(5)\n sock.close()\n\n self._start_server(socket_handler)\n with HTTPConnectionPool(self.host, self.port, retries=False) as pool:\n r = pool.request(\"GET\", \"/\", timeout=LONG_TIMEOUT, preload_content=False)\n\n # Stream should read to the end.\n \n\n done_event.set()", "test_prefix_file_path": "test/with_dummyserver/test_socketlevel.py", "test_prefix_start_lineno": 2263, "test_prefix_end_lineno": 2290, "test_target": "test/with_dummyserver/test_socketlevel.py::TestStream::test_stream_none_unchunked_response_does_not_hang", "ground_truth_oracle": "assert [b\"hello, world\"] == list(r.stream(None))", "ground_truth_oracle_lineno": 2288, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def stream(\n self, amt: int | None = 2**16, decode_content: bool | None = None\n ) -> typing.Iterator[bytes]:\n raise NotImplementedError()", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 436, "focal_method_end_lineno": 439} {"index": 457, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_dict_conversion", "test_class_name": "TestHTTPHeaderDict", "original_test_prefix": " def test_dict_conversion(self, d: HTTPHeaderDict) -> None:\n # Also tested in connectionpool, needs to preserve case\n hdict = {\n \"Content-Length\": \"0\",\n \"Content-type\": \"text/plain\",\n \"Server\": \"Hypercorn/1.2.3\",\n }\n h = dict(HTTPHeaderDict(hdict).items())\n assert hdict == h\n assert hdict == dict(HTTPHeaderDict(hdict))", "test_prefix": " def test_dict_conversion(self, d: HTTPHeaderDict) -> None:\n # Also tested in connectionpool, needs to preserve case\n hdict = {\n \"Content-Length\": \"0\",\n \"Content-type\": \"text/plain\",\n \"Server\": \"Hypercorn/1.2.3\",\n }\n h = dict(HTTPHeaderDict(hdict).items())\n \n assert hdict == dict(HTTPHeaderDict(hdict))", "test_prefix_file_path": "test/test_collections.py", "test_prefix_start_lineno": 383, "test_prefix_end_lineno": 392, "test_target": "test/test_collections.py::TestHTTPHeaderDict::test_dict_conversion", "ground_truth_oracle": "assert hdict == h", "ground_truth_oracle_lineno": 391, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def items(self) -> HTTPHeaderDictItemView: # type: ignore[override]\n return HTTPHeaderDictItemView(self)", "focal_method_file_path": "src/urllib3/_collections.py", "focal_method_start_lineno": 444, "focal_method_end_lineno": 445} {"index": 458, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_many_urls", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_many_urls(self) -> None:\n urls = [\n \"http://localhost:8081/foo\",\n \"http://www.google.com/mail\",\n \"http://localhost:8081/bar\",\n \"https://www.google.com/\",\n \"https://www.google.com/mail\",\n \"http://yahoo.com\",\n \"http://bing.com\",\n \"http://yahoo.com/\",\n ]\n\n connections = set()\n\n p = PoolManager(10)\n\n for url in urls:\n conn = p.connection_from_url(url)\n connections.add(conn)\n\n assert len(connections) == 5", "test_prefix": " def test_many_urls(self) -> None:\n urls = [\n \"http://localhost:8081/foo\",\n \"http://www.google.com/mail\",\n \"http://localhost:8081/bar\",\n \"https://www.google.com/\",\n \"https://www.google.com/mail\",\n \"http://yahoo.com\",\n \"http://bing.com\",\n \"http://yahoo.com/\",\n ]\n\n connections = set()\n\n p = PoolManager(10)\n\n for url in urls:\n conn = p.connection_from_url(url)\n connections.add(conn)\n\n ", "test_prefix_file_path": "test/test_poolmanager.py", "test_prefix_start_lineno": 49, "test_prefix_end_lineno": 69, "test_target": "test/test_poolmanager.py::TestPoolManager::test_many_urls", "ground_truth_oracle": "assert len(connections) == 5", "ground_truth_oracle_lineno": 69, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def connection_from_url(\n self, url: str, pool_kwargs: dict[str, typing.Any] | None = None\n ) -> HTTPConnectionPool:\n \"\"\"\n Similar to :func:`urllib3.connectionpool.connection_from_url`.\n\n If ``pool_kwargs`` is not provided and a new pool needs to be\n constructed, ``self.connection_pool_kw`` is used to initialize\n the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``\n is provided, it is used instead. Note that if a new pool does not\n need to be created for the request, the provided ``pool_kwargs`` are\n not used.\n \"\"\"\n u = parse_url(url)\n return self.connection_from_host(\n u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs\n )", "focal_method_file_path": "src/urllib3/poolmanager.py", "focal_method_start_lineno": 372, "focal_method_end_lineno": 388} {"index": 459, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test__is_legal_header_name", "test_class_name": "TestHTTP2Connection", "original_test_prefix": " def test__is_legal_header_name(self) -> None:\n assert _is_legal_header_name(b\"foo\"), \"foo\"\n assert _is_legal_header_name(b\"foo-bar\"), \"foo-bar\"\n assert _is_legal_header_name(b\"foo-bar-baz\"), \"foo-bar-baz\"\n\n # A field name MUST NOT contain characters in the ranges 0x00-0x20,\n # 0x41-0x5a, or 0x7f-0xff (all ranges inclusive). [1]\n for i in range(0x00, 0x20):\n assert not _is_legal_header_name(\n f\"foo{chr(i)}bar\".encode()\n ), f\"foo\\\\x{i}bar\"\n for i in range(0x41, 0x5A):\n assert not _is_legal_header_name(\n f\"foo{chr(i)}bar\".encode()\n ), f\"foo\\\\x{i}bar\"\n for i in range(0x7F, 0xFF):\n assert not _is_legal_header_name(\n f\"foo{chr(i)}bar\".encode()\n ), f\"foo\\\\x{i}bar\"\n\n # This specifically excludes all non-visible ASCII characters, ASCII SP\n # (0x20), and uppercase characters ('A' to 'Z', ASCII 0x41 to 0x5a). [1]\n assert not _is_legal_header_name(b\"foo bar\"), \"foo bar\"\n assert not _is_legal_header_name(b\"foo\\x20bar\"), \"foo\\\\x20bar\"\n assert not _is_legal_header_name(b\"Foo-Bar\"), \"Foo-Bar\"\n\n # With the exception of pseudo-header fields (Section 8.3), which have a\n # name that starts with a single colon, field names MUST NOT include a\n # colon (ASCII COLON, 0x3a). [1]\n assert not _is_legal_header_name(b\":foo\"), \":foo\"\n assert not _is_legal_header_name(b\"foo:bar\"), \"foo:bar\"\n assert not _is_legal_header_name(b\"foo:\"), \"foo:\"", "test_prefix": " def test__is_legal_header_name(self) -> None:\n assert _is_legal_header_name(b\"foo\"), \"foo\"\n assert _is_legal_header_name(b\"foo-bar\"), \"foo-bar\"\n assert _is_legal_header_name(b\"foo-bar-baz\"), \"foo-bar-baz\"\n\n # A field name MUST NOT contain characters in the ranges 0x00-0x20,\n # 0x41-0x5a, or 0x7f-0xff (all ranges inclusive). [1]\n for i in range(0x00, 0x20):\n assert not _is_legal_header_name(\n f\"foo{chr(i)}bar\".encode()\n ), f\"foo\\\\x{i}bar\"\n for i in range(0x41, 0x5A):\n assert not _is_legal_header_name(\n f\"foo{chr(i)}bar\".encode()\n ), f\"foo\\\\x{i}bar\"\n for i in range(0x7F, 0xFF):\n assert not _is_legal_header_name(\n f\"foo{chr(i)}bar\".encode()\n ), f\"foo\\\\x{i}bar\"\n\n # This specifically excludes all non-visible ASCII characters, ASCII SP\n # (0x20), and uppercase characters ('A' to 'Z', ASCII 0x41 to 0x5a). [1]\n assert not _is_legal_header_name(b\"foo bar\"), \"foo bar\"\n assert not _is_legal_header_name(b\"foo\\x20bar\"), \"foo\\\\x20bar\"\n assert not _is_legal_header_name(b\"Foo-Bar\"), \"Foo-Bar\"\n\n # With the exception of pseudo-header fields (Section 8.3), which have a\n # name that starts with a single colon, field names MUST NOT include a\n # colon (ASCII COLON, 0x3a). [1]\n assert not _is_legal_header_name(b\":foo\"), \":foo\"\n assert not _is_legal_header_name(b\"foo:bar\"), \"foo:bar\"\n ", "test_prefix_file_path": "test/test_http2_connection.py", "test_prefix_start_lineno": 20, "test_prefix_end_lineno": 51, "test_target": "test/test_http2_connection.py::TestHTTP2Connection::test__is_legal_header_name", "ground_truth_oracle": "assert not _is_legal_header_name(b\"foo:\"), \"foo:\"", "ground_truth_oracle_lineno": 51, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _is_legal_header_name(name: bytes) -> bool:\n \"\"\"\n \"An implementation that validates fields according to the definitions in Sections\n 5.1 and 5.5 of [HTTP] only needs an additional check that field names do not\n include uppercase characters.\" (https://httpwg.org/specs/rfc9113.html#n-field-validity)\n\n `http.client._is_legal_header_name` does not validate the field name according to the\n HTTP 1.1 spec, so we do that here, in addition to checking for uppercase characters.\n\n This does not allow for the `:` character in the header name, so should not\n be used to validate pseudo-headers.\n \"\"\"\n return bool(RE_IS_LEGAL_HEADER_NAME.match(name))", "focal_method_file_path": "src/urllib3/http2/connection.py", "focal_method_start_lineno": 29, "focal_method_end_lineno": 41} {"index": 460, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_pool_close_twice", "test_class_name": "TestConnectionPool", "original_test_prefix": " def test_pool_close_twice(self) -> None:\n pool = connection_from_url(\"http://google.com:80\")\n\n # Populate with some connections\n conn1 = pool._get_conn()\n conn2 = pool._get_conn()\n pool._put_conn(conn1)\n pool._put_conn(conn2)\n\n pool.close()\n assert pool.pool is None\n\n try:\n pool.close()\n except AttributeError:\n pytest.fail(\"Pool of the ConnectionPool is None and has no attribute get.\")", "test_prefix": " def test_pool_close_twice(self) -> None:\n pool = connection_from_url(\"http://google.com:80\")\n\n # Populate with some connections\n conn1 = pool._get_conn()\n conn2 = pool._get_conn()\n pool._put_conn(conn1)\n pool._put_conn(conn2)\n\n pool.close()\n \n\n try:\n pool.close()\n except AttributeError:\n pytest.fail(\"Pool of the ConnectionPool is None and has no attribute get.\")", "test_prefix_file_path": "test/test_connectionpool.py", "test_prefix_start_lineno": 399, "test_prefix_end_lineno": 414, "test_target": "test/test_connectionpool.py::TestConnectionPool::test_pool_close_twice", "ground_truth_oracle": "assert pool.pool is None", "ground_truth_oracle_lineno": 409, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection:\n \"\"\"\n Get a connection. Will return a pooled connection if one is available.\n\n If no connections are available and :prop:`.block` is ``False``, then a\n fresh connection is returned.\n\n :param timeout:\n Seconds to wait before giving up and raising\n :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and\n :prop:`.block` is ``True``.\n \"\"\"\n conn = None\n\n if self.pool is None:\n raise ClosedPoolError(self, \"Pool is closed.\")\n\n try:\n conn = self.pool.get(block=self.block, timeout=timeout)\n\n except AttributeError: # self.pool is None\n raise ClosedPoolError(self, \"Pool is closed.\") from None # Defensive:\n\n except queue.Empty:\n if self.block:\n raise EmptyPoolError(\n self,\n \"Pool is empty and a new connection can't be opened due to blocking mode.\",\n ) from None\n pass # Oh well, we'll create a new connection then\n\n # If this is a persistent connection, check if it got disconnected\n if conn and is_connection_dropped(conn):\n log.debug(\"Resetting dropped connection: %s\", self.host)\n conn.close()\n\n return conn or self._new_conn()", "focal_method_file_path": "src/urllib3/connectionpool.py", "focal_method_start_lineno": 256, "focal_method_end_lineno": 292} {"index": 461, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_redirect_cross_host_remove_headers", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_redirect_cross_host_remove_headers(self) -> None:\n with PoolManager() as http:\n r = http.request(\n \"GET\",\n f\"{self.base_url}/redirect\",\n fields={\"target\": f\"{self.base_url_alt}/headers\"},\n headers={\n \"Authorization\": \"foo\",\n \"Proxy-Authorization\": \"bar\",\n \"Cookie\": \"foo=bar\",\n },\n )\n\n assert r.status == 200\n\n data = r.json()\n\n assert \"Authorization\" not in data\n assert \"Proxy-Authorization\" not in data\n assert \"Cookie\" not in data\n\n r = http.request(\n \"GET\",\n f\"{self.base_url}/redirect\",\n fields={\"target\": f\"{self.base_url_alt}/headers\"},\n headers={\n \"authorization\": \"foo\",\n \"proxy-authorization\": \"baz\",\n \"cookie\": \"foo=bar\",\n },\n )\n\n assert r.status == 200\n\n data = r.json()\n\n assert \"authorization\" not in data\n assert \"Authorization\" not in data\n assert \"proxy-authorization\" not in data\n assert \"Proxy-Authorization\" not in data\n assert \"cookie\" not in data\n assert \"Cookie\" not in data", "test_prefix": " def test_redirect_cross_host_remove_headers(self) -> None:\n with PoolManager() as http:\n r = http.request(\n \"GET\",\n f\"{self.base_url}/redirect\",\n fields={\"target\": f\"{self.base_url_alt}/headers\"},\n headers={\n \"Authorization\": \"foo\",\n \"Proxy-Authorization\": \"bar\",\n \"Cookie\": \"foo=bar\",\n },\n )\n\n assert r.status == 200\n\n data = r.json()\n\n \n assert \"Proxy-Authorization\" not in data\n assert \"Cookie\" not in data\n\n r = http.request(\n \"GET\",\n f\"{self.base_url}/redirect\",\n fields={\"target\": f\"{self.base_url_alt}/headers\"},\n headers={\n \"authorization\": \"foo\",\n \"proxy-authorization\": \"baz\",\n \"cookie\": \"foo=bar\",\n },\n )\n\n assert r.status == 200\n\n data = r.json()\n\n assert \"authorization\" not in data\n \n assert \"proxy-authorization\" not in data\n assert \"Proxy-Authorization\" not in data\n assert \"cookie\" not in data\n assert \"Cookie\" not in data", "test_prefix_file_path": "test/with_dummyserver/test_poolmanager.py", "test_prefix_start_lineno": 242, "test_prefix_end_lineno": 283, "test_target": "test/with_dummyserver/test_poolmanager.py::TestPoolManager::test_redirect_cross_host_remove_headers", "ground_truth_oracle": "assert \"Authorization\" not in data", "ground_truth_oracle_lineno": 279, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def json(self) -> typing.Any:\n \"\"\"\n Deserializes the body of the HTTP response as a Python object.\n\n The body of the HTTP response must be encoded using UTF-8, as per\n `RFC 8529 Section 8.1 `_.\n\n To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to\n your custom decoder instead.\n\n If the body of the HTTP response is not decodable to UTF-8, a\n `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a\n valid JSON document, a `json.JSONDecodeError` will be raised.\n\n Read more :ref:`here `.\n\n :returns: The body of the HTTP response as a Python object.\n \"\"\"\n data = self.data.decode(\"utf-8\")\n return _json.loads(data)", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 392, "focal_method_end_lineno": 411} {"index": 462, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_tls_in_tls_tunnel", "test_class_name": "TlsInTlsTestCase", "original_test_prefix": " @pytest.mark.timeout(PER_TEST_TIMEOUT)\n def test_tls_in_tls_tunnel(self) -> None:\n \"\"\"\n Basic communication over the TLS in TLS tunnel.\n \"\"\"\n self.start_destination_server()\n self.start_proxy_server()\n\n sock = socket.create_connection(\n (self.proxy_server.host, self.proxy_server.port)\n )\n with self.client_context.wrap_socket(\n sock, server_hostname=\"localhost\"\n ) as proxy_sock:\n with SSLTransport(\n proxy_sock, self.client_context, server_hostname=\"localhost\"\n ) as destination_sock:\n assert destination_sock.version() is not None\n destination_sock.send(sample_request())\n response = consume_socket(destination_sock)\n validate_response(response)", "test_prefix": " @pytest.mark.timeout(PER_TEST_TIMEOUT)\n def test_tls_in_tls_tunnel(self) -> None:\n \"\"\"\n Basic communication over the TLS in TLS tunnel.\n \"\"\"\n self.start_destination_server()\n self.start_proxy_server()\n\n sock = socket.create_connection(\n (self.proxy_server.host, self.proxy_server.port)\n )\n with self.client_context.wrap_socket(\n sock, server_hostname=\"localhost\"\n ) as proxy_sock:\n with SSLTransport(\n proxy_sock, self.client_context, server_hostname=\"localhost\"\n ) as destination_sock:\n \n destination_sock.send(sample_request())\n response = consume_socket(destination_sock)\n validate_response(response)", "test_prefix_file_path": "test/test_ssltransport.py", "test_prefix_start_lineno": 387, "test_prefix_end_lineno": 407, "test_target": "test/test_ssltransport.py::TlsInTlsTestCase::test_tls_in_tls_tunnel", "ground_truth_oracle": "assert destination_sock.version() is not None", "ground_truth_oracle_lineno": 404, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def version(self) -> str | None:\n return self.sslobj.version()", "focal_method_file_path": "src/urllib3/util/ssltransport.py", "focal_method_start_lineno": 185, "focal_method_end_lineno": 186} {"index": 463, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_chunked_head_response_does_not_hang", "test_class_name": "TestHEAD", "original_test_prefix": " def test_chunked_head_response_does_not_hang(self) -> None:\n self.start_response_handler(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\"\n b\"Content-type: text/plain\\r\\n\"\n b\"\\r\\n\"\n )\n with HTTPConnectionPool(self.host, self.port, retries=False) as pool:\n r = pool.request(\"HEAD\", \"/\", timeout=LONG_TIMEOUT, preload_content=False)\n\n # stream will use the read_chunked method here.\n assert [] == list(r.stream())", "test_prefix": " def test_chunked_head_response_does_not_hang(self) -> None:\n self.start_response_handler(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\"\n b\"Content-type: text/plain\\r\\n\"\n b\"\\r\\n\"\n )\n with HTTPConnectionPool(self.host, self.port, retries=False) as pool:\n r = pool.request(\"HEAD\", \"/\", timeout=LONG_TIMEOUT, preload_content=False)\n\n # stream will use the read_chunked method here.\n ", "test_prefix_file_path": "test/with_dummyserver/test_socketlevel.py", "test_prefix_start_lineno": 2235, "test_prefix_end_lineno": 2246, "test_target": "test/with_dummyserver/test_socketlevel.py::TestHEAD::test_chunked_head_response_does_not_hang", "ground_truth_oracle": "assert [] == list(r.stream())", "ground_truth_oracle_lineno": 2246, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def stream(\n self, amt: int | None = 2**16, decode_content: bool | None = None\n ) -> typing.Iterator[bytes]:\n raise NotImplementedError()", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 436, "focal_method_end_lineno": 439} {"index": 464, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_merge_pool_kwargs", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_merge_pool_kwargs(self) -> None:\n \"\"\"Assert _merge_pool_kwargs works in the happy case\"\"\"\n retries = retry.Retry(total=100)\n p = PoolManager(retries=retries)\n merged = p._merge_pool_kwargs({\"new_key\": \"value\"})\n assert {\"retries\": retries, \"new_key\": \"value\"} == merged", "test_prefix": " def test_merge_pool_kwargs(self) -> None:\n \"\"\"Assert _merge_pool_kwargs works in the happy case\"\"\"\n retries = retry.Retry(total=100)\n p = PoolManager(retries=retries)\n merged = p._merge_pool_kwargs({\"new_key\": \"value\"})\n ", "test_prefix_file_path": "test/test_poolmanager.py", "test_prefix_start_lineno": 380, "test_prefix_end_lineno": 385, "test_target": "test/test_poolmanager.py::TestPoolManager::test_merge_pool_kwargs", "ground_truth_oracle": "assert {\"retries\": retries, \"new_key\": \"value\"} == merged", "ground_truth_oracle_lineno": 385, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def _merge_pool_kwargs(\n self, override: dict[str, typing.Any] | None\n ) -> dict[str, typing.Any]:\n \"\"\"\n Merge a dictionary of override values for self.connection_pool_kw.\n\n This does not modify self.connection_pool_kw and returns a new dict.\n Any keys in the override dictionary with a value of ``None`` are\n removed from the merged dictionary.\n \"\"\"\n base_pool_kwargs = self.connection_pool_kw.copy()\n if override:\n for key, value in override.items():\n if value is None:\n try:\n del base_pool_kwargs[key]\n except KeyError:\n pass\n else:\n base_pool_kwargs[key] = value\n return base_pool_kwargs", "focal_method_file_path": "src/urllib3/poolmanager.py", "focal_method_start_lineno": 390, "focal_method_end_lineno": 410} {"index": 465, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_httplib_headers_case_insensitive", "test_class_name": "TestHeaders", "original_test_prefix": " def test_httplib_headers_case_insensitive(self) -> None:\n self.start_response_handler(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 0\\r\\n\"\n b\"Content-type: text/plain\\r\\n\"\n b\"\\r\\n\"\n )\n with HTTPConnectionPool(self.host, self.port, retries=False) as pool:\n HEADERS = {\"Content-Length\": \"0\", \"Content-type\": \"text/plain\"}\n r = pool.request(\"GET\", \"/\")\n assert HEADERS == dict(r.headers.items()) # to preserve case sensitivity", "test_prefix": " def test_httplib_headers_case_insensitive(self) -> None:\n self.start_response_handler(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 0\\r\\n\"\n b\"Content-type: text/plain\\r\\n\"\n b\"\\r\\n\"\n )\n with HTTPConnectionPool(self.host, self.port, retries=False) as pool:\n HEADERS = {\"Content-Length\": \"0\", \"Content-type\": \"text/plain\"}\n r = pool.request(\"GET\", \"/\")\n ", "test_prefix_file_path": "test/with_dummyserver/test_socketlevel.py", "test_prefix_start_lineno": 1967, "test_prefix_end_lineno": 1977, "test_target": "test/with_dummyserver/test_socketlevel.py::TestHeaders::test_httplib_headers_case_insensitive", "ground_truth_oracle": "assert HEADERS == dict(r.headers.items()) # to preserve case sensitivity", "ground_truth_oracle_lineno": 1977, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def items(self) -> HTTPHeaderDictItemView: # type: ignore[override]\n return HTTPHeaderDictItemView(self)", "focal_method_file_path": "src/urllib3/_collections.py", "focal_method_start_lineno": 444, "focal_method_end_lineno": 445} {"index": 466, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_no_user_agent_header", "test_class_name": "TestConnectionPool", "original_test_prefix": " def test_no_user_agent_header(self) -> None:\n \"\"\"ConnectionPool can suppress sending a user agent header\"\"\"\n custom_ua = \"I'm not a web scraper, what are you talking about?\"\n with HTTPConnectionPool(self.host, self.port) as pool:\n # Suppress user agent in the request headers.\n no_ua_headers = {\"User-Agent\": SKIP_HEADER}\n r = pool.request(\"GET\", \"/headers\", headers=no_ua_headers)\n request_headers = r.json()\n assert \"User-Agent\" not in request_headers\n assert no_ua_headers[\"User-Agent\"] == SKIP_HEADER\n\n # Suppress user agent in the pool headers.\n pool.headers = no_ua_headers\n r = pool.request(\"GET\", \"/headers\")\n request_headers = r.json()\n assert \"User-Agent\" not in request_headers\n assert no_ua_headers[\"User-Agent\"] == SKIP_HEADER\n\n # Request headers override pool headers.\n pool_headers = {\"User-Agent\": custom_ua}\n pool.headers = pool_headers\n r = pool.request(\"GET\", \"/headers\", headers=no_ua_headers)\n request_headers = r.json()\n assert \"User-Agent\" not in request_headers\n assert no_ua_headers[\"User-Agent\"] == SKIP_HEADER\n assert pool_headers.get(\"User-Agent\") == custom_ua", "test_prefix": " def test_no_user_agent_header(self) -> None:\n \"\"\"ConnectionPool can suppress sending a user agent header\"\"\"\n custom_ua = \"I'm not a web scraper, what are you talking about?\"\n with HTTPConnectionPool(self.host, self.port) as pool:\n # Suppress user agent in the request headers.\n no_ua_headers = {\"User-Agent\": SKIP_HEADER}\n r = pool.request(\"GET\", \"/headers\", headers=no_ua_headers)\n request_headers = r.json()\n assert \"User-Agent\" not in request_headers\n \n\n # Suppress user agent in the pool headers.\n pool.headers = no_ua_headers\n r = pool.request(\"GET\", \"/headers\")\n request_headers = r.json()\n assert \"User-Agent\" not in request_headers\n \n\n # Request headers override pool headers.\n pool_headers = {\"User-Agent\": custom_ua}\n pool.headers = pool_headers\n r = pool.request(\"GET\", \"/headers\", headers=no_ua_headers)\n request_headers = r.json()\n assert \"User-Agent\" not in request_headers\n \n assert pool_headers.get(\"User-Agent\") == custom_ua", "test_prefix_file_path": "test/with_dummyserver/test_connectionpool.py", "test_prefix_start_lineno": 993, "test_prefix_end_lineno": 1018, "test_target": "test/with_dummyserver/test_connectionpool.py::TestConnectionPool::test_no_user_agent_header", "ground_truth_oracle": "assert no_ua_headers[\"User-Agent\"] == SKIP_HEADER", "ground_truth_oracle_lineno": 1009, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def json(self) -> typing.Any:\n \"\"\"\n Deserializes the body of the HTTP response as a Python object.\n\n The body of the HTTP response must be encoded using UTF-8, as per\n `RFC 8529 Section 8.1 `_.\n\n To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to\n your custom decoder instead.\n\n If the body of the HTTP response is not decodable to UTF-8, a\n `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a\n valid JSON document, a `json.JSONDecodeError` will be raised.\n\n Read more :ref:`here `.\n\n :returns: The body of the HTTP response as a Python object.\n \"\"\"\n data = self.data.decode(\"utf-8\")\n return _json.loads(data)", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 392, "focal_method_end_lineno": 411} {"index": 467, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_request_chunked_is_deprecated", "test_class_name": "TestConnectionPool", "original_test_prefix": " def test_request_chunked_is_deprecated(\n self,\n ) -> None:\n with HTTPConnectionPool(self.host, self.port) as pool:\n conn = pool._get_conn()\n\n with pytest.warns(DeprecationWarning) as w:\n conn.request_chunked(\"GET\", \"/headers\") # type: ignore[attr-defined]\n assert len(w) == 1 and str(w[0].message) == (\n \"HTTPConnection.request_chunked() is deprecated and will be removed in urllib3 v2.1.0. \"\n \"Instead use HTTPConnection.request(..., chunked=True).\"\n )\n\n resp = conn.getresponse()\n assert resp.status == 200\n assert resp.json()[\"Transfer-Encoding\"] == \"chunked\"\n conn.close()", "test_prefix": " def test_request_chunked_is_deprecated(\n self,\n ) -> None:\n with HTTPConnectionPool(self.host, self.port) as pool:\n conn = pool._get_conn()\n\n with pytest.warns(DeprecationWarning) as w:\n conn.request_chunked(\"GET\", \"/headers\") # type: ignore[attr-defined]\n assert len(w) == 1 and str(w[0].message) == (\n \"HTTPConnection.request_chunked() is deprecated and will be removed in urllib3 v2.1.0. \"\n \"Instead use HTTPConnection.request(..., chunked=True).\"\n )\n\n resp = conn.getresponse()\n \n assert resp.json()[\"Transfer-Encoding\"] == \"chunked\"\n conn.close()", "test_prefix_file_path": "test/with_dummyserver/test_connectionpool.py", "test_prefix_start_lineno": 1076, "test_prefix_end_lineno": 1092, "test_target": "test/with_dummyserver/test_connectionpool.py::TestConnectionPool::test_request_chunked_is_deprecated", "ground_truth_oracle": "assert resp.status == 200", "ground_truth_oracle_lineno": 1090, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def getresponse(self) -> BaseHTTPResponse: ...", "focal_method_file_path": "src/urllib3/_base_connection.py", "focal_method_start_lineno": 93, "focal_method_end_lineno": 93} {"index": 468, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_http_connection_from_url_case_insensitive", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_http_connection_from_url_case_insensitive(self) -> None:\n \"\"\"Assert scheme case is ignored when pooling HTTP connections.\"\"\"\n p = PoolManager()\n pool = p.connection_from_url(\"http://example.com/\")\n other_pool = p.connection_from_url(\"HTTP://EXAMPLE.COM/\")\n\n assert 1 == len(p.pools)\n assert pool is other_pool\n assert all(isinstance(key, PoolKey) for key in p.pools.keys())", "test_prefix": " def test_http_connection_from_url_case_insensitive(self) -> None:\n \"\"\"Assert scheme case is ignored when pooling HTTP connections.\"\"\"\n p = PoolManager()\n pool = p.connection_from_url(\"http://example.com/\")\n other_pool = p.connection_from_url(\"HTTP://EXAMPLE.COM/\")\n\n \n assert pool is other_pool\n assert all(isinstance(key, PoolKey) for key in p.pools.keys())", "test_prefix_file_path": "test/test_poolmanager.py", "test_prefix_start_lineno": 220, "test_prefix_end_lineno": 228, "test_target": "test/test_poolmanager.py::TestPoolManager::test_http_connection_from_url_case_insensitive", "ground_truth_oracle": "assert 1 == len(p.pools)", "ground_truth_oracle_lineno": 226, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def connection_from_url(\n self, url: str, pool_kwargs: dict[str, typing.Any] | None = None\n ) -> HTTPConnectionPool:\n \"\"\"\n Similar to :func:`urllib3.connectionpool.connection_from_url`.\n\n If ``pool_kwargs`` is not provided and a new pool needs to be\n constructed, ``self.connection_pool_kw`` is used to initialize\n the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``\n is provided, it is used instead. Note that if a new pool does not\n need to be created for the request, the provided ``pool_kwargs`` are\n not used.\n \"\"\"\n u = parse_url(url)\n return self.connection_from_host(\n u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs\n )", "focal_method_file_path": "src/urllib3/poolmanager.py", "focal_method_start_lineno": 372, "focal_method_end_lineno": 388} {"index": 469, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_empty_head_response_does_not_hang", "test_class_name": "TestHEAD", "original_test_prefix": " def test_empty_head_response_does_not_hang(self) -> None:\n self.start_response_handler(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 256\\r\\n\"\n b\"Content-type: text/plain\\r\\n\"\n b\"\\r\\n\"\n )\n with HTTPConnectionPool(self.host, self.port, retries=False) as pool:\n r = pool.request(\"HEAD\", \"/\", timeout=LONG_TIMEOUT, preload_content=False)\n\n # stream will use the read method here.\n assert [] == list(r.stream())", "test_prefix": " def test_empty_head_response_does_not_hang(self) -> None:\n self.start_response_handler(\n b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 256\\r\\n\"\n b\"Content-type: text/plain\\r\\n\"\n b\"\\r\\n\"\n )\n with HTTPConnectionPool(self.host, self.port, retries=False) as pool:\n r = pool.request(\"HEAD\", \"/\", timeout=LONG_TIMEOUT, preload_content=False)\n\n # stream will use the read method here.\n ", "test_prefix_file_path": "test/with_dummyserver/test_socketlevel.py", "test_prefix_start_lineno": 2248, "test_prefix_end_lineno": 2259, "test_target": "test/with_dummyserver/test_socketlevel.py::TestHEAD::test_empty_head_response_does_not_hang", "ground_truth_oracle": "assert [] == list(r.stream())", "ground_truth_oracle_lineno": 2259, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def stream(\n self, amt: int | None = 2**16, decode_content: bool | None = None\n ) -> typing.Iterator[bytes]:\n raise NotImplementedError()", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 436, "focal_method_end_lineno": 439} {"index": 470, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_default_user_agent_header", "test_class_name": "TestConnectionPool", "original_test_prefix": " def test_default_user_agent_header(self) -> None:\n \"\"\"ConnectionPool has a default user agent\"\"\"\n default_ua = _get_default_user_agent()\n custom_ua = \"I'm not a web scraper, what are you talking about?\"\n custom_ua2 = \"Yet Another User Agent\"\n with HTTPConnectionPool(self.host, self.port) as pool:\n # Use default user agent if no user agent was specified.\n r = pool.request(\"GET\", \"/headers\")\n request_headers = r.json()\n assert request_headers.get(\"User-Agent\") == _get_default_user_agent()\n\n # Prefer the request user agent over the default.\n headers = {\"UsEr-AGENt\": custom_ua}\n r = pool.request(\"GET\", \"/headers\", headers=headers)\n request_headers = r.json()\n assert request_headers.get(\"User-Agent\") == custom_ua\n\n # Do not modify pool headers when using the default user agent.\n pool_headers = {\"foo\": \"bar\"}\n pool.headers = pool_headers\n r = pool.request(\"GET\", \"/headers\")\n request_headers = r.json()\n assert request_headers.get(\"User-Agent\") == default_ua\n assert \"User-Agent\" not in pool_headers\n\n pool.headers.update({\"User-Agent\": custom_ua2})\n r = pool.request(\"GET\", \"/headers\")\n request_headers = r.json()\n assert request_headers.get(\"User-Agent\") == custom_ua2", "test_prefix": " def test_default_user_agent_header(self) -> None:\n \"\"\"ConnectionPool has a default user agent\"\"\"\n default_ua = _get_default_user_agent()\n custom_ua = \"I'm not a web scraper, what are you talking about?\"\n custom_ua2 = \"Yet Another User Agent\"\n with HTTPConnectionPool(self.host, self.port) as pool:\n # Use default user agent if no user agent was specified.\n r = pool.request(\"GET\", \"/headers\")\n request_headers = r.json()\n \n\n # Prefer the request user agent over the default.\n headers = {\"UsEr-AGENt\": custom_ua}\n r = pool.request(\"GET\", \"/headers\", headers=headers)\n request_headers = r.json()\n assert request_headers.get(\"User-Agent\") == custom_ua\n\n # Do not modify pool headers when using the default user agent.\n pool_headers = {\"foo\": \"bar\"}\n pool.headers = pool_headers\n r = pool.request(\"GET\", \"/headers\")\n request_headers = r.json()\n assert request_headers.get(\"User-Agent\") == default_ua\n assert \"User-Agent\" not in pool_headers\n\n pool.headers.update({\"User-Agent\": custom_ua2})\n r = pool.request(\"GET\", \"/headers\")\n request_headers = r.json()\n assert request_headers.get(\"User-Agent\") == custom_ua2", "test_prefix_file_path": "test/with_dummyserver/test_connectionpool.py", "test_prefix_start_lineno": 938, "test_prefix_end_lineno": 966, "test_target": "test/with_dummyserver/test_connectionpool.py::TestConnectionPool::test_default_user_agent_header", "ground_truth_oracle": "assert request_headers.get(\"User-Agent\") == _get_default_user_agent()", "ground_truth_oracle_lineno": 947, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _get_default_user_agent() -> str:\n return f\"python-urllib3/{__version__}\"", "focal_method_file_path": "src/urllib3/connection.py", "focal_method_start_lineno": 1071, "focal_method_end_lineno": 1072} {"index": 471, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_encode_invalid_chars_none", "test_class_name": "TestUtil", "original_test_prefix": " def test_encode_invalid_chars_none(self) -> None:\n assert _encode_invalid_chars(None, set()) is None", "test_prefix": " def test_encode_invalid_chars_none(self) -> None:\n ", "test_prefix_file_path": "test/test_util.py", "test_prefix_start_lineno": 152, "test_prefix_end_lineno": 153, "test_target": "test/test_util.py::TestUtil::test_encode_invalid_chars_none", "ground_truth_oracle": "assert _encode_invalid_chars(None, set()) is None", "ground_truth_oracle_lineno": 153, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _encode_invalid_chars(\n component: str | None, allowed_chars: typing.Container[str]\n) -> str | None:\n \"\"\"Percent-encodes a URI component without reapplying\n onto an already percent-encoded component.\n \"\"\"\n if component is None:\n return component\n\n component = to_str(component)\n\n # Normalize existing percent-encoded bytes.\n # Try to see if the component we're encoding is already percent-encoded\n # so we can skip all '%' characters but still encode all others.\n component, percent_encodings = _PERCENT_RE.subn(\n lambda match: match.group(0).upper(), component\n )\n\n uri_bytes = component.encode(\"utf-8\", \"surrogatepass\")\n is_percent_encoded = percent_encodings == uri_bytes.count(b\"%\")\n encoded_component = bytearray()\n\n for i in range(0, len(uri_bytes)):\n # Will return a single character bytestring\n byte = uri_bytes[i : i + 1]\n byte_ord = ord(byte)\n if (is_percent_encoded and byte == b\"%\") or (\n byte_ord < 128 and byte.decode() in allowed_chars\n ):\n encoded_component += byte\n continue\n encoded_component.extend(b\"%\" + (hex(byte_ord)[2:].encode().zfill(2).upper()))\n\n return encoded_component.decode()", "focal_method_file_path": "src/urllib3/util/url.py", "focal_method_start_lineno": 227, "focal_method_end_lineno": 260} {"index": 472, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_create", "test_class_name": "TestRequestField", "original_test_prefix": " def test_create(self) -> None:\n simple_field = RequestField(\"somename\", \"data\")\n assert simple_field.render_headers() == \"\\r\\n\"\n filename_field = RequestField(\"somename\", \"data\", filename=\"somefile.txt\")\n assert filename_field.render_headers() == \"\\r\\n\"\n headers_field = RequestField(\n \"somename\", \"data\", headers={\"Content-Length\": \"4\"}\n )\n assert headers_field.render_headers() == \"Content-Length: 4\\r\\n\\r\\n\"", "test_prefix": " def test_create(self) -> None:\n simple_field = RequestField(\"somename\", \"data\")\n \n filename_field = RequestField(\"somename\", \"data\", filename=\"somefile.txt\")\n assert filename_field.render_headers() == \"\\r\\n\"\n headers_field = RequestField(\n \"somename\", \"data\", headers={\"Content-Length\": \"4\"}\n )\n assert headers_field.render_headers() == \"Content-Length: 4\\r\\n\\r\\n\"", "test_prefix_file_path": "test/test_fields.py", "test_prefix_start_lineno": 29, "test_prefix_end_lineno": 37, "test_target": "test/test_fields.py::TestRequestField::test_create", "ground_truth_oracle": "assert simple_field.render_headers() == \"\\r\\n\"", "ground_truth_oracle_lineno": 31, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def render_headers(self) -> str:\n \"\"\"\n Renders the headers for this request field.\n \"\"\"\n lines = []\n\n sort_keys = [\"Content-Disposition\", \"Content-Type\", \"Content-Location\"]\n for sort_key in sort_keys:\n if self.headers.get(sort_key, False):\n lines.append(f\"{sort_key}: {self.headers[sort_key]}\")\n\n for header_name, header_value in self.headers.items():\n if header_name not in sort_keys:\n if header_value:\n lines.append(f\"{header_name}: {header_value}\")\n\n lines.append(\"\\r\\n\")\n return \"\\r\\n\".join(lines)", "focal_method_file_path": "src/urllib3/fields.py", "focal_method_start_lineno": 291, "focal_method_end_lineno": 308} {"index": 473, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_backoff_reset_after_redirect", "test_class_name": "TestRetry", "original_test_prefix": " def test_backoff_reset_after_redirect(self) -> None:\n retry = Retry(total=100, redirect=5, backoff_factor=0.2)\n retry = retry.increment(method=\"GET\")\n retry = retry.increment(method=\"GET\")\n assert retry.get_backoff_time() == 0.4\n redirect_response = HTTPResponse(status=302, headers={\"location\": \"test\"})\n retry = retry.increment(method=\"GET\", response=redirect_response)\n assert retry.get_backoff_time() == 0\n retry = retry.increment(method=\"GET\")\n retry = retry.increment(method=\"GET\")\n assert retry.get_backoff_time() == 0.4", "test_prefix": " def test_backoff_reset_after_redirect(self) -> None:\n retry = Retry(total=100, redirect=5, backoff_factor=0.2)\n retry = retry.increment(method=\"GET\")\n retry = retry.increment(method=\"GET\")\n .4\n redirect_response = HTTPResponse(status=302, headers={\"location\": \"test\"})\n retry = retry.increment(method=\"GET\", response=redirect_response)\n \n retry = retry.increment(method=\"GET\")\n retry = retry.increment(method=\"GET\")\n .4", "test_prefix_file_path": "test/test_retry.py", "test_prefix_start_lineno": 220, "test_prefix_end_lineno": 230, "test_target": "test/test_retry.py::TestRetry::test_backoff_reset_after_redirect", "ground_truth_oracle": "assert retry.get_backoff_time() == 0", "ground_truth_oracle_lineno": 227, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_backoff_time(self) -> float:\n \"\"\"Formula for computing the current backoff\n\n :rtype: float\n \"\"\"\n # We want to consider only the last consecutive errors sequence (Ignore redirects).\n consecutive_errors_len = len(\n list(\n takewhile(lambda x: x.redirect_location is None, reversed(self.history))\n )\n )\n if consecutive_errors_len <= 1:\n return 0\n\n backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))\n if self.backoff_jitter != 0.0:\n backoff_value += random.random() * self.backoff_jitter\n return float(max(0, min(self.backoff_max, backoff_value)))", "focal_method_file_path": "src/urllib3/util/retry.py", "focal_method_start_lineno": 289, "focal_method_end_lineno": 306} {"index": 474, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_header_parsing_errors", "test_class_name": "TestFormat", "original_test_prefix": " def test_header_parsing_errors(self) -> None:\n hpe = HeaderParsingError([MessageDefect(\"defects\")], \"unparsed_data\")\n\n assert \"defects\" in str(hpe)\n assert \"unparsed_data\" in str(hpe)", "test_prefix": " def test_header_parsing_errors(self) -> None:\n hpe = HeaderParsingError([MessageDefect(\"defects\")], \"unparsed_data\")\n\n assert \"defects\" in str(hpe)\n ", "test_prefix_file_path": "test/test_exceptions.py", "test_prefix_start_lineno": 70, "test_prefix_end_lineno": 74, "test_target": "test/test_exceptions.py::TestFormat::test_header_parsing_errors", "ground_truth_oracle": "assert \"unparsed_data\" in str(hpe)", "ground_truth_oracle_lineno": 74, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "class HeaderParsingError(HTTPError):\n \"\"\"Raised by assert_header_parsing, but we convert it to a log.warning statement.\"\"\"\n\n def __init__(\n self, defects: list[MessageDefect], unparsed_data: bytes | str | None\n ) -> None:\n message = f\"{defects or 'Unknown'}, unparsed data: {unparsed_data!r}\"\n super().__init__(message)", "focal_method_file_path": "src/urllib3/exceptions.py", "focal_method_start_lineno": 324, "focal_method_end_lineno": 331} {"index": 475, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_url_from_pool", "test_class_name": "TestConnectionPool", "original_test_prefix": " def test_url_from_pool(self) -> None:\n with connection_from_url(\"http://google.com:80\") as pool:\n path = \"path?query=foo\"\n assert f\"http://google.com:80/{path}\" == _url_from_pool(pool, path)", "test_prefix": " def test_url_from_pool(self) -> None:\n with connection_from_url(\"http://google.com:80\") as pool:\n path = \"path?query=foo\"\n ", "test_prefix_file_path": "test/test_connectionpool.py", "test_prefix_start_lineno": 456, "test_prefix_end_lineno": 459, "test_target": "test/test_connectionpool.py::TestConnectionPool::test_url_from_pool", "ground_truth_oracle": "assert f\"http://google.com:80/{path}\" == _url_from_pool(pool, path)", "ground_truth_oracle_lineno": 459, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _url_from_pool(\n pool: HTTPConnectionPool | HTTPSConnectionPool, path: str | None = None\n) -> str:\n \"\"\"Returns the URL from a given connection pool. This is mainly used for testing and logging.\"\"\"\n return Url(scheme=pool.scheme, host=pool.host, port=pool.port, path=path).url", "focal_method_file_path": "src/urllib3/connectionpool.py", "focal_method_start_lineno": 1163, "focal_method_end_lineno": 1167} {"index": 476, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_backoff_jitter", "test_class_name": "TestRetry", "original_test_prefix": " def test_backoff_jitter(self) -> None:\n \"\"\"Backoff with jitter is computed correctly\"\"\"\n max_backoff = 1\n jitter = 0.4\n retry = Retry(\n total=100,\n backoff_factor=0.2,\n backoff_max=max_backoff,\n backoff_jitter=jitter,\n )\n assert retry.get_backoff_time() == 0 # First request\n\n retry = retry.increment(method=\"GET\")\n assert retry.get_backoff_time() == 0 # First retry\n\n retry = retry.increment(method=\"GET\")\n assert retry.backoff_factor == 0.2\n assert retry.total == 98\n assert 0.4 <= retry.get_backoff_time() <= 0.8 # Start backoff\n\n retry = retry.increment(method=\"GET\")\n assert 0.8 <= retry.get_backoff_time() <= max_backoff\n\n retry = retry.increment(method=\"GET\")\n assert retry.get_backoff_time() == max_backoff\n\n retry = retry.increment(method=\"GET\")\n assert retry.get_backoff_time() == max_backoff", "test_prefix": " def test_backoff_jitter(self) -> None:\n \"\"\"Backoff with jitter is computed correctly\"\"\"\n max_backoff = 1\n jitter = 0.4\n retry = Retry(\n total=100,\n backoff_factor=0.2,\n backoff_max=max_backoff,\n backoff_jitter=jitter,\n )\n assert retry.get_backoff_time() == 0 # First request\n\n retry = retry.increment(method=\"GET\")\n assert retry.get_backoff_time() == 0 # First retry\n\n retry = retry.increment(method=\"GET\")\n assert retry.backoff_factor == 0.2\n assert retry.total == 98\n assert 0.4 <= retry.get_backoff_time() <= 0.8 # Start backoff\n\n retry = retry.increment(method=\"GET\")\n \n\n retry = retry.increment(method=\"GET\")\n assert retry.get_backoff_time() == max_backoff\n\n retry = retry.increment(method=\"GET\")\n assert retry.get_backoff_time() == max_backoff", "test_prefix_file_path": "test/test_retry.py", "test_prefix_start_lineno": 184, "test_prefix_end_lineno": 211, "test_target": "test/test_retry.py::TestRetry::test_backoff_jitter", "ground_truth_oracle": "assert 0.8 <= retry.get_backoff_time() <= max_backoff", "ground_truth_oracle_lineno": 205, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def get_backoff_time(self) -> float:\n \"\"\"Formula for computing the current backoff\n\n :rtype: float\n \"\"\"\n # We want to consider only the last consecutive errors sequence (Ignore redirects).\n consecutive_errors_len = len(\n list(\n takewhile(lambda x: x.redirect_location is None, reversed(self.history))\n )\n )\n if consecutive_errors_len <= 1:\n return 0\n\n backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))\n if self.backoff_jitter != 0.0:\n backoff_value += random.random() * self.backoff_jitter\n return float(max(0, min(self.backoff_max, backoff_value)))", "focal_method_file_path": "src/urllib3/util/retry.py", "focal_method_start_lineno": 289, "focal_method_end_lineno": 306} {"index": 477, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_merge_pool_kwargs_remove_key", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_merge_pool_kwargs_remove_key(self) -> None:\n \"\"\"Assert keys can be removed with _merge_pool_kwargs\"\"\"\n p = PoolManager(retries=100)\n merged = p._merge_pool_kwargs({\"retries\": None})\n assert \"retries\" not in merged", "test_prefix": " def test_merge_pool_kwargs_remove_key(self) -> None:\n \"\"\"Assert keys can be removed with _merge_pool_kwargs\"\"\"\n p = PoolManager(retries=100)\n merged = p._merge_pool_kwargs({\"retries\": None})\n ", "test_prefix_file_path": "test/test_poolmanager.py", "test_prefix_start_lineno": 395, "test_prefix_end_lineno": 399, "test_target": "test/test_poolmanager.py::TestPoolManager::test_merge_pool_kwargs_remove_key", "ground_truth_oracle": "assert \"retries\" not in merged", "ground_truth_oracle_lineno": 399, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def _merge_pool_kwargs(\n self, override: dict[str, typing.Any] | None\n ) -> dict[str, typing.Any]:\n \"\"\"\n Merge a dictionary of override values for self.connection_pool_kw.\n\n This does not modify self.connection_pool_kw and returns a new dict.\n Any keys in the override dictionary with a value of ``None`` are\n removed from the merged dictionary.\n \"\"\"\n base_pool_kwargs = self.connection_pool_kw.copy()\n if override:\n for key, value in override.items():\n if value is None:\n try:\n del base_pool_kwargs[key]\n except KeyError:\n pass\n else:\n base_pool_kwargs[key] = value\n return base_pool_kwargs", "focal_method_file_path": "src/urllib3/poolmanager.py", "focal_method_start_lineno": 390, "focal_method_end_lineno": 410} {"index": 478, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_top_level_request_with_json_with_httpheaderdict", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_top_level_request_with_json_with_httpheaderdict(self) -> None:\n body = {\"attribute\": \"value\"}\n header = HTTPHeaderDict(cookie=\"foo, bar\")\n with PoolManager(headers=header) as http:\n r = http.request(method=\"POST\", url=f\"{self.base_url}/echo_json\", json=body)\n assert r.status == 200\n assert r.json() == body\n assert \"application/json\" in r.headers[\"Content-Type\"].replace(\n \" \", \"\"\n ).split(\",\")", "test_prefix": " def test_top_level_request_with_json_with_httpheaderdict(self) -> None:\n body = {\"attribute\": \"value\"}\n header = HTTPHeaderDict(cookie=\"foo, bar\")\n with PoolManager(headers=header) as http:\n r = http.request(method=\"POST\", url=f\"{self.base_url}/echo_json\", json=body)\n assert r.status == 200\n \n assert \"application/json\" in r.headers[\"Content-Type\"].replace(\n \" \", \"\"\n ).split(\",\")", "test_prefix_file_path": "test/with_dummyserver/test_poolmanager.py", "test_prefix_start_lineno": 759, "test_prefix_end_lineno": 768, "test_target": "test/with_dummyserver/test_poolmanager.py::TestPoolManager::test_top_level_request_with_json_with_httpheaderdict", "ground_truth_oracle": "assert r.json() == body", "ground_truth_oracle_lineno": 765, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def json(self) -> typing.Any:\n \"\"\"\n Deserializes the body of the HTTP response as a Python object.\n\n The body of the HTTP response must be encoded using UTF-8, as per\n `RFC 8529 Section 8.1 `_.\n\n To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to\n your custom decoder instead.\n\n If the body of the HTTP response is not decodable to UTF-8, a\n `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a\n valid JSON document, a `json.JSONDecodeError` will be raised.\n\n Read more :ref:`here `.\n\n :returns: The body of the HTTP response as a Python object.\n \"\"\"\n data = self.data.decode(\"utf-8\")\n return _json.loads(data)", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 392, "focal_method_end_lineno": 411} {"index": 479, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_same_url", "test_class_name": "TestPoolManager", "original_test_prefix": " @resolvesLocalhostFQDN()\n def test_same_url(self) -> None:\n # Convince ourselves that normally we don't get the same object\n conn1 = connection_from_url(\"http://localhost:8081/foo\")\n conn2 = connection_from_url(\"http://localhost:8081/bar\")\n\n assert conn1 != conn2\n\n # Now try again using the PoolManager\n p = PoolManager(1)\n\n conn1 = p.connection_from_url(\"http://localhost:8081/foo\")\n conn2 = p.connection_from_url(\"http://localhost:8081/bar\")\n\n assert conn1 == conn2\n\n # Ensure that FQDNs are handled separately from relative domains\n p = PoolManager(2)\n\n conn1 = p.connection_from_url(\"http://localhost.:8081/foo\")\n conn2 = p.connection_from_url(\"http://localhost:8081/bar\")\n\n assert conn1 != conn2", "test_prefix": " @resolvesLocalhostFQDN()\n def test_same_url(self) -> None:\n # Convince ourselves that normally we don't get the same object\n conn1 = connection_from_url(\"http://localhost:8081/foo\")\n conn2 = connection_from_url(\"http://localhost:8081/bar\")\n\n \n\n # Now try again using the PoolManager\n p = PoolManager(1)\n\n conn1 = p.connection_from_url(\"http://localhost:8081/foo\")\n conn2 = p.connection_from_url(\"http://localhost:8081/bar\")\n\n assert conn1 == conn2\n\n # Ensure that FQDNs are handled separately from relative domains\n p = PoolManager(2)\n\n conn1 = p.connection_from_url(\"http://localhost.:8081/foo\")\n conn2 = p.connection_from_url(\"http://localhost:8081/bar\")\n\n ", "test_prefix_file_path": "test/test_poolmanager.py", "test_prefix_start_lineno": 25, "test_prefix_end_lineno": 47, "test_target": "test/test_poolmanager.py::TestPoolManager::test_same_url", "ground_truth_oracle": "assert conn1 != conn2", "ground_truth_oracle_lineno": 47, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def connection_from_url(\n self, url: str, pool_kwargs: dict[str, typing.Any] | None = None\n ) -> HTTPConnectionPool:\n \"\"\"\n Similar to :func:`urllib3.connectionpool.connection_from_url`.\n\n If ``pool_kwargs`` is not provided and a new pool needs to be\n constructed, ``self.connection_pool_kw`` is used to initialize\n the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``\n is provided, it is used instead. Note that if a new pool does not\n need to be created for the request, the provided ``pool_kwargs`` are\n not used.\n \"\"\"\n u = parse_url(url)\n return self.connection_from_host(\n u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs\n )", "focal_method_file_path": "src/urllib3/poolmanager.py", "focal_method_start_lineno": 372, "focal_method_end_lineno": 388} {"index": 480, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_defaults_are_applied", "test_class_name": "TestConnectionPool", "original_test_prefix": " def test_defaults_are_applied(self) -> None:\n \"\"\"Test that modifying the default socket options works.\"\"\"\n # This test needs to be here in order to be run. socket.create_connection actually tries\n # to connect to the host provided so we need a dummyserver to be running.\n with HTTPConnectionPool(self.host, self.port) as pool:\n # Get the HTTPConnection instance\n conn = pool._new_conn()\n try:\n # Update the default socket options\n assert conn.socket_options is not None\n conn.socket_options += [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]\n s = conn._new_conn() # type: ignore[attr-defined]\n nagle_disabled = (\n s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) > 0\n )\n using_keepalive = (\n s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0\n )\n assert nagle_disabled\n assert using_keepalive\n finally:\n conn.close()\n s.close()", "test_prefix": " def test_defaults_are_applied(self) -> None:\n \"\"\"Test that modifying the default socket options works.\"\"\"\n # This test needs to be here in order to be run. socket.create_connection actually tries\n # to connect to the host provided so we need a dummyserver to be running.\n with HTTPConnectionPool(self.host, self.port) as pool:\n # Get the HTTPConnection instance\n conn = pool._new_conn()\n try:\n # Update the default socket options\n \n conn.socket_options += [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]\n s = conn._new_conn() # type: ignore[attr-defined]\n nagle_disabled = (\n s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) > 0\n )\n using_keepalive = (\n s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0\n )\n assert nagle_disabled\n assert using_keepalive\n finally:\n conn.close()\n s.close()", "test_prefix_file_path": "test/with_dummyserver/test_connectionpool.py", "test_prefix_start_lineno": 365, "test_prefix_end_lineno": 387, "test_target": "test/with_dummyserver/test_connectionpool.py::TestConnectionPool::test_defaults_are_applied", "ground_truth_oracle": "assert conn.socket_options is not None", "ground_truth_oracle_lineno": 374, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def _new_conn(self) -> BaseHTTPConnection:\n \"\"\"\n Return a fresh :class:`HTTPConnection`.\n \"\"\"\n self.num_connections += 1\n log.debug(\n \"Starting new HTTP connection (%d): %s:%s\",\n self.num_connections,\n self.host,\n self.port or \"80\",\n )\n\n conn = self.ConnectionCls(\n host=self.host,\n port=self.port,\n timeout=self.timeout.connect_timeout,\n **self.conn_kw,\n )\n return conn", "focal_method_file_path": "src/urllib3/connectionpool.py", "focal_method_start_lineno": 236, "focal_method_end_lineno": 254} {"index": 481, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_proxy_pooling_ext", "test_class_name": "TestHTTPProxyManager", "original_test_prefix": " def test_proxy_pooling_ext(self) -> None:\n with proxy_from_url(self.proxy_url) as http:\n hc1 = http.connection_from_url(self.http_url)\n hc2 = http.connection_from_host(self.http_host, self.http_port)\n hc3 = http.connection_from_url(self.http_url_alt)\n hc4 = http.connection_from_host(self.http_host_alt, self.http_port)\n assert hc1 == hc2\n assert hc2 == hc3\n assert hc3 == hc4\n\n sc1 = http.connection_from_url(self.https_url)\n sc2 = http.connection_from_host(\n self.https_host, self.https_port, scheme=\"https\"\n )\n sc3 = http.connection_from_url(self.https_url_alt)\n sc4 = http.connection_from_host(\n self.https_host_alt, self.https_port, scheme=\"https\"\n )\n assert sc1 == sc2\n assert sc2 != sc3\n assert sc3 == sc4", "test_prefix": " def test_proxy_pooling_ext(self) -> None:\n with proxy_from_url(self.proxy_url) as http:\n hc1 = http.connection_from_url(self.http_url)\n hc2 = http.connection_from_host(self.http_host, self.http_port)\n hc3 = http.connection_from_url(self.http_url_alt)\n hc4 = http.connection_from_host(self.http_host_alt, self.http_port)\n assert hc1 == hc2\n assert hc2 == hc3\n assert hc3 == hc4\n\n sc1 = http.connection_from_url(self.https_url)\n sc2 = http.connection_from_host(\n self.https_host, self.https_port, scheme=\"https\"\n )\n sc3 = http.connection_from_url(self.https_url_alt)\n sc4 = http.connection_from_host(\n self.https_host_alt, self.https_port, scheme=\"https\"\n )\n \n assert sc2 != sc3\n assert sc3 == sc4", "test_prefix_file_path": "test/with_dummyserver/test_proxy_poolmanager.py", "test_prefix_start_lineno": 481, "test_prefix_end_lineno": 501, "test_target": "test/with_dummyserver/test_proxy_poolmanager.py::TestHTTPProxyManager::test_proxy_pooling_ext", "ground_truth_oracle": "assert sc1 == sc2", "ground_truth_oracle_lineno": 499, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def connection_from_host(\n self,\n host: str | None,\n port: int | None = None,\n scheme: str | None = \"http\",\n pool_kwargs: dict[str, typing.Any] | None = None,\n ) -> HTTPConnectionPool:\n if scheme == \"https\":\n return super().connection_from_host(\n host, port, scheme, pool_kwargs=pool_kwargs\n )\n\n return super().connection_from_host(\n self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs # type: ignore[union-attr]\n )", "focal_method_file_path": "src/urllib3/poolmanager.py", "focal_method_start_lineno": 604, "focal_method_end_lineno": 618} {"index": 482, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_contextmanager", "test_class_name": "TestConnectionPool", "original_test_prefix": " def test_contextmanager(self) -> None:\n with connection_from_url(\"http://google.com:80\") as pool:\n # Populate with some connections\n conn1 = pool._get_conn()\n conn2 = pool._get_conn()\n conn3 = pool._get_conn()\n pool._put_conn(conn1)\n pool._put_conn(conn2)\n\n old_pool_queue = pool.pool\n\n assert pool.pool is None\n with pytest.raises(ClosedPoolError):\n pool._get_conn()\n\n pool._put_conn(conn3)\n with pytest.raises(ClosedPoolError):\n pool._get_conn()\n with pytest.raises(Empty):\n assert old_pool_queue is not None\n old_pool_queue.get(block=False)", "test_prefix": " def test_contextmanager(self) -> None:\n with connection_from_url(\"http://google.com:80\") as pool:\n # Populate with some connections\n conn1 = pool._get_conn()\n conn2 = pool._get_conn()\n conn3 = pool._get_conn()\n pool._put_conn(conn1)\n pool._put_conn(conn2)\n\n old_pool_queue = pool.pool\n\n \n with pytest.raises(ClosedPoolError):\n pool._get_conn()\n\n pool._put_conn(conn3)\n with pytest.raises(ClosedPoolError):\n pool._get_conn()\n with pytest.raises(Empty):\n assert old_pool_queue is not None\n old_pool_queue.get(block=False)", "test_prefix_file_path": "test/test_connectionpool.py", "test_prefix_start_lineno": 434, "test_prefix_end_lineno": 454, "test_target": "test/test_connectionpool.py::TestConnectionPool::test_contextmanager", "ground_truth_oracle": "assert pool.pool is None", "ground_truth_oracle_lineno": 445, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection:\n \"\"\"\n Get a connection. Will return a pooled connection if one is available.\n\n If no connections are available and :prop:`.block` is ``False``, then a\n fresh connection is returned.\n\n :param timeout:\n Seconds to wait before giving up and raising\n :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and\n :prop:`.block` is ``True``.\n \"\"\"\n conn = None\n\n if self.pool is None:\n raise ClosedPoolError(self, \"Pool is closed.\")\n\n try:\n conn = self.pool.get(block=self.block, timeout=timeout)\n\n except AttributeError: # self.pool is None\n raise ClosedPoolError(self, \"Pool is closed.\") from None # Defensive:\n\n except queue.Empty:\n if self.block:\n raise EmptyPoolError(\n self,\n \"Pool is empty and a new connection can't be opened due to blocking mode.\",\n ) from None\n pass # Oh well, we'll create a new connection then\n\n # If this is a persistent connection, check if it got disconnected\n if conn and is_connection_dropped(conn):\n log.debug(\"Resetting dropped connection: %s\", self.host)\n conn.close()\n\n return conn or self._new_conn()", "focal_method_file_path": "src/urllib3/connectionpool.py", "focal_method_start_lineno": 256, "focal_method_end_lineno": 292} {"index": 483, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_has_ipv6_disabled_on_compile", "test_class_name": "TestUtil", "original_test_prefix": " def test_has_ipv6_disabled_on_compile(self) -> None:\n with patch(\"socket.has_ipv6\", False):\n assert not _has_ipv6(\"::1\")", "test_prefix": " def test_has_ipv6_disabled_on_compile(self) -> None:\n with patch(\"socket.has_ipv6\", False):\n ", "test_prefix_file_path": "test/test_util.py", "test_prefix_start_lineno": 776, "test_prefix_end_lineno": 778, "test_target": "test/test_util.py::TestUtil::test_has_ipv6_disabled_on_compile", "ground_truth_oracle": "assert not _has_ipv6(\"::1\")", "ground_truth_oracle_lineno": 778, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _has_ipv6(host: str) -> bool:\n \"\"\"Returns True if the system can bind an IPv6 address.\"\"\"\n sock = None\n has_ipv6 = False\n\n if socket.has_ipv6:\n # has_ipv6 returns true if cPython was compiled with IPv6 support.\n # It does not tell us if the system has IPv6 support enabled. To\n # determine that we must bind to an IPv6 address.\n # https://github.com/urllib3/urllib3/pull/611\n # https://bugs.python.org/issue658327\n try:\n sock = socket.socket(socket.AF_INET6)\n sock.bind((host, 0))\n has_ipv6 = True\n except Exception:\n pass\n\n if sock:\n sock.close()\n return has_ipv6", "focal_method_file_path": "src/urllib3/util/connection.py", "focal_method_start_lineno": 114, "focal_method_end_lineno": 134} {"index": 484, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_request_fields", "test_class_name": "TestMultipartEncoding", "original_test_prefix": " def test_request_fields(self) -> None:\n fields = [\n RequestField(\n \"k\",\n b\"v\",\n filename=\"somefile.txt\",\n headers={\"Content-Type\": \"image/jpeg\"},\n )\n ]\n\n encoded, content_type = encode_multipart_formdata(fields, boundary=BOUNDARY)\n expected = (\n b\"--\" + BOUNDARY_BYTES + b\"\\r\\n\"\n b\"Content-Type: image/jpeg\\r\\n\"\n b\"\\r\\n\"\n b\"v\\r\\n\"\n b\"--\" + BOUNDARY_BYTES + b\"--\\r\\n\"\n )\n\n assert encoded == expected", "test_prefix": " def test_request_fields(self) -> None:\n fields = [\n RequestField(\n \"k\",\n b\"v\",\n filename=\"somefile.txt\",\n headers={\"Content-Type\": \"image/jpeg\"},\n )\n ]\n\n encoded, content_type = encode_multipart_formdata(fields, boundary=BOUNDARY)\n expected = (\n b\"--\" + BOUNDARY_BYTES + b\"\\r\\n\"\n b\"Content-Type: image/jpeg\\r\\n\"\n b\"\\r\\n\"\n b\"v\\r\\n\"\n b\"--\" + BOUNDARY_BYTES + b\"--\\r\\n\"\n )\n\n ", "test_prefix_file_path": "test/test_filepost.py", "test_prefix_start_lineno": 97, "test_prefix_end_lineno": 116, "test_target": "test/test_filepost.py::TestMultipartEncoding::test_request_fields", "ground_truth_oracle": "assert encoded == expected", "ground_truth_oracle_lineno": 116, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def encode_multipart_formdata(\n fields: _TYPE_FIELDS, boundary: str | None = None\n) -> tuple[bytes, str]:\n \"\"\"\n Encode a dictionary of ``fields`` using the multipart/form-data MIME format.\n\n :param fields:\n Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).\n Values are processed by :func:`urllib3.fields.RequestField.from_tuples`.\n\n :param boundary:\n If not specified, then a random boundary will be generated using\n :func:`urllib3.filepost.choose_boundary`.\n \"\"\"\n body = BytesIO()\n if boundary is None:\n boundary = choose_boundary()\n\n for field in iter_field_objects(fields):\n body.write(f\"--{boundary}\\r\\n\".encode(\"latin-1\"))\n\n writer(body).write(field.render_headers())\n data = field.data\n\n if isinstance(data, int):\n data = str(data) # Backwards compatibility\n\n if isinstance(data, str):\n writer(body).write(data)\n else:\n body.write(data)\n\n body.write(b\"\\r\\n\")\n\n body.write(f\"--{boundary}--\\r\\n\".encode(\"latin-1\"))\n\n content_type = f\"multipart/form-data; boundary={boundary}\"\n\n return body.getvalue(), content_type", "focal_method_file_path": "src/urllib3/filepost.py", "focal_method_start_lineno": 51, "focal_method_end_lineno": 89} {"index": 485, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_http_connection_from_host_case_insensitive", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_http_connection_from_host_case_insensitive(self) -> None:\n \"\"\"Assert scheme case is ignored when getting the https key class.\"\"\"\n p = PoolManager()\n pool = p.connection_from_host(\"example.com\", scheme=\"http\")\n other_pool = p.connection_from_host(\"EXAMPLE.COM\", scheme=\"HTTP\")\n\n assert 1 == len(p.pools)\n assert pool is other_pool\n assert all(isinstance(key, PoolKey) for key in p.pools.keys())", "test_prefix": " def test_http_connection_from_host_case_insensitive(self) -> None:\n \"\"\"Assert scheme case is ignored when getting the https key class.\"\"\"\n p = PoolManager()\n pool = p.connection_from_host(\"example.com\", scheme=\"http\")\n other_pool = p.connection_from_host(\"EXAMPLE.COM\", scheme=\"HTTP\")\n\n \n assert pool is other_pool\n assert all(isinstance(key, PoolKey) for key in p.pools.keys())", "test_prefix_file_path": "test/test_poolmanager.py", "test_prefix_start_lineno": 230, "test_prefix_end_lineno": 238, "test_target": "test/test_poolmanager.py::TestPoolManager::test_http_connection_from_host_case_insensitive", "ground_truth_oracle": "assert 1 == len(p.pools)", "ground_truth_oracle_lineno": 236, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def connection_from_host(\n self,\n host: str | None,\n port: int | None = None,\n scheme: str | None = \"http\",\n pool_kwargs: dict[str, typing.Any] | None = None,\n ) -> HTTPConnectionPool:\n \"\"\"\n Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme.\n\n If ``port`` isn't given, it will be derived from the ``scheme`` using\n ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is\n provided, it is merged with the instance's ``connection_pool_kw``\n variable and used to create the new connection pool, if one is\n needed.\n \"\"\"\n\n if not host:\n raise LocationValueError(\"No host specified.\")\n\n request_context = self._merge_pool_kwargs(pool_kwargs)\n request_context[\"scheme\"] = scheme or \"http\"\n if not port:\n port = port_by_scheme.get(request_context[\"scheme\"].lower(), 80)\n request_context[\"port\"] = port\n request_context[\"host\"] = host\n\n return self.connection_from_context(request_context)", "focal_method_file_path": "src/urllib3/poolmanager.py", "focal_method_start_lineno": 292, "focal_method_end_lineno": 319} {"index": 486, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_from_tuples_rfc2231", "test_class_name": "TestRequestField", "original_test_prefix": " def test_from_tuples_rfc2231(self) -> None:\n with pytest.deprecated_call(match=r\"urllib3 v2\\.1\\.0\"):\n field = RequestField.from_tuples(\n \"file\", (\"n\u00e4me\", \"data\"), header_formatter=format_header_param_rfc2231\n )\n\n cd = field.headers[\"Content-Disposition\"]\n assert cd == \"form-data; name=\\\"file\\\"; filename*=utf-8''n%C3%A4me\"", "test_prefix": " def test_from_tuples_rfc2231(self) -> None:\n with pytest.deprecated_call(match=r\"urllib3 v2\\.1\\.0\"):\n field = RequestField.from_tuples(\n \"file\", (\"n\u00e4me\", \"data\"), header_formatter=format_header_param_rfc2231\n )\n\n cd = field.headers[\"Content-Disposition\"]\n ", "test_prefix_file_path": "test/test_fields.py", "test_prefix_start_lineno": 113, "test_prefix_end_lineno": 120, "test_target": "test/test_fields.py::TestRequestField::test_from_tuples_rfc2231", "ground_truth_oracle": "assert cd == \"form-data; name=\\\"file\\\"; filename*=utf-8''n%C3%A4me\"", "ground_truth_oracle_lineno": 120, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def from_tuples(\n cls,\n fieldname: str,\n value: _TYPE_FIELD_VALUE_TUPLE,\n header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None,\n ) -> RequestField:\n \"\"\"\n A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.\n\n Supports constructing :class:`~urllib3.fields.RequestField` from\n parameter of key/value strings AND key/filetuple. A filetuple is a\n (filename, data, MIME type) tuple where the MIME type is optional.\n For example::\n\n 'foo': 'bar',\n 'fakefile': ('foofile.txt', 'contents of foofile'),\n 'realfile': ('barfile.txt', open('realfile').read()),\n 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),\n 'nonamefile': 'contents of nonamefile field',\n\n Field names and filenames must be unicode.\n \"\"\"\n filename: str | None\n content_type: str | None\n data: _TYPE_FIELD_VALUE\n\n if isinstance(value, tuple):\n if len(value) == 3:\n filename, data, content_type = value\n else:\n filename, data = value\n content_type = guess_content_type(filename)\n else:\n filename = None\n content_type = None\n data = value\n\n request_param = cls(\n fieldname, data, filename=filename, header_formatter=header_formatter\n )\n request_param.make_multipart(content_type=content_type)\n\n return request_param", "focal_method_file_path": "src/urllib3/fields.py", "focal_method_start_lineno": 199, "focal_method_end_lineno": 242} {"index": 487, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_reference_read1", "test_class_name": "TestResponse", "original_test_prefix": " def test_reference_read1(self) -> None:\n fp = BytesIO(b\"foobar\")\n r = HTTPResponse(fp, preload_content=False)\n\n assert r.read1(0) == b\"\"\n assert r.read1(1) == b\"f\"\n assert r.read1(2) == b\"oo\"\n assert r.read1() == b\"bar\"\n assert r.read1() == b\"\"", "test_prefix": " def test_reference_read1(self) -> None:\n fp = BytesIO(b\"foobar\")\n r = HTTPResponse(fp, preload_content=False)\n\n assert r.read1(0) == b\"\"\n assert r.read1(1) == b\"f\"\n \n assert r.read1() == b\"bar\"\n assert r.read1() == b\"\"", "test_prefix_file_path": "test/test_response.py", "test_prefix_start_lineno": 243, "test_prefix_end_lineno": 251, "test_target": "test/test_response.py::TestResponse::test_reference_read1", "ground_truth_oracle": "assert r.read1(2) == b\"oo\"", "ground_truth_oracle_lineno": 249, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def read1(\n self,\n amt: int | None = None,\n decode_content: bool | None = None,\n ) -> bytes:\n \"\"\"\n Similar to ``http.client.HTTPResponse.read1`` and documented\n in :meth:`io.BufferedReader.read1`, but with an additional parameter:\n ``decode_content``.\n\n :param amt:\n How much of the content to read.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n \"\"\"\n if decode_content is None:\n decode_content = self.decode_content\n if amt and amt < 0:\n # Negative numbers and `None` should be treated the same.\n amt = None\n # try and respond without going to the network\n if self._has_decoded_content:\n if not decode_content:\n raise RuntimeError(\n \"Calling read1(decode_content=False) is not supported after \"\n \"read1(decode_content=True) was called.\"\n )\n if len(self._decoded_buffer) > 0:\n if amt is None:\n return self._decoded_buffer.get_all()\n return self._decoded_buffer.get(amt)\n if amt == 0:\n return b\"\"\n\n # FIXME, this method's type doesn't say returning None is possible\n data = self._raw_read(amt, read1=True)\n if not decode_content or data is None:\n return data\n\n self._init_decoder()\n while True:\n flush_decoder = not data\n decoded_data = self._decode(data, decode_content, flush_decoder)\n self._decoded_buffer.put(decoded_data)\n if decoded_data or flush_decoder:\n break\n data = self._raw_read(8192, read1=True)\n\n if amt is None:\n return self._decoded_buffer.get_all()\n return self._decoded_buffer.get(amt)", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 1015, "focal_method_end_lineno": 1067} {"index": 488, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_deflate_streaming", "test_class_name": "TestResponse", "original_test_prefix": " def test_deflate_streaming(self) -> None:\n data = zlib.compress(b\"foo\")\n\n fp = BytesIO(data)\n resp = HTTPResponse(\n fp, headers={\"content-encoding\": \"deflate\"}, preload_content=False\n )\n stream = resp.stream(2)\n\n assert next(stream) == b\"fo\"\n assert next(stream) == b\"o\"\n with pytest.raises(StopIteration):\n next(stream)", "test_prefix": " def test_deflate_streaming(self) -> None:\n data = zlib.compress(b\"foo\")\n\n fp = BytesIO(data)\n resp = HTTPResponse(\n fp, headers={\"content-encoding\": \"deflate\"}, preload_content=False\n )\n stream = resp.stream(2)\n\n assert next(stream) == b\"fo\"\n \n with pytest.raises(StopIteration):\n next(stream)", "test_prefix_file_path": "test/test_response.py", "test_prefix_start_lineno": 1053, "test_prefix_end_lineno": 1065, "test_target": "test/test_response.py::TestResponse::test_deflate_streaming", "ground_truth_oracle": "assert next(stream) == b\"o\"", "ground_truth_oracle_lineno": 1063, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def stream(\n self, amt: int | None = 2**16, decode_content: bool | None = None\n ) -> typing.Generator[bytes]:\n \"\"\"\n A generator wrapper for the read() method. A call will block until\n ``amt`` bytes have been read from the connection or until the\n connection is closed.\n\n :param amt:\n How much of the content to read. The generator will return up to\n much data per iteration, but may return less. This is particularly\n likely when using compressed data. However, the empty string will\n never be returned.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n \"\"\"\n if self.chunked and self.supports_chunked_reads():\n yield from self.read_chunked(amt, decode_content=decode_content)\n else:\n while not is_fp_closed(self._fp) or len(self._decoded_buffer) > 0:\n data = self.read(amt=amt, decode_content=decode_content)\n\n if data:\n yield data", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 1069, "focal_method_end_lineno": 1094} {"index": 489, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_decoding_read1", "test_class_name": "TestResponse", "original_test_prefix": " def test_decoding_read1(self) -> None:\n data = zlib.compress(b\"foobar\")\n\n fp = BytesIO(data)\n r = HTTPResponse(\n fp, headers={\"content-encoding\": \"deflate\"}, preload_content=False\n )\n\n assert r.read1(1) == b\"f\"\n assert r.read1(2) == b\"oo\"\n assert r.read1() == b\"bar\"\n assert r.read1() == b\"\"", "test_prefix": " def test_decoding_read1(self) -> None:\n data = zlib.compress(b\"foobar\")\n\n fp = BytesIO(data)\n r = HTTPResponse(\n fp, headers={\"content-encoding\": \"deflate\"}, preload_content=False\n )\n\n assert r.read1(1) == b\"f\"\n \n assert r.read1() == b\"bar\"\n assert r.read1() == b\"\"", "test_prefix_file_path": "test/test_response.py", "test_prefix_start_lineno": 271, "test_prefix_end_lineno": 282, "test_target": "test/test_response.py::TestResponse::test_decoding_read1", "ground_truth_oracle": "assert r.read1(2) == b\"oo\"", "ground_truth_oracle_lineno": 280, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def read1(\n self,\n amt: int | None = None,\n decode_content: bool | None = None,\n ) -> bytes:\n \"\"\"\n Similar to ``http.client.HTTPResponse.read1`` and documented\n in :meth:`io.BufferedReader.read1`, but with an additional parameter:\n ``decode_content``.\n\n :param amt:\n How much of the content to read.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n \"\"\"\n if decode_content is None:\n decode_content = self.decode_content\n if amt and amt < 0:\n # Negative numbers and `None` should be treated the same.\n amt = None\n # try and respond without going to the network\n if self._has_decoded_content:\n if not decode_content:\n raise RuntimeError(\n \"Calling read1(decode_content=False) is not supported after \"\n \"read1(decode_content=True) was called.\"\n )\n if len(self._decoded_buffer) > 0:\n if amt is None:\n return self._decoded_buffer.get_all()\n return self._decoded_buffer.get(amt)\n if amt == 0:\n return b\"\"\n\n # FIXME, this method's type doesn't say returning None is possible\n data = self._raw_read(amt, read1=True)\n if not decode_content or data is None:\n return data\n\n self._init_decoder()\n while True:\n flush_decoder = not data\n decoded_data = self._decode(data, decode_content, flush_decoder)\n self._decoded_buffer.put(decoded_data)\n if decoded_data or flush_decoder:\n break\n data = self._raw_read(8192, read1=True)\n\n if amt is None:\n return self._decoded_buffer.get_all()\n return self._decoded_buffer.get(amt)", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 1015, "focal_method_end_lineno": 1067} {"index": 490, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_reference_read1_nodecode", "test_class_name": "TestResponse", "original_test_prefix": " def test_reference_read1_nodecode(self) -> None:\n fp = BytesIO(b\"foobar\")\n r = HTTPResponse(fp, preload_content=False, decode_content=False)\n\n assert r.read1(0) == b\"\"\n assert r.read1(1) == b\"f\"\n assert r.read1(2) == b\"oo\"\n assert r.read1() == b\"bar\"\n assert r.read1() == b\"\"", "test_prefix": " def test_reference_read1_nodecode(self) -> None:\n fp = BytesIO(b\"foobar\")\n r = HTTPResponse(fp, preload_content=False, decode_content=False)\n\n assert r.read1(0) == b\"\"\n assert r.read1(1) == b\"f\"\n assert r.read1(2) == b\"oo\"\n assert r.read1() == b\"bar\"\n ", "test_prefix_file_path": "test/test_response.py", "test_prefix_start_lineno": 261, "test_prefix_end_lineno": 269, "test_target": "test/test_response.py::TestResponse::test_reference_read1_nodecode", "ground_truth_oracle": "assert r.read1() == b\"\"", "ground_truth_oracle_lineno": 269, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def read1(\n self,\n amt: int | None = None,\n decode_content: bool | None = None,\n ) -> bytes:\n \"\"\"\n Similar to ``http.client.HTTPResponse.read1`` and documented\n in :meth:`io.BufferedReader.read1`, but with an additional parameter:\n ``decode_content``.\n\n :param amt:\n How much of the content to read.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n \"\"\"\n if decode_content is None:\n decode_content = self.decode_content\n if amt and amt < 0:\n # Negative numbers and `None` should be treated the same.\n amt = None\n # try and respond without going to the network\n if self._has_decoded_content:\n if not decode_content:\n raise RuntimeError(\n \"Calling read1(decode_content=False) is not supported after \"\n \"read1(decode_content=True) was called.\"\n )\n if len(self._decoded_buffer) > 0:\n if amt is None:\n return self._decoded_buffer.get_all()\n return self._decoded_buffer.get(amt)\n if amt == 0:\n return b\"\"\n\n # FIXME, this method's type doesn't say returning None is possible\n data = self._raw_read(amt, read1=True)\n if not decode_content or data is None:\n return data\n\n self._init_decoder()\n while True:\n flush_decoder = not data\n decoded_data = self._decode(data, decode_content, flush_decoder)\n self._decoded_buffer.put(decoded_data)\n if decoded_data or flush_decoder:\n break\n data = self._raw_read(8192, read1=True)\n\n if amt is None:\n return self._decoded_buffer.get_all()\n return self._decoded_buffer.get(amt)", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 1015, "focal_method_end_lineno": 1067} {"index": 491, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_mock_transfer_encoding_chunked", "test_class_name": "TestResponse", "original_test_prefix": " def test_mock_transfer_encoding_chunked(self) -> None:\n stream = [b\"fo\", b\"o\", b\"bar\"]\n fp = MockChunkedEncodingResponse(stream)\n r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]\n r.fp = fp # type: ignore[assignment]\n resp = HTTPResponse(\n r, preload_content=False, headers={\"transfer-encoding\": \"chunked\"}\n )\n\n for i, c in enumerate(resp.stream()):\n assert c == stream[i]", "test_prefix": " def test_mock_transfer_encoding_chunked(self) -> None:\n stream = [b\"fo\", b\"o\", b\"bar\"]\n fp = MockChunkedEncodingResponse(stream)\n r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]\n r.fp = fp # type: ignore[assignment]\n resp = HTTPResponse(\n r, preload_content=False, headers={\"transfer-encoding\": \"chunked\"}\n )\n\n for i, c in enumerate(resp.stream()):\n ", "test_prefix_file_path": "test/test_response.py", "test_prefix_start_lineno": 1234, "test_prefix_end_lineno": 1244, "test_target": "test/test_response.py::TestResponse::test_mock_transfer_encoding_chunked", "ground_truth_oracle": "assert c == stream[i]", "ground_truth_oracle_lineno": 1244, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def stream(\n self, amt: int | None = 2**16, decode_content: bool | None = None\n ) -> typing.Generator[bytes]:\n \"\"\"\n A generator wrapper for the read() method. A call will block until\n ``amt`` bytes have been read from the connection or until the\n connection is closed.\n\n :param amt:\n How much of the content to read. The generator will return up to\n much data per iteration, but may return less. This is particularly\n likely when using compressed data. However, the empty string will\n never be returned.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n \"\"\"\n if self.chunked and self.supports_chunked_reads():\n yield from self.read_chunked(amt, decode_content=decode_content)\n else:\n while not is_fp_closed(self._fp) or len(self._decoded_buffer) > 0:\n data = self.read(amt=amt, decode_content=decode_content)\n\n if data:\n yield data", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 1069, "focal_method_end_lineno": 1094} {"index": 492, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_ssl_object_attributes", "test_class_name": "SingleTLSLayerTestCase", "original_test_prefix": " @pytest.mark.timeout(PER_TEST_TIMEOUT)\n def test_ssl_object_attributes(self) -> None:\n \"\"\"Ensures common ssl attributes are exposed\"\"\"\n self.start_dummy_server()\n\n sock = socket.create_connection((self.host, self.port))\n with SSLTransport(\n sock, self.client_context, server_hostname=\"localhost\"\n ) as ssock:\n cipher = ssock.cipher()\n assert type(cipher) is tuple\n\n # No chosen protocol.\n assert ssock.selected_alpn_protocol() is None\n\n shared_ciphers = ssock.shared_ciphers()\n # SSLContext.shared_ciphers() changed behavior completely in a patch version.\n # See: https://github.com/python/cpython/issues/96931\n assert shared_ciphers is None or (\n type(shared_ciphers) is list and len(shared_ciphers) > 0\n )\n\n assert ssock.compression() is None\n\n validate_peercert(ssock)\n\n ssock.send(sample_request())\n response = consume_socket(ssock)\n validate_response(response)", "test_prefix": " @pytest.mark.timeout(PER_TEST_TIMEOUT)\n def test_ssl_object_attributes(self) -> None:\n \"\"\"Ensures common ssl attributes are exposed\"\"\"\n self.start_dummy_server()\n\n sock = socket.create_connection((self.host, self.port))\n with SSLTransport(\n sock, self.client_context, server_hostname=\"localhost\"\n ) as ssock:\n cipher = ssock.cipher()\n assert type(cipher) is tuple\n\n # No chosen protocol.\n assert ssock.selected_alpn_protocol() is None\n\n shared_ciphers = ssock.shared_ciphers()\n # SSLContext.shared_ciphers() changed behavior completely in a patch version.\n # See: https://github.com/python/cpython/issues/96931\n assert shared_ciphers is None or (\n type(shared_ciphers) is list and len(shared_ciphers) > 0\n )\n\n \n\n validate_peercert(ssock)\n\n ssock.send(sample_request())\n response = consume_socket(ssock)\n validate_response(response)", "test_prefix_file_path": "test/test_ssltransport.py", "test_prefix_start_lineno": 217, "test_prefix_end_lineno": 245, "test_target": "test/test_ssltransport.py::SingleTLSLayerTestCase::test_ssl_object_attributes", "ground_truth_oracle": "assert ssock.compression() is None", "ground_truth_oracle_lineno": 239, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def compression(self) -> str | None:\n return self.sslobj.compression()", "focal_method_file_path": "src/urllib3/util/ssltransport.py", "focal_method_start_lineno": 197, "focal_method_end_lineno": 198} {"index": 493, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_from_tuples", "test_class_name": "TestRequestField", "original_test_prefix": " def test_from_tuples(self) -> None:\n field = RequestField.from_tuples(\"file\", (\"\u30b9\u30ad\u30fc\u65c5\u884c.txt\", \"data\"))\n cd = field.headers[\"Content-Disposition\"]\n assert cd == 'form-data; name=\"file\"; filename=\"\u30b9\u30ad\u30fc\u65c5\u884c.txt\"'", "test_prefix": " def test_from_tuples(self) -> None:\n field = RequestField.from_tuples(\"file\", (\"\u30b9\u30ad\u30fc\u65c5\u884c.txt\", \"data\"))\n cd = field.headers[\"Content-Disposition\"]\n ", "test_prefix_file_path": "test/test_fields.py", "test_prefix_start_lineno": 108, "test_prefix_end_lineno": 111, "test_target": "test/test_fields.py::TestRequestField::test_from_tuples", "ground_truth_oracle": "assert cd == 'form-data; name=\"file\"; filename=\"\u30b9\u30ad\u30fc\u65c5\u884c.txt\"'", "ground_truth_oracle_lineno": 111, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @classmethod\n def from_tuples(\n cls,\n fieldname: str,\n value: _TYPE_FIELD_VALUE_TUPLE,\n header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None,\n ) -> RequestField:\n \"\"\"\n A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.\n\n Supports constructing :class:`~urllib3.fields.RequestField` from\n parameter of key/value strings AND key/filetuple. A filetuple is a\n (filename, data, MIME type) tuple where the MIME type is optional.\n For example::\n\n 'foo': 'bar',\n 'fakefile': ('foofile.txt', 'contents of foofile'),\n 'realfile': ('barfile.txt', open('realfile').read()),\n 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),\n 'nonamefile': 'contents of nonamefile field',\n\n Field names and filenames must be unicode.\n \"\"\"\n filename: str | None\n content_type: str | None\n data: _TYPE_FIELD_VALUE\n\n if isinstance(value, tuple):\n if len(value) == 3:\n filename, data, content_type = value\n else:\n filename, data = value\n content_type = guess_content_type(filename)\n else:\n filename = None\n content_type = None\n data = value\n\n request_param = cls(\n fieldname, data, filename=filename, header_formatter=header_formatter\n )\n request_param.make_multipart(content_type=content_type)\n\n return request_param", "focal_method_file_path": "src/urllib3/fields.py", "focal_method_start_lineno": 199, "focal_method_end_lineno": 242} {"index": 494, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_retry_other", "test_class_name": "TestRetry", "original_test_prefix": " def test_retry_other(self) -> None:\n \"\"\"If an unexpected error is raised, should retry other times\"\"\"\n other_error = SSLError()\n retry = Retry(connect=1)\n retry = retry.increment(error=other_error)\n retry = retry.increment(error=other_error)\n assert not retry.is_exhausted()\n\n retry = Retry(other=1)\n retry = retry.increment(error=other_error)\n with pytest.raises(MaxRetryError) as e:\n retry.increment(error=other_error)\n assert e.value.reason == other_error", "test_prefix": " def test_retry_other(self) -> None:\n \"\"\"If an unexpected error is raised, should retry other times\"\"\"\n other_error = SSLError()\n retry = Retry(connect=1)\n retry = retry.increment(error=other_error)\n retry = retry.increment(error=other_error)\n \n\n retry = Retry(other=1)\n retry = retry.increment(error=other_error)\n with pytest.raises(MaxRetryError) as e:\n retry.increment(error=other_error)\n assert e.value.reason == other_error", "test_prefix_file_path": "test/test_retry.py", "test_prefix_start_lineno": 103, "test_prefix_end_lineno": 115, "test_target": "test/test_retry.py::TestRetry::test_retry_other", "ground_truth_oracle": "assert not retry.is_exhausted()", "ground_truth_oracle_lineno": 109, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def is_exhausted(self) -> bool:\n \"\"\"Are we out of retries?\"\"\"\n retry_counts = [\n x\n for x in (\n self.total,\n self.connect,\n self.read,\n self.redirect,\n self.status,\n self.other,\n )\n if x\n ]\n if not retry_counts:\n return False\n\n return min(retry_counts) < 0", "focal_method_file_path": "src/urllib3/util/retry.py", "focal_method_start_lineno": 409, "focal_method_end_lineno": 426} {"index": 495, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_dnsname_to_stdlib_leading_period", "test_class_name": "TestPyOpenSSLHelpers", "original_test_prefix": " def test_dnsname_to_stdlib_leading_period(self) -> None:\n \"\"\"\n If there is a . in front of the domain name we correctly encode it.\n \"\"\"\n name = \".\u0909\u0926\u093e\u0939\u0930\u0923.\u092a\u0930\u0940\u0915\"\n expected_result = \".xn--p1b6ci4b4b3a.xn--11b5bs8d\"\n\n assert _dnsname_to_stdlib(name) == expected_result", "test_prefix": " def test_dnsname_to_stdlib_leading_period(self) -> None:\n \"\"\"\n If there is a . in front of the domain name we correctly encode it.\n \"\"\"\n name = \".\u0909\u0926\u093e\u0939\u0930\u0923.\u092a\u0930\u0940\u0915\"\n expected_result = \".xn--p1b6ci4b4b3a.xn--11b5bs8d\"\n\n ", "test_prefix_file_path": "test/contrib/test_pyopenssl.py", "test_prefix_start_lineno": 72, "test_prefix_end_lineno": 79, "test_target": "test/contrib/test_pyopenssl.py::TestPyOpenSSLHelpers::test_dnsname_to_stdlib_leading_period", "ground_truth_oracle": "assert _dnsname_to_stdlib(name) == expected_result", "ground_truth_oracle_lineno": 79, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": "def _dnsname_to_stdlib(name: str) -> str | None:\n \"\"\"\n Converts a dNSName SubjectAlternativeName field to the form used by the\n standard library on the given Python version.\n\n Cryptography produces a dNSName as a unicode string that was idna-decoded\n from ASCII bytes. We need to idna-encode that string to get it back, and\n then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib\n uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).\n\n If the name cannot be idna-encoded then we return None signalling that\n the name given should be skipped.\n \"\"\"\n\n def idna_encode(name: str) -> bytes | None:\n \"\"\"\n Borrowed wholesale from the Python Cryptography Project. It turns out\n that we can't just safely call `idna.encode`: it can explode for\n wildcard names. This avoids that problem.\n \"\"\"\n import idna\n\n try:\n for prefix in [\"*.\", \".\"]:\n if name.startswith(prefix):\n name = name[len(prefix) :]\n return prefix.encode(\"ascii\") + idna.encode(name)\n return idna.encode(name)\n except idna.core.IDNAError:\n return None\n\n # Don't send IPv6 addresses through the IDNA encoder.\n if \":\" in name:\n return name\n\n encoded_name = idna_encode(name)\n if encoded_name is None:\n return None\n return encoded_name.decode(\"utf-8\")", "focal_method_file_path": "src/urllib3/contrib/pyopenssl.py", "focal_method_start_lineno": 185, "focal_method_end_lineno": 223} {"index": 496, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_update", "test_class_name": "TestHTTPHeaderDict", "original_test_prefix": " def test_update(self, d: HTTPHeaderDict) -> None:\n d.update(dict(Cookie=\"foo\"))\n assert d[\"cookie\"] == \"foo\"\n d.update(dict(cookie=\"with, comma\"))\n assert d.getlist(\"cookie\") == [\"with, comma\"]", "test_prefix": " def test_update(self, d: HTTPHeaderDict) -> None:\n d.update(dict(Cookie=\"foo\"))\n assert d[\"cookie\"] == \"foo\"\n d.update(dict(cookie=\"with, comma\"))\n ", "test_prefix_file_path": "test/test_collections.py", "test_prefix_start_lineno": 222, "test_prefix_end_lineno": 226, "test_target": "test/test_collections.py::TestHTTPHeaderDict::test_update", "ground_truth_oracle": "assert d.getlist(\"cookie\") == [\"with, comma\"]", "ground_truth_oracle_lineno": 226, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " @typing.overload\n def getlist(self, key: str) -> list[str]: ...", "focal_method_file_path": "src/urllib3/_collections.py", "focal_method_start_lineno": 368, "focal_method_end_lineno": 369} {"index": 497, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_http_connection_from_context_case_insensitive", "test_class_name": "TestPoolManager", "original_test_prefix": " def test_http_connection_from_context_case_insensitive(self) -> None:\n \"\"\"Assert scheme case is ignored when getting the https key class.\"\"\"\n p = PoolManager()\n context = {\"scheme\": \"http\", \"host\": \"example.com\", \"port\": \"8080\"}\n other_context = {\"scheme\": \"HTTP\", \"host\": \"EXAMPLE.COM\", \"port\": \"8080\"}\n pool = p.connection_from_context(context)\n other_pool = p.connection_from_context(other_context)\n\n assert 1 == len(p.pools)\n assert pool is other_pool\n assert all(isinstance(key, PoolKey) for key in p.pools.keys())", "test_prefix": " def test_http_connection_from_context_case_insensitive(self) -> None:\n \"\"\"Assert scheme case is ignored when getting the https key class.\"\"\"\n p = PoolManager()\n context = {\"scheme\": \"http\", \"host\": \"example.com\", \"port\": \"8080\"}\n other_context = {\"scheme\": \"HTTP\", \"host\": \"EXAMPLE.COM\", \"port\": \"8080\"}\n pool = p.connection_from_context(context)\n other_pool = p.connection_from_context(other_context)\n\n assert 1 == len(p.pools)\n assert pool is other_pool\n ", "test_prefix_file_path": "test/test_poolmanager.py", "test_prefix_start_lineno": 250, "test_prefix_end_lineno": 260, "test_target": "test/test_poolmanager.py::TestPoolManager::test_http_connection_from_context_case_insensitive", "ground_truth_oracle": "assert all(isinstance(key, PoolKey) for key in p.pools.keys())", "ground_truth_oracle_lineno": 260, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def keys(self) -> set[_KT]: # type: ignore[override]\n with self.lock:\n return set(self._container.keys())", "focal_method_file_path": "src/urllib3/_collections.py", "focal_method_start_lineno": 151, "focal_method_end_lineno": 153} {"index": 498, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_deflate2_streaming", "test_class_name": "TestResponse", "original_test_prefix": " def test_deflate2_streaming(self) -> None:\n compress = zlib.compressobj(6, zlib.DEFLATED, -zlib.MAX_WBITS)\n data = compress.compress(b\"foo\")\n data += compress.flush()\n\n fp = BytesIO(data)\n resp = HTTPResponse(\n fp, headers={\"content-encoding\": \"deflate\"}, preload_content=False\n )\n stream = resp.stream(2)\n\n assert next(stream) == b\"fo\"\n assert next(stream) == b\"o\"\n with pytest.raises(StopIteration):\n next(stream)", "test_prefix": " def test_deflate2_streaming(self) -> None:\n compress = zlib.compressobj(6, zlib.DEFLATED, -zlib.MAX_WBITS)\n data = compress.compress(b\"foo\")\n data += compress.flush()\n\n fp = BytesIO(data)\n resp = HTTPResponse(\n fp, headers={\"content-encoding\": \"deflate\"}, preload_content=False\n )\n stream = resp.stream(2)\n\n \n assert next(stream) == b\"o\"\n with pytest.raises(StopIteration):\n next(stream)", "test_prefix_file_path": "test/test_response.py", "test_prefix_start_lineno": 1067, "test_prefix_end_lineno": 1081, "test_target": "test/test_response.py::TestResponse::test_deflate2_streaming", "ground_truth_oracle": "assert next(stream) == b\"fo\"", "ground_truth_oracle_lineno": 1078, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def stream(\n self, amt: int | None = 2**16, decode_content: bool | None = None\n ) -> typing.Generator[bytes]:\n \"\"\"\n A generator wrapper for the read() method. A call will block until\n ``amt`` bytes have been read from the connection or until the\n connection is closed.\n\n :param amt:\n How much of the content to read. The generator will return up to\n much data per iteration, but may return less. This is particularly\n likely when using compressed data. However, the empty string will\n never be returned.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n \"\"\"\n if self.chunked and self.supports_chunked_reads():\n yield from self.read_chunked(amt, decode_content=decode_content)\n else:\n while not is_fp_closed(self._fp) or len(self._decoded_buffer) > 0:\n data = self.read(amt=amt, decode_content=decode_content)\n\n if data:\n yield data", "focal_method_file_path": "src/urllib3/response.py", "focal_method_start_lineno": 1069, "focal_method_end_lineno": 1094} {"index": 499, "repo_name": "urllib3", "github": "https://github.com/urllib3/urllib3.git", "version": "2.5.0", "install_cmd": "python -m venv .venv\nsource .venv/bin/activate\nuv pip install -e .\nuv pip install --group dev\nuv pip install ipdb", "activate_cmd": "source .venv/bin/activate\nhash -r", "test_function_name": "test_socket_object_attributes", "test_class_name": "SingleTLSLayerTestCase", "original_test_prefix": " @pytest.mark.timeout(PER_TEST_TIMEOUT)\n def test_socket_object_attributes(self) -> None:\n \"\"\"Ensures common socket attributes are exposed\"\"\"\n self.start_dummy_server()\n\n sock = socket.create_connection((self.host, self.port))\n with SSLTransport(\n sock, self.client_context, server_hostname=\"localhost\"\n ) as ssock:\n assert ssock.fileno() is not None\n test_timeout = 10\n ssock.settimeout(test_timeout)\n assert ssock.gettimeout() == test_timeout\n assert ssock.socket.gettimeout() == test_timeout\n\n ssock.send(sample_request())\n response = consume_socket(ssock)\n validate_response(response)", "test_prefix": " @pytest.mark.timeout(PER_TEST_TIMEOUT)\n def test_socket_object_attributes(self) -> None:\n \"\"\"Ensures common socket attributes are exposed\"\"\"\n self.start_dummy_server()\n\n sock = socket.create_connection((self.host, self.port))\n with SSLTransport(\n sock, self.client_context, server_hostname=\"localhost\"\n ) as ssock:\n \n test_timeout = 10\n ssock.settimeout(test_timeout)\n assert ssock.gettimeout() == test_timeout\n assert ssock.socket.gettimeout() == test_timeout\n\n ssock.send(sample_request())\n response = consume_socket(ssock)\n validate_response(response)", "test_prefix_file_path": "test/test_ssltransport.py", "test_prefix_start_lineno": 247, "test_prefix_end_lineno": 264, "test_target": "test/test_ssltransport.py::SingleTLSLayerTestCase::test_socket_object_attributes", "ground_truth_oracle": "assert ssock.fileno() is not None", "ground_truth_oracle_lineno": 256, "test_setup": "", "test_setup_file_path": "", "test_setup_start_lineno": -1, "test_setup_end_lineno": -1, "focal_method": " def fileno(self) -> int:\n return self.socket.fileno()", "focal_method_file_path": "src/urllib3/util/ssltransport.py", "focal_method_start_lineno": 78, "focal_method_end_lineno": 79}