Dataset Viewer
Auto-converted to Parquet Duplicate
index
int64
0
499
repo_name
stringclasses
9 values
github
stringclasses
9 values
version
stringclasses
9 values
install_cmd
stringclasses
8 values
activate_cmd
stringclasses
1 value
test_function_name
stringlengths
7
75
test_class_name
stringclasses
99 values
original_test_prefix
stringlengths
78
2.28k
test_prefix
stringlengths
43
2.25k
test_prefix_file_path
stringlengths
17
54
test_prefix_start_lineno
int64
4
6.21k
test_prefix_end_lineno
int64
8
6.23k
test_target
stringlengths
27
112
ground_truth_oracle
stringlengths
10
109
ground_truth_oracle_lineno
int64
5
6.23k
test_setup
stringclasses
3 values
test_setup_file_path
stringclasses
2 values
test_setup_start_lineno
int64
-1
55
test_setup_end_lineno
int64
-1
59
focal_method
stringlengths
50
2.91k
focal_method_file_path
stringlengths
11
56
focal_method_start_lineno
int64
4
2.63k
focal_method_end_lineno
int64
10
2.63k
0
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_pep_572_version_detection
BlackTestCase
def test_pep_572_version_detection(self) -> None: source, _ = read_data("cases", "pep_572") root = black.lib2to3_parse(source) features = black.get_features_used(root) self.assertIn(black.Feature.ASSIGNMENT_EXPRESSIONS, features) versions = black.detect_target_versions(root) self.assertIn(black.TargetVersion.PY38, versions)
def test_pep_572_version_detection(self) -> None: source, _ = read_data("cases", "pep_572") root = black.lib2to3_parse(source) features = black.get_features_used(root) self.assertIn(black.Feature.ASSIGNMENT_EXPRESSIONS, features) versions = black.detect_target_versions(root) <AssertPlaceHolder>
tests/test_black.py
243
249
tests/test_black.py::BlackTestCase::test_pep_572_version_detection
self.assertIn(black.TargetVersion.PY38, versions)
249
-1
-1
def detect_target_versions( node: Node, *, future_imports: Optional[set[str]] = None ) -> set[TargetVersion]: """Detect the version to target based on the nodes used.""" features = get_features_used(node, future_imports=future_imports) return { version for version in TargetVersion if features <= VERSION_TO_FEATURES[version] }
src/black/__init__.py
1,510
1,517
1
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_detect_pos_only_arguments
BlackTestCase
def test_detect_pos_only_arguments(self) -> None: source, _ = read_data("cases", "pep_570") root = black.lib2to3_parse(source) features = black.get_features_used(root) self.assertIn(black.Feature.POS_ONLY_ARGUMENTS, features) versions = black.detect_target_versions(root) self.assertIn(black.TargetVersion.PY38, versions)
def test_detect_pos_only_arguments(self) -> None: source, _ = read_data("cases", "pep_570") root = black.lib2to3_parse(source) features = black.get_features_used(root) self.assertIn(black.Feature.POS_ONLY_ARGUMENTS, features) versions = black.detect_target_versions(root) <AssertPlaceHolder>
tests/test_black.py
334
340
tests/test_black.py::BlackTestCase::test_detect_pos_only_arguments
self.assertIn(black.TargetVersion.PY38, versions)
340
-1
-1
def detect_target_versions( node: Node, *, future_imports: Optional[set[str]] = None ) -> set[TargetVersion]: """Detect the version to target based on the nodes used.""" features = get_features_used(node, future_imports=future_imports) return { version for version in TargetVersion if features <= VERSION_TO_FEATURES[version] }
src/black/__init__.py
1,510
1,517
2
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_detect_debug_f_strings
BlackTestCase
def test_detect_debug_f_strings(self) -> None: root = black.lib2to3_parse("""f"{x=}" """) features = black.get_features_used(root) self.assertIn(black.Feature.DEBUG_F_STRINGS, features) versions = black.detect_target_versions(root) self.assertIn(black.TargetVersion.PY38, versions) root = black.lib2to3_parse( """f"{x}"\nf'{"="}'\nf'{(x:=5)}'\nf'{f(a="3=")}'\nf'{x:=10}'\n""" ) features = black.get_features_used(root) self.assertNotIn(black.Feature.DEBUG_F_STRINGS, features) root = black.lib2to3_parse( """f"heard a rumour that { f'{1+1=}' } ... seems like it could be true" """ ) features = black.get_features_used(root) self.assertIn(black.Feature.DEBUG_F_STRINGS, features)
def test_detect_debug_f_strings(self) -> None: root = black.lib2to3_parse("""f"{x=}" """) features = black.get_features_used(root) self.assertIn(black.Feature.DEBUG_F_STRINGS, features) versions = black.detect_target_versions(root) <AssertPlaceHolder> root = black.lib2to3_parse( """f"{x}"\nf'{"="}'\nf'{(x:=5)}'\nf'{f(a="3=")}'\nf'{x:=10}'\n""" ) features = black.get_features_used(root) self.assertNotIn(black.Feature.DEBUG_F_STRINGS, features) root = black.lib2to3_parse( """f"heard a rumour that { f'{1+1=}' } ... seems like it could be true" """ ) features = black.get_features_used(root) self.assertIn(black.Feature.DEBUG_F_STRINGS, features)
tests/test_black.py
342
359
tests/test_black.py::BlackTestCase::test_detect_debug_f_strings
self.assertIn(black.TargetVersion.PY38, versions)
347
-1
-1
def detect_target_versions( node: Node, *, future_imports: Optional[set[str]] = None ) -> set[TargetVersion]: """Detect the version to target based on the nodes used.""" features = get_features_used(node, future_imports=future_imports) return { version for version in TargetVersion if features <= VERSION_TO_FEATURES[version] }
src/black/__init__.py
1,510
1,517
3
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_get_future_imports
BlackTestCase
def test_get_future_imports(self) -> None: node = black.lib2to3_parse("\n") self.assertEqual(set(), black.get_future_imports(node)) node = black.lib2to3_parse("from __future__ import black\n") self.assertEqual({"black"}, black.get_future_imports(node)) node = black.lib2to3_parse("from __future__ import multiple, imports\n") self.assertEqual({"multiple", "imports"}, black.get_future_imports(node)) node = black.lib2to3_parse("from __future__ import (parenthesized, imports)\n") self.assertEqual({"parenthesized", "imports"}, black.get_future_imports(node)) node = black.lib2to3_parse( "from __future__ import multiple\nfrom __future__ import imports\n" ) self.assertEqual({"multiple", "imports"}, black.get_future_imports(node)) node = black.lib2to3_parse("# comment\nfrom __future__ import black\n") self.assertEqual({"black"}, black.get_future_imports(node)) node = black.lib2to3_parse('"""docstring"""\nfrom __future__ import black\n') self.assertEqual({"black"}, black.get_future_imports(node)) node = black.lib2to3_parse("some(other, code)\nfrom __future__ import black\n") self.assertEqual(set(), black.get_future_imports(node)) node = black.lib2to3_parse("from some.module import black\n") self.assertEqual(set(), black.get_future_imports(node)) node = black.lib2to3_parse( "from __future__ import unicode_literals as _unicode_literals" ) self.assertEqual({"unicode_literals"}, black.get_future_imports(node)) node = black.lib2to3_parse( "from __future__ import unicode_literals as _lol, print" ) self.assertEqual({"unicode_literals", "print"}, black.get_future_imports(node))
def test_get_future_imports(self) -> None: node = black.lib2to3_parse("\n") self.assertEqual(set(), black.get_future_imports(node)) node = black.lib2to3_parse("from __future__ import black\n") self.assertEqual({"black"}, black.get_future_imports(node)) node = black.lib2to3_parse("from __future__ import multiple, imports\n") <AssertPlaceHolder> node = black.lib2to3_parse("from __future__ import (parenthesized, imports)\n") self.assertEqual({"parenthesized", "imports"}, black.get_future_imports(node)) node = black.lib2to3_parse( "from __future__ import multiple\nfrom __future__ import imports\n" ) <AssertPlaceHolder> node = black.lib2to3_parse("# comment\nfrom __future__ import black\n") self.assertEqual({"black"}, black.get_future_imports(node)) node = black.lib2to3_parse('"""docstring"""\nfrom __future__ import black\n') self.assertEqual({"black"}, black.get_future_imports(node)) node = black.lib2to3_parse("some(other, code)\nfrom __future__ import black\n") self.assertEqual(set(), black.get_future_imports(node)) node = black.lib2to3_parse("from some.module import black\n") self.assertEqual(set(), black.get_future_imports(node)) node = black.lib2to3_parse( "from __future__ import unicode_literals as _unicode_literals" ) self.assertEqual({"unicode_literals"}, black.get_future_imports(node)) node = black.lib2to3_parse( "from __future__ import unicode_literals as _lol, print" ) self.assertEqual({"unicode_literals", "print"}, black.get_future_imports(node))
tests/test_black.py
930
958
tests/test_black.py::BlackTestCase::test_get_future_imports
self.assertEqual({"multiple", "imports"}, black.get_future_imports(node))
942
-1
-1
def get_future_imports(node: Node) -> set[str]: """Return a set of __future__ imports in the file.""" imports: set[str] = set() def get_imports_from_children(children: list[LN]) -> Generator[str, None, None]: for child in children: if isinstance(child, Leaf): if child.type == token.NAME: yield child.value elif child.type == syms.import_as_name: orig_name = child.children[0] assert isinstance(orig_name, Leaf), "Invalid syntax parsing imports" assert orig_name.type == token.NAME, "Invalid syntax parsing imports" yield orig_name.value elif child.type == syms.import_as_names: yield from get_imports_from_children(child.children) else: raise AssertionError("Invalid syntax parsing imports") for child in node.children: if child.type != syms.simple_stmt: break first_child = child.children[0] if isinstance(first_child, Leaf): # Continue looking if we see a docstring; otherwise stop. if ( len(child.children) == 2 and first_child.type == token.STRING and child.children[1].type == token.NEWLINE ): continue break elif first_child.type == syms.import_from: module_name = first_child.children[1] if not isinstance(module_name, Leaf) or module_name.value != "__future__": break imports |= set(get_imports_from_children(first_child.children[3:])) else: break return imports
src/black/__init__.py
1,520
1,567
4
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_endmarker
BlackTestCase
def test_endmarker(self) -> None: n = black.lib2to3_parse("\n") self.assertEqual(n.type, black.syms.file_input) self.assertEqual(len(n.children), 1) self.assertEqual(n.children[0].type, black.token.ENDMARKER)
def test_endmarker(self) -> None: n = black.lib2to3_parse("\n") self.assertEqual(n.type, black.syms.file_input) <AssertPlaceHolder> self.assertEqual(n.children[0].type, black.token.ENDMARKER)
tests/test_black.py
1,015
1,019
tests/test_black.py::BlackTestCase::test_endmarker
self.assertEqual(len(n.children), 1)
1,018
-1
-1
def lib2to3_parse( src_txt: str, target_versions: Collection[TargetVersion] = () ) -> Node: """Given a string with source, return the lib2to3 Node.""" if not src_txt.endswith("\n"): src_txt += "\n" grammars = get_grammars(set(target_versions)) if target_versions: max_tv = max(target_versions, key=lambda tv: tv.value) tv_str = f" for target version {max_tv.pretty()}" else: tv_str = "" errors = {} for grammar in grammars: drv = driver.Driver(grammar) try: result = drv.parse_string(src_txt, False) break except ParseError as pe: lineno, column = pe.context[1] lines = src_txt.splitlines() try: faulty_line = lines[lineno - 1] except IndexError: faulty_line = "<line number missing in source>" errors[grammar.version] = InvalidInput( f"Cannot parse{tv_str}: {lineno}:{column}: {faulty_line}" ) except TokenError as te: # In edge cases these are raised; and typically don't have a "faulty_line". lineno, column = te.args[1] errors[grammar.version] = InvalidInput( f"Cannot parse{tv_str}: {lineno}:{column}: {te.args[0]}" ) else: # Choose the latest version when raising the actual parsing error. assert len(errors) >= 1 exc = errors[max(errors)] raise exc from None if isinstance(result, Leaf): result = Node(syms.file_input, [result]) return result
src/black/parsing.py
55
102
5
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_single_file_force_pyi
BlackTestCase
def test_single_file_force_pyi(self) -> None: pyi_mode = replace(DEFAULT_MODE, is_pyi=True) contents, expected = read_data("miscellaneous", "force_pyi") with cache_dir() as workspace: path = (workspace / "file.py").resolve() path.write_text(contents, encoding="utf-8") self.invokeBlack([str(path), "--pyi"]) actual = path.read_text(encoding="utf-8") # verify cache with --pyi is separate pyi_cache = black.Cache.read(pyi_mode) assert not pyi_cache.is_changed(path) normal_cache = black.Cache.read(DEFAULT_MODE) assert normal_cache.is_changed(path) self.assertFormatEqual(expected, actual) black.assert_equivalent(contents, actual) black.assert_stable(contents, actual, pyi_mode)
def test_single_file_force_pyi(self) -> None: pyi_mode = replace(DEFAULT_MODE, is_pyi=True) contents, expected = read_data("miscellaneous", "force_pyi") with cache_dir() as workspace: path = (workspace / "file.py").resolve() path.write_text(contents, encoding="utf-8") self.invokeBlack([str(path), "--pyi"]) actual = path.read_text(encoding="utf-8") # verify cache with --pyi is separate pyi_cache = black.Cache.read(pyi_mode) assert not pyi_cache.is_changed(path) normal_cache = black.Cache.read(DEFAULT_MODE) assert normal_cache.is_changed(path) <AssertPlaceHolder> black.assert_equivalent(contents, actual) black.assert_stable(contents, actual, pyi_mode)
tests/test_black.py
1,106
1,121
tests/test_black.py::BlackTestCase::test_single_file_force_pyi
self.assertFormatEqual(expected, actual)
1,119
-1
-1
@classmethod def read(cls, mode: Mode) -> Self: """Read the cache if it exists and is well-formed. If it is not well-formed, the call to write later should resolve the issue. """ cache_file = get_cache_file(mode) try: exists = cache_file.exists() except OSError as e: # Likely file too long; see #4172 and #4174 err(f"Unable to read cache file {cache_file} due to {e}") return cls(mode, cache_file) if not exists: return cls(mode, cache_file) with cache_file.open("rb") as fobj: try: data: dict[str, tuple[float, int, str]] = pickle.load(fobj) file_data = {k: FileData(*v) for k, v in data.items()} except (pickle.UnpicklingError, ValueError, IndexError): return cls(mode, cache_file) return cls(mode, cache_file, file_data)
src/black/cache.py
61
85
6
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_multi_file_force_pyi
BlackTestCase
@event_loop() def test_multi_file_force_pyi(self) -> None: reg_mode = DEFAULT_MODE pyi_mode = replace(DEFAULT_MODE, is_pyi=True) contents, expected = read_data("miscellaneous", "force_pyi") with cache_dir() as workspace: paths = [ (workspace / "file1.py").resolve(), (workspace / "file2.py").resolve(), ] for path in paths: path.write_text(contents, encoding="utf-8") self.invokeBlack([str(p) for p in paths] + ["--pyi"]) for path in paths: actual = path.read_text(encoding="utf-8") self.assertEqual(actual, expected) # verify cache with --pyi is separate pyi_cache = black.Cache.read(pyi_mode) normal_cache = black.Cache.read(reg_mode) for path in paths: assert not pyi_cache.is_changed(path) assert normal_cache.is_changed(path)
@event_loop() def test_multi_file_force_pyi(self) -> None: reg_mode = DEFAULT_MODE pyi_mode = replace(DEFAULT_MODE, is_pyi=True) contents, expected = read_data("miscellaneous", "force_pyi") with cache_dir() as workspace: paths = [ (workspace / "file1.py").resolve(), (workspace / "file2.py").resolve(), ] for path in paths: path.write_text(contents, encoding="utf-8") self.invokeBlack([str(p) for p in paths] + ["--pyi"]) for path in paths: actual = path.read_text(encoding="utf-8") self.assertEqual(actual, expected) # verify cache with --pyi is separate pyi_cache = black.Cache.read(pyi_mode) normal_cache = black.Cache.read(reg_mode) for path in paths: <AssertPlaceHolder> assert normal_cache.is_changed(path)
tests/test_black.py
1,123
1,144
tests/test_black.py::BlackTestCase::test_multi_file_force_pyi
assert not pyi_cache.is_changed(path)
1,143
-1
-1
def is_changed(self, source: Path) -> bool: """Check if source has changed compared to cached version.""" res_src = source.resolve() old = self.file_data.get(str(res_src)) if old is None: return True st = res_src.stat() if st.st_size != old.st_size: return True if st.st_mtime != old.st_mtime: new_hash = Cache.hash_digest(res_src) if new_hash != old.hash: return True return False
src/black/cache.py
102
116
7
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_single_file_force_py36
BlackTestCase
def test_single_file_force_py36(self) -> None: reg_mode = DEFAULT_MODE py36_mode = replace(DEFAULT_MODE, target_versions=PY36_VERSIONS) source, expected = read_data("miscellaneous", "force_py36") with cache_dir() as workspace: path = (workspace / "file.py").resolve() path.write_text(source, encoding="utf-8") self.invokeBlack([str(path), *PY36_ARGS]) actual = path.read_text(encoding="utf-8") # verify cache with --target-version is separate py36_cache = black.Cache.read(py36_mode) assert not py36_cache.is_changed(path) normal_cache = black.Cache.read(reg_mode) assert normal_cache.is_changed(path) self.assertEqual(actual, expected)
def test_single_file_force_py36(self) -> None: reg_mode = DEFAULT_MODE py36_mode = replace(DEFAULT_MODE, target_versions=PY36_VERSIONS) source, expected = read_data("miscellaneous", "force_py36") with cache_dir() as workspace: path = (workspace / "file.py").resolve() path.write_text(source, encoding="utf-8") self.invokeBlack([str(path), *PY36_ARGS]) actual = path.read_text(encoding="utf-8") # verify cache with --target-version is separate py36_cache = black.Cache.read(py36_mode) assert not py36_cache.is_changed(path) normal_cache = black.Cache.read(reg_mode) assert normal_cache.is_changed(path) <AssertPlaceHolder>
tests/test_black.py
1,155
1,169
tests/test_black.py::BlackTestCase::test_single_file_force_py36
self.assertEqual(actual, expected)
1,169
-1
-1
@classmethod def read(cls, mode: Mode) -> Self: """Read the cache if it exists and is well-formed. If it is not well-formed, the call to write later should resolve the issue. """ cache_file = get_cache_file(mode) try: exists = cache_file.exists() except OSError as e: # Likely file too long; see #4172 and #4174 err(f"Unable to read cache file {cache_file} due to {e}") return cls(mode, cache_file) if not exists: return cls(mode, cache_file) with cache_file.open("rb") as fobj: try: data: dict[str, tuple[float, int, str]] = pickle.load(fobj) file_data = {k: FileData(*v) for k, v in data.items()} except (pickle.UnpicklingError, ValueError, IndexError): return cls(mode, cache_file) return cls(mode, cache_file, file_data)
src/black/cache.py
61
85
8
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_parse_pyproject_toml
BlackTestCase
def test_parse_pyproject_toml(self) -> None: test_toml_file = THIS_DIR / "test.toml" config = black.parse_pyproject_toml(str(test_toml_file)) self.assertEqual(config["verbose"], 1) self.assertEqual(config["check"], "no") self.assertEqual(config["diff"], "y") self.assertEqual(config["color"], True) self.assertEqual(config["line_length"], 79) self.assertEqual(config["target_version"], ["py36", "py37", "py38"]) self.assertEqual(config["python_cell_magics"], ["custom1", "custom2"]) self.assertEqual(config["exclude"], r"\.pyi?$") self.assertEqual(config["include"], r"\.py?$")
def test_parse_pyproject_toml(self) -> None: test_toml_file = THIS_DIR / "test.toml" config = black.parse_pyproject_toml(str(test_toml_file)) self.assertEqual(config["verbose"], 1) self.assertEqual(config["check"], "no") self.assertEqual(config["diff"], "y") self.assertEqual(config["color"], True) <AssertPlaceHolder> self.assertEqual(config["target_version"], ["py36", "py37", "py38"]) self.assertEqual(config["python_cell_magics"], ["custom1", "custom2"]) self.assertEqual(config["exclude"], r"\.pyi?$") self.assertEqual(config["include"], r"\.py?$")
tests/test_black.py
1,476
1,487
tests/test_black.py::BlackTestCase::test_parse_pyproject_toml
self.assertEqual(config["line_length"], 79)
1,483
-1
-1
@mypyc_attr(patchable=True) def parse_pyproject_toml(path_config: str) -> dict[str, Any]: """Parse a pyproject toml file, pulling out relevant parts for Black. If parsing fails, will raise a tomllib.TOMLDecodeError. """ pyproject_toml = _load_toml(path_config) config: dict[str, Any] = pyproject_toml.get("tool", {}).get("black", {}) config = {k.replace("--", "").replace("-", "_"): v for k, v in config.items()} if "target_version" not in config: inferred_target_version = infer_target_version(pyproject_toml) if inferred_target_version is not None: config["target_version"] = [v.name.lower() for v in inferred_target_version] return config
src/black/files.py
120
135
9
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_find_pyproject_toml
BlackTestCase
@patch( "black.files.find_user_pyproject_toml", ) def test_find_pyproject_toml(self, find_user_pyproject_toml: MagicMock) -> None: find_user_pyproject_toml.side_effect = RuntimeError() with redirect_stderr(io.StringIO()) as stderr: result = black.files.find_pyproject_toml( path_search_start=(str(Path.cwd().root),) ) assert result is None err = stderr.getvalue() assert "Ignoring user configuration" in err
@patch( "black.files.find_user_pyproject_toml", ) def test_find_pyproject_toml(self, find_user_pyproject_toml: MagicMock) -> None: find_user_pyproject_toml.side_effect = RuntimeError() with redirect_stderr(io.StringIO()) as stderr: result = black.files.find_pyproject_toml( path_search_start=(str(Path.cwd().root),) ) <AssertPlaceHolder> err = stderr.getvalue() assert "Ignoring user configuration" in err
tests/test_black.py
1,708
1,721
tests/test_black.py::BlackTestCase::test_find_pyproject_toml
assert result is None
1,719
-1
-1
def find_pyproject_toml( path_search_start: tuple[str, ...], stdin_filename: Optional[str] = None ) -> Optional[str]: """Find the absolute filepath to a pyproject.toml if it exists""" path_project_root, _ = find_project_root(path_search_start, stdin_filename) path_pyproject_toml = path_project_root / "pyproject.toml" if path_pyproject_toml.is_file(): return str(path_pyproject_toml) try: path_user_pyproject_toml = find_user_pyproject_toml() return ( str(path_user_pyproject_toml) if path_user_pyproject_toml.is_file() else None ) except (PermissionError, RuntimeError) as e: # We do not have access to the user-level config directory, so ignore it. err(f"Ignoring user configuration directory due to {e!r}") return None
src/black/files.py
98
117
10
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_bpo_33660_workaround
BlackTestCase
def test_bpo_33660_workaround(self) -> None: if system() == "Windows": return # https://bugs.python.org/issue33660 # Can be removed when we drop support for Python 3.8.5 root = Path("/") with change_directory(root): path = Path("workspace") / "project" report = black.Report(verbose=True) resolves_outside = black.resolves_outside_root_or_cannot_stat( path, root, report ) self.assertIs(resolves_outside, False)
def test_bpo_33660_workaround(self) -> None: if system() == "Windows": return # https://bugs.python.org/issue33660 # Can be removed when we drop support for Python 3.8.5 root = Path("/") with change_directory(root): path = Path("workspace") / "project" report = black.Report(verbose=True) resolves_outside = black.resolves_outside_root_or_cannot_stat( path, root, report ) <AssertPlaceHolder>
tests/test_black.py
1,756
1,769
tests/test_black.py::BlackTestCase::test_bpo_33660_workaround
self.assertIs(resolves_outside, False)
1,769
-1
-1
def resolves_outside_root_or_cannot_stat( path: Path, root: Path, report: Optional[Report] = None, ) -> bool: """ Returns whether the path is a symbolic link that points outside the root directory. Also returns True if we failed to resolve the path. """ try: resolved_path = _cached_resolve(path) except OSError as e: if report: report.path_ignored(path, f"cannot be read because {e}") return True try: resolved_path.relative_to(root) except ValueError: if report: report.path_ignored(path, f"is a symbolic link that points outside {root}") return True return False
src/black/files.py
255
276
11
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_lines_with_leading_tabs_expanded
BlackTestCase
def test_lines_with_leading_tabs_expanded(self) -> None: # See CVE-2024-21503. Mostly test that this completes in a reasonable # time. payload = "\t" * 10_000 assert lines_with_leading_tabs_expanded(payload) == [payload] tab = " " * 8 assert lines_with_leading_tabs_expanded("\tx") == [f"{tab}x"] assert lines_with_leading_tabs_expanded("\t\tx") == [f"{tab}{tab}x"] assert lines_with_leading_tabs_expanded("\tx\n y") == [f"{tab}x", " y"]
def test_lines_with_leading_tabs_expanded(self) -> None: # See CVE-2024-21503. Mostly test that this completes in a reasonable # time. payload = "\t" * 10_000 assert lines_with_leading_tabs_expanded(payload) == [payload] tab = " " * 8 assert lines_with_leading_tabs_expanded("\tx") == [f"{tab}x"] assert lines_with_leading_tabs_expanded("\t\tx") == [f"{tab}{tab}x"] <AssertPlaceHolder>
tests/test_black.py
2,046
2,055
tests/test_black.py::BlackTestCase::test_lines_with_leading_tabs_expanded
assert lines_with_leading_tabs_expanded("\tx\n y") == [f"{tab}x", " y"]
2,055
-1
-1
def lines_with_leading_tabs_expanded(s: str) -> list[str]: """ Splits string into lines and expands only leading tabs (following the normal Python rules) """ lines = [] for line in s.splitlines(): stripped_line = line.lstrip() if not stripped_line or stripped_line == line: lines.append(line) else: prefix_length = len(line) - len(stripped_line) prefix = line[:prefix_length].expandtabs() lines.append(prefix + stripped_line) if s.endswith("\n"): lines.append("") return lines
src/black/strings.py
47
63
12
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_preview_newline_type_detection
BlackTestCase
def test_preview_newline_type_detection(self) -> None: mode = Mode(enabled_features={Preview.normalize_cr_newlines}) newline_types = ["A\n", "A\r\n", "A\r"] for test_case in itertools.permutations(newline_types): assert black.format_str("".join(test_case), mode=mode) == test_case[0] * 3
def test_preview_newline_type_detection(self) -> None: mode = Mode(enabled_features={Preview.normalize_cr_newlines}) newline_types = ["A\n", "A\r\n", "A\r"] for test_case in itertools.permutations(newline_types): <AssertPlaceHolder>
tests/test_black.py
2,087
2,091
tests/test_black.py::BlackTestCase::test_preview_newline_type_detection
assert black.format_str("".join(test_case), mode=mode) == test_case[0] * 3
2,091
-1
-1
def format_str( src_contents: str, *, mode: Mode, lines: Collection[tuple[int, int]] = () ) -> str: """Reformat a string and return new contents. `mode` determines formatting options, such as how many characters per line are allowed. Example: >>> import black >>> print(black.format_str("def f(arg:str='')->None:...", mode=black.Mode())) def f(arg: str = "") -> None: ... A more complex example: >>> print( ... black.format_str( ... "def f(arg:str='')->None: hey", ... mode=black.Mode( ... target_versions={black.TargetVersion.PY36}, ... line_length=10, ... string_normalization=False, ... is_pyi=False, ... ), ... ), ... ) def f( arg: str = '', ) -> None: hey """ if lines: lines = sanitized_lines(lines, src_contents) if not lines: return src_contents # Nothing to format dst_contents = _format_str_once(src_contents, mode=mode, lines=lines) # Forced second pass to work around optional trailing commas (becoming # forced trailing commas on pass 2) interacting differently with optional # parentheses. Admittedly ugly. if src_contents != dst_contents: if lines: lines = adjusted_lines(lines, src_contents, dst_contents) return _format_str_once(dst_contents, mode=mode, lines=lines) return dst_contents
src/black/__init__.py
1,176
1,220
13
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_get_cache_dir
TestCaching
def test_get_cache_dir( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: # Create multiple cache directories workspace1 = tmp_path / "ws1" workspace1.mkdir() workspace2 = tmp_path / "ws2" workspace2.mkdir() # Force user_cache_dir to use the temporary directory for easier assertions patch_user_cache_dir = patch( target="black.cache.user_cache_dir", autospec=True, return_value=str(workspace1), ) # If BLACK_CACHE_DIR is not set, use user_cache_dir monkeypatch.delenv("BLACK_CACHE_DIR", raising=False) with patch_user_cache_dir: assert get_cache_dir().parent == workspace1 # If it is set, use the path provided in the env var. monkeypatch.setenv("BLACK_CACHE_DIR", str(workspace2)) assert get_cache_dir().parent == workspace2
def test_get_cache_dir( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: # Create multiple cache directories workspace1 = tmp_path / "ws1" workspace1.mkdir() workspace2 = tmp_path / "ws2" workspace2.mkdir() # Force user_cache_dir to use the temporary directory for easier assertions patch_user_cache_dir = patch( target="black.cache.user_cache_dir", autospec=True, return_value=str(workspace1), ) # If BLACK_CACHE_DIR is not set, use user_cache_dir monkeypatch.delenv("BLACK_CACHE_DIR", raising=False) with patch_user_cache_dir: assert get_cache_dir().parent == workspace1 # If it is set, use the path provided in the env var. monkeypatch.setenv("BLACK_CACHE_DIR", str(workspace2)) <AssertPlaceHolder>
tests/test_black.py
2,095
2,120
tests/test_black.py::TestCaching::test_get_cache_dir
assert get_cache_dir().parent == workspace2
2,120
-1
-1
def get_cache_dir() -> Path: """Get the cache directory used by black. Users can customize this directory on all systems using `BLACK_CACHE_DIR` environment variable. By default, the cache directory is the user cache directory under the black application. This result is immediately set to a constant `black.cache.CACHE_DIR` as to avoid repeated calls. """ # NOTE: Function mostly exists as a clean way to test getting the cache directory. default_cache_dir = user_cache_dir("black") cache_dir = Path(os.environ.get("BLACK_CACHE_DIR", default_cache_dir)) cache_dir = cache_dir / __version__ return cache_dir
src/black/cache.py
31
45
14
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_cache_file_length
TestCaching
def test_cache_file_length(self) -> None: cases = [ DEFAULT_MODE, # all of the target versions Mode(target_versions=set(TargetVersion)), # all of the features Mode(enabled_features=set(Preview)), # all of the magics Mode(python_cell_magics={f"magic{i}" for i in range(500)}), # all of the things Mode( target_versions=set(TargetVersion), enabled_features=set(Preview), python_cell_magics={f"magic{i}" for i in range(500)}, ), ] for case in cases: cache_file = get_cache_file(case) # Some common file systems enforce a maximum path length # of 143 (issue #4174). We can't do anything if the directory # path is too long, but ensure the name of the cache file itself # doesn't get too crazy. assert len(cache_file.name) <= 96
def test_cache_file_length(self) -> None: cases = [ DEFAULT_MODE, # all of the target versions Mode(target_versions=set(TargetVersion)), # all of the features Mode(enabled_features=set(Preview)), # all of the magics Mode(python_cell_magics={f"magic{i}" for i in range(500)}), # all of the things Mode( target_versions=set(TargetVersion), enabled_features=set(Preview), python_cell_magics={f"magic{i}" for i in range(500)}, ), ] for case in cases: cache_file = get_cache_file(case) # Some common file systems enforce a maximum path length # of 143 (issue #4174). We can't do anything if the directory # path is too long, but ensure the name of the cache file itself # doesn't get too crazy. <AssertPlaceHolder>
tests/test_black.py
2,122
2,144
tests/test_black.py::TestCaching::test_cache_file_length
assert len(cache_file.name) <= 96
2,144
-1
-1
def get_cache_file(mode: Mode) -> Path: return CACHE_DIR / f"cache.{mode.get_cache_key()}.pickle"
src/black/cache.py
51
52
15
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_cache_broken_file
TestCaching
def test_cache_broken_file(self) -> None: mode = DEFAULT_MODE with cache_dir() as workspace: cache_file = get_cache_file(mode) cache_file.write_text("this is not a pickle", encoding="utf-8") assert black.Cache.read(mode).file_data == {} src = (workspace / "test.py").resolve() src.write_text("print('hello')", encoding="utf-8") invokeBlack([str(src)]) cache = black.Cache.read(mode) assert not cache.is_changed(src)
def test_cache_broken_file(self) -> None: mode = DEFAULT_MODE with cache_dir() as workspace: cache_file = get_cache_file(mode) cache_file.write_text("this is not a pickle", encoding="utf-8") assert black.Cache.read(mode).file_data == {} src = (workspace / "test.py").resolve() src.write_text("print('hello')", encoding="utf-8") invokeBlack([str(src)]) cache = black.Cache.read(mode) <AssertPlaceHolder>
tests/test_black.py
2,146
2,156
tests/test_black.py::TestCaching::test_cache_broken_file
assert not cache.is_changed(src)
2,156
-1
-1
def is_changed(self, source: Path) -> bool: """Check if source has changed compared to cached version.""" res_src = source.resolve() old = self.file_data.get(str(res_src)) if old is None: return True st = res_src.stat() if st.st_size != old.st_size: return True if st.st_mtime != old.st_mtime: new_hash = Cache.hash_digest(res_src) if new_hash != old.hash: return True return False
src/black/cache.py
102
116
16
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_read_cache_no_cachefile
TestCaching
def test_read_cache_no_cachefile(self) -> None: mode = DEFAULT_MODE with cache_dir(): assert black.Cache.read(mode).file_data == {}
def test_read_cache_no_cachefile(self) -> None: mode = DEFAULT_MODE with cache_dir(): <AssertPlaceHolder>
tests/test_black.py
2,236
2,239
tests/test_black.py::TestCaching::test_read_cache_no_cachefile
assert black.Cache.read(mode).file_data == {}
2,239
-1
-1
@classmethod def read(cls, mode: Mode) -> Self: """Read the cache if it exists and is well-formed. If it is not well-formed, the call to write later should resolve the issue. """ cache_file = get_cache_file(mode) try: exists = cache_file.exists() except OSError as e: # Likely file too long; see #4172 and #4174 err(f"Unable to read cache file {cache_file} due to {e}") return cls(mode, cache_file) if not exists: return cls(mode, cache_file) with cache_file.open("rb") as fobj: try: data: dict[str, tuple[float, int, str]] = pickle.load(fobj) file_data = {k: FileData(*v) for k, v in data.items()} except (pickle.UnpicklingError, ValueError, IndexError): return cls(mode, cache_file) return cls(mode, cache_file, file_data)
src/black/cache.py
61
85
17
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_write_cache_read_cache
TestCaching
def test_write_cache_read_cache(self) -> None: mode = DEFAULT_MODE with cache_dir() as workspace: src = (workspace / "test.py").resolve() src.touch() write_cache = black.Cache.read(mode) write_cache.write([src]) read_cache = black.Cache.read(mode) assert not read_cache.is_changed(src)
def test_write_cache_read_cache(self) -> None: mode = DEFAULT_MODE with cache_dir() as workspace: src = (workspace / "test.py").resolve() src.touch() write_cache = black.Cache.read(mode) write_cache.write([src]) read_cache = black.Cache.read(mode) <AssertPlaceHolder>
tests/test_black.py
2,241
2,249
tests/test_black.py::TestCaching::test_write_cache_read_cache
assert not read_cache.is_changed(src)
2,249
-1
-1
def is_changed(self, source: Path) -> bool: """Check if source has changed compared to cached version.""" res_src = source.resolve() old = self.file_data.get(str(res_src)) if old is None: return True st = res_src.stat() if st.st_size != old.st_size: return True if st.st_mtime != old.st_mtime: new_hash = Cache.hash_digest(res_src) if new_hash != old.hash: return True return False
src/black/cache.py
102
116
18
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_filter_cached
TestCaching
@pytest.mark.incompatible_with_mypyc def test_filter_cached(self) -> None: with TemporaryDirectory() as workspace: path = Path(workspace) uncached = (path / "uncached").resolve() cached = (path / "cached").resolve() cached_but_changed = (path / "changed").resolve() uncached.touch() cached.touch() cached_but_changed.touch() cache = black.Cache.read(DEFAULT_MODE) orig_func = black.Cache.get_file_data def wrapped_func(path: Path) -> FileData: if path == cached: return orig_func(path) if path == cached_but_changed: return FileData(0.0, 0, "") raise AssertionError with patch.object(black.Cache, "get_file_data", side_effect=wrapped_func): cache.write([cached, cached_but_changed]) todo, done = cache.filtered_cached({uncached, cached, cached_but_changed}) assert todo == {uncached, cached_but_changed} assert done == {cached}
@pytest.mark.incompatible_with_mypyc def test_filter_cached(self) -> None: with TemporaryDirectory() as workspace: path = Path(workspace) uncached = (path / "uncached").resolve() cached = (path / "cached").resolve() cached_but_changed = (path / "changed").resolve() uncached.touch() cached.touch() cached_but_changed.touch() cache = black.Cache.read(DEFAULT_MODE) orig_func = black.Cache.get_file_data def wrapped_func(path: Path) -> FileData: if path == cached: return orig_func(path) if path == cached_but_changed: return FileData(0.0, 0, "") raise AssertionError with patch.object(black.Cache, "get_file_data", side_effect=wrapped_func): cache.write([cached, cached_but_changed]) todo, done = cache.filtered_cached({uncached, cached, cached_but_changed}) <AssertPlaceHolder> assert done == {cached}
tests/test_black.py
2,251
2,276
tests/test_black.py::TestCaching::test_filter_cached
assert todo == {uncached, cached_but_changed}
2,275
-1
-1
def filtered_cached(self, sources: Iterable[Path]) -> tuple[set[Path], set[Path]]: """Split an iterable of paths in `sources` into two sets. The first contains paths of files that modified on disk or are not in the cache. The other contains paths to non-modified files. """ changed: set[Path] = set() done: set[Path] = set() for src in sources: if self.is_changed(src): changed.add(src) else: done.add(src) return changed, done
src/black/cache.py
118
131
19
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_filter_cached_hash
TestCaching
def test_filter_cached_hash(self) -> None: with TemporaryDirectory() as workspace: path = Path(workspace) src = (path / "test.py").resolve() src.write_text("print('hello')", encoding="utf-8") st = src.stat() cache = black.Cache.read(DEFAULT_MODE) cache.write([src]) cached_file_data = cache.file_data[str(src)] todo, done = cache.filtered_cached([src]) assert todo == set() assert done == {src} assert cached_file_data.st_mtime == st.st_mtime # Modify st_mtime cached_file_data = cache.file_data[str(src)] = FileData( cached_file_data.st_mtime - 1, cached_file_data.st_size, cached_file_data.hash, ) todo, done = cache.filtered_cached([src]) assert todo == set() assert done == {src} assert cached_file_data.st_mtime < st.st_mtime assert cached_file_data.st_size == st.st_size assert cached_file_data.hash == black.Cache.hash_digest(src) # Modify contents src.write_text("print('hello world')", encoding="utf-8") new_st = src.stat() todo, done = cache.filtered_cached([src]) assert todo == {src} assert done == set() assert cached_file_data.st_mtime < new_st.st_mtime assert cached_file_data.st_size != new_st.st_size assert cached_file_data.hash != black.Cache.hash_digest(src)
def test_filter_cached_hash(self) -> None: with TemporaryDirectory() as workspace: path = Path(workspace) src = (path / "test.py").resolve() src.write_text("print('hello')", encoding="utf-8") st = src.stat() cache = black.Cache.read(DEFAULT_MODE) cache.write([src]) cached_file_data = cache.file_data[str(src)] todo, done = cache.filtered_cached([src]) assert todo == set() assert done == {src} <AssertPlaceHolder> # Modify st_mtime cached_file_data = cache.file_data[str(src)] = FileData( cached_file_data.st_mtime - 1, cached_file_data.st_size, cached_file_data.hash, ) todo, done = cache.filtered_cached([src]) assert todo == set() assert done == {src} assert cached_file_data.st_mtime < st.st_mtime assert cached_file_data.st_size == st.st_size assert cached_file_data.hash == black.Cache.hash_digest(src) # Modify contents src.write_text("print('hello world')", encoding="utf-8") new_st = src.stat() todo, done = cache.filtered_cached([src]) assert todo == {src} assert done == set() assert cached_file_data.st_mtime < new_st.st_mtime assert cached_file_data.st_size != new_st.st_size assert cached_file_data.hash != black.Cache.hash_digest(src)
tests/test_black.py
2,278
2,314
tests/test_black.py::TestCaching::test_filter_cached_hash
assert cached_file_data.st_mtime == st.st_mtime
2,291
-1
-1
def filtered_cached(self, sources: Iterable[Path]) -> tuple[set[Path], set[Path]]: """Split an iterable of paths in `sources` into two sets. The first contains paths of files that modified on disk or are not in the cache. The other contains paths to non-modified files. """ changed: set[Path] = set() done: set[Path] = set() for src in sources: if self.is_changed(src): changed.add(src) else: done.add(src) return changed, done
src/black/cache.py
118
131
20
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_write_cache_creates_directory_if_needed
TestCaching
def test_write_cache_creates_directory_if_needed(self) -> None: mode = DEFAULT_MODE with cache_dir(exists=False) as workspace: assert not workspace.exists() cache = black.Cache.read(mode) cache.write([]) assert workspace.exists()
def test_write_cache_creates_directory_if_needed(self) -> None: mode = DEFAULT_MODE with cache_dir(exists=False) as workspace: assert not workspace.exists() cache = black.Cache.read(mode) cache.write([]) <AssertPlaceHolder>
tests/test_black.py
2,316
2,322
tests/test_black.py::TestCaching::test_write_cache_creates_directory_if_needed
assert workspace.exists()
2,322
-1
-1
@classmethod def read(cls, mode: Mode) -> Self: """Read the cache if it exists and is well-formed. If it is not well-formed, the call to write later should resolve the issue. """ cache_file = get_cache_file(mode) try: exists = cache_file.exists() except OSError as e: # Likely file too long; see #4172 and #4174 err(f"Unable to read cache file {cache_file} due to {e}") return cls(mode, cache_file) if not exists: return cls(mode, cache_file) with cache_file.open("rb") as fobj: try: data: dict[str, tuple[float, int, str]] = pickle.load(fobj) file_data = {k: FileData(*v) for k, v in data.items()} except (pickle.UnpicklingError, ValueError, IndexError): return cls(mode, cache_file) return cls(mode, cache_file, file_data)
src/black/cache.py
61
85
21
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_failed_formatting_does_not_get_cached
TestCaching
@event_loop() def test_failed_formatting_does_not_get_cached(self) -> None: mode = DEFAULT_MODE with ( cache_dir() as workspace, patch("concurrent.futures.ProcessPoolExecutor", new=ThreadPoolExecutor), ): failing = (workspace / "failing.py").resolve() failing.write_text("not actually python", encoding="utf-8") clean = (workspace / "clean.py").resolve() clean.write_text('print("hello")\n', encoding="utf-8") invokeBlack([str(workspace)], exit_code=123) cache = black.Cache.read(mode) assert cache.is_changed(failing) assert not cache.is_changed(clean)
@event_loop() def test_failed_formatting_does_not_get_cached(self) -> None: mode = DEFAULT_MODE with ( cache_dir() as workspace, patch("concurrent.futures.ProcessPoolExecutor", new=ThreadPoolExecutor), ): failing = (workspace / "failing.py").resolve() failing.write_text("not actually python", encoding="utf-8") clean = (workspace / "clean.py").resolve() clean.write_text('print("hello")\n', encoding="utf-8") invokeBlack([str(workspace)], exit_code=123) cache = black.Cache.read(mode) assert cache.is_changed(failing) <AssertPlaceHolder>
tests/test_black.py
2,324
2,338
tests/test_black.py::TestCaching::test_failed_formatting_does_not_get_cached
assert not cache.is_changed(clean)
2,338
-1
-1
def is_changed(self, source: Path) -> bool: """Check if source has changed compared to cached version.""" res_src = source.resolve() old = self.file_data.get(str(res_src)) if old is None: return True st = res_src.stat() if st.st_size != old.st_size: return True if st.st_mtime != old.st_mtime: new_hash = Cache.hash_digest(res_src) if new_hash != old.hash: return True return False
src/black/cache.py
102
116
22
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_read_cache_line_lengths
TestCaching
def test_read_cache_line_lengths(self) -> None: mode = DEFAULT_MODE short_mode = replace(DEFAULT_MODE, line_length=1) with cache_dir() as workspace: path = (workspace / "file.py").resolve() path.touch() cache = black.Cache.read(mode) cache.write([path]) one = black.Cache.read(mode) assert not one.is_changed(path) two = black.Cache.read(short_mode) assert two.is_changed(path)
def test_read_cache_line_lengths(self) -> None: mode = DEFAULT_MODE short_mode = replace(DEFAULT_MODE, line_length=1) with cache_dir() as workspace: path = (workspace / "file.py").resolve() path.touch() cache = black.Cache.read(mode) cache.write([path]) one = black.Cache.read(mode) <AssertPlaceHolder> two = black.Cache.read(short_mode) assert two.is_changed(path)
tests/test_black.py
2,348
2,359
tests/test_black.py::TestCaching::test_read_cache_line_lengths
assert not one.is_changed(path)
2,357
-1
-1
def is_changed(self, source: Path) -> bool: """Check if source has changed compared to cached version.""" res_src = source.resolve() old = self.file_data.get(str(res_src)) if old is None: return True st = res_src.stat() if st.st_size != old.st_size: return True if st.st_mtime != old.st_mtime: new_hash = Cache.hash_digest(res_src) if new_hash != old.hash: return True return False
src/black/cache.py
102
116
23
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_cache_key
TestCaching
def test_cache_key(self) -> None: # Test that all members of the mode enum affect the cache key. for field in fields(Mode): values: list[Any] if field.name == "target_versions": values = [ {TargetVersion.PY312}, {TargetVersion.PY313}, ] elif field.name == "python_cell_magics": values = [{"magic1"}, {"magic2"}] elif field.name == "enabled_features": # If you are looking to remove one of these features, just # replace it with any other feature. values = [ {Preview.multiline_string_handling}, {Preview.string_processing}, ] elif field.type is bool: values = [True, False] elif field.type is int: values = [1, 2] else: raise AssertionError( f"Unhandled field type: {field.type} for field {field.name}" ) modes = [replace(DEFAULT_MODE, **{field.name: value}) for value in values] keys = [mode.get_cache_key() for mode in modes] assert len(set(keys)) == len(modes)
def test_cache_key(self) -> None: # Test that all members of the mode enum affect the cache key. for field in fields(Mode): values: list[Any] if field.name == "target_versions": values = [ {TargetVersion.PY312}, {TargetVersion.PY313}, ] elif field.name == "python_cell_magics": values = [{"magic1"}, {"magic2"}] elif field.name == "enabled_features": # If you are looking to remove one of these features, just # replace it with any other feature. values = [ {Preview.multiline_string_handling}, {Preview.string_processing}, ] elif field.type is bool: values = [True, False] elif field.type is int: values = [1, 2] else: raise AssertionError( f"Unhandled field type: {field.type} for field {field.name}" ) modes = [replace(DEFAULT_MODE, **{field.name: value}) for value in values] keys = [mode.get_cache_key() for mode in modes] <AssertPlaceHolder>
tests/test_black.py
2,361
2,389
tests/test_black.py::TestCaching::test_cache_key
assert len(set(keys)) == len(modes)
2,389
-1
-1
def get_cache_key(self) -> str: if self.target_versions: version_str = ",".join( str(version.value) for version in sorted(self.target_versions, key=attrgetter("value")) ) else: version_str = "-" if len(version_str) > _MAX_CACHE_KEY_PART_LENGTH: version_str = sha256(version_str.encode()).hexdigest()[ :_MAX_CACHE_KEY_PART_LENGTH ] features_and_magics = ( ",".join(sorted(f.name for f in self.enabled_features)) + "@" + ",".join(sorted(self.python_cell_magics)) ) if len(features_and_magics) > _MAX_CACHE_KEY_PART_LENGTH: features_and_magics = sha256(features_and_magics.encode()).hexdigest()[ :_MAX_CACHE_KEY_PART_LENGTH ] parts = [ version_str, str(self.line_length), str(int(self.string_normalization)), str(int(self.is_pyi)), str(int(self.is_ipynb)), str(int(self.skip_source_first_line)), str(int(self.magic_trailing_comma)), str(int(self.preview)), str(int(self.unstable)), features_and_magics, ] return ".".join(parts)
src/black/mode.py
286
319
24
black
https://github.com/psf/black.git
25.9.0
python -m venv .venv source .venv/bin/activate pip install -r test_requirements.txt pip install -e . pip install ipdb
source .venv/bin/activate hash -r
test_fexpr_spans
def test_fexpr_spans() -> None: def check( string: str, expected_spans: list[tuple[int, int]], expected_slices: list[str] ) -> None: spans = list(iter_fexpr_spans(string)) # Checking slices isn't strictly necessary, but it's easier to verify at # a glance than only spans assert len(spans) == len(expected_slices) for (i, j), slice in zip(spans, expected_slices): assert 0 <= i <= j <= len(string) assert string[i:j] == slice assert spans == expected_spans # Most of these test cases omit the leading 'f' and leading / closing quotes # for convenience # Some additional property-based tests can be found in # https://github.com/psf/black/pull/2654#issuecomment-981411748 check("""{var}""", [(0, 5)], ["{var}"]) check("""f'{var}'""", [(2, 7)], ["{var}"]) check("""f'{1 + f() + 2 + "asdf"}'""", [(2, 24)], ["""{1 + f() + 2 + "asdf"}"""]) check("""text {var} text""", [(5, 10)], ["{var}"]) check("""text {{ {var} }} text""", [(8, 13)], ["{var}"]) check("""{a} {b} {c}""", [(0, 3), (4, 7), (8, 11)], ["{a}", "{b}", "{c}"]) check("""f'{a} {b} {c}'""", [(2, 5), (6, 9), (10, 13)], ["{a}", "{b}", "{c}"]) check("""{ {} }""", [(0, 6)], ["{ {} }"]) check("""{ {{}} }""", [(0, 8)], ["{ {{}} }"]) check("""{ {{{}}} }""", [(0, 10)], ["{ {{{}}} }"]) check("""{{ {{{}}} }}""", [(5, 7)], ["{}"]) check("""{{ {{{var}}} }}""", [(5, 10)], ["{var}"]) check("""{f"{0}"}""", [(0, 8)], ["""{f"{0}"}"""]) check("""{"'"}""", [(0, 5)], ["""{"'"}"""]) check("""{"{"}""", [(0, 5)], ["""{"{"}"""]) check("""{"}"}""", [(0, 5)], ["""{"}"}"""]) check("""{"{{"}""", [(0, 6)], ["""{"{{"}"""]) check("""{''' '''}""", [(0, 9)], ["""{''' '''}"""]) check("""{'''{'''}""", [(0, 9)], ["""{'''{'''}"""]) check("""{''' {'{ '''}""", [(0, 13)], ["""{''' {'{ '''}"""]) check( '''f\'\'\'-{f"""*{f"+{f'.{x}.'}+"}*"""}-'y\\'\'\'\'''', [(5, 33)], ['''{f"""*{f"+{f'.{x}.'}+"}*"""}'''], ) check(r"""{}{""", [(0, 2)], ["{}"]) check("""f"{'{'''''''''}\"""", [(2, 15)], ["{'{'''''''''}"])
def test_fexpr_spans() -> None: def check( string: str, expected_spans: list[tuple[int, int]], expected_slices: list[str] ) -> None: spans = list(iter_fexpr_spans(string)) # Checking slices isn't strictly necessary, but it's easier to verify at # a glance than only spans <AssertPlaceHolder> for (i, j), slice in zip(spans, expected_slices): assert 0 <= i <= j <= len(string) assert string[i:j] == slice assert spans == expected_spans # Most of these test cases omit the leading 'f' and leading / closing quotes # for convenience # Some additional property-based tests can be found in # https://github.com/psf/black/pull/2654#issuecomment-981411748 check("""{var}""", [(0, 5)], ["{var}"]) check("""f'{var}'""", [(2, 7)], ["{var}"]) check("""f'{1 + f() + 2 + "asdf"}'""", [(2, 24)], ["""{1 + f() + 2 + "asdf"}"""]) check("""text {var} text""", [(5, 10)], ["{var}"]) check("""text {{ {var} }} text""", [(8, 13)], ["{var}"]) check("""{a} {b} {c}""", [(0, 3), (4, 7), (8, 11)], ["{a}", "{b}", "{c}"]) check("""f'{a} {b} {c}'""", [(2, 5), (6, 9), (10, 13)], ["{a}", "{b}", "{c}"]) check("""{ {} }""", [(0, 6)], ["{ {} }"]) check("""{ {{}} }""", [(0, 8)], ["{ {{}} }"]) check("""{ {{{}}} }""", [(0, 10)], ["{ {{{}}} }"]) check("""{{ {{{}}} }}""", [(5, 7)], ["{}"]) check("""{{ {{{var}}} }}""", [(5, 10)], ["{var}"]) check("""{f"{0}"}""", [(0, 8)], ["""{f"{0}"}"""]) check("""{"'"}""", [(0, 5)], ["""{"'"}"""]) check("""{"{"}""", [(0, 5)], ["""{"{"}"""]) check("""{"}"}""", [(0, 5)], ["""{"}"}"""]) check("""{"{{"}""", [(0, 6)], ["""{"{{"}"""]) check("""{''' '''}""", [(0, 9)], ["""{''' '''}"""]) check("""{'''{'''}""", [(0, 9)], ["""{'''{'''}"""]) check("""{''' {'{ '''}""", [(0, 13)], ["""{''' {'{ '''}"""]) check( '''f\'\'\'-{f"""*{f"+{f'.{x}.'}+"}*"""}-'y\\'\'\'\'''', [(5, 33)], ['''{f"""*{f"+{f'.{x}.'}+"}*"""}'''], ) check(r"""{}{""", [(0, 2)], ["{}"]) check("""f"{'{'''''''''}\"""", [(2, 15)], ["{'{'''''''''}"])
tests/test_trans.py
4
49
tests/test_trans.py::test_fexpr_spans
assert len(spans) == len(expected_slices)
12
-1
-1
def iter_fexpr_spans(s: str) -> Iterator[tuple[int, int]]: """ Yields spans corresponding to expressions in a given f-string. Spans are half-open ranges (left inclusive, right exclusive). Assumes the input string is a valid f-string, but will not crash if the input string is invalid. """ stack: list[int] = [] # our curly paren stack i = 0 while i < len(s): if s[i] == "{": # if we're in a string part of the f-string, ignore escaped curly braces if not stack and i + 1 < len(s) and s[i + 1] == "{": i += 2 continue stack.append(i) i += 1 continue if s[i] == "}": if not stack: i += 1 continue j = stack.pop() # we've made it back out of the expression! yield the span if not stack: yield (j, i + 1) i += 1 continue # if we're in an expression part of the f-string, fast-forward through strings # note that backslashes are not legal in the expression portion of f-strings if stack: delim = None if s[i : i + 3] in ("'''", '"""'): delim = s[i : i + 3] elif s[i] in ("'", '"'): delim = s[i] if delim: i += len(delim) while i < len(s) and s[i : i + len(delim)] != delim: i += 1 i += len(delim) continue i += 1
src/black/trans.py
1,309
1,353
25
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_buffer_protocol
TestConcatKDFHash
def test_buffer_protocol(self, backend): prk = binascii.unhexlify( b"52169af5c485dcc2321eb8d26d5efa21fb9b93c98e38412ee2484cf14f0d0d23" ) okm = binascii.unhexlify(b"1c3bc9e7c4547c5191c0d478cccaed55") oinfo = binascii.unhexlify( b"a1b2c3d4e53728157e634612c12d6d5223e204aeea4341565369647bd184bcd2" b"46f72971f292badaa2fe4124612cba" ) ckdf = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend) assert ckdf.derive(bytearray(prk)) == okm
def test_buffer_protocol(self, backend): prk = binascii.unhexlify( b"52169af5c485dcc2321eb8d26d5efa21fb9b93c98e38412ee2484cf14f0d0d23" ) okm = binascii.unhexlify(b"1c3bc9e7c4547c5191c0d478cccaed55") oinfo = binascii.unhexlify( b"a1b2c3d4e53728157e634612c12d6d5223e204aeea4341565369647bd184bcd2" b"46f72971f292badaa2fe4124612cba" ) ckdf = ConcatKDFHash(hashes.SHA256(), 16, oinfo, backend) <AssertPlaceHolder>
tests/hazmat/primitives/test_concatkdf.py
49
63
tests/hazmat/primitives/test_concatkdf.py::TestConcatKDFHash::test_buffer_protocol
assert ckdf.derive(bytearray(prk)) == okm
63
-1
-1
def derive(self, key_material: utils.Buffer) -> bytes: if self._used: raise AlreadyFinalized self._used = True return _concatkdf_derive( key_material, self._length, self._hash, self._otherinfo )
src/cryptography/hazmat/primitives/kdf/concatkdf.py
73
79
26
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_eq
TestUserNotice
def test_eq(self): nr = x509.NoticeReference("org", [1, 2]) nr2 = x509.NoticeReference("org", [1, 2]) un = x509.UserNotice(nr, "text") un2 = x509.UserNotice(nr2, "text") assert un == un2
def test_eq(self): nr = x509.NoticeReference("org", [1, 2]) nr2 = x509.NoticeReference("org", [1, 2]) un = x509.UserNotice(nr, "text") un2 = x509.UserNotice(nr2, "text") <AssertPlaceHolder>
tests/x509/test_x509_ext.py
530
535
tests/x509/test_x509_ext.py::TestUserNotice::test_eq
assert un == un2
535
-1
-1
class UserNotice: def __init__( self, notice_reference: NoticeReference | None, explicit_text: str | None, ) -> None: if notice_reference and not isinstance( notice_reference, NoticeReference ): raise TypeError( "notice_reference must be None or a NoticeReference" ) self._notice_reference = notice_reference self._explicit_text = explicit_text def __repr__(self) -> str: return ( f"<UserNotice(notice_reference={self.notice_reference}, " f"explicit_text={self.explicit_text!r})>" ) def __eq__(self, other: object) -> bool: if not isinstance(other, UserNotice): return NotImplemented return ( self.notice_reference == other.notice_reference and self.explicit_text == other.explicit_text ) def __hash__(self) -> int: return hash((self.notice_reference, self.explicit_text)) @property def notice_reference(self) -> NoticeReference | None: return self._notice_reference @property def explicit_text(self) -> str | None: return self._explicit_text
src/cryptography/x509/extensions.py
905
945
27
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_add_multiple_extensions
TestRevokedCertificateBuilder
def test_add_multiple_extensions(self, backend): serial_number = 333 revocation_date = datetime.datetime(2002, 1, 1, 12, 1) invalidity_date = x509.InvalidityDate( datetime.datetime(2015, 1, 1, 0, 0) ) certificate_issuer = x509.CertificateIssuer( [x509.DNSName("cryptography.io")] ) crl_reason = x509.CRLReason(x509.ReasonFlags.aa_compromise) builder = ( x509.RevokedCertificateBuilder() .serial_number(serial_number) .revocation_date(revocation_date) .add_extension(invalidity_date, True) .add_extension(crl_reason, True) .add_extension(certificate_issuer, True) ) revoked_certificate = builder.build(backend) assert len(revoked_certificate.extensions) == 3 for ext_data in [invalidity_date, certificate_issuer, crl_reason]: ext = revoked_certificate.extensions.get_extension_for_class( type(ext_data) ) assert ext.critical is True assert ext.value == ext_data
def test_add_multiple_extensions(self, backend): serial_number = 333 revocation_date = datetime.datetime(2002, 1, 1, 12, 1) invalidity_date = x509.InvalidityDate( datetime.datetime(2015, 1, 1, 0, 0) ) certificate_issuer = x509.CertificateIssuer( [x509.DNSName("cryptography.io")] ) crl_reason = x509.CRLReason(x509.ReasonFlags.aa_compromise) builder = ( x509.RevokedCertificateBuilder() .serial_number(serial_number) .revocation_date(revocation_date) .add_extension(invalidity_date, True) .add_extension(crl_reason, True) .add_extension(certificate_issuer, True) ) revoked_certificate = builder.build(backend) assert len(revoked_certificate.extensions) == 3 for ext_data in [invalidity_date, certificate_issuer, crl_reason]: ext = revoked_certificate.extensions.get_extension_for_class( type(ext_data) ) <AssertPlaceHolder> assert ext.value == ext_data
tests/x509/test_x509_revokedcertbuilder.py
179
205
tests/x509/test_x509_revokedcertbuilder.py::TestRevokedCertificateBuilder::test_add_multiple_extensions
assert ext.critical is True
204
-1
-1
def get_extension_for_class( self, extclass: type[ExtensionTypeVar] ) -> Extension[ExtensionTypeVar]: if extclass is UnrecognizedExtension: raise TypeError( "UnrecognizedExtension can't be used with " "get_extension_for_class because more than one instance of the" " class may be present." ) for ext in self: if isinstance(ext.value, extclass): return ext raise ExtensionNotFound( f"No {extclass} extension was found", extclass.oid )
src/cryptography/x509/extensions.py
125
141
28
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_ipaddress
TestRSASubjectAlternativeNameExtension
def test_ipaddress(self, backend): cert = _load_cert( os.path.join("x509", "custom", "san_ipaddr.pem"), x509.load_pem_x509_certificate, ) ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ) assert ext is not None assert ext.critical is False san = ext.value ip = san.get_values_for_type(x509.IPAddress) assert [ ipaddress.ip_address("127.0.0.1"), ipaddress.ip_address("ff::"), ] == ip
def test_ipaddress(self, backend): cert = _load_cert( os.path.join("x509", "custom", "san_ipaddr.pem"), x509.load_pem_x509_certificate, ) ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ) assert ext is not None <AssertPlaceHolder> san = ext.value ip = san.get_values_for_type(x509.IPAddress) assert [ ipaddress.ip_address("127.0.0.1"), ipaddress.ip_address("ff::"), ] == ip
tests/x509/test_x509_ext.py
2,751
2,768
tests/x509/test_x509_ext.py::TestRSASubjectAlternativeNameExtension::test_ipaddress
assert ext.critical is False
2,760
-1
-1
def get_extension_for_class( self, extclass: type[ExtensionTypeVar] ) -> Extension[ExtensionTypeVar]: if extclass is UnrecognizedExtension: raise TypeError( "UnrecognizedExtension can't be used with " "get_extension_for_class because more than one instance of the" " class may be present." ) for ext in self: if isinstance(ext.value, extclass): return ext raise ExtensionNotFound( f"No {extclass} extension was found", extclass.oid )
src/cryptography/x509/extensions.py
125
141
29
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_hash
TestOtherName
def test_hash(self): gn = x509.OtherName(x509.ObjectIdentifier("1.2.3.4"), b"derdata") gn2 = x509.OtherName(x509.ObjectIdentifier("1.2.3.4"), b"derdata") gn3 = x509.OtherName(x509.ObjectIdentifier("1.2.3.5"), b"derdata") assert hash(gn) == hash(gn2) assert hash(gn) != hash(gn3)
def test_hash(self): gn = x509.OtherName(x509.ObjectIdentifier("1.2.3.4"), b"derdata") gn2 = x509.OtherName(x509.ObjectIdentifier("1.2.3.4"), b"derdata") gn3 = x509.OtherName(x509.ObjectIdentifier("1.2.3.5"), b"derdata") <AssertPlaceHolder> assert hash(gn) != hash(gn3)
tests/x509/test_x509_ext.py
2,379
2,384
tests/x509/test_x509_ext.py::TestOtherName::test_hash
assert hash(gn) == hash(gn2)
2,383
-1
-1
class OtherName(GeneralName): def __init__(self, type_id: ObjectIdentifier, value: bytes) -> None: if not isinstance(type_id, ObjectIdentifier): raise TypeError("type_id must be an ObjectIdentifier") if not isinstance(value, bytes): raise TypeError("value must be a binary string") self._type_id = type_id self._value = value @property def type_id(self) -> ObjectIdentifier: return self._type_id @property def value(self) -> bytes: return self._value def __repr__(self) -> str: return f"<OtherName(type_id={self.type_id}, value={self.value!r})>" def __eq__(self, other: object) -> bool: if not isinstance(other, OtherName): return NotImplemented return self.type_id == other.type_id and self.value == other.value def __hash__(self) -> int: return hash((self.type_id, self.value))
src/cryptography/x509/general_name.py
253
281
30
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_hash
TestUniformResourceIdentifier
def test_hash(self): g1 = x509.UniformResourceIdentifier("http://host.com") g2 = x509.UniformResourceIdentifier("http://host.com") g3 = x509.UniformResourceIdentifier("http://other.com") assert hash(g1) == hash(g2) assert hash(g1) != hash(g3)
def test_hash(self): g1 = x509.UniformResourceIdentifier("http://host.com") g2 = x509.UniformResourceIdentifier("http://host.com") g3 = x509.UniformResourceIdentifier("http://other.com") <AssertPlaceHolder> assert hash(g1) != hash(g3)
tests/x509/test_x509_ext.py
2,250
2,256
tests/x509/test_x509_ext.py::TestUniformResourceIdentifier::test_hash
assert hash(g1) == hash(g2)
2,255
-1
-1
class UniformResourceIdentifier(GeneralName): def __init__(self, value: str) -> None: if isinstance(value, str): try: value.encode("ascii") except UnicodeEncodeError: raise ValueError( "URI values should be passed as an A-label string. " "This means unicode characters should be encoded via " "a library like idna." ) else: raise TypeError("value must be string") self._value = value @property def value(self) -> str: return self._value @classmethod def _init_without_validation(cls, value: str) -> UniformResourceIdentifier: instance = cls.__new__(cls) instance._value = value return instance def __repr__(self) -> str: return f"<UniformResourceIdentifier(value={self.value!r})>" def __eq__(self, other: object) -> bool: if not isinstance(other, UniformResourceIdentifier): return NotImplemented return self.value == other.value def __hash__(self) -> int: return hash(self.value)
src/cryptography/x509/general_name.py
120
156
31
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_eq
TestSubjectKeyIdentifier
def test_eq(self): ski = x509.SubjectKeyIdentifier( binascii.unhexlify(b"092384932230498bc980aa8098456f6ff7ff3ac9") ) ski2 = x509.SubjectKeyIdentifier( binascii.unhexlify(b"092384932230498bc980aa8098456f6ff7ff3ac9") ) assert ski == ski2
def test_eq(self): ski = x509.SubjectKeyIdentifier( binascii.unhexlify(b"092384932230498bc980aa8098456f6ff7ff3ac9") ) ski2 = x509.SubjectKeyIdentifier( binascii.unhexlify(b"092384932230498bc980aa8098456f6ff7ff3ac9") ) <AssertPlaceHolder>
tests/x509/test_x509_ext.py
1,200
1,207
tests/x509/test_x509_ext.py::TestSubjectKeyIdentifier::test_eq
assert ski == ski2
1,207
-1
-1
class SubjectKeyIdentifier(ExtensionType): oid = ExtensionOID.SUBJECT_KEY_IDENTIFIER def __init__(self, digest: bytes) -> None: self._digest = digest @classmethod def from_public_key( cls, public_key: CertificatePublicKeyTypes ) -> SubjectKeyIdentifier: return cls(_key_identifier_from_public_key(public_key)) @property def digest(self) -> bytes: return self._digest @property def key_identifier(self) -> bytes: return self._digest def __repr__(self) -> str: return f"<SubjectKeyIdentifier(digest={self.digest!r})>" def __eq__(self, other: object) -> bool: if not isinstance(other, SubjectKeyIdentifier): return NotImplemented return constant_time.bytes_eq(self.digest, other.digest) def __hash__(self) -> int: return hash(self.digest) def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
286
319
32
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_iter_input
TestNoticeReference
def test_iter_input(self): numbers = [1, 3, 4] nr = x509.NoticeReference("org", iter(numbers)) assert list(nr.notice_numbers) == numbers
def test_iter_input(self): numbers = [1, 3, 4] nr = x509.NoticeReference("org", iter(numbers)) <AssertPlaceHolder>
tests/x509/test_x509_ext.py
480
483
tests/x509/test_x509_ext.py::TestNoticeReference::test_iter_input
assert list(nr.notice_numbers) == numbers
483
-1
-1
class NoticeReference: def __init__( self, organization: str | None, notice_numbers: Iterable[int], ) -> None: self._organization = organization notice_numbers = list(notice_numbers) if not all(isinstance(x, int) for x in notice_numbers): raise TypeError("notice_numbers must be a list of integers") self._notice_numbers = notice_numbers def __repr__(self) -> str: return ( f"<NoticeReference(organization={self.organization!r}, " f"notice_numbers={self.notice_numbers})>" ) def __eq__(self, other: object) -> bool: if not isinstance(other, NoticeReference): return NotImplemented return ( self.organization == other.organization and self.notice_numbers == other.notice_numbers ) def __hash__(self) -> int: return hash((self.organization, tuple(self.notice_numbers))) @property def organization(self) -> str | None: return self._organization @property def notice_numbers(self) -> list[int]: return self._notice_numbers
src/cryptography/x509/extensions.py
948
985
33
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_public_key_equality
@pytest.mark.supported( only_if=lambda backend: backend.x25519_supported(), skip_message="Requires OpenSSL with X25519 support", ) def test_public_key_equality(backend): key_bytes = load_vectors_from_file( os.path.join("asymmetric", "X25519", "x25519-pkcs8.der"), lambda derfile: derfile.read(), mode="rb", ) key1 = serialization.load_der_private_key(key_bytes, None).public_key() key2 = serialization.load_der_private_key(key_bytes, None).public_key() key3 = X25519PrivateKey.generate().public_key() assert key1 == key2 assert key1 != key3 assert key1 != object() with pytest.raises(TypeError): key1 < key2 # type: ignore[operator]
@pytest.mark.supported( only_if=lambda backend: backend.x25519_supported(), skip_message="Requires OpenSSL with X25519 support", ) def test_public_key_equality(backend): key_bytes = load_vectors_from_file( os.path.join("asymmetric", "X25519", "x25519-pkcs8.der"), lambda derfile: derfile.read(), mode="rb", ) key1 = serialization.load_der_private_key(key_bytes, None).public_key() key2 = serialization.load_der_private_key(key_bytes, None).public_key() key3 = X25519PrivateKey.generate().public_key() assert key1 == key2 <AssertPlaceHolder> assert key1 != object() with pytest.raises(TypeError): key1 < key2 # type: ignore[operator]
tests/hazmat/primitives/test_x25519.py
346
363
tests/hazmat/primitives/test_x25519.py::test_public_key_equality
assert key1 != key3
360
-1
-1
@abc.abstractmethod def public_key(self) -> X25519PublicKey: """ Returns the public key associated with this private key """
src/cryptography/hazmat/primitives/asymmetric/x25519.py
85
89
34
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_ne
TestDeltaCRLIndicator
def test_ne(self): delta1 = x509.DeltaCRLIndicator(1) delta2 = x509.DeltaCRLIndicator(2) assert delta1 != delta2 assert delta1 != object()
def test_ne(self): delta1 = x509.DeltaCRLIndicator(1) delta2 = x509.DeltaCRLIndicator(2) <AssertPlaceHolder> assert delta1 != object()
tests/x509/test_x509_ext.py
392
396
tests/x509/test_x509_ext.py::TestDeltaCRLIndicator::test_ne
assert delta1 != delta2
395
-1
-1
class DeltaCRLIndicator(ExtensionType): oid = ExtensionOID.DELTA_CRL_INDICATOR def __init__(self, crl_number: int) -> None: if not isinstance(crl_number, int): raise TypeError("crl_number must be an integer") self._crl_number = crl_number @property def crl_number(self) -> int: return self._crl_number def __eq__(self, other: object) -> bool: if not isinstance(other, DeltaCRLIndicator): return NotImplemented return self.crl_number == other.crl_number def __hash__(self) -> int: return hash(self.crl_number) def __repr__(self) -> str: return f"<DeltaCRLIndicator(crl_number={self.crl_number})>" def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
470
496
35
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_zany_py2_bytes_subclass
TestPKCS7
def test_zany_py2_bytes_subclass(self): class mybytes(bytes): # noqa: N801 def __str__(self): return "broken" str(mybytes()) padder = padding.PKCS7(128).padder() data = padder.update(mybytes(b"abc")) + padder.finalize() unpadder = padding.PKCS7(128).unpadder() unpadder.update(mybytes(data)) assert unpadder.finalize() == b"abc"
def test_zany_py2_bytes_subclass(self): class mybytes(bytes): # noqa: N801 def __str__(self): return "broken" str(mybytes()) padder = padding.PKCS7(128).padder() data = padder.update(mybytes(b"abc")) + padder.finalize() unpadder = padding.PKCS7(128).unpadder() unpadder.update(mybytes(data)) <AssertPlaceHolder>
tests/hazmat/primitives/test_padding.py
43
53
tests/hazmat/primitives/test_padding.py::TestPKCS7::test_zany_py2_bytes_subclass
assert unpadder.finalize() == b"abc"
53
-1
-1
@abc.abstractmethod def finalize(self) -> bytes: """ Finalize the padding, returns bytes. """
src/cryptography/hazmat/primitives/padding.py
25
29
36
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_get_revoked_certificate_doesnt_reorder
TestRevokedCertificate
def test_get_revoked_certificate_doesnt_reorder( self, rsa_key_2048: rsa.RSAPrivateKey, backend ): private_key = rsa_key_2048 last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) builder = ( x509.CertificateRevocationListBuilder() .issuer_name( x509.Name( [ x509.NameAttribute( NameOID.COMMON_NAME, "cryptography.io CA" ) ] ) ) .last_update(last_update) .next_update(next_update) ) for i in [2, 500, 3, 49, 7, 1]: revoked_cert = ( x509.RevokedCertificateBuilder() .serial_number(i) .revocation_date(datetime.datetime(2012, 1, 1, 1, 1)) .build(backend) ) builder = builder.add_revoked_certificate(revoked_cert) crl = builder.sign(private_key, hashes.SHA256(), backend) assert crl[0].serial_number == 2 assert crl[2].serial_number == 3 # make sure get_revoked_certificate_by_serial_number doesn't affect # ordering after being invoked crl.get_revoked_certificate_by_serial_number(500) assert crl[0].serial_number == 2 assert crl[2].serial_number == 3
def test_get_revoked_certificate_doesnt_reorder( self, rsa_key_2048: rsa.RSAPrivateKey, backend ): private_key = rsa_key_2048 last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) builder = ( x509.CertificateRevocationListBuilder() .issuer_name( x509.Name( [ x509.NameAttribute( NameOID.COMMON_NAME, "cryptography.io CA" ) ] ) ) .last_update(last_update) .next_update(next_update) ) for i in [2, 500, 3, 49, 7, 1]: revoked_cert = ( x509.RevokedCertificateBuilder() .serial_number(i) .revocation_date(datetime.datetime(2012, 1, 1, 1, 1)) .build(backend) ) builder = builder.add_revoked_certificate(revoked_cert) crl = builder.sign(private_key, hashes.SHA256(), backend) <AssertPlaceHolder> assert crl[2].serial_number == 3 # make sure get_revoked_certificate_by_serial_number doesn't affect # ordering after being invoked crl.get_revoked_certificate_by_serial_number(500) <AssertPlaceHolder> assert crl[2].serial_number == 3
tests/x509/test_x509.py
772
807
tests/x509/test_x509.py::TestRevokedCertificate::test_get_revoked_certificate_doesnt_reorder
assert crl[0].serial_number == 2
801
-1
-1
def sign( self, private_key: CertificateIssuerPrivateKeyTypes, algorithm: _AllowedHashTypes | None, backend: typing.Any = None, *, rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, ecdsa_deterministic: bool | None = None, ) -> CertificateRevocationList: if self._issuer_name is None: raise ValueError("A CRL must have an issuer name") if self._last_update is None: raise ValueError("A CRL must have a last update time") if self._next_update is None: raise ValueError("A CRL must have a next update time") if rsa_padding is not None: if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): raise TypeError("Padding must be PSS or PKCS1v15") if not isinstance(private_key, rsa.RSAPrivateKey): raise TypeError("Padding is only supported for RSA keys") if ecdsa_deterministic is not None: if not isinstance(private_key, ec.EllipticCurvePrivateKey): raise TypeError( "Deterministic ECDSA is only supported for EC keys" ) return rust_x509.create_x509_crl( self, private_key, algorithm, rsa_padding, ecdsa_deterministic, )
src/cryptography/x509/base.py
735
771
37
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_hash
TestSignedCertificateTimestampsExtension
def test_hash(self, backend): sct1 = ( _load_data( os.path.join("x509", "ocsp", "resp-sct-extension.der"), ocsp.load_der_ocsp_response, ) .single_extensions.get_extension_for_class( x509.SignedCertificateTimestamps ) .value ) sct2 = ( _load_data( os.path.join("x509", "ocsp", "resp-sct-extension.der"), ocsp.load_der_ocsp_response, ) .single_extensions.get_extension_for_class( x509.SignedCertificateTimestamps ) .value ) sct3 = x509.SignedCertificateTimestamps([]) assert hash(sct1) == hash(sct2) assert hash(sct1) != hash(sct3)
def test_hash(self, backend): sct1 = ( _load_data( os.path.join("x509", "ocsp", "resp-sct-extension.der"), ocsp.load_der_ocsp_response, ) .single_extensions.get_extension_for_class( x509.SignedCertificateTimestamps ) .value ) sct2 = ( _load_data( os.path.join("x509", "ocsp", "resp-sct-extension.der"), ocsp.load_der_ocsp_response, ) .single_extensions.get_extension_for_class( x509.SignedCertificateTimestamps ) .value ) sct3 = x509.SignedCertificateTimestamps([]) assert hash(sct1) == hash(sct2) <AssertPlaceHolder>
tests/x509/test_ocsp.py
1,234
1,257
tests/x509/test_ocsp.py::TestSignedCertificateTimestampsExtension::test_hash
assert hash(sct1) != hash(sct3)
1,257
-1
-1
class SignedCertificateTimestamps(ExtensionType): oid = ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS def __init__( self, signed_certificate_timestamps: Iterable[SignedCertificateTimestamp], ) -> None: signed_certificate_timestamps = list(signed_certificate_timestamps) if not all( isinstance(sct, SignedCertificateTimestamp) for sct in signed_certificate_timestamps ): raise TypeError( "Every item in the signed_certificate_timestamps list must be " "a SignedCertificateTimestamp" ) self._signed_certificate_timestamps = signed_certificate_timestamps __len__, __iter__, __getitem__ = _make_sequence_methods( "_signed_certificate_timestamps" ) def __repr__(self) -> str: return f"<SignedCertificateTimestamps({list(self)})>" def __hash__(self) -> int: return hash(tuple(self._signed_certificate_timestamps)) def __eq__(self, other: object) -> bool: if not isinstance(other, SignedCertificateTimestamps): return NotImplemented return ( self._signed_certificate_timestamps == other._signed_certificate_timestamps ) def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
1,899
1,937
38
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_ne
TestSignedCertificateTimestampsExtension
def test_ne(self, backend): sct1 = ( _load_data( os.path.join("x509", "ocsp", "resp-sct-extension.der"), ocsp.load_der_ocsp_response, ) .single_extensions.get_extension_for_class( x509.SignedCertificateTimestamps ) .value ) sct2 = x509.SignedCertificateTimestamps([]) assert sct1 != sct2 assert sct1 != object()
def test_ne(self, backend): sct1 = ( _load_data( os.path.join("x509", "ocsp", "resp-sct-extension.der"), ocsp.load_der_ocsp_response, ) .single_extensions.get_extension_for_class( x509.SignedCertificateTimestamps ) .value ) sct2 = x509.SignedCertificateTimestamps([]) <AssertPlaceHolder> assert sct1 != object()
tests/x509/test_ocsp.py
1,219
1,232
tests/x509/test_ocsp.py::TestSignedCertificateTimestampsExtension::test_ne
assert sct1 != sct2
1,231
-1
-1
class SignedCertificateTimestamps(ExtensionType): oid = ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS def __init__( self, signed_certificate_timestamps: Iterable[SignedCertificateTimestamp], ) -> None: signed_certificate_timestamps = list(signed_certificate_timestamps) if not all( isinstance(sct, SignedCertificateTimestamp) for sct in signed_certificate_timestamps ): raise TypeError( "Every item in the signed_certificate_timestamps list must be " "a SignedCertificateTimestamp" ) self._signed_certificate_timestamps = signed_certificate_timestamps __len__, __iter__, __getitem__ = _make_sequence_methods( "_signed_certificate_timestamps" ) def __repr__(self) -> str: return f"<SignedCertificateTimestamps({list(self)})>" def __hash__(self) -> int: return hash(tuple(self._signed_certificate_timestamps)) def __eq__(self, other: object) -> bool: if not isinstance(other, SignedCertificateTimestamps): return NotImplemented return ( self._signed_certificate_timestamps == other._signed_certificate_timestamps ) def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
1,899
1,937
39
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_public_bytes
TestDeltaCRLIndicator
def test_public_bytes(self): ext = x509.DeltaCRLIndicator(2) assert ext.public_bytes() == b"\x02\x01\x02"
def test_public_bytes(self): ext = x509.DeltaCRLIndicator(2) <AssertPlaceHolder>
tests/x509/test_x509_ext.py
409
411
tests/x509/test_x509_ext.py::TestDeltaCRLIndicator::test_public_bytes
assert ext.public_bytes() == b"\x02\x01\x02"
411
-1
-1
def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
495
496
40
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_no_parsed_hostname
TestUniformResourceIdentifier
def test_no_parsed_hostname(self): gn = x509.UniformResourceIdentifier("singlelabel") assert gn.value == "singlelabel"
def test_no_parsed_hostname(self): gn = x509.UniformResourceIdentifier("singlelabel") <AssertPlaceHolder>
tests/x509/test_x509_ext.py
2,232
2,234
tests/x509/test_x509_ext.py::TestUniformResourceIdentifier::test_no_parsed_hostname
assert gn.value == "singlelabel"
2,234
-1
-1
class UniformResourceIdentifier(GeneralName): def __init__(self, value: str) -> None: if isinstance(value, str): try: value.encode("ascii") except UnicodeEncodeError: raise ValueError( "URI values should be passed as an A-label string. " "This means unicode characters should be encoded via " "a library like idna." ) else: raise TypeError("value must be string") self._value = value @property def value(self) -> str: return self._value @classmethod def _init_without_validation(cls, value: str) -> UniformResourceIdentifier: instance = cls.__new__(cls) instance._value = value return instance def __repr__(self) -> str: return f"<UniformResourceIdentifier(value={self.value!r})>" def __eq__(self, other: object) -> bool: if not isinstance(other, UniformResourceIdentifier): return NotImplemented return self.value == other.value def __hash__(self) -> int: return hash(self.value)
src/cryptography/x509/general_name.py
120
156
41
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_repr
TestIPAddress
def test_repr(self): gn = x509.IPAddress(ipaddress.IPv4Address("127.0.0.1")) assert repr(gn) == "<IPAddress(value=127.0.0.1)>" gn2 = x509.IPAddress(ipaddress.IPv6Address("ff::")) assert repr(gn2) == "<IPAddress(value=ff::)>" gn3 = x509.IPAddress(ipaddress.IPv4Network("192.168.0.0/24")) assert repr(gn3) == "<IPAddress(value=192.168.0.0/24)>" gn4 = x509.IPAddress(ipaddress.IPv6Network("ff::/96")) assert repr(gn4) == "<IPAddress(value=ff::/96)>"
def test_repr(self): gn = x509.IPAddress(ipaddress.IPv4Address("127.0.0.1")) assert repr(gn) == "<IPAddress(value=127.0.0.1)>" gn2 = x509.IPAddress(ipaddress.IPv6Address("ff::")) assert repr(gn2) == "<IPAddress(value=ff::)>" gn3 = x509.IPAddress(ipaddress.IPv4Network("192.168.0.0/24")) <AssertPlaceHolder> gn4 = x509.IPAddress(ipaddress.IPv6Network("ff::/96")) assert repr(gn4) == "<IPAddress(value=ff::/96)>"
tests/x509/test_x509_ext.py
2,305
2,316
tests/x509/test_x509_ext.py::TestIPAddress::test_repr
assert repr(gn3) == "<IPAddress(value=192.168.0.0/24)>"
2,313
-1
-1
class IPAddress(GeneralName): def __init__(self, value: _IPAddressTypes) -> None: if not isinstance( value, ( ipaddress.IPv4Address, ipaddress.IPv6Address, ipaddress.IPv4Network, ipaddress.IPv6Network, ), ): raise TypeError( "value must be an instance of ipaddress.IPv4Address, " "ipaddress.IPv6Address, ipaddress.IPv4Network, or " "ipaddress.IPv6Network" ) self._value = value @property def value(self) -> _IPAddressTypes: return self._value def _packed(self) -> bytes: if isinstance( self.value, (ipaddress.IPv4Address, ipaddress.IPv6Address) ): return self.value.packed else: return ( self.value.network_address.packed + self.value.netmask.packed ) def __repr__(self) -> str: return f"<IPAddress(value={self.value})>" def __eq__(self, other: object) -> bool: if not isinstance(other, IPAddress): return NotImplemented return self.value == other.value def __hash__(self) -> int: return hash(self.value)
src/cryptography/x509/general_name.py
207
250
42
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_rsa_padding_supported_pkcs1v15
TestOpenSSLRSA
def test_rsa_padding_supported_pkcs1v15(self): assert backend.rsa_padding_supported(padding.PKCS1v15()) is True
def test_rsa_padding_supported_pkcs1v15(self): <AssertPlaceHolder>
tests/hazmat/backends/test_openssl.py
126
127
tests/hazmat/backends/test_openssl.py::TestOpenSSLRSA::test_rsa_padding_supported_pkcs1v15
assert backend.rsa_padding_supported(padding.PKCS1v15()) is True
127
-1
-1
def rsa_padding_supported(self, padding: AsymmetricPadding) -> bool: if isinstance(padding, PKCS1v15): return True elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1): # FIPS 186-4 only allows salt length == digest length for PSS # It is technically acceptable to set an explicit salt length # equal to the digest length and this will incorrectly fail, but # since we don't do that in the tests and this method is # private, we'll ignore that until we need to do otherwise. if ( self._fips_enabled and padding._salt_length != PSS.DIGEST_LENGTH ): return False return self.hash_supported(padding._mgf._algorithm) elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1): return self._oaep_hash_supported( padding._mgf._algorithm ) and self._oaep_hash_supported(padding._algorithm) else: return False
src/cryptography/hazmat/backends/openssl/backend.py
180
200
43
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_block_size_padding
TestANSIX923
def test_block_size_padding(self): padder = padding.ANSIX923(64).padder() data = padder.update(b"a" * 8) + padder.finalize() assert data == b"a" * 8 + b"\x00" * 7 + b"\x08"
def test_block_size_padding(self): padder = padding.ANSIX923(64).padder() data = padder.update(b"a" * 8) + padder.finalize() <AssertPlaceHolder>
tests/hazmat/primitives/test_padding.py
249
252
tests/hazmat/primitives/test_padding.py::TestANSIX923::test_block_size_padding
assert data == b"a" * 8 + b"\x00" * 7 + b"\x08"
252
-1
-1
@abc.abstractmethod def finalize(self) -> bytes: """ Finalize the padding, returns bytes. """
src/cryptography/hazmat/primitives/padding.py
25
29
44
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_sign_with_appended_certs
TestOCSPResponseBuilder
def test_sign_with_appended_certs(self): builder = ocsp.OCSPResponseBuilder() cert, issuer = _cert_and_issuer() root_cert, private_key = _generate_root() current_time = ( datetime.datetime.now(datetime.timezone.utc) .replace(tzinfo=None) .replace(microsecond=0) ) this_update = current_time - datetime.timedelta(days=1) next_update = this_update + datetime.timedelta(days=7) builder = ( builder.responder_id(ocsp.OCSPResponderEncoding.NAME, root_cert) .add_response( cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.GOOD, this_update, next_update, None, None, ) .certificates([root_cert]) ) resp = builder.sign(private_key, hashes.SHA256()) assert resp.certificates == [root_cert]
def test_sign_with_appended_certs(self): builder = ocsp.OCSPResponseBuilder() cert, issuer = _cert_and_issuer() root_cert, private_key = _generate_root() current_time = ( datetime.datetime.now(datetime.timezone.utc) .replace(tzinfo=None) .replace(microsecond=0) ) this_update = current_time - datetime.timedelta(days=1) next_update = this_update + datetime.timedelta(days=7) builder = ( builder.responder_id(ocsp.OCSPResponderEncoding.NAME, root_cert) .add_response( cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.GOOD, this_update, next_update, None, None, ) .certificates([root_cert]) ) resp = builder.sign(private_key, hashes.SHA256()) <AssertPlaceHolder>
tests/x509/test_ocsp.py
752
778
tests/x509/test_ocsp.py::TestOCSPResponseBuilder::test_sign_with_appended_certs
assert resp.certificates == [root_cert]
778
-1
-1
def sign( self, private_key: CertificateIssuerPrivateKeyTypes, algorithm: hashes.HashAlgorithm | None, ) -> OCSPResponse: if self._response is None: raise ValueError("You must add a response before signing") if self._responder_id is None: raise ValueError("You must add a responder_id before signing") return ocsp.create_ocsp_response( OCSPResponseStatus.SUCCESSFUL, self, private_key, algorithm )
src/cryptography/x509/ocsp.py
350
362
45
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_recover_prime_factors
TestRSAPrimeFactorRecovery
def test_recover_prime_factors(self, subtests): for key in [ RSA_KEY_1024, RSA_KEY_1025, RSA_KEY_1026, RSA_KEY_1027, RSA_KEY_1028, RSA_KEY_1029, RSA_KEY_1030, RSA_KEY_1031, RSA_KEY_1536, RSA_KEY_2048, ]: with subtests.test(): p, q = rsa.rsa_recover_prime_factors( key.public_numbers.n, key.public_numbers.e, key.d, ) # Unfortunately there is no convention on which prime should be # p and which one q. The function we use always makes p > q, # but the NIST vectors are not so consistent. Accordingly, we # verify we've recovered the proper (p, q) by sorting them and # asserting on that. assert sorted([p, q]) == sorted([key.p, key.q]) assert p > q
def test_recover_prime_factors(self, subtests): for key in [ RSA_KEY_1024, RSA_KEY_1025, RSA_KEY_1026, RSA_KEY_1027, RSA_KEY_1028, RSA_KEY_1029, RSA_KEY_1030, RSA_KEY_1031, RSA_KEY_1536, RSA_KEY_2048, ]: with subtests.test(): p, q = rsa.rsa_recover_prime_factors( key.public_numbers.n, key.public_numbers.e, key.d, ) # Unfortunately there is no convention on which prime should be # p and which one q. The function we use always makes p > q, # but the NIST vectors are not so consistent. Accordingly, we # verify we've recovered the proper (p, q) by sorting them and # asserting on that. <AssertPlaceHolder> assert p > q
tests/hazmat/primitives/test_rsa.py
2,353
2,378
tests/hazmat/primitives/test_rsa.py::TestRSAPrimeFactorRecovery::test_recover_prime_factors
assert sorted([p, q]) == sorted([key.p, key.q])
2,377
-1
-1
def rsa_recover_prime_factors(n: int, e: int, d: int) -> tuple[int, int]: """ Compute factors p and q from the private exponent d. We assume that n has no more than two factors. This function is adapted from code in PyCrypto. """ # reject invalid values early if d <= 1 or e <= 1: raise ValueError("d, e can't be <= 1") if 17 != pow(17, e * d, n): raise ValueError("n, d, e don't match") # See 8.2.2(i) in Handbook of Applied Cryptography. ktot = d * e - 1 # The quantity d*e-1 is a multiple of phi(n), even, # and can be represented as t*2^s. t = ktot while t % 2 == 0: t = t // 2 # Cycle through all multiplicative inverses in Zn. # The algorithm is non-deterministic, but there is a 50% chance # any candidate a leads to successful factoring. # See "Digitalized Signatures and Public Key Functions as Intractable # as Factorization", M. Rabin, 1979 spotted = False tries = 0 while not spotted and tries < _MAX_RECOVERY_ATTEMPTS: a = random.randint(2, n - 1) tries += 1 k = t # Cycle through all values a^{t*2^i}=a^k while k < ktot: cand = pow(a, k, n) # Check if a^k is a non-trivial root of unity (mod n) if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1: # We have found a number such that (cand-1)(cand+1)=0 (mod n). # Either of the terms divides n. p = gcd(cand + 1, n) spotted = True break k *= 2 if not spotted: raise ValueError("Unable to compute factors p and q from exponent d.") # Found ! q, r = divmod(n, p) assert r == 0 p, q = sorted((p, q), reverse=True) return (p, q)
src/cryptography/hazmat/primitives/asymmetric/rsa.py
240
285
46
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_hash
TestDNSName
def test_hash(self): n1 = x509.DNSName("test1") n2 = x509.DNSName("test2") n3 = x509.DNSName("test2") assert hash(n1) != hash(n2) assert hash(n2) == hash(n3)
def test_hash(self): n1 = x509.DNSName("test1") n2 = x509.DNSName("test2") n3 = x509.DNSName("test2") <AssertPlaceHolder> assert hash(n2) == hash(n3)
tests/x509/test_x509_ext.py
2,117
2,122
tests/x509/test_x509_ext.py::TestDNSName::test_hash
assert hash(n1) != hash(n2)
2,121
-1
-1
class DNSName(GeneralName): def __init__(self, value: str) -> None: if isinstance(value, str): try: value.encode("ascii") except UnicodeEncodeError: raise ValueError( "DNSName values should be passed as an A-label string. " "This means unicode characters should be encoded via " "a library like idna." ) else: raise TypeError("value must be string") self._value = value @property def value(self) -> str: return self._value @classmethod def _init_without_validation(cls, value: str) -> DNSName: instance = cls.__new__(cls) instance._value = value return instance def __repr__(self) -> str: return f"<DNSName(value={self.value!r})>" def __eq__(self, other: object) -> bool: if not isinstance(other, DNSName): return NotImplemented return self.value == other.value def __hash__(self) -> int: return hash(self.value)
src/cryptography/x509/general_name.py
81
117
47
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_generate
TestX448Exchange
def test_generate(self, backend): key = X448PrivateKey.generate() assert key assert key.public_key()
def test_generate(self, backend): key = X448PrivateKey.generate() assert key <AssertPlaceHolder>
tests/hazmat/primitives/test_x448.py
180
183
tests/hazmat/primitives/test_x448.py::TestX448Exchange::test_generate
assert key.public_key()
183
-1
-1
@classmethod def generate(cls) -> X448PrivateKey: from cryptography.hazmat.backends.openssl.backend import backend if not backend.x448_supported(): raise UnsupportedAlgorithm( "X448 is not supported by this version of OpenSSL.", _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, ) return rust_openssl.x448.generate_key()
src/cryptography/hazmat/primitives/asymmetric/x448.py
63
73
48
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_delta_crl_indicator
TestCertificateRevocationList
def test_delta_crl_indicator(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_delta_crl_indicator.pem"), x509.load_pem_x509_crl, ) dci = crl.extensions.get_extension_for_oid( ExtensionOID.DELTA_CRL_INDICATOR ) assert dci.value == x509.DeltaCRLIndicator(12345678901234567890) assert dci.critical is True
def test_delta_crl_indicator(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_delta_crl_indicator.pem"), x509.load_pem_x509_crl, ) dci = crl.extensions.get_extension_for_oid( ExtensionOID.DELTA_CRL_INDICATOR ) assert dci.value == x509.DeltaCRLIndicator(12345678901234567890) <AssertPlaceHolder>
tests/x509/test_x509.py
437
447
tests/x509/test_x509.py::TestCertificateRevocationList::test_delta_crl_indicator
assert dci.critical is True
447
-1
-1
def get_extension_for_oid( self, oid: ObjectIdentifier ) -> Extension[ExtensionType]: for ext in self: if ext.oid == oid: return ext raise ExtensionNotFound(f"No {oid} extension was found", oid)
src/cryptography/x509/extensions.py
116
123
49
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_with_port
TestUniformResourceIdentifier
def test_with_port(self): gn = x509.UniformResourceIdentifier("singlelabel:443/test") assert gn.value == "singlelabel:443/test"
def test_with_port(self): gn = x509.UniformResourceIdentifier("singlelabel:443/test") <AssertPlaceHolder>
tests/x509/test_x509_ext.py
2,236
2,238
tests/x509/test_x509_ext.py::TestUniformResourceIdentifier::test_with_port
assert gn.value == "singlelabel:443/test"
2,238
-1
-1
class UniformResourceIdentifier(GeneralName): def __init__(self, value: str) -> None: if isinstance(value, str): try: value.encode("ascii") except UnicodeEncodeError: raise ValueError( "URI values should be passed as an A-label string. " "This means unicode characters should be encoded via " "a library like idna." ) else: raise TypeError("value must be string") self._value = value @property def value(self) -> str: return self._value @classmethod def _init_without_validation(cls, value: str) -> UniformResourceIdentifier: instance = cls.__new__(cls) instance._value = value return instance def __repr__(self) -> str: return f"<UniformResourceIdentifier(value={self.value!r})>" def __eq__(self, other: object) -> bool: if not isinstance(other, UniformResourceIdentifier): return NotImplemented return self.value == other.value def __hash__(self) -> int: return hash(self.value)
src/cryptography/x509/general_name.py
120
156
50
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_build_ca_request_with_ed448
TestCertificateSigningRequestBuilder
@pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), skip_message="Requires OpenSSL with Ed448 support", ) def test_build_ca_request_with_ed448(self, backend): private_key = ed448.Ed448PrivateKey.generate() request = ( x509.CertificateSigningRequestBuilder() .subject_name( x509.Name( [ x509.NameAttribute( NameOID.STATE_OR_PROVINCE_NAME, "Texas" ), ] ) ) .add_extension( x509.BasicConstraints(ca=True, path_length=2), critical=True ) .sign(private_key, None, backend) ) assert request.signature_hash_algorithm is None public_key = request.public_key() assert isinstance(public_key, ed448.Ed448PublicKey) subject = request.subject assert isinstance(subject, x509.Name) assert list(subject) == [ x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Texas"), ] basic_constraints = request.extensions.get_extension_for_class( x509.BasicConstraints ) assert basic_constraints.value.ca is True assert basic_constraints.value.path_length == 2
@pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), skip_message="Requires OpenSSL with Ed448 support", ) def test_build_ca_request_with_ed448(self, backend): private_key = ed448.Ed448PrivateKey.generate() request = ( x509.CertificateSigningRequestBuilder() .subject_name( x509.Name( [ x509.NameAttribute( NameOID.STATE_OR_PROVINCE_NAME, "Texas" ), ] ) ) .add_extension( x509.BasicConstraints(ca=True, path_length=2), critical=True ) .sign(private_key, None, backend) ) assert request.signature_hash_algorithm is None public_key = request.public_key() assert isinstance(public_key, ed448.Ed448PublicKey) subject = request.subject assert isinstance(subject, x509.Name) assert list(subject) == [ x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Texas"), ] basic_constraints = request.extensions.get_extension_for_class( x509.BasicConstraints ) <AssertPlaceHolder> assert basic_constraints.value.path_length == 2
tests/x509/test_x509.py
4,951
4,987
tests/x509/test_x509.py::TestCertificateSigningRequestBuilder::test_build_ca_request_with_ed448
assert basic_constraints.value.ca is True
4,986
-1
-1
def get_extension_for_class( self, extclass: type[ExtensionTypeVar] ) -> Extension[ExtensionTypeVar]: if extclass is UnrecognizedExtension: raise TypeError( "UnrecognizedExtension can't be used with " "get_extension_for_class because more than one instance of the" " class may be present." ) for ext in self: if isinstance(ext.value, extclass): return ext raise ExtensionNotFound( f"No {extclass} extension was found", extclass.oid )
src/cryptography/x509/extensions.py
125
141
51
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_public_key_equality
@pytest.mark.supported( only_if=lambda backend: backend.ed25519_supported(), skip_message="Requires OpenSSL with Ed25519 support", ) def test_public_key_equality(backend): key_bytes = load_vectors_from_file( os.path.join("asymmetric", "Ed25519", "ed25519-pkcs8.der"), lambda derfile: derfile.read(), mode="rb", ) key1 = serialization.load_der_private_key(key_bytes, None).public_key() key2 = serialization.load_der_private_key(key_bytes, None).public_key() key3 = Ed25519PrivateKey.generate().public_key() assert key1 == key2 assert key1 != key3 assert key1 != object() with pytest.raises(TypeError): key1 < key2 # type: ignore[operator]
@pytest.mark.supported( only_if=lambda backend: backend.ed25519_supported(), skip_message="Requires OpenSSL with Ed25519 support", ) def test_public_key_equality(backend): key_bytes = load_vectors_from_file( os.path.join("asymmetric", "Ed25519", "ed25519-pkcs8.der"), lambda derfile: derfile.read(), mode="rb", ) key1 = serialization.load_der_private_key(key_bytes, None).public_key() key2 = serialization.load_der_private_key(key_bytes, None).public_key() key3 = Ed25519PrivateKey.generate().public_key() assert key1 == key2 <AssertPlaceHolder> assert key1 != object() with pytest.raises(TypeError): key1 < key2 # type: ignore[operator]
tests/hazmat/primitives/test_ed25519.py
295
313
tests/hazmat/primitives/test_ed25519.py::test_public_key_equality
assert key1 != key3
309
-1
-1
@abc.abstractmethod def public_key(self) -> Ed25519PublicKey: """ The Ed25519PublicKey derived from the private key. """
src/cryptography/hazmat/primitives/asymmetric/ed25519.py
92
96
52
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_idna2003_invalid
TestRSASubjectAlternativeNameExtension
def test_idna2003_invalid(self, backend): cert = _load_cert( os.path.join("x509", "custom", "san_idna2003_dnsname.pem"), x509.load_pem_x509_certificate, ) san = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value assert len(san) == 1 [name] = san assert name.value == "xn--k4h.ws"
def test_idna2003_invalid(self, backend): cert = _load_cert( os.path.join("x509", "custom", "san_idna2003_dnsname.pem"), x509.load_pem_x509_certificate, ) san = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value assert len(san) == 1 [name] = san <AssertPlaceHolder>
tests/x509/test_x509_ext.py
2,812
2,823
tests/x509/test_x509_ext.py::TestRSASubjectAlternativeNameExtension::test_idna2003_invalid
assert name.value == "xn--k4h.ws"
2,823
-1
-1
def get_extension_for_class( self, extclass: type[ExtensionTypeVar] ) -> Extension[ExtensionTypeVar]: if extclass is UnrecognizedExtension: raise TypeError( "UnrecognizedExtension can't be used with " "get_extension_for_class because more than one instance of the" " class may be present." ) for ext in self: if isinstance(ext.value, extclass): return ext raise ExtensionNotFound( f"No {extclass} extension was found", extclass.oid )
src/cryptography/x509/extensions.py
125
141
53
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_encrypt
TestMultiFernet
def test_encrypt(self, backend): f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend) f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend) f = MultiFernet([f1, f2]) assert f1.decrypt(f.encrypt(b"abc")) == b"abc"
def test_encrypt(self, backend): f1 = Fernet(base64.urlsafe_b64encode(b"\x00" * 32), backend=backend) f2 = Fernet(base64.urlsafe_b64encode(b"\x01" * 32), backend=backend) f = MultiFernet([f1, f2]) <AssertPlaceHolder>
tests/test_fernet.py
168
173
tests/test_fernet.py::TestMultiFernet::test_encrypt
assert f1.decrypt(f.encrypt(b"abc")) == b"abc"
173
-1
-1
def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes: timestamp, data = Fernet._get_unverified_token_data(token) if ttl is None: time_info = None else: time_info = (ttl, int(time.time())) return self._decrypt_data(data, timestamp, time_info)
src/cryptography/fernet.py
84
90
54
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_ne
TestExtendedKeyUsage
def test_ne(self): eku = x509.ExtendedKeyUsage([x509.ObjectIdentifier("1.3.6")]) eku2 = x509.ExtendedKeyUsage([x509.ObjectIdentifier("1.3.6.1")]) assert eku != eku2 assert eku != object()
def test_ne(self): eku = x509.ExtendedKeyUsage([x509.ObjectIdentifier("1.3.6")]) eku2 = x509.ExtendedKeyUsage([x509.ObjectIdentifier("1.3.6.1")]) <AssertPlaceHolder> assert eku != object()
tests/x509/test_x509_ext.py
1,484
1,488
tests/x509/test_x509_ext.py::TestExtendedKeyUsage::test_ne
assert eku != eku2
1,487
-1
-1
class ExtendedKeyUsage(ExtensionType): oid = ExtensionOID.EXTENDED_KEY_USAGE def __init__(self, usages: Iterable[ObjectIdentifier]) -> None: usages = list(usages) if not all(isinstance(x, ObjectIdentifier) for x in usages): raise TypeError( "Every item in the usages list must be an ObjectIdentifier" ) self._usages = usages __len__, __iter__, __getitem__ = _make_sequence_methods("_usages") def __repr__(self) -> str: return f"<ExtendedKeyUsage({self._usages})>" def __eq__(self, other: object) -> bool: if not isinstance(other, ExtendedKeyUsage): return NotImplemented return self._usages == other._usages def __hash__(self) -> int: return hash(tuple(self._usages)) def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
988
1,015
55
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_hash
TestCRLDistributionPoints
def test_hash(self): cdp = x509.CRLDistributionPoints( [ x509.DistributionPoint( [x509.UniformResourceIdentifier("ftp://domain")], None, frozenset( [ x509.ReasonFlags.key_compromise, x509.ReasonFlags.ca_compromise, ] ), [x509.UniformResourceIdentifier("uri://thing")], ), ] ) cdp2 = x509.CRLDistributionPoints( [ x509.DistributionPoint( [x509.UniformResourceIdentifier("ftp://domain")], None, frozenset( [ x509.ReasonFlags.key_compromise, x509.ReasonFlags.ca_compromise, ] ), [x509.UniformResourceIdentifier("uri://thing")], ), ] ) cdp3 = x509.CRLDistributionPoints( [ x509.DistributionPoint( [x509.UniformResourceIdentifier("ftp://domain")], None, frozenset([x509.ReasonFlags.key_compromise]), [x509.UniformResourceIdentifier("uri://thing")], ), ] ) assert hash(cdp) == hash(cdp2) assert hash(cdp) != hash(cdp3)
def test_hash(self): cdp = x509.CRLDistributionPoints( [ x509.DistributionPoint( [x509.UniformResourceIdentifier("ftp://domain")], None, frozenset( [ x509.ReasonFlags.key_compromise, x509.ReasonFlags.ca_compromise, ] ), [x509.UniformResourceIdentifier("uri://thing")], ), ] ) cdp2 = x509.CRLDistributionPoints( [ x509.DistributionPoint( [x509.UniformResourceIdentifier("ftp://domain")], None, frozenset( [ x509.ReasonFlags.key_compromise, x509.ReasonFlags.ca_compromise, ] ), [x509.UniformResourceIdentifier("uri://thing")], ), ] ) cdp3 = x509.CRLDistributionPoints( [ x509.DistributionPoint( [x509.UniformResourceIdentifier("ftp://domain")], None, frozenset([x509.ReasonFlags.key_compromise]), [x509.UniformResourceIdentifier("uri://thing")], ), ] ) assert hash(cdp) == hash(cdp2) <AssertPlaceHolder>
tests/x509/test_x509_ext.py
4,816
4,858
tests/x509/test_x509_ext.py::TestCRLDistributionPoints::test_hash
assert hash(cdp) != hash(cdp3)
4,858
-1
-1
class CRLDistributionPoints(ExtensionType): oid = ExtensionOID.CRL_DISTRIBUTION_POINTS def __init__( self, distribution_points: Iterable[DistributionPoint] ) -> None: distribution_points = list(distribution_points) if not all( isinstance(x, DistributionPoint) for x in distribution_points ): raise TypeError( "distribution_points must be a list of DistributionPoint " "objects" ) self._distribution_points = distribution_points __len__, __iter__, __getitem__ = _make_sequence_methods( "_distribution_points" ) def __repr__(self) -> str: return f"<CRLDistributionPoints({self._distribution_points})>" def __eq__(self, other: object) -> bool: if not isinstance(other, CRLDistributionPoints): return NotImplemented return self._distribution_points == other._distribution_points def __hash__(self) -> int: return hash(tuple(self._distribution_points)) def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
499
533
56
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_iter_input
TestExtendedKeyUsage
def test_iter_input(self): usages = [ x509.ObjectIdentifier("1.3.6.1.5.5.7.3.1"), x509.ObjectIdentifier("1.3.6.1.5.5.7.3.2"), ] aia = x509.ExtendedKeyUsage(iter(usages)) assert list(aia) == usages
def test_iter_input(self): usages = [ x509.ObjectIdentifier("1.3.6.1.5.5.7.3.1"), x509.ObjectIdentifier("1.3.6.1.5.5.7.3.2"), ] aia = x509.ExtendedKeyUsage(iter(usages)) <AssertPlaceHolder>
tests/x509/test_x509_ext.py
1,454
1,460
tests/x509/test_x509_ext.py::TestExtendedKeyUsage::test_iter_input
assert list(aia) == usages
1,460
-1
-1
class ExtendedKeyUsage(ExtensionType): oid = ExtensionOID.EXTENDED_KEY_USAGE def __init__(self, usages: Iterable[ObjectIdentifier]) -> None: usages = list(usages) if not all(isinstance(x, ObjectIdentifier) for x in usages): raise TypeError( "Every item in the usages list must be an ObjectIdentifier" ) self._usages = usages __len__, __iter__, __getitem__ = _make_sequence_methods("_usages") def __repr__(self) -> str: return f"<ExtendedKeyUsage({self._usages})>" def __eq__(self, other: object) -> bool: if not isinstance(other, ExtendedKeyUsage): return NotImplemented return self._usages == other._usages def __hash__(self) -> int: return hash(tuple(self._usages)) def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
988
1,015
57
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_equality
TestUniformResourceIdentifier
def test_equality(self): gn = x509.UniformResourceIdentifier("string") gn2 = x509.UniformResourceIdentifier("string2") gn3 = x509.UniformResourceIdentifier("string") assert gn != gn2 assert gn != object() assert gn == gn3
def test_equality(self): gn = x509.UniformResourceIdentifier("string") gn2 = x509.UniformResourceIdentifier("string2") gn3 = x509.UniformResourceIdentifier("string") assert gn != gn2 assert gn != object() <AssertPlaceHolder>
tests/x509/test_x509_ext.py
2,220
2,226
tests/x509/test_x509_ext.py::TestUniformResourceIdentifier::test_equality
assert gn == gn3
2,226
-1
-1
class UniformResourceIdentifier(GeneralName): def __init__(self, value: str) -> None: if isinstance(value, str): try: value.encode("ascii") except UnicodeEncodeError: raise ValueError( "URI values should be passed as an A-label string. " "This means unicode characters should be encoded via " "a library like idna." ) else: raise TypeError("value must be string") self._value = value @property def value(self) -> str: return self._value @classmethod def _init_without_validation(cls, value: str) -> UniformResourceIdentifier: instance = cls.__new__(cls) instance._value = value return instance def __repr__(self) -> str: return f"<UniformResourceIdentifier(value={self.value!r})>" def __eq__(self, other: object) -> bool: if not isinstance(other, UniformResourceIdentifier): return NotImplemented return self.value == other.value def __hash__(self) -> int: return hash(self.value)
src/cryptography/x509/general_name.py
120
156
58
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_eq
TestCRLDistributionPoints
def test_eq(self): cdp = x509.CRLDistributionPoints( [ x509.DistributionPoint( [x509.UniformResourceIdentifier("ftp://domain")], None, frozenset( [ x509.ReasonFlags.key_compromise, x509.ReasonFlags.ca_compromise, ] ), [x509.UniformResourceIdentifier("uri://thing")], ), ] ) cdp2 = x509.CRLDistributionPoints( [ x509.DistributionPoint( [x509.UniformResourceIdentifier("ftp://domain")], None, frozenset( [ x509.ReasonFlags.key_compromise, x509.ReasonFlags.ca_compromise, ] ), [x509.UniformResourceIdentifier("uri://thing")], ), ] ) assert cdp == cdp2
def test_eq(self): cdp = x509.CRLDistributionPoints( [ x509.DistributionPoint( [x509.UniformResourceIdentifier("ftp://domain")], None, frozenset( [ x509.ReasonFlags.key_compromise, x509.ReasonFlags.ca_compromise, ] ), [x509.UniformResourceIdentifier("uri://thing")], ), ] ) cdp2 = x509.CRLDistributionPoints( [ x509.DistributionPoint( [x509.UniformResourceIdentifier("ftp://domain")], None, frozenset( [ x509.ReasonFlags.key_compromise, x509.ReasonFlags.ca_compromise, ] ), [x509.UniformResourceIdentifier("uri://thing")], ), ] ) <AssertPlaceHolder>
tests/x509/test_x509_ext.py
4,722
4,753
tests/x509/test_x509_ext.py::TestCRLDistributionPoints::test_eq
assert cdp == cdp2
4,753
-1
-1
class CRLDistributionPoints(ExtensionType): oid = ExtensionOID.CRL_DISTRIBUTION_POINTS def __init__( self, distribution_points: Iterable[DistributionPoint] ) -> None: distribution_points = list(distribution_points) if not all( isinstance(x, DistributionPoint) for x in distribution_points ): raise TypeError( "distribution_points must be a list of DistributionPoint " "objects" ) self._distribution_points = distribution_points __len__, __iter__, __getitem__ = _make_sequence_methods( "_distribution_points" ) def __repr__(self) -> str: return f"<CRLDistributionPoints({self._distribution_points})>" def __eq__(self, other: object) -> bool: if not isinstance(other, CRLDistributionPoints): return NotImplemented return self._distribution_points == other._distribution_points def __hash__(self) -> int: return hash(tuple(self._distribution_points)) def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
499
533
59
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_public_bytes
TestPrecertPoisonExtension
def test_public_bytes(self): ext = x509.PrecertPoison() assert ext.public_bytes() == b"\x05\x00"
def test_public_bytes(self): ext = x509.PrecertPoison() <AssertPlaceHolder>
tests/x509/test_x509_ext.py
5,974
5,976
tests/x509/test_x509_ext.py::TestPrecertPoisonExtension::test_public_bytes
assert ext.public_bytes() == b"\x05\x00"
5,976
-1
-1
def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
1,052
1,053
60
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_ne
TestInvalidityDate
def test_ne(self): invalid1 = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 1)) invalid2 = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 2)) assert invalid1 != invalid2 assert invalid1 != object()
def test_ne(self): invalid1 = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 1)) invalid2 = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 2)) <AssertPlaceHolder> assert invalid1 != object()
tests/x509/test_x509_ext.py
424
428
tests/x509/test_x509_ext.py::TestInvalidityDate::test_ne
assert invalid1 != invalid2
427
-1
-1
class InvalidityDate(ExtensionType): oid = CRLEntryExtensionOID.INVALIDITY_DATE def __init__(self, invalidity_date: datetime.datetime) -> None: if not isinstance(invalidity_date, datetime.datetime): raise TypeError("invalidity_date must be a datetime.datetime") self._invalidity_date = invalidity_date def __repr__(self) -> str: return f"<InvalidityDate(invalidity_date={self._invalidity_date})>" def __eq__(self, other: object) -> bool: if not isinstance(other, InvalidityDate): return NotImplemented return self.invalidity_date == other.invalidity_date def __hash__(self) -> int: return hash(self.invalidity_date) @property def invalidity_date(self) -> datetime.datetime: return self._invalidity_date @property def invalidity_date_utc(self) -> datetime.datetime: if self._invalidity_date.tzinfo is None: return self._invalidity_date.replace(tzinfo=datetime.timezone.utc) else: return self._invalidity_date.astimezone(tz=datetime.timezone.utc) def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
1,822
1,855
61
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_eq
TestInhibitAnyPolicy
def test_eq(self): iap = x509.InhibitAnyPolicy(1) iap2 = x509.InhibitAnyPolicy(1) assert iap == iap2
def test_eq(self): iap = x509.InhibitAnyPolicy(1) iap2 = x509.InhibitAnyPolicy(1) <AssertPlaceHolder>
tests/x509/test_x509_ext.py
5,361
5,364
tests/x509/test_x509_ext.py::TestInhibitAnyPolicy::test_eq
assert iap == iap2
5,364
-1
-1
class InhibitAnyPolicy(ExtensionType): oid = ExtensionOID.INHIBIT_ANY_POLICY def __init__(self, skip_certs: int) -> None: if not isinstance(skip_certs, int): raise TypeError("skip_certs must be an integer") if skip_certs < 0: raise ValueError("skip_certs must be a non-negative integer") self._skip_certs = skip_certs def __repr__(self) -> str: return f"<InhibitAnyPolicy(skip_certs={self.skip_certs})>" def __eq__(self, other: object) -> bool: if not isinstance(other, InhibitAnyPolicy): return NotImplemented return self.skip_certs == other.skip_certs def __hash__(self) -> int: return hash(self.skip_certs) @property def skip_certs(self) -> int: return self._skip_certs def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
1,104
1,133
62
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_nocheck
TestOCSPNoCheckExtension
def test_nocheck(self, backend): cert = _load_cert( os.path.join("x509", "custom", "ocsp_nocheck.pem"), x509.load_pem_x509_certificate, ) ext = cert.extensions.get_extension_for_oid(ExtensionOID.OCSP_NO_CHECK) assert isinstance(ext.value, x509.OCSPNoCheck)
def test_nocheck(self, backend): cert = _load_cert( os.path.join("x509", "custom", "ocsp_nocheck.pem"), x509.load_pem_x509_certificate, ) ext = cert.extensions.get_extension_for_oid(ExtensionOID.OCSP_NO_CHECK) <AssertPlaceHolder>
tests/x509/test_x509_ext.py
5,310
5,316
tests/x509/test_x509_ext.py::TestOCSPNoCheckExtension::test_nocheck
assert isinstance(ext.value, x509.OCSPNoCheck)
5,316
-1
-1
def get_extension_for_oid( self, oid: ObjectIdentifier ) -> Extension[ExtensionType]: for ext in self: if ext.oid == oid: return ext raise ExtensionNotFound(f"No {oid} extension was found", oid)
src/cryptography/x509/extensions.py
116
123
63
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_gcm_tag_with_only_aad
TestAESModeGCM
def test_gcm_tag_with_only_aad(self, backend): key = binascii.unhexlify(b"5211242698bed4774a090620a6ca56f3") iv = binascii.unhexlify(b"b1e1349120b6e832ef976f5d") aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193") tag = binascii.unhexlify(b"0f247e7f9c2505de374006738018493b") cipher = base.Cipher( algorithms.AES(key), modes.GCM(iv), backend=backend ) encryptor = cipher.encryptor() encryptor.authenticate_additional_data(aad) encryptor.finalize() assert encryptor.tag == tag
def test_gcm_tag_with_only_aad(self, backend): key = binascii.unhexlify(b"5211242698bed4774a090620a6ca56f3") iv = binascii.unhexlify(b"b1e1349120b6e832ef976f5d") aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193") tag = binascii.unhexlify(b"0f247e7f9c2505de374006738018493b") cipher = base.Cipher( algorithms.AES(key), modes.GCM(iv), backend=backend ) encryptor = cipher.encryptor() encryptor.authenticate_additional_data(aad) encryptor.finalize() <AssertPlaceHolder>
tests/hazmat/primitives/test_aes_gcm.py
41
53
tests/hazmat/primitives/test_aes_gcm.py::TestAESModeGCM::test_gcm_tag_with_only_aad
assert encryptor.tag == tag
53
-1
-1
@typing.overload def encryptor( self: Cipher[modes.ModeWithAuthenticationTag], ) -> AEADEncryptionContext: ...
src/cryptography/hazmat/primitives/ciphers/base.py
97
100
64
cryptography
https://github.com/pyca/cryptography.git
46.0.0
python -m venv .venv source .venv/bin/activate pip install -e ".[test]" pip install ipdb
source .venv/bin/activate hash -r
test_public_bytes
TestSubjectAlternativeName
def test_public_bytes(self): ext = x509.SubjectAlternativeName([x509.DNSName("cryptography.io")]) assert ext.public_bytes() == b"0\x11\x82\x0fcryptography.io"
def test_public_bytes(self): ext = x509.SubjectAlternativeName([x509.DNSName("cryptography.io")]) <AssertPlaceHolder>
tests/x509/test_x509_ext.py
2,649
2,651
tests/x509/test_x509_ext.py::TestSubjectAlternativeName::test_public_bytes
assert ext.public_bytes() == b"0\x11\x82\x0fcryptography.io"
2,651
-1
-1
def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
src/cryptography/x509/extensions.py
1,645
1,646
End of preview. Expand in Data Studio

py500

Human-level test oracle generation in real-world Python repositories.

Here is an example:

{
    "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        <AssertPlaceHolder>",
    "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
}
  • Focal method
def detect_target_versions(
    node: Node, *, future_imports: Optional[set[str]] = None
) -> set[TargetVersion]:
    """Detect the version to target based on the nodes used."""
    features = get_features_used(node, future_imports=future_imports)
    return {
        version for version in TargetVersion if features <= VERSION_TO_FEATURES[version]
    }
  • Test setup

  • Test prefix
    def test_pep_572_version_detection(self) -> None:
        source, _ = read_data("cases", "pep_572")
        root = black.lib2to3_parse(source)
        features = black.get_features_used(root)
        self.assertIn(black.Feature.ASSIGNMENT_EXPRESSIONS, features)
        versions = black.detect_target_versions(root)
        <AssertPlaceHolder>
  • Ground truth oracle
self.assertIn(black.TargetVersion.PY38, versions)

Install

In the script below, the test.jsonl file in the dataset needs to be renamed to py500.jsonl.

Install venv

install.py

Run

Run the ground truth oracle

run.py

Evaluate

Evaluate whether an oracle is same with the ground truth

evaluate.py

GitHub

AssertAgents

Downloads last month
9