Create custom exception class for modifying an immutable object.

stix2.1
Greg Back 2017-04-18 15:05:20 -05:00
parent 91cecb7b0c
commit 6bf3584616
5 changed files with 13 additions and 6 deletions

View File

@ -4,7 +4,8 @@ import collections
import datetime as dt
import json
from .exceptions import ExtraFieldsError, InvalidValueError, MissingFieldsError
from .exceptions import ExtraFieldsError, ImmutableError, InvalidValueError, \
MissingFieldsError
from .utils import format_datetime, get_timestamp, NOW
__all__ = ['STIXJSONEncoder', '_STIXBase']
@ -85,8 +86,7 @@ class _STIXBase(collections.Mapping):
def __setattr__(self, name, value):
if name != '_inner' and not name.startswith("_STIXBase__"):
print(name)
raise ValueError("Cannot modify properties after creation.")
raise ImmutableError
super(_STIXBase, self).__setattr__(name, value)
def __str__(self):

View File

@ -42,3 +42,10 @@ class ExtraFieldsError(STIXError, TypeError):
msg = "Unexpected field(s) for {0}: ({1})."
return msg.format(self.cls.__name__,
", ".join(x for x in self.fields))
class ImmutableError(STIXError, ValueError):
"""Attempted to modify an object after creation"""
def __init__(self):
super(ImmutableError, self).__init__("Cannot modify properties after creation.")

View File

@ -125,7 +125,7 @@ def test_indicator_revoked_invalid():
def test_cannot_assign_to_indicator_attributes(indicator):
with pytest.raises(ValueError) as excinfo:
with pytest.raises(stix2.exceptions.ImmutableError) as excinfo:
indicator.valid_from = dt.datetime.now()
assert str(excinfo.value) == "Cannot modify properties after creation."

View File

@ -89,7 +89,7 @@ def test_malware_required_field_name():
def test_cannot_assign_to_malware_attributes(malware):
with pytest.raises(ValueError) as excinfo:
with pytest.raises(stix2.exceptions.ImmutableError) as excinfo:
malware.name = "Cryptolocker II"
assert str(excinfo.value) == "Cannot modify properties after creation."

View File

@ -98,7 +98,7 @@ def test_relationship_required_field_target_ref():
def test_cannot_assign_to_relationship_attributes(relationship):
with pytest.raises(ValueError) as excinfo:
with pytest.raises(stix2.exceptions.ImmutableError) as excinfo:
relationship.relationship_type = "derived-from"
assert str(excinfo.value) == "Cannot modify properties after creation."