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
|
||
65
|
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_ed448_key
|
TestCertificateRevocationListBuilder
|
@pytest.mark.supported(
only_if=lambda backend: backend.ed448_supported(),
skip_message="Requires OpenSSL with Ed448 support",
)
def test_sign_ed448_key(self, backend):
private_key = ed448.Ed448PrivateKey.generate()
invalidity_date = x509.InvalidityDate(
datetime.datetime(2002, 1, 1, 0, 0)
)
ian = x509.IssuerAlternativeName(
[x509.UniformResourceIdentifier("https://cryptography.io")]
)
revoked_cert0 = (
x509.RevokedCertificateBuilder()
.serial_number(2)
.revocation_date(datetime.datetime(2012, 1, 1, 1, 1))
.add_extension(invalidity_date, False)
.build(backend)
)
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)
.add_revoked_certificate(revoked_cert0)
.add_extension(ian, False)
)
crl = builder.sign(private_key, None, backend)
assert crl.signature_hash_algorithm is None
assert crl.signature_algorithm_oid == SignatureAlgorithmOID.ED448
assert (
crl.extensions.get_extension_for_class(
x509.IssuerAlternativeName
).value
== ian
)
assert crl[0].serial_number == revoked_cert0.serial_number
with pytest.warns(utils.DeprecatedIn42):
assert crl[0].revocation_date == revoked_cert0.revocation_date
assert crl[0].revocation_date_utc == revoked_cert0.revocation_date_utc
assert len(crl[0].extensions) == 1
ext = crl[0].extensions.get_extension_for_class(x509.InvalidityDate)
assert ext.critical is False
assert ext.value == invalidity_date
|
@pytest.mark.supported(
only_if=lambda backend: backend.ed448_supported(),
skip_message="Requires OpenSSL with Ed448 support",
)
def test_sign_ed448_key(self, backend):
private_key = ed448.Ed448PrivateKey.generate()
invalidity_date = x509.InvalidityDate(
datetime.datetime(2002, 1, 1, 0, 0)
)
ian = x509.IssuerAlternativeName(
[x509.UniformResourceIdentifier("https://cryptography.io")]
)
revoked_cert0 = (
x509.RevokedCertificateBuilder()
.serial_number(2)
.revocation_date(datetime.datetime(2012, 1, 1, 1, 1))
.add_extension(invalidity_date, False)
.build(backend)
)
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)
.add_revoked_certificate(revoked_cert0)
.add_extension(ian, False)
)
crl = builder.sign(private_key, None, backend)
<AssertPlaceHolder>
assert crl.signature_algorithm_oid == SignatureAlgorithmOID.ED448
assert (
crl.extensions.get_extension_for_class(
x509.IssuerAlternativeName
).value
== ian
)
assert crl[0].serial_number == revoked_cert0.serial_number
with pytest.warns(utils.DeprecatedIn42):
assert crl[0].revocation_date == revoked_cert0.revocation_date
assert crl[0].revocation_date_utc == revoked_cert0.revocation_date_utc
assert len(crl[0].extensions) == 1
ext = crl[0].extensions.get_extension_for_class(x509.InvalidityDate)
assert ext.critical is False
assert ext.value == invalidity_date
|
tests/x509/test_x509_crlbuilder.py
| 785
| 839
|
tests/x509/test_x509_crlbuilder.py::TestCertificateRevocationListBuilder::test_sign_ed448_key
|
assert crl.signature_hash_algorithm is None
| 824
| -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
|
||
66
|
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
|
TestRelativeDistinguishedName
|
def test_hash(self):
rdn1 = x509.RelativeDistinguishedName(
[
x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), "value1"),
x509.NameAttribute(x509.ObjectIdentifier("2.999.2"), "value2"),
]
)
rdn2 = x509.RelativeDistinguishedName(
[
x509.NameAttribute(x509.ObjectIdentifier("2.999.2"), "value2"),
x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), "value1"),
]
)
rdn3 = x509.RelativeDistinguishedName(
[
x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), "value1"),
x509.NameAttribute(x509.ObjectIdentifier("2.999.2"), "value3"),
]
)
assert hash(rdn1) == hash(rdn2)
assert hash(rdn1) != hash(rdn3)
|
def test_hash(self):
rdn1 = x509.RelativeDistinguishedName(
[
x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), "value1"),
x509.NameAttribute(x509.ObjectIdentifier("2.999.2"), "value2"),
]
)
rdn2 = x509.RelativeDistinguishedName(
[
x509.NameAttribute(x509.ObjectIdentifier("2.999.2"), "value2"),
x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), "value1"),
]
)
rdn3 = x509.RelativeDistinguishedName(
[
x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), "value1"),
x509.NameAttribute(x509.ObjectIdentifier("2.999.2"), "value3"),
]
)
<AssertPlaceHolder>
assert hash(rdn1) != hash(rdn3)
|
tests/x509/test_x509.py
| 6,214
| 6,234
|
tests/x509/test_x509.py::TestRelativeDistinguishedName::test_hash
|
assert hash(rdn1) == hash(rdn2)
| 6,233
| -1
| -1
|
class RelativeDistinguishedName:
def __init__(self, attributes: Iterable[NameAttribute]):
attributes = list(attributes)
if not attributes:
raise ValueError("a relative distinguished name cannot be empty")
if not all(isinstance(x, NameAttribute) for x in attributes):
raise TypeError("attributes must be an iterable of NameAttribute")
# Keep list and frozenset to preserve attribute order where it matters
self._attributes = attributes
self._attribute_set = frozenset(attributes)
if len(self._attribute_set) != len(attributes):
raise ValueError("duplicate attributes are not allowed")
def get_attributes_for_oid(
self,
oid: ObjectIdentifier,
) -> list[NameAttribute[str | bytes]]:
return [i for i in self if i.oid == oid]
def rfc4514_string(
self, attr_name_overrides: _OidNameMap | None = None
) -> str:
"""
Format as RFC4514 Distinguished Name string.
Within each RDN, attributes are joined by '+', although that is rarely
used in certificates.
"""
return "+".join(
attr.rfc4514_string(attr_name_overrides)
for attr in self._attributes
)
def __eq__(self, other: object) -> bool:
if not isinstance(other, RelativeDistinguishedName):
return NotImplemented
return self._attribute_set == other._attribute_set
def __hash__(self) -> int:
return hash(self._attribute_set)
def __iter__(self) -> Iterator[NameAttribute]:
return iter(self._attributes)
def __len__(self) -> int:
return len(self._attributes)
def __repr__(self) -> str:
return f"<RelativeDistinguishedName({self.rfc4514_string()})>"
|
src/cryptography/x509/name.py
| 227
| 278
|
||
67
|
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_load_key_and_certificates_key_only
|
TestPKCS12Loading
|
def test_load_key_and_certificates_key_only(self, backend):
_, key = _load_ca(backend)
assert isinstance(key, ec.EllipticCurvePrivateKey)
parsed_key, parsed_cert, parsed_more_certs = load_vectors_from_file(
os.path.join("pkcs12", "no-cert-key-aes256cbc.p12"),
lambda data: load_key_and_certificates(
data.read(), b"cryptography", backend
),
mode="rb",
)
assert isinstance(parsed_key, ec.EllipticCurvePrivateKey)
assert parsed_key.private_numbers() == key.private_numbers()
assert parsed_cert is None
assert parsed_more_certs == []
|
def test_load_key_and_certificates_key_only(self, backend):
_, key = _load_ca(backend)
assert isinstance(key, ec.EllipticCurvePrivateKey)
parsed_key, parsed_cert, parsed_more_certs = load_vectors_from_file(
os.path.join("pkcs12", "no-cert-key-aes256cbc.p12"),
lambda data: load_key_and_certificates(
data.read(), b"cryptography", backend
),
mode="rb",
)
assert isinstance(parsed_key, ec.EllipticCurvePrivateKey)
<AssertPlaceHolder>
assert parsed_cert is None
assert parsed_more_certs == []
|
tests/hazmat/primitives/test_pkcs12.py
| 114
| 127
|
tests/hazmat/primitives/test_pkcs12.py::TestPKCS12Loading::test_load_key_and_certificates_key_only
|
assert parsed_key.private_numbers() == key.private_numbers()
| 125
| -1
| -1
|
@abc.abstractmethod
def private_numbers(self) -> EllipticCurvePrivateNumbers:
"""
Returns an EllipticCurvePrivateNumbers.
"""
|
src/cryptography/hazmat/primitives/asymmetric/ec.py
| 114
| 118
|
||
68
|
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
|
TestPolicyInformation
|
def test_hash(self):
pi = x509.PolicyInformation(
x509.ObjectIdentifier("1.2.3"),
["string", x509.UserNotice(None, "hi")],
)
pi2 = x509.PolicyInformation(
x509.ObjectIdentifier("1.2.3"),
["string", x509.UserNotice(None, "hi")],
)
pi3 = x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), None)
assert hash(pi) == hash(pi2)
assert hash(pi) != hash(pi3)
|
def test_hash(self):
pi = x509.PolicyInformation(
x509.ObjectIdentifier("1.2.3"),
["string", x509.UserNotice(None, "hi")],
)
pi2 = x509.PolicyInformation(
x509.ObjectIdentifier("1.2.3"),
["string", x509.UserNotice(None, "hi")],
)
pi3 = x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), None)
assert hash(pi) == hash(pi2)
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 621
| 632
|
tests/x509/test_x509_ext.py::TestPolicyInformation::test_hash
|
assert hash(pi) != hash(pi3)
| 632
| -1
| -1
|
class PolicyInformation:
def __init__(
self,
policy_identifier: ObjectIdentifier,
policy_qualifiers: Iterable[str | UserNotice] | None,
) -> None:
if not isinstance(policy_identifier, ObjectIdentifier):
raise TypeError("policy_identifier must be an ObjectIdentifier")
self._policy_identifier = policy_identifier
if policy_qualifiers is not None:
policy_qualifiers = list(policy_qualifiers)
if not all(
isinstance(x, (str, UserNotice)) for x in policy_qualifiers
):
raise TypeError(
"policy_qualifiers must be a list of strings and/or "
"UserNotice objects or None"
)
self._policy_qualifiers = policy_qualifiers
def __repr__(self) -> str:
return (
f"<PolicyInformation(policy_identifier={self.policy_identifier}, "
f"policy_qualifiers={self.policy_qualifiers})>"
)
def __eq__(self, other: object) -> bool:
if not isinstance(other, PolicyInformation):
return NotImplemented
return (
self.policy_identifier == other.policy_identifier
and self.policy_qualifiers == other.policy_qualifiers
)
def __hash__(self) -> int:
if self.policy_qualifiers is not None:
pq = tuple(self.policy_qualifiers)
else:
pq = None
return hash((self.policy_identifier, pq))
@property
def policy_identifier(self) -> ObjectIdentifier:
return self._policy_identifier
@property
def policy_qualifiers(
self,
) -> list[str | UserNotice] | None:
return self._policy_qualifiers
|
src/cryptography/x509/extensions.py
| 848
| 902
|
||
69
|
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
|
TestPrecertPoisonExtension
|
def test_repr(self):
pcp = x509.PrecertPoison()
assert repr(pcp) == "<PrecertPoison()>"
|
def test_repr(self):
pcp = x509.PrecertPoison()
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 5,969
| 5,972
|
tests/x509/test_x509_ext.py::TestPrecertPoisonExtension::test_repr
|
assert repr(pcp) == "<PrecertPoison()>"
| 5,972
| -1
| -1
|
class PrecertPoison(ExtensionType):
oid = ExtensionOID.PRECERT_POISON
def __eq__(self, other: object) -> bool:
if not isinstance(other, PrecertPoison):
return NotImplemented
return True
def __hash__(self) -> int:
return hash(PrecertPoison)
def __repr__(self) -> str:
return "<PrecertPoison()>"
def public_bytes(self) -> bytes:
return rust_x509.encode_extension_value(self)
|
src/cryptography/x509/extensions.py
| 1,037
| 1,053
|
||
70
|
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
|
TestCRLReason
|
def test_hash(self):
reason1 = x509.CRLReason(x509.ReasonFlags.unspecified)
reason2 = x509.CRLReason(x509.ReasonFlags.unspecified)
reason3 = x509.CRLReason(x509.ReasonFlags.ca_compromise)
assert hash(reason1) == hash(reason2)
assert hash(reason1) != hash(reason3)
|
def test_hash(self):
reason1 = x509.CRLReason(x509.ReasonFlags.unspecified)
reason2 = x509.CRLReason(x509.ReasonFlags.unspecified)
reason3 = x509.CRLReason(x509.ReasonFlags.ca_compromise)
<AssertPlaceHolder>
assert hash(reason1) != hash(reason3)
|
tests/x509/test_x509_ext.py
| 365
| 371
|
tests/x509/test_x509_ext.py::TestCRLReason::test_hash
|
assert hash(reason1) == hash(reason2)
| 370
| -1
| -1
|
class CRLReason(ExtensionType):
oid = CRLEntryExtensionOID.CRL_REASON
def __init__(self, reason: ReasonFlags) -> None:
if not isinstance(reason, ReasonFlags):
raise TypeError("reason must be an element from ReasonFlags")
self._reason = reason
def __repr__(self) -> str:
return f"<CRLReason(reason={self._reason})>"
def __eq__(self, other: object) -> bool:
if not isinstance(other, CRLReason):
return NotImplemented
return self.reason == other.reason
def __hash__(self) -> int:
return hash(self.reason)
@property
def reason(self) -> ReasonFlags:
return self._reason
def public_bytes(self) -> bytes:
return rust_x509.encode_extension_value(self)
|
src/cryptography/x509/extensions.py
| 1,793
| 1,819
|
||
71
|
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_valid_pss_parameters_maximum
|
TestPSS
|
def test_valid_pss_parameters_maximum(self):
algorithm = hashes.SHA256()
mgf = padding.MGF1(algorithm)
pss = padding.PSS(mgf=mgf, salt_length=padding.PSS.MAX_LENGTH)
assert pss._mgf == mgf
assert pss._salt_length == padding.PSS.MAX_LENGTH
|
def test_valid_pss_parameters_maximum(self):
algorithm = hashes.SHA256()
mgf = padding.MGF1(algorithm)
pss = padding.PSS(mgf=mgf, salt_length=padding.PSS.MAX_LENGTH)
<AssertPlaceHolder>
assert pss._salt_length == padding.PSS.MAX_LENGTH
|
tests/hazmat/primitives/test_rsa.py
| 1,633
| 1,638
|
tests/hazmat/primitives/test_rsa.py::TestPSS::test_valid_pss_parameters_maximum
|
assert pss._mgf == mgf
| 1,637
| -1
| -1
|
class PSS(AsymmetricPadding):
MAX_LENGTH = _MaxLength()
AUTO = _Auto()
DIGEST_LENGTH = _DigestLength()
name = "EMSA-PSS"
_salt_length: int | _MaxLength | _Auto | _DigestLength
def __init__(
self,
mgf: MGF,
salt_length: int | _MaxLength | _Auto | _DigestLength,
) -> None:
self._mgf = mgf
if not isinstance(
salt_length, (int, _MaxLength, _Auto, _DigestLength)
):
raise TypeError(
"salt_length must be an integer, MAX_LENGTH, "
"DIGEST_LENGTH, or AUTO"
)
if isinstance(salt_length, int) and salt_length < 0:
raise ValueError("salt_length must be zero or greater.")
self._salt_length = salt_length
@property
def mgf(self) -> MGF:
return self._mgf
|
src/cryptography/hazmat/primitives/asymmetric/padding.py
| 32
| 61
|
||
72
|
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
|
TestPolicyConstraints
|
def test_public_bytes(self):
ext = x509.PolicyConstraints(2, 1)
assert ext.public_bytes() == b"0\x06\x80\x01\x02\x81\x01\x01"
|
def test_public_bytes(self):
ext = x509.PolicyConstraints(2, 1)
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 3,086
| 3,088
|
tests/x509/test_x509_ext.py::TestPolicyConstraints::test_public_bytes
|
assert ext.public_bytes() == b"0\x06\x80\x01\x02\x81\x01\x01"
| 3,088
| -1
| -1
|
def public_bytes(self) -> bytes:
return rust_x509.encode_extension_value(self)
|
src/cryptography/x509/extensions.py
| 814
| 815
|
||
73
|
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.ed448_supported(),
skip_message="Requires OpenSSL with Ed448 support",
)
def test_public_key_equality(backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "Ed448", "ed448-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 = Ed448PrivateKey.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.ed448_supported(),
skip_message="Requires OpenSSL with Ed448 support",
)
def test_public_key_equality(backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "Ed448", "ed448-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 = Ed448PrivateKey.generate().public_key()
assert key1 == key2
<AssertPlaceHolder>
assert key1 != object()
with pytest.raises(TypeError):
key1 < key2 # type: ignore[operator]
|
tests/hazmat/primitives/test_ed448.py
| 289
| 307
|
tests/hazmat/primitives/test_ed448.py::test_public_key_equality
|
assert key1 != key3
| 303
| -1
| -1
|
@abc.abstractmethod
def public_key(self) -> Ed448PublicKey:
"""
The Ed448PublicKey derived from the private key.
"""
|
src/cryptography/hazmat/primitives/asymmetric/ed448.py
| 93
| 97
|
|||
74
|
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_exchange
|
TestDH
|
def test_exchange(self, backend):
parameters = FFDH3072_P.parameters(backend)
assert isinstance(parameters, dh.DHParameters)
key1 = parameters.generate_private_key()
key2 = parameters.generate_private_key()
symkey1 = key1.exchange(key2.public_key())
assert symkey1
assert len(symkey1) == 3072 // 8
symkey2 = key2.exchange(key1.public_key())
assert symkey1 == symkey2
|
def test_exchange(self, backend):
parameters = FFDH3072_P.parameters(backend)
assert isinstance(parameters, dh.DHParameters)
key1 = parameters.generate_private_key()
key2 = parameters.generate_private_key()
symkey1 = key1.exchange(key2.public_key())
assert symkey1
<AssertPlaceHolder>
symkey2 = key2.exchange(key1.public_key())
assert symkey1 == symkey2
|
tests/hazmat/primitives/test_dh.py
| 291
| 303
|
tests/hazmat/primitives/test_dh.py::TestDH::test_exchange
|
assert len(symkey1) == 3072 // 8
| 300
| -1
| -1
|
@abc.abstractmethod
def exchange(self, peer_public_key: DHPublicKey) -> bytes:
"""
Given peer's DHPublicKey, carry out the key exchange and
return shared key as bytes.
"""
|
src/cryptography/hazmat/primitives/asymmetric/dh.py
| 115
| 120
|
||
75
|
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
|
TestInhibitAnyPolicy
|
def test_hash(self):
iap = x509.InhibitAnyPolicy(1)
iap2 = x509.InhibitAnyPolicy(1)
iap3 = x509.InhibitAnyPolicy(4)
assert hash(iap) == hash(iap2)
assert hash(iap) != hash(iap3)
|
def test_hash(self):
iap = x509.InhibitAnyPolicy(1)
iap2 = x509.InhibitAnyPolicy(1)
iap3 = x509.InhibitAnyPolicy(4)
assert hash(iap) == hash(iap2)
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 5,372
| 5,377
|
tests/x509/test_x509_ext.py::TestInhibitAnyPolicy::test_hash
|
assert hash(iap) != hash(iap3)
| 5,377
| -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
|
||
76
|
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_unaligned_block_encryption
|
TestCipherContext
|
def test_unaligned_block_encryption(self, backend):
cipher = Cipher(
algorithms.AES(binascii.unhexlify(b"0" * 32)), modes.ECB(), backend
)
encryptor = cipher.encryptor()
ct = encryptor.update(b"a" * 15)
assert ct == b""
ct += encryptor.update(b"a" * 65)
assert len(ct) == 80
ct += encryptor.finalize()
decryptor = cipher.decryptor()
pt = decryptor.update(ct[:3])
assert pt == b""
pt += decryptor.update(ct[3:])
assert len(pt) == 80
assert pt == b"a" * 80
decryptor.finalize()
|
def test_unaligned_block_encryption(self, backend):
cipher = Cipher(
algorithms.AES(binascii.unhexlify(b"0" * 32)), modes.ECB(), backend
)
encryptor = cipher.encryptor()
ct = encryptor.update(b"a" * 15)
assert ct == b""
ct += encryptor.update(b"a" * 65)
assert len(ct) == 80
ct += encryptor.finalize()
decryptor = cipher.decryptor()
pt = decryptor.update(ct[:3])
<AssertPlaceHolder>
pt += decryptor.update(ct[3:])
assert len(pt) == 80
assert pt == b"a" * 80
decryptor.finalize()
|
tests/hazmat/primitives/test_block.py
| 88
| 104
|
tests/hazmat/primitives/test_block.py::TestCipherContext::test_unaligned_block_encryption
|
assert pt == b""
| 100
| -1
| -1
|
@abc.abstractmethod
def update(self, data: Buffer) -> bytes:
"""
Processes the provided bytes through the cipher and returns the results
as bytes.
"""
|
src/cryptography/hazmat/primitives/ciphers/base.py
| 17
| 22
|
||
77
|
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_key_cert_sign_crl_sign
|
TestKeyUsageExtension
|
def test_key_cert_sign_crl_sign(self, backend):
cert = _load_cert(
os.path.join(
"x509", "PKITS_data", "certs", "pathLenConstraint6CACert.crt"
),
x509.load_der_x509_certificate,
)
ext = cert.extensions.get_extension_for_class(x509.KeyUsage)
assert ext is not None
assert ext.critical is True
ku = ext.value
assert ku.digital_signature is False
assert ku.content_commitment is False
assert ku.key_encipherment is False
assert ku.data_encipherment is False
assert ku.key_agreement is False
assert ku.key_cert_sign is True
assert ku.crl_sign is True
|
def test_key_cert_sign_crl_sign(self, backend):
cert = _load_cert(
os.path.join(
"x509", "PKITS_data", "certs", "pathLenConstraint6CACert.crt"
),
x509.load_der_x509_certificate,
)
ext = cert.extensions.get_extension_for_class(x509.KeyUsage)
assert ext is not None
assert ext.critical is True
ku = ext.value
assert ku.digital_signature is False
assert ku.content_commitment is False
assert ku.key_encipherment is False
<AssertPlaceHolder>
assert ku.key_agreement is False
assert ku.key_cert_sign is True
assert ku.crl_sign is True
|
tests/x509/test_x509_ext.py
| 1,857
| 1,875
|
tests/x509/test_x509_ext.py::TestKeyUsageExtension::test_key_cert_sign_crl_sign
|
assert ku.data_encipherment is False
| 1,872
| -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
|
||
78
|
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
|
TestUnrecognizedExtension
|
def test_public_bytes(self):
ext1 = x509.UnrecognizedExtension(
x509.ObjectIdentifier("1.2.3.5"), b"\x03\x02\x01"
)
assert ext1.public_bytes() == b"\x03\x02\x01"
# The following creates a BasicConstraints extension with an invalid
# value. The serialization code should still handle it correctly by
# special-casing UnrecognizedExtension.
ext2 = x509.UnrecognizedExtension(
x509.oid.ExtensionOID.BASIC_CONSTRAINTS, b"\x03\x02\x01"
)
assert ext2.public_bytes() == b"\x03\x02\x01"
|
def test_public_bytes(self):
ext1 = x509.UnrecognizedExtension(
x509.ObjectIdentifier("1.2.3.5"), b"\x03\x02\x01"
)
<AssertPlaceHolder>
# The following creates a BasicConstraints extension with an invalid
# value. The serialization code should still handle it correctly by
# special-casing UnrecognizedExtension.
ext2 = x509.UnrecognizedExtension(
x509.oid.ExtensionOID.BASIC_CONSTRAINTS, b"\x03\x02\x01"
)
assert ext2.public_bytes() == b"\x03\x02\x01"
|
tests/x509/test_x509_ext.py
| 273
| 285
|
tests/x509/test_x509_ext.py::TestUnrecognizedExtension::test_public_bytes
|
assert ext1.public_bytes() == b"\x03\x02\x01"
| 277
| -1
| -1
|
def public_bytes(self) -> bytes:
return self.value
|
src/cryptography/x509/extensions.py
| 2,527
| 2,528
|
||
79
|
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
|
TestExtension
|
def test_eq(self):
ext1 = x509.Extension(
x509.ObjectIdentifier("1.2.3.4"),
False,
x509.BasicConstraints(ca=False, path_length=None),
)
ext2 = x509.Extension(
x509.ObjectIdentifier("1.2.3.4"),
False,
x509.BasicConstraints(ca=False, path_length=None),
)
assert ext1 == ext2
|
def test_eq(self):
ext1 = x509.Extension(
x509.ObjectIdentifier("1.2.3.4"),
False,
x509.BasicConstraints(ca=False, path_length=None),
)
ext2 = x509.Extension(
x509.ObjectIdentifier("1.2.3.4"),
False,
x509.BasicConstraints(ca=False, path_length=None),
)
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 86
| 97
|
tests/x509/test_x509_ext.py::TestExtension::test_eq
|
assert ext1 == ext2
| 97
| -1
| -1
|
class Extension(typing.Generic[ExtensionTypeVar]):
def __init__(
self, oid: ObjectIdentifier, critical: bool, value: ExtensionTypeVar
) -> None:
if not isinstance(oid, ObjectIdentifier):
raise TypeError(
"oid argument must be an ObjectIdentifier instance."
)
if not isinstance(critical, bool):
raise TypeError("critical must be a boolean value")
self._oid = oid
self._critical = critical
self._value = value
@property
def oid(self) -> ObjectIdentifier:
return self._oid
@property
def critical(self) -> bool:
return self._critical
@property
def value(self) -> ExtensionTypeVar:
return self._value
def __repr__(self) -> str:
return (
f"<Extension(oid={self.oid}, critical={self.critical}, "
f"value={self.value})>"
)
def __eq__(self, other: object) -> bool:
if not isinstance(other, Extension):
return NotImplemented
return (
self.oid == other.oid
and self.critical == other.critical
and self.value == other.value
)
def __hash__(self) -> int:
return hash((self.oid, self.critical, self.value))
|
src/cryptography/x509/extensions.py
| 1,449
| 1,494
|
||
80
|
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
|
TestHOTP
|
def test_buffer_protocol(self, backend):
key = bytearray(b"a long key with lots of entropy goes here")
hotp = HOTP(key, 6, SHA1(), backend)
assert hotp.generate(10) == b"559978"
|
def test_buffer_protocol(self, backend):
key = bytearray(b"a long key with lots of entropy goes here")
hotp = HOTP(key, 6, SHA1(), backend)
<AssertPlaceHolder>
|
tests/hazmat/primitives/twofactor/test_hotp.py
| 106
| 109
|
tests/hazmat/primitives/twofactor/test_hotp.py::TestHOTP::test_buffer_protocol
|
assert hotp.generate(10) == b"559978"
| 109
| -1
| -1
|
def generate(self, counter: int) -> bytes:
if not isinstance(counter, int):
raise TypeError("Counter parameter must be an integer type.")
truncated_value = self._dynamic_truncate(counter)
hotp = truncated_value % (10**self._length)
return "{0:0{1}}".format(hotp, self._length).encode()
|
src/cryptography/hazmat/primitives/twofactor/hotp.py
| 70
| 76
|
||
81
|
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
|
TestRegisteredID
|
def test_eq(self):
gn = x509.RegisteredID(NameOID.COMMON_NAME)
gn2 = x509.RegisteredID(NameOID.COMMON_NAME)
assert gn == gn2
|
def test_eq(self):
gn = x509.RegisteredID(NameOID.COMMON_NAME)
gn2 = x509.RegisteredID(NameOID.COMMON_NAME)
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 2,278
| 2,281
|
tests/x509/test_x509_ext.py::TestRegisteredID::test_eq
|
assert gn == gn2
| 2,281
| -1
| -1
|
class RegisteredID(GeneralName):
def __init__(self, value: ObjectIdentifier) -> None:
if not isinstance(value, ObjectIdentifier):
raise TypeError("value must be an ObjectIdentifier")
self._value = value
@property
def value(self) -> ObjectIdentifier:
return self._value
def __repr__(self) -> str:
return f"<RegisteredID(value={self.value})>"
def __eq__(self, other: object) -> bool:
if not isinstance(other, RegisteredID):
return NotImplemented
return self.value == other.value
def __hash__(self) -> int:
return hash(self.value)
|
src/cryptography/x509/general_name.py
| 183
| 204
|
||
82
|
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
|
TestAccessDescription
|
def test_ne(self):
ad = x509.AccessDescription(
AuthorityInformationAccessOID.OCSP,
x509.UniformResourceIdentifier("http://ocsp.domain.com"),
)
ad2 = x509.AccessDescription(
AuthorityInformationAccessOID.CA_ISSUERS,
x509.UniformResourceIdentifier("http://ocsp.domain.com"),
)
ad3 = x509.AccessDescription(
AuthorityInformationAccessOID.OCSP,
x509.UniformResourceIdentifier("http://notthesame"),
)
assert ad != ad2
assert ad != ad3
assert ad != object()
|
def test_ne(self):
ad = x509.AccessDescription(
AuthorityInformationAccessOID.OCSP,
x509.UniformResourceIdentifier("http://ocsp.domain.com"),
)
ad2 = x509.AccessDescription(
AuthorityInformationAccessOID.CA_ISSUERS,
x509.UniformResourceIdentifier("http://ocsp.domain.com"),
)
ad3 = x509.AccessDescription(
AuthorityInformationAccessOID.OCSP,
x509.UniformResourceIdentifier("http://notthesame"),
)
assert ad != ad2
assert ad != ad3
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 3,011
| 3,026
|
tests/x509/test_x509_ext.py::TestAccessDescription::test_ne
|
assert ad != object()
| 3,026
| -1
| -1
|
class AccessDescription:
def __init__(
self, access_method: ObjectIdentifier, access_location: GeneralName
) -> None:
if not isinstance(access_method, ObjectIdentifier):
raise TypeError("access_method must be an ObjectIdentifier")
if not isinstance(access_location, GeneralName):
raise TypeError("access_location must be a GeneralName")
self._access_method = access_method
self._access_location = access_location
def __repr__(self) -> str:
return (
f"<AccessDescription(access_method={self.access_method}, "
f"access_location={self.access_location})>"
)
def __eq__(self, other: object) -> bool:
if not isinstance(other, AccessDescription):
return NotImplemented
return (
self.access_method == other.access_method
and self.access_location == other.access_location
)
def __hash__(self) -> int:
return hash((self.access_method, self.access_location))
@property
def access_method(self) -> ObjectIdentifier:
return self._access_method
@property
def access_location(self) -> GeneralName:
return self._access_location
|
src/cryptography/x509/extensions.py
| 384
| 421
|
||
83
|
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
|
TestInvalidityDate
|
def test_public_bytes(self):
ext = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 1))
assert ext.public_bytes() == b"\x18\x0f20150101010100Z"
|
def test_public_bytes(self):
ext = x509.InvalidityDate(datetime.datetime(2015, 1, 1, 1, 1))
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 443
| 445
|
tests/x509/test_x509_ext.py::TestInvalidityDate::test_public_bytes
|
assert ext.public_bytes() == b"\x18\x0f20150101010100Z"
| 445
| -1
| -1
|
def public_bytes(self) -> bytes:
return rust_x509.encode_extension_value(self)
|
src/cryptography/x509/extensions.py
| 1,854
| 1,855
|
||
84
|
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_distinguished_name
|
TestNameAttribute
|
def test_distinguished_name(self):
# Escaping
na = x509.NameAttribute(NameOID.COMMON_NAME, 'James "Jim" Smith, III')
assert na.rfc4514_string() == r"CN=James \"Jim\" Smith\, III"
na = x509.NameAttribute(NameOID.USER_ID, "# escape+,;\0this ")
assert na.rfc4514_string() == r"UID=\# escape\+\,\;\00this\ "
# Nonstandard attribute OID
na = x509.NameAttribute(NameOID.BUSINESS_CATEGORY, "banking")
assert na.rfc4514_string() == "2.5.4.15=banking"
# non-utf8 attribute (bitstring with raw bytes)
na_bytes = x509.NameAttribute(
x509.ObjectIdentifier("2.5.4.45"),
b"\x01\x02\x03\x04",
_ASN1Type.BitString,
)
assert na_bytes.rfc4514_string() == "2.5.4.45=#01020304"
|
def test_distinguished_name(self):
# Escaping
na = x509.NameAttribute(NameOID.COMMON_NAME, 'James "Jim" Smith, III')
<AssertPlaceHolder>
na = x509.NameAttribute(NameOID.USER_ID, "# escape+,;\0this ")
assert na.rfc4514_string() == r"UID=\# escape\+\,\;\00this\ "
# Nonstandard attribute OID
na = x509.NameAttribute(NameOID.BUSINESS_CATEGORY, "banking")
assert na.rfc4514_string() == "2.5.4.15=banking"
# non-utf8 attribute (bitstring with raw bytes)
na_bytes = x509.NameAttribute(
x509.ObjectIdentifier("2.5.4.45"),
b"\x01\x02\x03\x04",
_ASN1Type.BitString,
)
assert na_bytes.rfc4514_string() == "2.5.4.45=#01020304"
|
tests/x509/test_x509.py
| 6,146
| 6,163
|
tests/x509/test_x509.py::TestNameAttribute::test_distinguished_name
|
assert na.rfc4514_string() == r"CN=James \"Jim\" Smith\, III"
| 6,149
| -1
| -1
|
def rfc4514_string(
self, attr_name_overrides: _OidNameMap | None = None
) -> str:
"""
Format as RFC4514 Distinguished Name string.
Use short attribute name if available, otherwise fall back to OID
dotted string.
"""
attr_name = (
attr_name_overrides.get(self.oid) if attr_name_overrides else None
)
if attr_name is None:
attr_name = self.rfc4514_attribute_name
return f"{attr_name}={_escape_dn_value(self.value)}"
|
src/cryptography/x509/name.py
| 197
| 212
|
||
85
|
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
|
TestECEquality
|
def test_public_key_equality(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: pemfile.read().encode(),
)
key1 = serialization.load_pem_private_key(key_bytes, None).public_key()
key2 = serialization.load_pem_private_key(key_bytes, None).public_key()
key3 = ec.generate_private_key(ec.SECP256R1()).public_key()
assert key1 == key2
assert key1 != key3
assert key1 != object()
with pytest.raises(TypeError):
key1 < key2 # type: ignore[operator]
|
def test_public_key_equality(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "PKCS8", "ec_private_key.pem"),
lambda pemfile: pemfile.read().encode(),
)
key1 = serialization.load_pem_private_key(key_bytes, None).public_key()
key2 = serialization.load_pem_private_key(key_bytes, None).public_key()
key3 = ec.generate_private_key(ec.SECP256R1()).public_key()
assert key1 == key2
assert key1 != key3
<AssertPlaceHolder>
with pytest.raises(TypeError):
key1 < key2 # type: ignore[operator]
|
tests/hazmat/primitives/test_ec.py
| 746
| 759
|
tests/hazmat/primitives/test_ec.py::TestECEquality::test_public_key_equality
|
assert key1 != object()
| 757
| -1
| -1
|
@abc.abstractmethod
def public_key(self) -> EllipticCurvePublicKey:
"""
The EllipticCurvePublicKey for this private key.
"""
|
src/cryptography/hazmat/primitives/asymmetric/ec.py
| 84
| 88
|
||
86
|
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
|
TestInhibitAnyPolicy
|
def test_public_bytes(self):
ext = x509.InhibitAnyPolicy(1)
assert ext.public_bytes() == b"\x02\x01\x01"
|
def test_public_bytes(self):
ext = x509.InhibitAnyPolicy(1)
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 5,379
| 5,381
|
tests/x509/test_x509_ext.py::TestInhibitAnyPolicy::test_public_bytes
|
assert ext.public_bytes() == b"\x02\x01\x01"
| 5,381
| -1
| -1
|
def public_bytes(self) -> bytes:
return rust_x509.encode_extension_value(self)
|
src/cryptography/x509/extensions.py
| 1,132
| 1,133
|
||
87
|
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
|
TestExtendedKeyUsage
|
def test_public_bytes(self):
ext = x509.ExtendedKeyUsage(
[x509.ObjectIdentifier("1.3.6"), x509.ObjectIdentifier("1.3.7")]
)
assert ext.public_bytes() == b"0\x08\x06\x02+\x06\x06\x02+\x07"
|
def test_public_bytes(self):
ext = x509.ExtendedKeyUsage(
[x509.ObjectIdentifier("1.3.6"), x509.ObjectIdentifier("1.3.7")]
)
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 1,501
| 1,505
|
tests/x509/test_x509_ext.py::TestExtendedKeyUsage::test_public_bytes
|
assert ext.public_bytes() == b"0\x08\x06\x02+\x06\x06\x02+\x07"
| 1,505
| -1
| -1
|
def public_bytes(self) -> bytes:
return rust_x509.encode_extension_value(self)
|
src/cryptography/x509/extensions.py
| 1,014
| 1,015
|
||
88
|
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
|
TestPrecertPoisonExtension
|
def test_generate(self, rsa_key_2048: rsa.RSAPrivateKey, backend):
private_key = rsa_key_2048
cert = (
_make_certbuilder(private_key)
.add_extension(x509.PrecertPoison(), critical=True)
.sign(private_key, hashes.SHA256(), backend)
)
poison = cert.extensions.get_extension_for_oid(
ExtensionOID.PRECERT_POISON
).value
assert isinstance(poison, x509.PrecertPoison)
|
def test_generate(self, rsa_key_2048: rsa.RSAPrivateKey, backend):
private_key = rsa_key_2048
cert = (
_make_certbuilder(private_key)
.add_extension(x509.PrecertPoison(), critical=True)
.sign(private_key, hashes.SHA256(), backend)
)
poison = cert.extensions.get_extension_for_oid(
ExtensionOID.PRECERT_POISON
).value
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 5,937
| 5,947
|
tests/x509/test_x509_ext.py::TestPrecertPoisonExtension::test_generate
|
assert isinstance(poison, x509.PrecertPoison)
| 5,947
| -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
|
||
89
|
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
|
TestOCSPNoCheckExtension
|
def test_public_bytes(self):
ext = x509.OCSPNoCheck()
assert ext.public_bytes() == b"\x05\x00"
|
def test_public_bytes(self):
ext = x509.OCSPNoCheck()
<AssertPlaceHolder>
|
tests/x509/test_x509_ext.py
| 5,343
| 5,345
|
tests/x509/test_x509_ext.py::TestOCSPNoCheckExtension::test_public_bytes
|
assert ext.public_bytes() == b"\x05\x00"
| 5,345
| -1
| -1
|
def public_bytes(self) -> bytes:
return rust_x509.encode_extension_value(self)
|
src/cryptography/x509/extensions.py
| 1,033
| 1,034
|
||
90
|
gradio
|
https://github.com/gradio-app/gradio.git
|
gradio@5.49.0
|
python -m venv .venv
source .venv/bin/activate
pip install -e .
pip install pytest pytest-asyncio hypothesis
pip install ipdb
|
source .venv/bin/activate
hash -r
|
test_unsafe_value
|
TestSanitizeForCSV
|
def test_unsafe_value(self):
assert sanitize_value_for_csv("=OPEN()") == "'=OPEN()"
assert sanitize_value_for_csv("=1+2") == "'=1+2"
assert sanitize_value_for_csv('=1+2";=1+2') == "'=1+2\";=1+2"
|
def test_unsafe_value(self):
assert sanitize_value_for_csv("=OPEN()") == "'=OPEN()"
<AssertPlaceHolder>
assert sanitize_value_for_csv('=1+2";=1+2') == "'=1+2\";=1+2"
|
test/test_utils.py
| 176
| 179
|
test/test_utils.py::TestSanitizeForCSV::test_unsafe_value
|
assert sanitize_value_for_csv("=1+2") == "'=1+2"
| 178
| -1
| -1
|
def sanitize_value_for_csv(value: str | float) -> str | float:
"""
Sanitizes a value that is being written to a CSV file to prevent CSV injection attacks.
Reference: https://owasp.org/www-community/attacks/CSV_Injection
"""
if isinstance(value, (float, int)):
return value
unsafe_prefixes = ["=", "+", "-", "@", "\t", "\n"]
unsafe_sequences = [",=", ",+", ",-", ",@", ",\t", ",\n"]
if any(value.startswith(prefix) for prefix in unsafe_prefixes) or any(
sequence in value for sequence in unsafe_sequences
):
value = f"'{value}"
return value
|
gradio/utils.py
| 783
| 796
|
||
91
|
gradio
|
https://github.com/gradio-app/gradio.git
|
gradio@5.49.0
|
python -m venv .venv
source .venv/bin/activate
pip install -e .
pip install pytest pytest-asyncio hypothesis
pip install ipdb
|
source .venv/bin/activate
hash -r
|
test_safe_deepcopy_custom_object
|
TestSafeDeepCopy
|
def test_safe_deepcopy_custom_object(self):
class CustomClass:
def __init__(self, value):
self.value = value
original = CustomClass(10)
copied = safe_deepcopy(original)
assert copied.value == original.value
assert copied is not original
|
def test_safe_deepcopy_custom_object(self):
class CustomClass:
def __init__(self, value):
self.value = value
original = CustomClass(10)
copied = safe_deepcopy(original)
assert copied.value == original.value
<AssertPlaceHolder>
|
test/test_utils.py
| 719
| 728
|
test/test_utils.py::TestSafeDeepCopy::test_safe_deepcopy_custom_object
|
assert copied is not original
| 728
| -1
| -1
|
def safe_deepcopy(obj: Any) -> Any:
try:
return copy.deepcopy(obj)
except Exception:
if isinstance(obj, dict):
return {
safe_deepcopy(key): safe_deepcopy(value) for key, value in obj.items()
}
elif isinstance(obj, list):
return [safe_deepcopy(item) for item in obj]
elif isinstance(obj, tuple):
return tuple(safe_deepcopy(item) for item in obj)
elif isinstance(obj, set):
return {safe_deepcopy(item) for item in obj}
else:
return copy.copy(obj)
|
gradio/utils.py
| 521
| 536
|
||
92
|
gradio
|
https://github.com/gradio-app/gradio.git
|
gradio@5.49.0
|
python -m venv .venv
source .venv/bin/activate
pip install -e .
pip install pytest pytest-asyncio hypothesis
pip install ipdb
|
source .venv/bin/activate
hash -r
|
test_no_suffix
|
TestAppendUniqueSuffix
|
def test_no_suffix(self):
name = "test"
list_of_names = ["test_1", "test_2"]
assert append_unique_suffix(name, list_of_names) == name
|
def test_no_suffix(self):
name = "test"
list_of_names = ["test_1", "test_2"]
<AssertPlaceHolder>
|
test/test_utils.py
| 214
| 217
|
test/test_utils.py::TestAppendUniqueSuffix::test_no_suffix
|
assert append_unique_suffix(name, list_of_names) == name
| 217
| -1
| -1
|
def append_unique_suffix(name: str, list_of_names: list[str]):
"""Appends a numerical suffix to `name` so that it does not appear in `list_of_names`."""
set_of_names: set[str] = set(list_of_names) # for O(1) lookup
if name not in set_of_names:
return name
else:
suffix_counter = 1
new_name = f"{name}_{suffix_counter}"
while new_name in set_of_names:
suffix_counter += 1
new_name = f"{name}_{suffix_counter}"
return new_name
|
gradio/utils.py
| 815
| 826
|
||
93
|
gradio
|
https://github.com/gradio-app/gradio.git
|
gradio@5.49.0
|
python -m venv .venv
source .venv/bin/activate
pip install -e .
pip install pytest pytest-asyncio hypothesis
pip install ipdb
|
source .venv/bin/activate
hash -r
|
test_resolve_schema_ref_direct
|
def test_resolve_schema_ref_direct():
schema = {"type": "string"}
spec = {}
assert resolve_schema_ref(schema, spec) == schema
|
def test_resolve_schema_ref_direct():
schema = {"type": "string"}
spec = {}
<AssertPlaceHolder>
|
test/test_external_utils.py
| 28
| 31
|
test/test_external_utils.py::test_resolve_schema_ref_direct
|
assert resolve_schema_ref(schema, spec) == schema
| 31
| -1
| -1
|
def resolve_schema_ref(schema: dict, spec: dict) -> dict:
"""Resolve schema references in OpenAPI spec."""
if "$ref" in schema:
ref_path = schema["$ref"]
if ref_path.startswith("#/components/schemas/"):
schema_name = ref_path.split("/")[-1]
return spec.get("components", {}).get("schemas", {}).get(schema_name, {})
elif ref_path.startswith("#/"):
path_parts = ref_path.split("/")[1:]
current = spec
for part in path_parts:
current = current.get(part, {})
return current
return schema
|
gradio/external_utils.py
| 515
| 528
|
|||
94
|
gradio
|
https://github.com/gradio-app/gradio.git
|
gradio@5.49.0
|
python -m venv .venv
source .venv/bin/activate
pip install -e .
pip install pytest pytest-asyncio hypothesis
pip install ipdb
|
source .venv/bin/activate
hash -r
|
test_safe_deepcopy_handles_undeepcopyable
|
TestSafeDeepCopy
|
def test_safe_deepcopy_handles_undeepcopyable(self):
class Uncopyable:
def __deepcopy__(self, memo):
raise TypeError("Can't deepcopy")
original = Uncopyable()
result = safe_deepcopy(original)
assert result is not original
assert type(result) is type(original)
|
def test_safe_deepcopy_handles_undeepcopyable(self):
class Uncopyable:
def __deepcopy__(self, memo):
raise TypeError("Can't deepcopy")
original = Uncopyable()
result = safe_deepcopy(original)
assert result is not original
<AssertPlaceHolder>
|
test/test_utils.py
| 730
| 738
|
test/test_utils.py::TestSafeDeepCopy::test_safe_deepcopy_handles_undeepcopyable
|
assert type(result) is type(original)
| 738
| -1
| -1
|
def safe_deepcopy(obj: Any) -> Any:
try:
return copy.deepcopy(obj)
except Exception:
if isinstance(obj, dict):
return {
safe_deepcopy(key): safe_deepcopy(value) for key, value in obj.items()
}
elif isinstance(obj, list):
return [safe_deepcopy(item) for item in obj]
elif isinstance(obj, tuple):
return tuple(safe_deepcopy(item) for item in obj)
elif isinstance(obj, set):
return {safe_deepcopy(item) for item in obj}
else:
return copy.copy(obj)
|
gradio/utils.py
| 521
| 536
|
||
95
|
gradio
|
https://github.com/gradio-app/gradio.git
|
gradio@5.49.0
|
python -m venv .venv
source .venv/bin/activate
pip install -e .
pip install pytest pytest-asyncio hypothesis
pip install ipdb
|
source .venv/bin/activate
hash -r
|
test_safe_deepcopy_list
|
TestSafeDeepCopy
|
def test_safe_deepcopy_list(self):
original = [1, 2, [3, 4, {"key": "value"}]]
copied = safe_deepcopy(original)
assert copied == original
assert copied is not original
assert copied[2] is not original[2]
assert copied[2][2] is not original[2][2]
|
def test_safe_deepcopy_list(self):
original = [1, 2, [3, 4, {"key": "value"}]]
copied = safe_deepcopy(original)
assert copied == original
<AssertPlaceHolder>
assert copied[2] is not original[2]
assert copied[2][2] is not original[2][2]
|
test/test_utils.py
| 710
| 717
|
test/test_utils.py::TestSafeDeepCopy::test_safe_deepcopy_list
|
assert copied is not original
| 715
| -1
| -1
|
def safe_deepcopy(obj: Any) -> Any:
try:
return copy.deepcopy(obj)
except Exception:
if isinstance(obj, dict):
return {
safe_deepcopy(key): safe_deepcopy(value) for key, value in obj.items()
}
elif isinstance(obj, list):
return [safe_deepcopy(item) for item in obj]
elif isinstance(obj, tuple):
return tuple(safe_deepcopy(item) for item in obj)
elif isinstance(obj, set):
return {safe_deepcopy(item) for item in obj}
else:
return copy.copy(obj)
|
gradio/utils.py
| 521
| 536
|
||
96
|
gradio
|
https://github.com/gradio-app/gradio.git
|
gradio@5.49.0
|
python -m venv .venv
source .venv/bin/activate
pip install -e .
pip install pytest pytest-asyncio hypothesis
pip install ipdb
|
source .venv/bin/activate
hash -r
|
test_colab_check_no_ipython
|
TestUtils
|
@patch("IPython.get_ipython")
def test_colab_check_no_ipython(self, mock_get_ipython):
mock_get_ipython.return_value = None
assert colab_check() is False
|
@patch("IPython.get_ipython")
def test_colab_check_no_ipython(self, mock_get_ipython):
mock_get_ipython.return_value = None
<AssertPlaceHolder>
|
test/test_utils.py
| 55
| 58
|
test/test_utils.py::TestUtils::test_colab_check_no_ipython
|
assert colab_check() is False
| 58
| -1
| -1
|
def colab_check() -> bool:
"""
Check if interface is launching from Google Colab
:return is_colab (bool): True or False
"""
is_colab = False
try: # Check if running interactively using ipython.
from IPython.core.getipython import get_ipython
from_ipynb = get_ipython()
if "google.colab" in str(from_ipynb):
is_colab = True
except (ImportError, NameError):
pass
return is_colab
|
gradio/utils.py
| 422
| 436
|
||
97
|
gradio
|
https://github.com/gradio-app/gradio.git
|
gradio@5.49.0
|
python -m venv .venv
source .venv/bin/activate
pip install -e .
pip install pytest pytest-asyncio hypothesis
pip install ipdb
|
source .venv/bin/activate
hash -r
|
test_len
|
TestUnhashableKeyDict
|
def test_len(self):
d = UnhashableKeyDict()
assert len(d) == 0
d["a"] = 1
d["b"] = 2
assert len(d) == 2
|
def test_len(self):
d = UnhashableKeyDict()
<AssertPlaceHolder>
d["a"] = 1
d["b"] = 2
assert len(d) == 2
|
test/test_utils.py
| 681
| 686
|
test/test_utils.py::TestUnhashableKeyDict::test_len
|
assert len(d) == 0
| 683
| -1
| -1
|
class UnhashableKeyDict(MutableMapping):
"""
Essentially a list of key-value tuples that allows for keys that are not hashable,
but acts like a dictionary for convenience.
"""
def __init__(self):
self.data = []
def __getitem__(self, key):
for k, v in self.data:
if deep_equal(k, key):
return v
raise KeyError(key)
def __setitem__(self, key, value):
for i, (k, _) in enumerate(self.data):
if deep_equal(k, key):
self.data[i] = (key, value)
return
self.data.append((key, value))
def __delitem__(self, key):
for i, (k, _) in enumerate(self.data):
if deep_equal(k, key):
del self.data[i]
return
raise KeyError(key)
def __iter__(self):
return (k for k, _ in self.data)
def __len__(self):
return len(self.data)
def as_list(self):
return [v for _, v in self.data]
|
gradio/utils.py
| 1,520
| 1,556
|
||
98
|
gradio
|
https://github.com/gradio-app/gradio.git
|
gradio@5.49.0
|
python -m venv .venv
source .venv/bin/activate
pip install -e .
pip install pytest pytest-asyncio hypothesis
pip install ipdb
|
source .venv/bin/activate
hash -r
|
test_safe_deepcopy_dict
|
TestSafeDeepCopy
|
def test_safe_deepcopy_dict(self):
original = {"key1": [1, 2, {"nested_key": "value"}], "key2": "simple_string"}
copied = safe_deepcopy(original)
assert copied == original
assert copied is not original
assert copied["key1"] is not original["key1"]
assert copied["key1"][2] is not original["key1"][2]
|
def test_safe_deepcopy_dict(self):
original = {"key1": [1, 2, {"nested_key": "value"}], "key2": "simple_string"}
copied = safe_deepcopy(original)
<AssertPlaceHolder>
assert copied is not original
assert copied["key1"] is not original["key1"]
assert copied["key1"][2] is not original["key1"][2]
|
test/test_utils.py
| 701
| 708
|
test/test_utils.py::TestSafeDeepCopy::test_safe_deepcopy_dict
|
assert copied == original
| 705
| -1
| -1
|
def safe_deepcopy(obj: Any) -> Any:
try:
return copy.deepcopy(obj)
except Exception:
if isinstance(obj, dict):
return {
safe_deepcopy(key): safe_deepcopy(value) for key, value in obj.items()
}
elif isinstance(obj, list):
return [safe_deepcopy(item) for item in obj]
elif isinstance(obj, tuple):
return tuple(safe_deepcopy(item) for item in obj)
elif isinstance(obj, set):
return {safe_deepcopy(item) for item in obj}
else:
return copy.copy(obj)
|
gradio/utils.py
| 521
| 536
|
||
99
|
gradio
|
https://github.com/gradio-app/gradio.git
|
gradio@5.49.0
|
python -m venv .venv
source .venv/bin/activate
pip install -e .
pip install pytest pytest-asyncio hypothesis
pip install ipdb
|
source .venv/bin/activate
hash -r
|
test_format_ner_list_standard
|
TestFormatNERList
|
def test_format_ner_list_standard(self):
string = "Wolfgang lives in Berlin"
groups = [
{"entity_group": "PER", "start": 0, "end": 8},
{"entity_group": "LOC", "start": 18, "end": 24},
]
result = [
("", None),
("Wolfgang", "PER"),
(" lives in ", None),
("Berlin", "LOC"),
("", None),
]
assert format_ner_list(string, groups) == result
|
def test_format_ner_list_standard(self):
string = "Wolfgang lives in Berlin"
groups = [
{"entity_group": "PER", "start": 0, "end": 8},
{"entity_group": "LOC", "start": 18, "end": 24},
]
result = [
("", None),
("Wolfgang", "PER"),
(" lives in ", None),
("Berlin", "LOC"),
("", None),
]
<AssertPlaceHolder>
|
test/test_utils.py
| 125
| 138
|
test/test_utils.py::TestFormatNERList::test_format_ner_list_standard
|
assert format_ner_list(string, groups) == result
| 138
| -1
| -1
|
def format_ner_list(input_string: str, ner_groups: list[dict[str, str | int]]):
if len(ner_groups) == 0:
return [(input_string, None)]
output = []
end = 0
prev_end = 0
for group in ner_groups:
entity, start, end = group["entity_group"], group["start"], group["end"]
output.append((input_string[prev_end:start], None))
output.append((input_string[start:end], entity))
prev_end = end
output.append((input_string[end:], None))
return output
|
gradio/external_utils.py
| 177
| 192
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.