diff --git a/pyrit/executor/promptgen/gcg/config.py b/pyrit/executor/promptgen/gcg/config.py index dd7bf2e667..218f744498 100644 --- a/pyrit/executor/promptgen/gcg/config.py +++ b/pyrit/executor/promptgen/gcg/config.py @@ -21,7 +21,7 @@ import json from dataclasses import asdict, dataclass, field -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Self if TYPE_CHECKING: from pathlib import Path @@ -125,7 +125,7 @@ def to_json(self) -> str: return json.dumps(asdict(self), indent=2) @classmethod - def from_json(cls, payload: str) -> GCGDataConfig: + def from_json(cls, payload: str) -> Self: """ Deserialize a config previously produced by ``to_json``. @@ -142,7 +142,7 @@ def from_json(cls, payload: str) -> GCGDataConfig: return cls(**data) @classmethod - def from_json_file(cls, path: str | Path) -> GCGDataConfig: + def from_json_file(cls, path: str | Path) -> Self: """ Load a config from a JSON file. @@ -391,7 +391,7 @@ def to_json(self) -> str: return json.dumps(asdict(self), indent=2) @classmethod - def from_json(cls, payload: str) -> GCGConfig: + def from_json(cls, payload: str) -> Self: """ Deserialize a config previously produced by ``to_json``. @@ -413,7 +413,7 @@ def from_json(cls, payload: str) -> GCGConfig: return cls._from_dict(data) @classmethod - def from_json_file(cls, path: str | Path) -> GCGConfig: + def from_json_file(cls, path: str | Path) -> Self: """ Load a config from a JSON file produced by ``to_json_file``. @@ -437,7 +437,7 @@ def to_json_file(self, path: str | Path) -> None: f.write(self.to_json()) @classmethod - def _from_dict(cls, data: dict[str, Any]) -> GCGConfig: + def _from_dict(cls, data: dict[str, Any]) -> Self: if "models" not in data or not isinstance(data["models"], list): raise ValueError("GCGConfig payload must contain a 'models' list.") return cls( diff --git a/pyrit/scenario/core/technique_tokens.py b/pyrit/scenario/core/technique_tokens.py index 702d46a484..5b902f4d13 100644 --- a/pyrit/scenario/core/technique_tokens.py +++ b/pyrit/scenario/core/technique_tokens.py @@ -21,13 +21,17 @@ from __future__ import annotations from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Literal, NamedTuple +from typing import TYPE_CHECKING, Generic, Literal, NamedTuple, TypeVar if TYPE_CHECKING: from collections.abc import Sequence from pyrit.converter import Converter - from pyrit.scenario.core.scenario_technique import ScenarioTechnique + from pyrit.registry import InstanceRegistry + from pyrit.scenario import ScenarioTechnique + + +TechniqueT = TypeVar("TechniqueT", bound="ScenarioTechnique") CONVERTER_MODIFIER_PREFIX = "converter." @@ -81,10 +85,10 @@ class TechniqueTokenIssue: @dataclass(frozen=True) -class TechniqueTokenResolution: +class TechniqueTokenResolution(Generic[TechniqueT]): """Everything a set of technique tokens resolved to, plus what did not resolve.""" - techniques: list[Any] = field(default_factory=list) + techniques: list[TechniqueT] = field(default_factory=list) technique_converters: dict[str, list[Converter]] = field(default_factory=dict) issues: list[TechniqueTokenIssue] = field(default_factory=list) @@ -92,9 +96,9 @@ class TechniqueTokenResolution: def resolve_technique_tokens( *, tokens: Sequence[str], - technique_class: type[ScenarioTechnique], + technique_class: type[TechniqueT], scenario_name: str, -) -> TechniqueTokenResolution: +) -> TechniqueTokenResolution[TechniqueT]: """ Resolve technique tokens into technique members and their additive converters. @@ -111,8 +115,8 @@ def resolve_technique_tokens( TechniqueTokenResolution: Resolved technique members, converters keyed by concrete technique name, and the references that did not resolve. """ - resolution = TechniqueTokenResolution() - converter_instances: Any = None + resolution: TechniqueTokenResolution[TechniqueT] = TechniqueTokenResolution() + converter_instances: InstanceRegistry[Converter] | None = None for token in tokens: base_name, modifiers = parse_technique_token(token) diff --git a/tests/unit/executor/promptgen/gcg/test_config.py b/tests/unit/executor/promptgen/gcg/test_config.py index 64cb415cde..5792b0f165 100644 --- a/tests/unit/executor/promptgen/gcg/test_config.py +++ b/tests/unit/executor/promptgen/gcg/test_config.py @@ -9,7 +9,7 @@ from __future__ import annotations import json -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, assert_type import pytest @@ -255,6 +255,46 @@ def test_data_config_json_round_trip(tmp_path: Path) -> None: assert GCGDataConfig.from_json_file(target) == original +class _DerivedGCGDataConfig(GCGDataConfig): + pass + + +class _DerivedGCGConfig(GCGConfig): + pass + + +def test_json_factories_preserve_data_config_subclass(tmp_path: Path) -> None: + original = _DerivedGCGDataConfig(train_data="train.csv", n_train_data=2) + + from_json = _DerivedGCGDataConfig.from_json(original.to_json()) + assert_type(from_json, _DerivedGCGDataConfig) + assert isinstance(from_json, _DerivedGCGDataConfig) + assert from_json == original + + target = tmp_path / "data.json" + original.to_json_file(target) + from_file = _DerivedGCGDataConfig.from_json_file(target) + assert_type(from_file, _DerivedGCGDataConfig) + assert isinstance(from_file, _DerivedGCGDataConfig) + assert from_file == original + + +def test_json_factories_preserve_config_subclass(tmp_path: Path) -> None: + original = _DerivedGCGConfig(models=[GCGModelConfig(name=_LLAMA_2)]) + + from_json = _DerivedGCGConfig.from_json(original.to_json()) + assert_type(from_json, _DerivedGCGConfig) + assert isinstance(from_json, _DerivedGCGConfig) + assert from_json.models == original.models + + target = tmp_path / "config.json" + original.to_json_file(target) + from_file = _DerivedGCGConfig.from_json_file(target) + assert_type(from_file, _DerivedGCGConfig) + assert isinstance(from_file, _DerivedGCGConfig) + assert from_file.models == original.models + + def test_to_json_is_pretty_printed() -> None: payload = _minimal_config().to_json() assert "\n" in payload diff --git a/tests/unit/scenario/core/test_technique_tokens.py b/tests/unit/scenario/core/test_technique_tokens.py new file mode 100644 index 0000000000..75f8f64498 --- /dev/null +++ b/tests/unit/scenario/core/test_technique_tokens.py @@ -0,0 +1,47 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from typing import assert_type + +from pyrit.scenario import ScenarioTechnique +from pyrit.scenario.core import TechniqueTokenResolution, parse_technique_token, resolve_technique_tokens + + +class _TypedTechnique(ScenarioTechnique): + ALL = ("all", {"all"}) + First = ("first", set()) + Second = ("second", set()) + + +def test_parse_technique_token_preserves_ordered_modifiers() -> None: + parsed = parse_technique_token("first:converter.one:converter.two") + + assert parsed.base_name == "first" + assert parsed.modifiers == ("converter.one", "converter.two") + + +def test_resolve_technique_tokens_preserves_concrete_technique_type() -> None: + resolution = resolve_technique_tokens( + tokens=["first", "second"], + technique_class=_TypedTechnique, + scenario_name="typed-test", + ) + + assert_type(resolution, TechniqueTokenResolution[_TypedTechnique]) + assert_type(resolution.techniques, list[_TypedTechnique]) + assert resolution.techniques == [_TypedTechnique.First, _TypedTechnique.Second] + assert resolution.technique_converters == {} + assert resolution.issues == [] + + +def test_resolve_technique_tokens_reports_invalid_techniques_without_changing_types() -> None: + resolution = resolve_technique_tokens( + tokens=["missing", "first"], + technique_class=_TypedTechnique, + scenario_name="typed-test", + ) + + assert_type(resolution.techniques, list[_TypedTechnique]) + assert resolution.techniques == [_TypedTechnique.First] + assert [issue.kind for issue in resolution.issues] == ["unknown_technique"] + assert resolution.issues[0].name == "missing"