Skip to content

Commit

Permalink
update python annotations
Browse files Browse the repository at this point in the history
Signed-off-by: NicholasTanz <[email protected]>
  • Loading branch information
NicholasTanz committed Nov 4, 2024
1 parent 42c3b2d commit 5c71f4f
Show file tree
Hide file tree
Showing 28 changed files with 183 additions and 180 deletions.
5 changes: 2 additions & 3 deletions examples/manual_repo/basic_repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import tempfile
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Dict

from securesystemslib.signer import CryptoSigner, Signer

Expand Down Expand Up @@ -87,8 +86,8 @@ def _in(days: float) -> datetime:

# Define containers for role objects and cryptographic keys created below. This
# allows us to sign and write metadata in a batch more easily.
roles: Dict[str, Metadata] = {}
signers: Dict[str, Signer] = {}
roles: dict[str, Metadata] = {}
signers: dict[str, Signer] = {}


# Targets (integrity)
Expand Down
8 changes: 4 additions & 4 deletions examples/manual_repo/hashed_bin_delegation.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
import hashlib
import os
import tempfile
from collections.abc import Iterator
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Dict, Iterator, List, Tuple

from securesystemslib.signer import CryptoSigner, Signer

Expand All @@ -42,8 +42,8 @@ def _in(days: float) -> datetime:
)


roles: Dict[str, Metadata[Targets]] = {}
signers: Dict[str, Signer] = {}
roles: dict[str, Metadata[Targets]] = {}
signers: dict[str, Signer] = {}

# Hash bin delegation
# ===================
Expand Down Expand Up @@ -96,7 +96,7 @@ def _bin_name(low: int, high: int) -> str:
return f"{low:0{PREFIX_LEN}x}-{high:0{PREFIX_LEN}x}"


def generate_hash_bins() -> Iterator[Tuple[str, List[str]]]:
def generate_hash_bins() -> Iterator[tuple[str, list[str]]]:
"""Returns generator for bin names and hash prefixes per bin."""
# Iterate over the total number of hash prefixes in 'bin size'-steps to
# generate bin names and a list of hash prefixes served by each bin.
Expand Down
5 changes: 2 additions & 3 deletions examples/manual_repo/succinct_hash_bin_delegations.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import tempfile
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Dict

from securesystemslib.signer import CryptoSigner

Expand Down Expand Up @@ -105,7 +104,7 @@
bit_length=BIT_LENGTH,
name_prefix=NAME_PREFIX,
)
delegations_keys_info: Dict[str, Key] = {}
delegations_keys_info: dict[str, Key] = {}
delegations_keys_info[bins_key.keyid] = bins_key

targets.signed.delegations = Delegations(
Expand All @@ -119,7 +118,7 @@

assert targets.signed.delegations.succinct_roles is not None # make mypy happy

delegated_bins: Dict[str, Metadata[Targets]] = {}
delegated_bins: dict[str, Metadata[Targets]] = {}
for delegated_bin_name in targets.signed.delegations.succinct_roles.get_roles():
delegated_bins[delegated_bin_name] = Metadata(
Targets(expires=expiration_date)
Expand Down
12 changes: 6 additions & 6 deletions examples/repository/_simplerepo.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import logging
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from typing import Dict, List, Union
from typing import Union

from securesystemslib.signer import CryptoSigner, Key, Signer

Expand Down Expand Up @@ -59,16 +59,16 @@ class SimpleRepository(Repository):

def __init__(self) -> None:
# all versions of all metadata
self.role_cache: Dict[str, List[Metadata]] = defaultdict(list)
self.role_cache: dict[str, list[Metadata]] = defaultdict(list)
# all current keys
self.signer_cache: Dict[str, List[Signer]] = defaultdict(list)
self.signer_cache: dict[str, list[Signer]] = defaultdict(list)
# all target content
self.target_cache: Dict[str, bytes] = {}
self.target_cache: dict[str, bytes] = {}
# version cache for snapshot and all targets, updated in close().
# The 'defaultdict(lambda: ...)' trick allows close() to easily modify
# the version without always creating a new MetaFile
self._snapshot_info = MetaFile(1)
self._targets_infos: Dict[str, MetaFile] = defaultdict(
self._targets_infos: dict[str, MetaFile] = defaultdict(
lambda: MetaFile(1)
)

Expand All @@ -84,7 +84,7 @@ def __init__(self) -> None:
pass

@property
def targets_infos(self) -> Dict[str, MetaFile]:
def targets_infos(self) -> dict[str, MetaFile]:
return self._targets_infos

@property
Expand Down
3 changes: 1 addition & 2 deletions examples/uploader/_localrepo.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import logging
import os
from datetime import datetime, timedelta, timezone
from typing import Dict

import requests
from securesystemslib.signer import CryptoSigner, Signer
Expand Down Expand Up @@ -50,7 +49,7 @@ def __init__(self, metadata_dir: str, key_dir: str, base_url: str):
self.updater.refresh()

@property
def targets_infos(self) -> Dict[str, MetaFile]:
def targets_infos(self) -> dict[str, MetaFile]:
raise NotImplementedError # we never call snapshot

@property
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ name = "tuf"
description = "A secure updater framework for Python"
readme = "README.md"
license = { text = "MIT OR Apache-2.0" }
requires-python = ">=3.8"
requires-python = ">=3.9"
authors = [
{ email = "[email protected]" },
]
Expand Down
10 changes: 5 additions & 5 deletions tests/generated_data/generate_md.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import os
import sys
from datetime import datetime, timezone
from typing import List, Optional
from typing import Optional

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from securesystemslib.signer import CryptoSigner, Signer, SSlibKey
Expand All @@ -16,13 +16,13 @@
from tuf.api.serialization.json import JSONSerializer

# Hardcode keys and expiry time to achieve reproducibility.
public_values: List[str] = [
public_values: list[str] = [
"b11d2ff132c033a657318c74c39526476c56de7556c776f11070842dbc4ac14c",
"250f9ae3d1d3d5c419a73cfb4a470c01de1d5d3d61a3825416b5f5d6b88f4a30",
"82380623abb9666d4bf274b1a02577469445a972e5650d270101faa5107b19c8",
"0e6738fc1ac6fb4de680b4be99ecbcd99b030f3963f291277eef67bb9bd123e9",
]
private_values: List[bytes] = [
private_values: list[bytes] = [
bytes.fromhex(
"510e5e04d7a364af850533856eacdf65d30cc0f8803ecd5fdc0acc56ca2aa91c"
),
Expand All @@ -36,14 +36,14 @@
"7e2e751145d1b22f6e40d4ba2aa47158207acfd3c003f1cbd5a08141dfc22a15"
),
]
keyids: List[str] = [
keyids: list[str] = [
"5822582e7072996c1eef1cec24b61115d364987faa486659fe3d3dce8dae2aba",
"09d440e3725cec247dcb8703b646a87dd2a4d75343e8095c036c32795eefe3b9",
"3458204ed467519c19a5316eb278b5608472a1bbf15850ebfb462d5315e4f86d",
"2be5c21e3614f9f178fb49c4a34d0c18ffac30abd14ced917c60a52c8d8094b7",
]

signers: List[Signer] = []
signers: list[Signer] = []
for index in range(len(keyids)):
key = SSlibKey(
keyids[index],
Expand Down
19 changes: 10 additions & 9 deletions tests/repository_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@
import logging
import os
import tempfile
from collections.abc import Iterator
from dataclasses import dataclass, field
from typing import Dict, Iterator, List, Optional, Tuple
from typing import Optional
from urllib import parse

import securesystemslib.hash as sslib_hash
Expand Down Expand Up @@ -80,8 +81,8 @@
class FetchTracker:
"""Fetcher counter for metadata and targets."""

metadata: List[Tuple[str, Optional[int]]] = field(default_factory=list)
targets: List[Tuple[str, Optional[str]]] = field(default_factory=list)
metadata: list[tuple[str, Optional[int]]] = field(default_factory=list)
targets: list[tuple[str, Optional[str]]] = field(default_factory=list)


@dataclass
Expand All @@ -96,18 +97,18 @@ class RepositorySimulator(FetcherInterface):
"""Simulates a repository that can be used for testing."""

def __init__(self) -> None:
self.md_delegates: Dict[str, Metadata[Targets]] = {}
self.md_delegates: dict[str, Metadata[Targets]] = {}

# other metadata is signed on-demand (when fetched) but roots must be
# explicitly published with publish_root() which maintains this list
self.signed_roots: List[bytes] = []
self.signed_roots: list[bytes] = []

# signers are used on-demand at fetch time to sign metadata
# keys are roles, values are dicts of {keyid: signer}
self.signers: Dict[str, Dict[str, Signer]] = {}
self.signers: dict[str, dict[str, Signer]] = {}

# target downloads are served from this dict
self.target_files: Dict[str, RepositoryTarget] = {}
self.target_files: dict[str, RepositoryTarget] = {}

# Whether to compute hashes and length for meta in snapshot/timestamp
self.compute_metafile_hashes_length = False
Expand Down Expand Up @@ -143,7 +144,7 @@ def snapshot(self) -> Snapshot:
def targets(self) -> Targets:
return self.md_targets.signed

def all_targets(self) -> Iterator[Tuple[str, Targets]]:
def all_targets(self) -> Iterator[tuple[str, Targets]]:
"""Yield role name and signed portion of targets one by one."""
yield Targets.type, self.md_targets.signed
for role, md in self.md_delegates.items():
Expand Down Expand Up @@ -287,7 +288,7 @@ def fetch_metadata(self, role: str, version: Optional[int] = None) -> bytes:

def _compute_hashes_and_length(
self, role: str
) -> Tuple[Dict[str, str], int]:
) -> tuple[dict[str, str], int]:
data = self.fetch_metadata(role)
digest_object = sslib_hash.digest(sslib_hash.DEFAULT_HASH_ALGORITHM)
digest_object.update(data)
Expand Down
6 changes: 3 additions & 3 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from copy import copy, deepcopy
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import ClassVar, Dict, Optional
from typing import ClassVar, Optional

from securesystemslib import exceptions as sslib_exceptions
from securesystemslib import hash as sslib_hash
Expand Down Expand Up @@ -54,7 +54,7 @@ class TestMetadata(unittest.TestCase):
temporary_directory: ClassVar[str]
repo_dir: ClassVar[str]
keystore_dir: ClassVar[str]
signers: ClassVar[Dict[str, Signer]]
signers: ClassVar[dict[str, Signer]]

@classmethod
def setUpClass(cls) -> None:
Expand Down Expand Up @@ -763,7 +763,7 @@ def test_targets_key_api(self) -> None:
}
)
assert isinstance(targets.delegations, Delegations)
assert isinstance(targets.delegations.roles, Dict)
assert isinstance(targets.delegations.roles, dict)
targets.delegations.roles["role2"] = delegated_role

key_dict = {
Expand Down
4 changes: 2 additions & 2 deletions tests/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import tempfile
import unittest
from pathlib import Path
from typing import ClassVar, List
from typing import ClassVar

from tests import utils

Expand Down Expand Up @@ -44,7 +44,7 @@ def tearDown(self) -> None:
shutil.rmtree(self.base_test_dir)

def _run_script_and_assert_files(
self, script_name: str, filenames_created: List[str]
self, script_name: str, filenames_created: list[str]
) -> None:
"""Run script in exmple dir and assert that it created the
files corresponding to the passed filenames inside a 'tmp*' test dir at
Expand Down
3 changes: 2 additions & 1 deletion tests/test_fetcher_ng.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
import sys
import tempfile
import unittest
from typing import Any, ClassVar, Iterator
from collections.abc import Iterator
from typing import Any, ClassVar
from unittest.mock import Mock, patch

import requests
Expand Down
6 changes: 3 additions & 3 deletions tests/test_metadata_eq_.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import os
import sys
import unittest
from typing import Any, ClassVar, Dict
from typing import Any, ClassVar

from securesystemslib.signer import SSlibKey

Expand All @@ -28,7 +28,7 @@
class TestMetadataComparisions(unittest.TestCase):
"""Test __eq__ for all classes inside tuf/api/metadata.py."""

metadata: ClassVar[Dict[str, bytes]]
metadata: ClassVar[dict[str, bytes]]

@classmethod
def setUpClass(cls) -> None:
Expand Down Expand Up @@ -85,7 +85,7 @@ def setUpClass(cls) -> None:
}

@utils.run_sub_tests_with_dataset(classes_attributes_modifications)
def test_classes_eq_(self, test_case_data: Dict[str, Any]) -> None:
def test_classes_eq_(self, test_case_data: dict[str, Any]) -> None:
obj = self.objects[self.case_name]

# Assert that obj is not equal to an object from another type
Expand Down
9 changes: 4 additions & 5 deletions tests/test_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import unittest
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from typing import Dict, List

from securesystemslib.signer import CryptoSigner, Signer

Expand Down Expand Up @@ -57,14 +56,14 @@ class TestingRepository(Repository):

def __init__(self) -> None:
# all versions of all metadata
self.role_cache: Dict[str, List[Metadata]] = defaultdict(list)
self.role_cache: dict[str, list[Metadata]] = defaultdict(list)
# all current keys
self.signer_cache: Dict[str, List[Signer]] = defaultdict(list)
self.signer_cache: dict[str, list[Signer]] = defaultdict(list)
# version cache for snapshot and all targets, updated in close().
# The 'defaultdict(lambda: ...)' trick allows close() to easily modify
# the version without always creating a new MetaFile
self._snapshot_info = MetaFile(1)
self._targets_infos: Dict[str, MetaFile] = defaultdict(
self._targets_infos: dict[str, MetaFile] = defaultdict(
lambda: MetaFile(1)
)

Expand All @@ -80,7 +79,7 @@ def __init__(self) -> None:
pass

@property
def targets_infos(self) -> Dict[str, MetaFile]:
def targets_infos(self) -> dict[str, MetaFile]:
return self._targets_infos

@property
Expand Down
8 changes: 4 additions & 4 deletions tests/test_trusted_metadata_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import sys
import unittest
from datetime import datetime, timezone
from typing import Callable, ClassVar, Dict, List, Optional, Tuple
from typing import Callable, ClassVar, Optional

from securesystemslib.signer import Signer

Expand Down Expand Up @@ -34,8 +34,8 @@
class TestTrustedMetadataSet(unittest.TestCase):
"""Tests for all public API of the TrustedMetadataSet class."""

keystore: ClassVar[Dict[str, Signer]]
metadata: ClassVar[Dict[str, bytes]]
keystore: ClassVar[dict[str, Signer]]
metadata: ClassVar[dict[str, bytes]]
repo_dir: ClassVar[str]

@classmethod
Expand Down Expand Up @@ -232,7 +232,7 @@ def test_bad_root_update(self) -> None:
self.trusted_set.update_root(self.metadata[Snapshot.type])

def test_top_level_md_with_invalid_json(self) -> None:
top_level_md: List[Tuple[bytes, Callable[[bytes], Signed]]] = [
top_level_md: list[tuple[bytes, Callable[[bytes], Signed]]] = [
(self.metadata[Timestamp.type], self.trusted_set.update_timestamp),
(self.metadata[Snapshot.type], self.trusted_set.update_snapshot),
(self.metadata[Targets.type], self.trusted_set.update_targets),
Expand Down
Loading

0 comments on commit 5c71f4f

Please sign in to comment.