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
5 changes: 3 additions & 2 deletions pyrit/models/harm_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import logging
import re
from pathlib import Path
from typing import Self

import yaml
from pydantic import BaseModel, Field
Expand Down Expand Up @@ -101,7 +102,7 @@ def validate_category(category: str, *, check_exists: bool = False) -> bool:
return True

@classmethod
def from_yaml(cls, harm_definition_path: str | Path) -> "HarmDefinition":
def from_yaml(cls, harm_definition_path: str | Path) -> Self:
"""
Load and validate a harm definition from a YAML file.

Expand All @@ -115,7 +116,7 @@ def from_yaml(cls, harm_definition_path: str | Path) -> "HarmDefinition":
relative to the standard harm_definition directory, or a full path.

Returns:
HarmDefinition: The loaded harm definition.
Self: The loaded harm definition, as an instance of the class it was called on.

Raises:
FileNotFoundError: If the harm definition file does not exist.
Expand Down
23 changes: 23 additions & 0 deletions tests/unit/models/test_harm_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"""

from pathlib import Path
from typing import assert_type

import pytest
import yaml
Expand Down Expand Up @@ -268,6 +269,28 @@ def test_from_yaml_valid_complete_file(self, tmp_path: Path) -> None:
assert harm_def.source_path == str(yaml_file)


class _CustomHarmDefinition(HarmDefinition):
"""Subclass used to verify that from_yaml returns the calling class."""


class TestHarmDefinitionFromYamlSelf:
"""Tests that HarmDefinition.from_yaml preserves the calling class."""

def test_from_yaml_returns_subclass(self) -> None:
"""Calling from_yaml on a subclass returns that subclass and keeps loaded fields."""
harm_def = _CustomHarmDefinition.from_yaml("violence.yaml")
assert_type(harm_def, _CustomHarmDefinition)
assert type(harm_def) is _CustomHarmDefinition
assert harm_def.category == "violence"
assert harm_def.source_path == str(HARM_DEFINITION_PATH / "violence.yaml")

def test_from_yaml_on_base_returns_harm_definition(self) -> None:
"""Calling from_yaml on the base class still returns a plain HarmDefinition."""
harm_def = HarmDefinition.from_yaml("violence.yaml")
assert_type(harm_def, HarmDefinition)
assert type(harm_def) is HarmDefinition


class TestGetAllHarmDefinitions:
"""Tests for the get_all_harm_definitions function."""

Expand Down
Loading