Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions pyrit/converter/image_prompt_style_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def __init__(

Raises:
ValueError: If both filter_name and filter_path are provided.
ValueError: If filter_name does not correspond to an existing YAML file.
ValueError: If filter_name isn't a built-in filter.
ValueError: If filter_path does not exist.
ValueError: If variation does not match any entry in the filter.
"""
Expand All @@ -84,10 +84,11 @@ def __init__(
raise ValueError(f"Filter path '{filter_path}' does not exist.")
self._filter_name = resolved_path.stem
elif filter_name is not None:
resolved_path = self.IMAGE_PROMPT_STYLE_DIR / f"{filter_name}.yaml"
if not resolved_path.exists():
available = self.list_available_filters()
available = self.list_available_filters()
# Only built-in names are accepted, so a name can't reach other files on this machine.
if filter_name not in available:
raise ValueError(f"Filter '{filter_name}' not found. Available filters: {available}")
resolved_path = self.IMAGE_PROMPT_STYLE_DIR / f"{filter_name}.yaml"
self._filter_name = filter_name
else:
# No filter specified — pick a random built-in filter
Expand Down Expand Up @@ -238,13 +239,12 @@ def list_available_variations(cls, *, filter_name: str) -> list[str]:
Sorted list of variation key names defined in the filter.

Raises:
ValueError: If filter_name does not correspond to an existing YAML file, or if the
filter file is malformed.
ValueError: If filter_name isn't a built-in filter, or if the filter file is malformed.
"""
resolved_path = cls.IMAGE_PROMPT_STYLE_DIR / f"{filter_name}.yaml"
if not resolved_path.exists():
available = cls.list_available_filters()
available = cls.list_available_filters()
if filter_name not in available:
raise ValueError(f"Filter '{filter_name}' not found. Available filters: {available}")
resolved_path = cls.IMAGE_PROMPT_STYLE_DIR / f"{filter_name}.yaml"

with open(resolved_path, encoding="utf-8") as f:
filter_data = safe_load_yaml(f)
Expand Down
13 changes: 5 additions & 8 deletions pyrit/converter/persuasion_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,11 @@ def __init__(
ValueError: If converter_target is not provided and no default has been configured.
ValueError: If the persuasion technique is not supported or does not exist.
"""
try:
system_prompt_template = SeedPrompt.from_yaml_file(
pathlib.Path(CONVERTER_SEED_PROMPT_PATH) / "persuasion" / f"{persuasion_technique}.yaml"
)
except FileNotFoundError:
raise ValueError(
f"Persuasion technique '{persuasion_technique}' does not exist or is not supported."
) from None
techniques_path = pathlib.Path(CONVERTER_SEED_PROMPT_PATH) / "persuasion"
# Only shipped names are accepted, so a name can't reach other files on this machine.
if persuasion_technique not in {path.stem for path in techniques_path.glob("*.yaml")}:
raise ValueError(f"Persuasion technique '{persuasion_technique}' does not exist or is not supported.")
system_prompt_template = SeedPrompt.from_yaml_file(techniques_path / f"{persuasion_technique}.yaml")

self.system_prompt = str(system_prompt_template.value)
self._persuasion_technique = persuasion_technique
Expand Down
26 changes: 26 additions & 0 deletions tests/unit/backend/test_converter_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,32 @@ async def test_create_converter_rejects_reserved_route_name(self, name: str) ->
with pytest.raises(ValueError, match="reserved"):
await service.create_converter_async(request=request)

@pytest.mark.usefixtures("patch_central_database")
@pytest.mark.parametrize(
("converter_type", "name_parameter", "file_text", "message"),
[
("PersuasionConverter", "persuasion_technique", 'value: "A file"\n', "does not exist or is not supported"),
("ImagePromptStyleConverter", "filter_name", "style_instructions: x\nvariations:\n v1: d\n", "not found"),
],
)
async def test_create_converter_refuses_a_template_name_that_names_a_file(
self, tmp_path: Path, converter_type: str, name_parameter: str, file_text: str, message: str
) -> None:
(tmp_path / "other.yaml").write_text(file_text)
service = ConverterService()
request = CreateConverterRequest(
name="named_file",
type=converter_type,
params={"converter_target": "chat", name_parameter: str(tmp_path / "other")},
)

with patch.object(TargetRegistry, "get_registry_singleton", return_value=TargetRegistry()):
TargetRegistry.get_registry_singleton().instances.register(MockPromptTarget(), name="chat")
with pytest.raises(ValueError, match=message):
await service.create_converter_async(request=request)

assert service.get_converter_object(converter_id="named_file") is None


class TestDeleteConverter:
"""Tests for ConverterService.delete_converter_async."""
Expand Down
17 changes: 17 additions & 0 deletions tests/unit/converter/test_image_prompt_style_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,23 @@ def test_init_invalid_filter_name_raises(mock_target) -> None:
)


@pytest.mark.parametrize(
"filter_name", ["../image_prompt_style/gritty_documentary", "image_prompt_style_system_prompt"]
)
def test_init_filter_name_accepts_only_built_in_filters(mock_target, filter_name: str) -> None:
with pytest.raises(ValueError, match="not found"):
ImagePromptStyleConverter(converter_target=mock_target, filter_name=filter_name)


def test_filter_name_does_not_read_a_file_named_by_its_path(mock_target, tmp_path: Path) -> None:
(tmp_path / "other.yaml").write_text("style_instructions: Another style.\nvariations:\n v1: desc\n")

with pytest.raises(ValueError, match="not found"):
ImagePromptStyleConverter(converter_target=mock_target, filter_name=str(tmp_path / "other"))
with pytest.raises(ValueError, match="not found"):
ImagePromptStyleConverter.list_available_variations(filter_name=str(tmp_path / "other"))


def test_init_invalid_variation_raises(mock_target) -> None:
with pytest.raises(ValueError, match="not found in filter"):
ImagePromptStyleConverter(
Expand Down
14 changes: 14 additions & 0 deletions tests/unit/converter/test_persuasion_converter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

from pathlib import Path
from unittest.mock import AsyncMock, patch

import pytest
Expand Down Expand Up @@ -144,3 +145,16 @@ def test_persuasion_converter_identifier_includes_technique(sqlite_instance):
prompt_persuasion = PersuasionConverter(converter_target=prompt_target, persuasion_technique="logical_appeal")
identifier = prompt_persuasion.get_identifier()
assert identifier.params["persuasion_technique"] == "logical_appeal"


@pytest.mark.parametrize("technique", ["unknown_technique", "../persuasion/logical_appeal"])
def test_persuasion_converter_accepts_only_shipped_techniques(sqlite_instance, technique: str):
with pytest.raises(ValueError, match="does not exist or is not supported"):
PersuasionConverter(converter_target=MockPromptTarget(), persuasion_technique=technique)


def test_persuasion_converter_does_not_read_a_file_named_by_its_path(sqlite_instance, tmp_path: Path):
(tmp_path / "other.yaml").write_text('value: "Another file on this machine"\n')

with pytest.raises(ValueError, match="does not exist or is not supported"):
PersuasionConverter(converter_target=MockPromptTarget(), persuasion_technique=str(tmp_path / "other"))
Loading