Update v20 tests to ensure right methods and classes are used

stix2.1
Emmanuelle Vargas-Gonzalez 2018-07-05 15:23:25 -04:00
parent 2c5ddc14af
commit 5be1636b10
32 changed files with 834 additions and 806 deletions

View File

@ -35,17 +35,17 @@ def uuid4(monkeypatch):
@pytest.fixture
def indicator(uuid4, clock):
return stix2.Indicator(**INDICATOR_KWARGS)
return stix2.v20.Indicator(**INDICATOR_KWARGS)
@pytest.fixture
def malware(uuid4, clock):
return stix2.Malware(**MALWARE_KWARGS)
return stix2.v20.Malware(**MALWARE_KWARGS)
@pytest.fixture
def relationship(uuid4, clock):
return stix2.Relationship(**RELATIONSHIP_KWARGS)
return stix2.v20.Relationship(**RELATIONSHIP_KWARGS)
@pytest.fixture
@ -156,4 +156,4 @@ def stix_objs2():
@pytest.fixture
def real_stix_objs2(stix_objs2):
return [stix2.parse(x) for x in stix_objs2]
return [stix2.parse(x, version="2.0") for x in stix_objs2]

View File

@ -79,8 +79,7 @@ INTRUSION_SET_KWARGS = dict(
MALWARE_KWARGS = dict(
labels=['ransomware'],
name="Cryptolocker",
is_family=False
name="Cryptolocker"
)
MALWARE_MORE_KWARGS = dict(
@ -90,8 +89,7 @@ MALWARE_MORE_KWARGS = dict(
modified="2016-04-06T20:03:00.000Z",
labels=['ransomware'],
name="Cryptolocker",
description="A ransomware related to ...",
is_family=False
description="A ransomware related to ..."
)
OBSERVED_DATA_KWARGS = dict(

View File

@ -24,7 +24,7 @@ EXPECTED = """{
def test_attack_pattern_example():
ap = stix2.AttackPattern(
ap = stix2.v20.AttackPattern(
id="attack-pattern--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061",
created="2016-05-12T08:17:27.000Z",
modified="2016-05-12T08:17:27.000Z",
@ -57,7 +57,7 @@ def test_attack_pattern_example():
},
])
def test_parse_attack_pattern(data):
ap = stix2.parse(data)
ap = stix2.parse(data, version="2.0")
assert ap.type == 'attack-pattern'
assert ap.id == ATTACK_PATTERN_ID
@ -71,7 +71,7 @@ def test_parse_attack_pattern(data):
def test_attack_pattern_invalid_labels():
with pytest.raises(stix2.exceptions.InvalidValueError):
stix2.AttackPattern(
stix2.v20.AttackPattern(
id="attack-pattern--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061",
created="2016-05-12T08:17:27Z",
modified="2016-05-12T08:17:27Z",

View File

@ -3,13 +3,11 @@ import json
import pytest
import stix2
import stix2.v21.bundle
import stix2.v21.sdo
EXPECTED_BUNDLE = """{
"type": "bundle",
"spec_version": "2.0",
"id": "bundle--00000000-0000-0000-0000-000000000007",
"spec_version": "2.0",
"objects": [
{
"type": "indicator",
@ -24,19 +22,16 @@ EXPECTED_BUNDLE = """{
},
{
"type": "malware",
"spec_version": "2.1",
"id": "malware--00000000-0000-0000-0000-000000000003",
"created": "2017-01-01T12:34:56.000Z",
"modified": "2017-01-01T12:34:56.000Z",
"name": "Cryptolocker",
"labels": [
"ransomware"
],
"is_family": false
]
},
{
"type": "relationship",
"spec_version": "2.1",
"id": "relationship--00000000-0000-0000-0000-000000000005",
"created": "2017-01-01T12:34:56.000Z",
"modified": "2017-01-01T12:34:56.000Z",
@ -49,8 +44,8 @@ EXPECTED_BUNDLE = """{
EXPECTED_BUNDLE_DICT = {
"type": "bundle",
"spec_version": "2.0",
"id": "bundle--00000000-0000-0000-0000-000000000007",
"spec_version": "2.0",
"objects": [
{
"type": "indicator",
@ -65,19 +60,16 @@ EXPECTED_BUNDLE_DICT = {
},
{
"type": "malware",
"spec_version": "2.1",
"id": "malware--00000000-0000-0000-0000-000000000003",
"created": "2017-01-01T12:34:56.000Z",
"modified": "2017-01-01T12:34:56.000Z",
"name": "Cryptolocker",
"labels": [
"ransomware"
],
"is_family": False
]
},
{
"type": "relationship",
"spec_version": "2.1",
"id": "relationship--00000000-0000-0000-0000-000000000005",
"created": "2017-01-01T12:34:56.000Z",
"modified": "2017-01-01T12:34:56.000Z",
@ -90,7 +82,7 @@ EXPECTED_BUNDLE_DICT = {
def test_empty_bundle():
bundle = stix2.Bundle()
bundle = stix2.v20.Bundle()
assert bundle.type == "bundle"
assert bundle.id.startswith("bundle--")
@ -100,9 +92,9 @@ def test_empty_bundle():
def test_bundle_with_wrong_type():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Bundle(type="not-a-bundle")
stix2.v20.Bundle(type="not-a-bundle")
assert excinfo.value.cls == stix2.Bundle
assert excinfo.value.cls == stix2.v20.Bundle
assert excinfo.value.prop_name == "type"
assert excinfo.value.reason == "must equal 'bundle'."
assert str(excinfo.value) == "Invalid value for Bundle 'type': must equal 'bundle'."
@ -110,78 +102,78 @@ def test_bundle_with_wrong_type():
def test_bundle_id_must_start_with_bundle():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Bundle(id='my-prefix--')
stix2.v20.Bundle(id='my-prefix--')
assert excinfo.value.cls == stix2.Bundle
assert excinfo.value.cls == stix2.v20.Bundle
assert excinfo.value.prop_name == "id"
assert excinfo.value.reason == "must start with 'bundle--'."
assert str(excinfo.value) == "Invalid value for Bundle 'id': must start with 'bundle--'."
def test_create_bundle1(indicator, malware, relationship):
bundle = stix2.Bundle(objects=[indicator, malware, relationship])
bundle = stix2.v20.Bundle(objects=[indicator, malware, relationship])
assert str(bundle) == EXPECTED_BUNDLE
assert bundle.serialize(pretty=True) == EXPECTED_BUNDLE
def test_create_bundle2(indicator, malware, relationship):
bundle = stix2.Bundle(objects=[indicator, malware, relationship])
bundle = stix2.v20.Bundle(objects=[indicator, malware, relationship])
assert json.loads(bundle.serialize()) == EXPECTED_BUNDLE_DICT
def test_create_bundle_with_positional_args(indicator, malware, relationship):
bundle = stix2.Bundle(indicator, malware, relationship)
bundle = stix2.v20.Bundle(indicator, malware, relationship)
assert str(bundle) == EXPECTED_BUNDLE
def test_create_bundle_with_positional_listarg(indicator, malware, relationship):
bundle = stix2.Bundle([indicator, malware, relationship])
bundle = stix2.v20.Bundle([indicator, malware, relationship])
assert str(bundle) == EXPECTED_BUNDLE
def test_create_bundle_with_listarg_and_positional_arg(indicator, malware, relationship):
bundle = stix2.Bundle([indicator, malware], relationship)
bundle = stix2.v20.Bundle([indicator, malware], relationship)
assert str(bundle) == EXPECTED_BUNDLE
def test_create_bundle_with_listarg_and_kwarg(indicator, malware, relationship):
bundle = stix2.Bundle([indicator, malware], objects=[relationship])
bundle = stix2.v20.Bundle([indicator, malware], objects=[relationship])
assert str(bundle) == EXPECTED_BUNDLE
def test_create_bundle_with_arg_listarg_and_kwarg(indicator, malware, relationship):
bundle = stix2.Bundle([indicator], malware, objects=[relationship])
bundle = stix2.v20.Bundle([indicator], malware, objects=[relationship])
assert str(bundle) == EXPECTED_BUNDLE
def test_create_bundle_invalid(indicator, malware, relationship):
with pytest.raises(ValueError) as excinfo:
stix2.Bundle(objects=[1])
stix2.v20.Bundle(objects=[1])
assert excinfo.value.reason == "This property may only contain a dictionary or object"
with pytest.raises(ValueError) as excinfo:
stix2.Bundle(objects=[{}])
stix2.v20.Bundle(objects=[{}])
assert excinfo.value.reason == "This property may only contain a non-empty dictionary or object"
with pytest.raises(ValueError) as excinfo:
stix2.Bundle(objects=[{'type': 'bundle'}])
stix2.v20.Bundle(objects=[{'type': 'bundle'}])
assert excinfo.value.reason == 'This property may not contain a Bundle object'
@pytest.mark.parametrize("version", ["2.1"])
@pytest.mark.parametrize("version", ["2.0"])
def test_parse_bundle(version):
bundle = stix2.parse(EXPECTED_BUNDLE, version=version)
assert bundle.type == "bundle"
assert bundle.id.startswith("bundle--")
assert type(bundle.objects[0]) is stix2.v21.sdo.Indicator
assert type(bundle.objects[0]) is stix2.v20.Indicator
assert bundle.objects[0].type == 'indicator'
assert bundle.objects[1].type == 'malware'
assert bundle.objects[2].type == 'relationship'
@ -199,12 +191,12 @@ def test_parse_unknown_type():
}
with pytest.raises(stix2.exceptions.ParseError) as excinfo:
stix2.parse(unknown)
stix2.parse(unknown, version="2.0")
assert str(excinfo.value) == "Can't parse unknown object type 'other'! For custom types, use the CustomObject decorator."
def test_stix_object_property():
prop = stix2.v21.bundle.STIXObjectProperty()
prop = stix2.v20.bundle.STIXObjectProperty()
identity = stix2.Identity(name="test", identity_class="individual")
identity = stix2.v20.Identity(name="test", identity_class="individual")
assert prop.clean(identity) is identity

View File

@ -19,7 +19,7 @@ EXPECTED = """{
def test_campaign_example():
campaign = stix2.Campaign(
campaign = stix2.v20.Campaign(
id="campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f",
created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff",
created="2016-04-06T20:03:00Z",
@ -44,7 +44,7 @@ def test_campaign_example():
},
])
def test_parse_campaign(data):
cmpn = stix2.parse(data)
cmpn = stix2.parse(data, version="2.0")
assert cmpn.type == 'campaign'
assert cmpn.id == CAMPAIGN_ID

View File

@ -19,7 +19,7 @@ EXPECTED = """{
def test_course_of_action_example():
coa = stix2.CourseOfAction(
coa = stix2.v20.CourseOfAction(
id="course-of-action--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f",
created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff",
created="2016-04-06T20:03:48.000Z",
@ -44,7 +44,7 @@ def test_course_of_action_example():
},
])
def test_parse_course_of_action(data):
coa = stix2.parse(data)
coa = stix2.parse(data, version="2.0")
assert coa.type == 'course-of-action'
assert coa.id == COURSE_OF_ACTION_ID

View File

@ -1,12 +1,10 @@
import pytest
import stix2
import stix2.base
import stix2.v21.sdo
from .constants import FAKE_TIME, MARKING_DEFINITION_ID
IDENTITY_CUSTOM_PROP = stix2.Identity(
IDENTITY_CUSTOM_PROP = stix2.v20.Identity(
name="John Smith",
identity_class="individual",
x_foo="bar",
@ -16,7 +14,7 @@ IDENTITY_CUSTOM_PROP = stix2.Identity(
def test_identity_custom_property():
with pytest.raises(ValueError) as excinfo:
stix2.Identity(
stix2.v20.Identity(
id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c",
created="2015-12-21T19:59:11Z",
modified="2015-12-21T19:59:11Z",
@ -27,7 +25,7 @@ def test_identity_custom_property():
assert str(excinfo.value) == "'custom_properties' must be a dictionary"
with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo:
stix2.Identity(
stix2.v20.Identity(
id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c",
created="2015-12-21T19:59:11Z",
modified="2015-12-21T19:59:11Z",
@ -40,7 +38,7 @@ def test_identity_custom_property():
)
assert "Unexpected properties for Identity" in str(excinfo.value)
identity = stix2.Identity(
identity = stix2.v20.Identity(
id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c",
created="2015-12-21T19:59:11Z",
modified="2015-12-21T19:59:11Z",
@ -55,7 +53,7 @@ def test_identity_custom_property():
def test_identity_custom_property_invalid():
with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo:
stix2.Identity(
stix2.v20.Identity(
id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c",
created="2015-12-21T19:59:11Z",
modified="2015-12-21T19:59:11Z",
@ -63,13 +61,13 @@ def test_identity_custom_property_invalid():
identity_class="individual",
x_foo="bar",
)
assert excinfo.value.cls == stix2.Identity
assert excinfo.value.cls == stix2.v20.Identity
assert excinfo.value.properties == ['x_foo']
assert "Unexpected properties for" in str(excinfo.value)
def test_identity_custom_property_allowed():
identity = stix2.Identity(
identity = stix2.v20.Identity(
id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c",
created="2015-12-21T19:59:11Z",
modified="2015-12-21T19:59:11Z",
@ -94,31 +92,31 @@ def test_identity_custom_property_allowed():
])
def test_parse_identity_custom_property(data):
with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo:
identity = stix2.parse(data)
assert excinfo.value.cls == stix2.v21.sdo.Identity
stix2.parse(data, version="2.0")
assert excinfo.value.cls == stix2.v20.Identity
assert excinfo.value.properties == ['foo']
assert "Unexpected properties for" in str(excinfo.value)
identity = stix2.parse(data, allow_custom=True)
identity = stix2.parse(data, version="2.0", allow_custom=True)
assert identity.foo == "bar"
def test_custom_property_object_in_bundled_object():
bundle = stix2.Bundle(IDENTITY_CUSTOM_PROP, allow_custom=True)
bundle = stix2.v20.Bundle(IDENTITY_CUSTOM_PROP, allow_custom=True)
assert bundle.objects[0].x_foo == "bar"
assert '"x_foo": "bar"' in str(bundle)
def test_custom_properties_object_in_bundled_object():
obj = stix2.Identity(
obj = stix2.v20.Identity(
name="John Smith",
identity_class="individual",
custom_properties={
"x_foo": "bar",
}
)
bundle = stix2.Bundle(obj, allow_custom=True)
bundle = stix2.v20.Bundle(obj, allow_custom=True)
assert bundle.objects[0].x_foo == "bar"
assert '"x_foo": "bar"' in str(bundle)
@ -134,9 +132,9 @@ def test_custom_property_dict_in_bundled_object():
'x_foo': 'bar',
}
with pytest.raises(stix2.exceptions.ExtraPropertiesError):
bundle = stix2.Bundle(custom_identity)
stix2.v20.Bundle(custom_identity)
bundle = stix2.Bundle(custom_identity, allow_custom=True)
bundle = stix2.v20.Bundle(custom_identity, allow_custom=True)
assert bundle.objects[0].x_foo == "bar"
assert '"x_foo": "bar"' in str(bundle)
@ -152,19 +150,19 @@ def test_custom_properties_dict_in_bundled_object():
'x_foo': 'bar',
},
}
bundle = stix2.Bundle(custom_identity)
bundle = stix2.v20.Bundle(custom_identity)
assert bundle.objects[0].x_foo == "bar"
assert '"x_foo": "bar"' in str(bundle)
def test_custom_property_in_observed_data():
artifact = stix2.File(
artifact = stix2.v20.File(
allow_custom=True,
name='test',
x_foo='bar'
)
observed_data = stix2.ObservedData(
observed_data = stix2.v20.ObservedData(
allow_custom=True,
first_observed="2015-12-21T19:00:00Z",
last_observed="2015-12-21T19:00:00Z",
@ -177,16 +175,16 @@ def test_custom_property_in_observed_data():
def test_custom_property_object_in_observable_extension():
ntfs = stix2.NTFSExt(
ntfs = stix2.v20.NTFSExt(
allow_custom=True,
sid=1,
x_foo='bar',
)
artifact = stix2.File(
artifact = stix2.v20.File(
name='test',
extensions={'ntfs-ext': ntfs},
)
observed_data = stix2.ObservedData(
observed_data = stix2.v20.ObservedData(
allow_custom=True,
first_observed="2015-12-21T19:00:00Z",
last_observed="2015-12-21T19:00:00Z",
@ -200,7 +198,7 @@ def test_custom_property_object_in_observable_extension():
def test_custom_property_dict_in_observable_extension():
with pytest.raises(stix2.exceptions.ExtraPropertiesError):
artifact = stix2.File(
stix2.v20.File(
name='test',
extensions={
'ntfs-ext': {
@ -210,7 +208,7 @@ def test_custom_property_dict_in_observable_extension():
},
)
artifact = stix2.File(
artifact = stix2.v20.File(
allow_custom=True,
name='test',
extensions={
@ -221,7 +219,7 @@ def test_custom_property_dict_in_observable_extension():
}
},
)
observed_data = stix2.ObservedData(
observed_data = stix2.v20.ObservedData(
allow_custom=True,
first_observed="2015-12-21T19:00:00Z",
last_observed="2015-12-21T19:00:00Z",
@ -239,15 +237,15 @@ def test_identity_custom_property_revoke():
def test_identity_custom_property_edit_markings():
marking_obj = stix2.MarkingDefinition(
marking_obj = stix2.v20.MarkingDefinition(
id=MARKING_DEFINITION_ID,
definition_type="statement",
definition=stix2.StatementMarking(statement="Copyright 2016, Example Corp")
definition=stix2.v20.StatementMarking(statement="Copyright 2016, Example Corp")
)
marking_obj2 = stix2.MarkingDefinition(
marking_obj2 = stix2.v20.MarkingDefinition(
id=MARKING_DEFINITION_ID,
definition_type="statement",
definition=stix2.StatementMarking(statement="Another one")
definition=stix2.v20.StatementMarking(statement="Another one")
)
# None of the following should throw exceptions
@ -260,8 +258,8 @@ def test_identity_custom_property_edit_markings():
def test_custom_marking_no_init_1():
@stix2.CustomMarking('x-new-obj', [
('property1', stix2.properties.StringProperty(required=True)),
@stix2.v20.CustomMarking('x-new-obj', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class NewObj():
pass
@ -271,8 +269,8 @@ def test_custom_marking_no_init_1():
def test_custom_marking_no_init_2():
@stix2.CustomMarking('x-new-obj2', [
('property1', stix2.properties.StringProperty(required=True)),
@stix2.v20.CustomMarking('x-new-obj2', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class NewObj2(object):
pass
@ -281,9 +279,9 @@ def test_custom_marking_no_init_2():
assert no2.property1 == 'something'
@stix2.sdo.CustomObject('x-new-type', [
('property1', stix2.properties.StringProperty(required=True)),
('property2', stix2.properties.IntegerProperty()),
@stix2.v20.CustomObject('x-new-type', [
('property1', stix2.v20.properties.StringProperty(required=True)),
('property2', stix2.v20.properties.IntegerProperty()),
])
class NewType(object):
def __init__(self, property2=None, **kwargs):
@ -314,8 +312,8 @@ def test_custom_object_type():
def test_custom_object_no_init_1():
@stix2.sdo.CustomObject('x-new-obj', [
('property1', stix2.properties.StringProperty(required=True)),
@stix2.v20.CustomObject('x-new-obj', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class NewObj():
pass
@ -325,8 +323,8 @@ def test_custom_object_no_init_1():
def test_custom_object_no_init_2():
@stix2.sdo.CustomObject('x-new-obj2', [
('property1', stix2.properties.StringProperty(required=True)),
@stix2.v20.CustomObject('x-new-obj2', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class NewObj2(object):
pass
@ -337,16 +335,16 @@ def test_custom_object_no_init_2():
def test_custom_object_invalid_type_name():
with pytest.raises(ValueError) as excinfo:
@stix2.sdo.CustomObject('x', [
('property1', stix2.properties.StringProperty(required=True)),
@stix2.v20.CustomObject('x', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class NewObj(object):
pass # pragma: no cover
assert "Invalid type name 'x': " in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
@stix2.sdo.CustomObject('x_new_object', [
('property1', stix2.properties.StringProperty(required=True)),
@stix2.v20.CustomObject('x_new_object', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class NewObj2(object):
pass # pragma: no cover
@ -360,7 +358,7 @@ def test_parse_custom_object_type():
"property1": "something"
}"""
nt = stix2.parse(nt_string, allow_custom=True)
nt = stix2.parse(nt_string, version="2.0", allow_custom=True)
assert nt["property1"] == 'something'
@ -372,7 +370,7 @@ def test_parse_unregistered_custom_object_type():
}"""
with pytest.raises(stix2.exceptions.ParseError) as excinfo:
stix2.parse(nt_string)
stix2.parse(nt_string, version="2.0")
assert "Can't parse unknown object type" in str(excinfo.value)
assert "use the CustomObject decorator." in str(excinfo.value)
@ -387,14 +385,14 @@ def test_parse_unregistered_custom_object_type_w_allow_custom():
"property1": "something"
}"""
custom_obj = stix2.parse(nt_string, allow_custom=True)
custom_obj = stix2.parse(nt_string, version="2.0", allow_custom=True)
assert custom_obj["type"] == "x-foobar-observable"
@stix2.observables.CustomObservable('x-new-observable', [
('property1', stix2.properties.StringProperty(required=True)),
('property2', stix2.properties.IntegerProperty()),
('x_property3', stix2.properties.BooleanProperty()),
@stix2.v20.CustomObservable('x-new-observable', [
('property1', stix2.v20.properties.StringProperty(required=True)),
('property2', stix2.v20.properties.IntegerProperty()),
('x_property3', stix2.v20.properties.BooleanProperty()),
])
class NewObservable():
def __init__(self, property2=None, **kwargs):
@ -430,8 +428,8 @@ def test_custom_observable_raises_exception():
def test_custom_observable_object_no_init_1():
@stix2.observables.CustomObservable('x-new-observable', [
('property1', stix2.properties.StringProperty()),
@stix2.v20.CustomObservable('x-new-observable', [
('property1', stix2.v20.properties.StringProperty()),
])
class NewObs():
pass
@ -441,8 +439,8 @@ def test_custom_observable_object_no_init_1():
def test_custom_observable_object_no_init_2():
@stix2.observables.CustomObservable('x-new-obs2', [
('property1', stix2.properties.StringProperty()),
@stix2.v20.CustomObservable('x-new-obs2', [
('property1', stix2.v20.properties.StringProperty()),
])
class NewObs2(object):
pass
@ -453,16 +451,16 @@ def test_custom_observable_object_no_init_2():
def test_custom_observable_object_invalid_type_name():
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomObservable('x', [
('property1', stix2.properties.StringProperty()),
@stix2.v20.CustomObservable('x', [
('property1', stix2.v20.properties.StringProperty()),
])
class NewObs(object):
pass # pragma: no cover
assert "Invalid observable type name 'x':" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomObservable('x_new_obs', [
('property1', stix2.properties.StringProperty()),
@stix2.v20.CustomObservable('x_new_obs', [
('property1', stix2.v20.properties.StringProperty()),
])
class NewObs2(object):
pass # pragma: no cover
@ -471,8 +469,8 @@ def test_custom_observable_object_invalid_type_name():
def test_custom_observable_object_invalid_ref_property():
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomObservable('x-new-obs', [
('property_ref', stix2.properties.StringProperty()),
@stix2.v20.CustomObservable('x-new-obs', [
('property_ref', stix2.v20.properties.StringProperty()),
])
class NewObs():
pass
@ -481,8 +479,8 @@ def test_custom_observable_object_invalid_ref_property():
def test_custom_observable_object_invalid_refs_property():
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomObservable('x-new-obs', [
('property_refs', stix2.properties.StringProperty()),
@stix2.v20.CustomObservable('x-new-obs', [
('property_refs', stix2.v20.properties.StringProperty()),
])
class NewObs():
pass
@ -491,8 +489,8 @@ def test_custom_observable_object_invalid_refs_property():
def test_custom_observable_object_invalid_refs_list_property():
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomObservable('x-new-obs', [
('property_refs', stix2.properties.ListProperty(stix2.properties.StringProperty)),
@stix2.v20.CustomObservable('x-new-obs', [
('property_refs', stix2.v20.properties.ListProperty(stix2.v20.properties.StringProperty)),
])
class NewObs():
pass
@ -500,9 +498,9 @@ def test_custom_observable_object_invalid_refs_list_property():
def test_custom_observable_object_invalid_valid_refs():
@stix2.observables.CustomObservable('x-new-obs', [
('property1', stix2.properties.StringProperty(required=True)),
('property_ref', stix2.properties.ObjectReferenceProperty(valid_types='email-addr')),
@stix2.v20.CustomObservable('x-new-obs', [
('property1', stix2.v20.properties.StringProperty(required=True)),
('property_ref', stix2.v20.properties.ObjectReferenceProperty(valid_types='email-addr')),
])
class NewObs():
pass
@ -517,7 +515,7 @@ def test_custom_observable_object_invalid_valid_refs():
def test_custom_no_properties_raises_exception():
with pytest.raises(ValueError):
@stix2.sdo.CustomObject('x-new-object-type')
@stix2.v20.CustomObject('x-new-object-type')
class NewObject1(object):
pass
@ -525,7 +523,7 @@ def test_custom_no_properties_raises_exception():
def test_custom_wrong_properties_arg_raises_exception():
with pytest.raises(ValueError):
@stix2.observables.CustomObservable('x-new-object-type', (("prop", stix2.properties.BooleanProperty())))
@stix2.v20.CustomObservable('x-new-object-type', (("prop", stix2.v20.properties.BooleanProperty())))
class NewObject2(object):
pass
@ -536,7 +534,7 @@ def test_parse_custom_observable_object():
"property1": "something"
}"""
nt = stix2.parse_observable(nt_string, [])
nt = stix2.parse_observable(nt_string, [], version='2.0')
assert isinstance(nt, stix2.base._STIXBase)
assert nt.property1 == 'something'
@ -548,10 +546,10 @@ def test_parse_unregistered_custom_observable_object():
}"""
with pytest.raises(stix2.exceptions.CustomContentError) as excinfo:
stix2.parse_observable(nt_string)
stix2.parse_observable(nt_string, version='2.0')
assert "Can't parse unknown observable type" in str(excinfo.value)
parsed_custom = stix2.parse_observable(nt_string, allow_custom=True)
parsed_custom = stix2.parse_observable(nt_string, allow_custom=True, version='2.0')
assert parsed_custom['property1'] == 'something'
with pytest.raises(AttributeError) as excinfo:
assert parsed_custom.property1 == 'something'
@ -564,7 +562,7 @@ def test_parse_unregistered_custom_observable_object_with_no_type():
}"""
with pytest.raises(stix2.exceptions.ParseError) as excinfo:
stix2.parse_observable(nt_string, allow_custom=True)
stix2.parse_observable(nt_string, allow_custom=True, version='2.0')
assert "Can't parse observable with no 'type' property" in str(excinfo.value)
@ -584,7 +582,7 @@ def test_parse_observed_data_with_custom_observable():
}
}
}"""
parsed = stix2.parse(input_str, allow_custom=True)
parsed = stix2.parse(input_str, version="2.0", allow_custom=True)
assert parsed.objects['0']['property1'] == 'something'
@ -594,7 +592,7 @@ def test_parse_invalid_custom_observable_object():
}"""
with pytest.raises(stix2.exceptions.ParseError) as excinfo:
stix2.parse_observable(nt_string)
stix2.parse_observable(nt_string, version='2.0')
assert "Can't parse observable with no 'type' property" in str(excinfo.value)
@ -636,7 +634,7 @@ def test_observable_custom_property_allowed():
def test_observed_data_with_custom_observable_object():
no = NewObservable(property1='something')
ob_data = stix2.ObservedData(
ob_data = stix2.v20.ObservedData(
first_observed=FAKE_TIME,
last_observed=FAKE_TIME,
number_observed=1,
@ -646,9 +644,9 @@ def test_observed_data_with_custom_observable_object():
assert ob_data.objects['0'].property1 == 'something'
@stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext', [
('property1', stix2.properties.StringProperty(required=True)),
('property2', stix2.properties.IntegerProperty()),
@stix2.v20.CustomExtension(stix2.v20.DomainName, 'x-new-ext', [
('property1', stix2.v20.properties.StringProperty(required=True)),
('property2', stix2.v20.properties.IntegerProperty()),
])
class NewExtension():
def __init__(self, property2=None, **kwargs):
@ -683,10 +681,11 @@ def test_custom_extension_wrong_observable_type():
# NewExtension is an extension of DomainName, not File
ext = NewExtension(property1='something')
with pytest.raises(ValueError) as excinfo:
stix2.File(name="abc.txt",
extensions={
"ntfs-ext": ext,
})
stix2.v20.File(
name="abc.txt",
extensions={
"ntfs-ext": ext,
})
assert 'Cannot determine extension type' in excinfo.value.reason
@ -702,8 +701,8 @@ def test_custom_extension_wrong_observable_type():
}""",
])
def test_custom_extension_with_list_and_dict_properties_observable_type(data):
@stix2.observables.CustomExtension(stix2.UserAccount, 'some-extension', [
('keys', stix2.properties.ListProperty(stix2.properties.DictionaryProperty, required=True))
@stix2.v20.CustomExtension(stix2.v20.UserAccount, 'some-extension', [
('keys', stix2.v20.properties.ListProperty(stix2.v20.properties.DictionaryProperty, required=True))
])
class SomeCustomExtension:
pass
@ -718,29 +717,29 @@ def test_custom_extension_invalid_observable():
class Foo(object):
pass
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomExtension(Foo, 'x-new-ext', [
('property1', stix2.properties.StringProperty(required=True)),
@stix2.v20.CustomExtension(Foo, 'x-new-ext', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class FooExtension():
pass # pragma: no cover
assert str(excinfo.value) == "'observable' must be a valid Observable class!"
class Bar(stix2.observables._Observable):
class Bar(stix2.v20.observables._Observable):
pass
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomExtension(Bar, 'x-new-ext', [
('property1', stix2.properties.StringProperty(required=True)),
@stix2.v20.CustomExtension(Bar, 'x-new-ext', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class BarExtension():
pass
assert "Unknown observable type" in str(excinfo.value)
assert "Custom observables must be created with the @CustomObservable decorator." in str(excinfo.value)
class Baz(stix2.observables._Observable):
class Baz(stix2.v20.observables._Observable):
_type = 'Baz'
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomExtension(Baz, 'x-new-ext', [
('property1', stix2.properties.StringProperty(required=True)),
@stix2.v20.CustomExtension(Baz, 'x-new-ext', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class BazExtension():
pass
@ -750,16 +749,16 @@ def test_custom_extension_invalid_observable():
def test_custom_extension_invalid_type_name():
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomExtension(stix2.File, 'x', {
'property1': stix2.properties.StringProperty(required=True),
@stix2.v20.CustomExtension(stix2.v20.File, 'x', {
'property1': stix2.v20.properties.StringProperty(required=True),
})
class FooExtension():
pass # pragma: no cover
assert "Invalid extension type name 'x':" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomExtension(stix2.File, 'x_new_ext', {
'property1': stix2.properties.StringProperty(required=True),
@stix2.v20.CustomExtension(stix2.File, 'x_new_ext', {
'property1': stix2.v20.properties.StringProperty(required=True),
})
class BlaExtension():
pass # pragma: no cover
@ -768,7 +767,7 @@ def test_custom_extension_invalid_type_name():
def test_custom_extension_no_properties():
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', None)
@stix2.v20.CustomExtension(stix2.v20.DomainName, 'x-new-ext2', None)
class BarExtension():
pass
assert "Must supply a list, containing tuples." in str(excinfo.value)
@ -776,7 +775,7 @@ def test_custom_extension_no_properties():
def test_custom_extension_empty_properties():
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', [])
@stix2.v20.CustomExtension(stix2.v20.DomainName, 'x-new-ext2', [])
class BarExtension():
pass
assert "Must supply a list, containing tuples." in str(excinfo.value)
@ -784,15 +783,15 @@ def test_custom_extension_empty_properties():
def test_custom_extension_dict_properties():
with pytest.raises(ValueError) as excinfo:
@stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', {})
@stix2.v20.CustomExtension(stix2.v20.DomainName, 'x-new-ext2', {})
class BarExtension():
pass
assert "Must supply a list, containing tuples." in str(excinfo.value)
def test_custom_extension_no_init_1():
@stix2.observables.CustomExtension(stix2.DomainName, 'x-new-extension', [
('property1', stix2.properties.StringProperty(required=True)),
@stix2.v20.CustomExtension(stix2.v20.DomainName, 'x-new-extension', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class NewExt():
pass
@ -802,8 +801,8 @@ def test_custom_extension_no_init_1():
def test_custom_extension_no_init_2():
@stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', [
('property1', stix2.properties.StringProperty(required=True)),
@stix2.v20.CustomExtension(stix2.v20.DomainName, 'x-new-ext2', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class NewExt2(object):
pass
@ -824,7 +823,7 @@ def test_parse_observable_with_custom_extension():
}
}"""
parsed = stix2.parse_observable(input_str)
parsed = stix2.parse_observable(input_str, version='2.0')
assert parsed.extensions['x-new-ext'].property2 == 12
@ -841,10 +840,10 @@ def test_parse_observable_with_unregistered_custom_extension():
}"""
with pytest.raises(ValueError) as excinfo:
stix2.parse_observable(input_str)
stix2.parse_observable(input_str, version='2.0')
assert "Can't parse unknown extension type" in str(excinfo.value)
parsed_ob = stix2.parse_observable(input_str, allow_custom=True)
parsed_ob = stix2.parse_observable(input_str, allow_custom=True, version='2.0')
assert parsed_ob['extensions']['x-foobar-ext']['property1'] == 'foo'
assert not isinstance(parsed_ob['extensions']['x-foobar-ext'], stix2.base._STIXBase)
@ -854,14 +853,14 @@ def test_register_custom_object():
class CustomObject2(object):
_type = 'awesome-object'
stix2._register_type(CustomObject2)
stix2._register_object(CustomObject2, version="2.0")
# Note that we will always check against newest OBJ_MAP.
assert (CustomObject2._type, CustomObject2) in stix2.OBJ_MAP.items()
assert (CustomObject2._type, CustomObject2) in stix2.v20.OBJ_MAP.items()
def test_extension_property_location():
assert 'extensions' in stix2.v21.observables.OBJ_MAP_OBSERVABLE['x-new-observable']._properties
assert 'extensions' not in stix2.v21.observables.EXT_MAP['domain-name']['x-new-ext']._properties
assert 'extensions' in stix2.v20.OBJ_MAP_OBSERVABLE['x-new-observable']._properties
assert 'extensions' not in stix2.v20.EXT_MAP['domain-name']['x-new-ext']._properties
@pytest.mark.parametrize("data", [
@ -879,8 +878,8 @@ def test_extension_property_location():
}""",
])
def test_custom_object_nested_dictionary(data):
@stix2.sdo.CustomObject('x-example', [
('dictionary', stix2.properties.DictionaryProperty()),
@stix2.v20.CustomObject('x-example', [
('dictionary', stix2.v20.properties.DictionaryProperty()),
])
class Example(object):
def __init__(self, **kwargs):

View File

@ -3,7 +3,7 @@ import pytest
from stix2.datastore import (CompositeDataSource, DataSink, DataSource,
DataStoreMixin)
from stix2.datastore.filters import Filter
from stix2.test.constants import CAMPAIGN_MORE_KWARGS
from stix2.test.v20.constants import CAMPAIGN_MORE_KWARGS
def test_datasource_abstract_class_raises_error():

View File

@ -4,13 +4,12 @@ import shutil
import pytest
from stix2 import (Bundle, Campaign, CustomObject, FileSystemSink,
FileSystemSource, FileSystemStore, Filter, Identity,
Indicator, Malware, Relationship, properties)
from stix2.test.constants import (CAMPAIGN_ID, CAMPAIGN_KWARGS, IDENTITY_ID,
IDENTITY_KWARGS, INDICATOR_ID,
INDICATOR_KWARGS, MALWARE_ID, MALWARE_KWARGS,
RELATIONSHIP_IDS)
import stix2
from stix2.test.v20.constants import (CAMPAIGN_ID, CAMPAIGN_KWARGS,
IDENTITY_ID, IDENTITY_KWARGS,
INDICATOR_ID, INDICATOR_KWARGS,
MALWARE_ID, MALWARE_KWARGS,
RELATIONSHIP_IDS)
FS_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stix2_data")
@ -18,7 +17,7 @@ FS_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stix2_data"
@pytest.fixture
def fs_store():
# create
yield FileSystemStore(FS_PATH)
yield stix2.FileSystemStore(FS_PATH)
# remove campaign dir
shutil.rmtree(os.path.join(FS_PATH, "campaign"), True)
@ -27,7 +26,7 @@ def fs_store():
@pytest.fixture
def fs_source():
# create
fs = FileSystemSource(FS_PATH)
fs = stix2.FileSystemSource(FS_PATH)
assert fs.stix_dir == FS_PATH
yield fs
@ -38,7 +37,7 @@ def fs_source():
@pytest.fixture
def fs_sink():
# create
fs = FileSystemSink(FS_PATH)
fs = stix2.FileSystemSink(FS_PATH)
assert fs.stix_dir == FS_PATH
yield fs
@ -83,15 +82,15 @@ def bad_stix_files():
@pytest.fixture(scope='module')
def rel_fs_store():
cam = Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS)
idy = Identity(id=IDENTITY_ID, **IDENTITY_KWARGS)
ind = Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS)
mal = Malware(id=MALWARE_ID, **MALWARE_KWARGS)
rel1 = Relationship(ind, 'indicates', mal, id=RELATIONSHIP_IDS[0])
rel2 = Relationship(mal, 'targets', idy, id=RELATIONSHIP_IDS[1])
rel3 = Relationship(cam, 'uses', mal, id=RELATIONSHIP_IDS[2])
cam = stix2.v20.Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS)
idy = stix2.v20.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS)
ind = stix2.v20.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS)
mal = stix2.v20.Malware(id=MALWARE_ID, **MALWARE_KWARGS)
rel1 = stix2.v20.Relationship(ind, 'indicates', mal, id=RELATIONSHIP_IDS[0])
rel2 = stix2.v20.Relationship(mal, 'targets', idy, id=RELATIONSHIP_IDS[1])
rel3 = stix2.v20.Relationship(cam, 'uses', mal, id=RELATIONSHIP_IDS[2])
stix_objs = [cam, idy, ind, mal, rel1, rel2, rel3]
fs = FileSystemStore(FS_PATH)
fs = stix2.FileSystemStore(FS_PATH)
for o in stix_objs:
fs.add(o)
yield fs
@ -102,13 +101,13 @@ def rel_fs_store():
def test_filesystem_source_nonexistent_folder():
with pytest.raises(ValueError) as excinfo:
FileSystemSource('nonexistent-folder')
stix2.FileSystemSource('nonexistent-folder')
assert "for STIX data does not exist" in str(excinfo)
def test_filesystem_sink_nonexistent_folder():
with pytest.raises(ValueError) as excinfo:
FileSystemSink('nonexistent-folder')
stix2.FileSystemSink('nonexistent-folder')
assert "for STIX data does not exist" in str(excinfo)
@ -154,7 +153,7 @@ def test_filesytem_source_all_versions(fs_source):
def test_filesytem_source_query_single(fs_source):
# query2
is_2 = fs_source.query([Filter("external_references.external_id", '=', "T1027")])
is_2 = fs_source.query([stix2.Filter("external_references.external_id", '=', "T1027")])
assert len(is_2) == 1
is_2 = is_2[0]
@ -164,7 +163,7 @@ def test_filesytem_source_query_single(fs_source):
def test_filesytem_source_query_multiple(fs_source):
# query
intrusion_sets = fs_source.query([Filter("type", '=', "intrusion-set")])
intrusion_sets = fs_source.query([stix2.Filter("type", '=', "intrusion-set")])
assert len(intrusion_sets) == 2
assert "intrusion-set--a653431d-6a5e-4600-8ad3-609b5af57064" in [is_.id for is_ in intrusion_sets]
assert "intrusion-set--f3bdec95-3d62-42d9-a840-29630f6cdc1a" in [is_.id for is_ in intrusion_sets]
@ -176,9 +175,10 @@ def test_filesytem_source_query_multiple(fs_source):
def test_filesystem_sink_add_python_stix_object(fs_sink, fs_source):
# add python stix object
camp1 = Campaign(name="Hannibal",
objective="Targeting Italian and Spanish Diplomat internet accounts",
aliases=["War Elephant"])
camp1 = stix2.v20.Campaign(
name="Hannibal",
objective="Targeting Italian and Spanish Diplomat internet accounts",
aliases=["War Elephant"])
fs_sink.add(camp1)
@ -278,9 +278,10 @@ def test_filesystem_sink_json_stix_bundle(fs_sink, fs_source):
def test_filesystem_sink_add_objects_list(fs_sink, fs_source):
# add list of objects
camp6 = Campaign(name="Comanche",
objective="US Midwest manufacturing firms, oil refineries, and businesses",
aliases=["Horse Warrior"])
camp6 = stix2.v20.Campaign(
name="Comanche",
objective="US Midwest manufacturing firms, oil refineries, and businesses",
aliases=["Horse Warrior"])
camp7 = {
"name": "Napolean",
@ -330,14 +331,14 @@ def test_filesystem_store_all_versions(fs_store):
def test_filesystem_store_query(fs_store):
# query()
tools = fs_store.query([Filter("labels", "in", "tool")])
tools = fs_store.query([stix2.Filter("labels", "in", "tool")])
assert len(tools) == 2
assert "tool--242f3da3-4425-4d11-8f5c-b842886da966" in [tool.id for tool in tools]
assert "tool--03342581-f790-4f03-ba41-e82e67392e23" in [tool.id for tool in tools]
def test_filesystem_store_query_single_filter(fs_store):
query = Filter("labels", "in", "tool")
query = stix2.Filter("labels", "in", "tool")
tools = fs_store.query(query)
assert len(tools) == 2
assert "tool--242f3da3-4425-4d11-8f5c-b842886da966" in [tool.id for tool in tools]
@ -352,22 +353,23 @@ def test_filesystem_store_empty_query(fs_store):
def test_filesystem_store_query_multiple_filters(fs_store):
fs_store.source.filters.add(Filter("labels", "in", "tool"))
tools = fs_store.query(Filter("id", "=", "tool--242f3da3-4425-4d11-8f5c-b842886da966"))
fs_store.source.filters.add(stix2.Filter("labels", "in", "tool"))
tools = fs_store.query(stix2.Filter("id", "=", "tool--242f3da3-4425-4d11-8f5c-b842886da966"))
assert len(tools) == 1
assert tools[0].id == "tool--242f3da3-4425-4d11-8f5c-b842886da966"
def test_filesystem_store_query_dont_include_type_folder(fs_store):
results = fs_store.query(Filter("type", "!=", "tool"))
results = fs_store.query(stix2.Filter("type", "!=", "tool"))
assert len(results) == 24
def test_filesystem_store_add(fs_store):
# add()
camp1 = Campaign(name="Great Heathen Army",
objective="Targeting the government of United Kingdom and insitutions affiliated with the Church Of England",
aliases=["Ragnar"])
camp1 = stix2.v20.Campaign(
name="Great Heathen Army",
objective="Targeting the government of United Kingdom and insitutions affiliated with the Church Of England",
aliases=["Ragnar"])
fs_store.add(camp1)
camp1_r = fs_store.get(camp1.id)
@ -379,11 +381,12 @@ def test_filesystem_store_add(fs_store):
def test_filesystem_store_add_as_bundle():
fs_store = FileSystemStore(FS_PATH, bundlify=True)
fs_store = stix2.FileSystemStore(FS_PATH, bundlify=True)
camp1 = Campaign(name="Great Heathen Army",
objective="Targeting the government of United Kingdom and insitutions affiliated with the Church Of England",
aliases=["Ragnar"])
camp1 = stix2.v20.Campaign(
name="Great Heathen Army",
objective="Targeting the government of United Kingdom and insitutions affiliated with the Church Of England",
aliases=["Ragnar"])
fs_store.add(camp1)
with open(os.path.join(FS_PATH, "campaign", camp1.id + ".json")) as bundle_file:
@ -397,7 +400,7 @@ def test_filesystem_store_add_as_bundle():
def test_filesystem_add_bundle_object(fs_store):
bundle = Bundle()
bundle = stix2.v20.Bundle()
fs_store.add(bundle)
@ -412,10 +415,11 @@ def test_filesystem_store_add_invalid_object(fs_store):
def test_filesystem_object_with_custom_property(fs_store):
camp = Campaign(name="Scipio Africanus",
objective="Defeat the Carthaginians",
x_empire="Roman",
allow_custom=True)
camp = stix2.v20.Campaign(
name="Scipio Africanus",
objective="Defeat the Carthaginians",
x_empire="Roman",
allow_custom=True)
fs_store.add(camp, True)
@ -425,12 +429,13 @@ def test_filesystem_object_with_custom_property(fs_store):
def test_filesystem_object_with_custom_property_in_bundle(fs_store):
camp = Campaign(name="Scipio Africanus",
objective="Defeat the Carthaginians",
x_empire="Roman",
allow_custom=True)
camp = stix2.v20.Campaign(
name="Scipio Africanus",
objective="Defeat the Carthaginians",
x_empire="Roman",
allow_custom=True)
bundle = Bundle(camp, allow_custom=True)
bundle = stix2.v20.Bundle(camp, allow_custom=True)
fs_store.add(bundle)
camp_r = fs_store.get(camp.id)
@ -439,8 +444,8 @@ def test_filesystem_object_with_custom_property_in_bundle(fs_store):
def test_filesystem_custom_object(fs_store):
@CustomObject('x-new-obj', [
('property1', properties.StringProperty(required=True)),
@stix2.v20.CustomObject('x-new-obj', [
('property1', stix2.v20.properties.StringProperty(required=True)),
])
class NewObj():
pass

View File

@ -9,7 +9,6 @@ stix_objs = [
"created": "2017-01-27T13:49:53.997Z",
"description": "\n\nTITLE:\n\tPoison Ivy",
"id": "malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111",
"spec_version": "2.1",
"labels": [
"remote-access-trojan"
],

View File

@ -5,8 +5,7 @@ import pytest
from requests.models import Response
from taxii2client import Collection, _filter_kwargs_to_query_params
from stix2 import (Bundle, TAXIICollectionSink, TAXIICollectionSource,
TAXIICollectionStore, ThreatActor)
import stix2
from stix2.datastore import DataSourceError
from stix2.datastore.filters import Filter
@ -39,7 +38,7 @@ class MockTAXIICollectionEndpoint(Collection):
[]
)
if objs:
return Bundle(objects=objs)
return stix2.v20.Bundle(objects=objs)
else:
resp = Response()
resp.status_code = 404
@ -59,7 +58,7 @@ class MockTAXIICollectionEndpoint(Collection):
[]
)
if objs:
return Bundle(objects=objs)
return stix2.v20.Bundle(objects=objs)
else:
resp = Response()
resp.status_code = 404
@ -101,78 +100,82 @@ def collection_no_rw_access(stix_objs1):
def test_ds_taxii(collection):
ds = TAXIICollectionSource(collection)
ds = stix2.TAXIICollectionSource(collection)
assert ds.collection is not None
def test_add_stix2_object(collection):
tc_sink = TAXIICollectionSink(collection)
tc_sink = stix2.TAXIICollectionSink(collection)
# create new STIX threat-actor
ta = ThreatActor(name="Teddy Bear",
labels=["nation-state"],
sophistication="innovator",
resource_level="government",
goals=[
"compromising environment NGOs",
"water-hole attacks geared towards energy sector",
])
ta = stix2.v20.ThreatActor(
name="Teddy Bear",
labels=["nation-state"],
sophistication="innovator",
resource_level="government",
goals=[
"compromising environment NGOs",
"water-hole attacks geared towards energy sector",
])
tc_sink.add(ta)
def test_add_stix2_with_custom_object(collection):
tc_sink = TAXIICollectionStore(collection, allow_custom=True)
tc_sink = stix2.TAXIICollectionStore(collection, allow_custom=True)
# create new STIX threat-actor
ta = ThreatActor(name="Teddy Bear",
labels=["nation-state"],
sophistication="innovator",
resource_level="government",
goals=[
"compromising environment NGOs",
"water-hole attacks geared towards energy sector",
],
foo="bar",
allow_custom=True)
ta = stix2.v20.ThreatActor(
name="Teddy Bear",
labels=["nation-state"],
sophistication="innovator",
resource_level="government",
goals=[
"compromising environment NGOs",
"water-hole attacks geared towards energy sector",
],
foo="bar",
allow_custom=True)
tc_sink.add(ta)
def test_add_list_object(collection, indicator):
tc_sink = TAXIICollectionSink(collection)
tc_sink = stix2.TAXIICollectionSink(collection)
# create new STIX threat-actor
ta = ThreatActor(name="Teddy Bear",
labels=["nation-state"],
sophistication="innovator",
resource_level="government",
goals=[
"compromising environment NGOs",
"water-hole attacks geared towards energy sector",
])
ta = stix2.v20.ThreatActor(
name="Teddy Bear",
labels=["nation-state"],
sophistication="innovator",
resource_level="government",
goals=[
"compromising environment NGOs",
"water-hole attacks geared towards energy sector",
])
tc_sink.add([ta, indicator])
def test_add_stix2_bundle_object(collection):
tc_sink = TAXIICollectionSink(collection)
tc_sink = stix2.TAXIICollectionSink(collection)
# create new STIX threat-actor
ta = ThreatActor(name="Teddy Bear",
labels=["nation-state"],
sophistication="innovator",
resource_level="government",
goals=[
"compromising environment NGOs",
"water-hole attacks geared towards energy sector",
])
ta = stix2.v20.ThreatActor(
name="Teddy Bear",
labels=["nation-state"],
sophistication="innovator",
resource_level="government",
goals=[
"compromising environment NGOs",
"water-hole attacks geared towards energy sector",
])
tc_sink.add(Bundle(objects=[ta]))
tc_sink.add(stix2.v20.Bundle(objects=[ta]))
def test_add_str_object(collection):
tc_sink = TAXIICollectionSink(collection)
tc_sink = stix2.TAXIICollectionSink(collection)
# create new STIX threat-actor
ta = """{
@ -196,7 +199,7 @@ def test_add_str_object(collection):
def test_add_dict_object(collection):
tc_sink = TAXIICollectionSink(collection)
tc_sink = stix2.TAXIICollectionSink(collection)
ta = {
"type": "threat-actor",
@ -219,7 +222,7 @@ def test_add_dict_object(collection):
def test_add_dict_bundle_object(collection):
tc_sink = TAXIICollectionSink(collection)
tc_sink = stix2.TAXIICollectionSink(collection)
ta = {
"type": "bundle",
@ -248,7 +251,7 @@ def test_add_dict_bundle_object(collection):
def test_get_stix2_object(collection):
tc_sink = TAXIICollectionSource(collection)
tc_sink = stix2.TAXIICollectionSource(collection)
objects = tc_sink.get("indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f")
@ -271,7 +274,7 @@ def test_parse_taxii_filters(collection):
Filter("version", "=", "first")
]
ds = TAXIICollectionSource(collection)
ds = stix2.TAXIICollectionSource(collection)
taxii_filters = ds._parse_taxii_filters(query)
@ -279,7 +282,7 @@ def test_parse_taxii_filters(collection):
def test_add_get_remove_filter(collection):
ds = TAXIICollectionSource(collection)
ds = stix2.TAXIICollectionSource(collection)
# First 3 filters are valid, remaining properties are erroneous in some way
valid_filters = [
@ -315,7 +318,7 @@ def test_add_get_remove_filter(collection):
def test_get_all_versions(collection):
ds = TAXIICollectionStore(collection)
ds = stix2.TAXIICollectionStore(collection)
indicators = ds.all_versions('indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f')
# There are 3 indicators but 2 share the same 'modified' timestamp
@ -327,7 +330,7 @@ def test_can_read_error(collection_no_rw_access):
instance that does not have read access, check ValueError exception is raised"""
with pytest.raises(DataSourceError) as excinfo:
TAXIICollectionSource(collection_no_rw_access)
stix2.TAXIICollectionSource(collection_no_rw_access)
assert "Collection object provided does not have read access" in str(excinfo.value)
@ -336,7 +339,7 @@ def test_can_write_error(collection_no_rw_access):
instance that does not have write access, check ValueError exception is raised"""
with pytest.raises(DataSourceError) as excinfo:
TAXIICollectionSink(collection_no_rw_access)
stix2.TAXIICollectionSink(collection_no_rw_access)
assert "Collection object provided does not have write access" in str(excinfo.value)
@ -357,7 +360,7 @@ def test_get_404():
resp.status_code = 404
resp.raise_for_status()
ds = TAXIICollectionSource(TAXIICollection404())
ds = stix2.TAXIICollectionSource(TAXIICollection404())
# this will raise 404 from mock TAXII Client but TAXIICollectionStore
# should handle gracefully and return None
@ -369,7 +372,7 @@ def test_all_versions_404(collection):
""" a TAXIICollectionSource.all_version() call that recieves an HTTP 404
response code from the taxii2client should be returned as an exception"""
ds = TAXIICollectionStore(collection)
ds = stix2.TAXIICollectionStore(collection)
with pytest.raises(DataSourceError) as excinfo:
ds.all_versions("indicator--1")
@ -381,7 +384,7 @@ def test_query_404(collection):
""" a TAXIICollectionSource.query() call that recieves an HTTP 404
response code from the taxii2client should be returned as an exception"""
ds = TAXIICollectionStore(collection)
ds = stix2.TAXIICollectionStore(collection)
query = [Filter("type", "=", "malware")]
with pytest.raises(DataSourceError) as excinfo:

View File

@ -9,92 +9,99 @@ from .constants import (CAMPAIGN_ID, CAMPAIGN_KWARGS, FAKE_TIME, IDENTITY_ID,
@pytest.fixture
def ds():
cam = stix2.Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS)
idy = stix2.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS)
ind = stix2.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS)
mal = stix2.Malware(id=MALWARE_ID, **MALWARE_KWARGS)
rel1 = stix2.Relationship(ind, 'indicates', mal, id=RELATIONSHIP_IDS[0])
rel2 = stix2.Relationship(mal, 'targets', idy, id=RELATIONSHIP_IDS[1])
rel3 = stix2.Relationship(cam, 'uses', mal, id=RELATIONSHIP_IDS[2])
cam = stix2.v20.Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS)
idy = stix2.v20.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS)
ind = stix2.v20.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS)
mal = stix2.v20.Malware(id=MALWARE_ID, **MALWARE_KWARGS)
rel1 = stix2.v20.Relationship(ind, 'indicates', mal, id=RELATIONSHIP_IDS[0])
rel2 = stix2.v20.Relationship(mal, 'targets', idy, id=RELATIONSHIP_IDS[1])
rel3 = stix2.v20.Relationship(cam, 'uses', mal, id=RELATIONSHIP_IDS[2])
stix_objs = [cam, idy, ind, mal, rel1, rel2, rel3]
yield stix2.MemoryStore(stix_objs)
def test_object_factory_created_by_ref_str():
factory = stix2.ObjectFactory(created_by_ref=IDENTITY_ID)
ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS)
ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS)
assert ind.created_by_ref == IDENTITY_ID
def test_object_factory_created_by_ref_obj():
id_obj = stix2.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS)
id_obj = stix2.v20.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS)
factory = stix2.ObjectFactory(created_by_ref=id_obj)
ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS)
ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS)
assert ind.created_by_ref == IDENTITY_ID
def test_object_factory_override_default():
factory = stix2.ObjectFactory(created_by_ref=IDENTITY_ID)
new_id = "identity--983b3172-44fe-4a80-8091-eb8098841fe8"
ind = factory.create(stix2.Indicator, created_by_ref=new_id, **INDICATOR_KWARGS)
ind = factory.create(stix2.v20.Indicator, created_by_ref=new_id, **INDICATOR_KWARGS)
assert ind.created_by_ref == new_id
def test_object_factory_created():
factory = stix2.ObjectFactory(created=FAKE_TIME)
ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS)
ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS)
assert ind.created == FAKE_TIME
assert ind.modified == FAKE_TIME
def test_object_factory_external_reference():
ext_ref = stix2.ExternalReference(source_name="ACME Threat Intel",
description="Threat report")
ext_ref = stix2.v20.ExternalReference(
source_name="ACME Threat Intel",
description="Threat report")
factory = stix2.ObjectFactory(external_references=ext_ref)
ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS)
ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS)
assert ind.external_references[0].source_name == "ACME Threat Intel"
assert ind.external_references[0].description == "Threat report"
ind2 = factory.create(stix2.Indicator, external_references=None, **INDICATOR_KWARGS)
ind2 = factory.create(stix2.v20.Indicator, external_references=None, **INDICATOR_KWARGS)
assert 'external_references' not in ind2
def test_object_factory_obj_markings():
stmt_marking = stix2.StatementMarking("Copyright 2016, Example Corp")
mark_def = stix2.MarkingDefinition(definition_type="statement",
definition=stmt_marking)
factory = stix2.ObjectFactory(object_marking_refs=[mark_def, stix2.TLP_AMBER])
ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS)
stmt_marking = stix2.v20.StatementMarking("Copyright 2016, Example Corp")
mark_def = stix2.v20.MarkingDefinition(
definition_type="statement",
definition=stmt_marking)
factory = stix2.ObjectFactory(object_marking_refs=[mark_def, stix2.v20.TLP_AMBER])
ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS)
assert mark_def.id in ind.object_marking_refs
assert stix2.TLP_AMBER.id in ind.object_marking_refs
assert stix2.v20.TLP_AMBER.id in ind.object_marking_refs
factory = stix2.ObjectFactory(object_marking_refs=stix2.TLP_RED)
ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS)
assert stix2.TLP_RED.id in ind.object_marking_refs
factory = stix2.ObjectFactory(object_marking_refs=stix2.v20.TLP_RED)
ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS)
assert stix2.v20.TLP_RED.id in ind.object_marking_refs
def test_object_factory_list_append():
ext_ref = stix2.ExternalReference(source_name="ACME Threat Intel",
description="Threat report from ACME")
ext_ref2 = stix2.ExternalReference(source_name="Yet Another Threat Report",
description="Threat report from YATR")
ext_ref3 = stix2.ExternalReference(source_name="Threat Report #3",
description="One more threat report")
ext_ref = stix2.v20.ExternalReference(
source_name="ACME Threat Intel",
description="Threat report from ACME")
ext_ref2 = stix2.v20.ExternalReference(
source_name="Yet Another Threat Report",
description="Threat report from YATR")
ext_ref3 = stix2.v20.ExternalReference(
source_name="Threat Report #3",
description="One more threat report")
factory = stix2.ObjectFactory(external_references=ext_ref)
ind = factory.create(stix2.Indicator, external_references=ext_ref2, **INDICATOR_KWARGS)
ind = factory.create(stix2.v20.Indicator, external_references=ext_ref2, **INDICATOR_KWARGS)
assert ind.external_references[1].source_name == "Yet Another Threat Report"
ind = factory.create(stix2.Indicator, external_references=[ext_ref2, ext_ref3], **INDICATOR_KWARGS)
ind = factory.create(stix2.v20.Indicator, external_references=[ext_ref2, ext_ref3], **INDICATOR_KWARGS)
assert ind.external_references[2].source_name == "Threat Report #3"
def test_object_factory_list_replace():
ext_ref = stix2.ExternalReference(source_name="ACME Threat Intel",
description="Threat report from ACME")
ext_ref2 = stix2.ExternalReference(source_name="Yet Another Threat Report",
description="Threat report from YATR")
ext_ref = stix2.v20.ExternalReference(
source_name="ACME Threat Intel",
description="Threat report from ACME")
ext_ref2 = stix2.v20.ExternalReference(
source_name="Yet Another Threat Report",
description="Threat report from YATR")
factory = stix2.ObjectFactory(external_references=ext_ref, list_append=False)
ind = factory.create(stix2.Indicator, external_references=ext_ref2, **INDICATOR_KWARGS)
ind = factory.create(stix2.v20.Indicator, external_references=ext_ref2, **INDICATOR_KWARGS)
assert len(ind.external_references) == 1
assert ind.external_references[0].source_name == "Yet Another Threat Report"
@ -104,7 +111,7 @@ def test_environment_functions():
stix2.MemoryStore())
# Create a STIX object
ind = env.create(stix2.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS)
ind = env.create(stix2.v20.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS)
assert ind.created_by_ref == IDENTITY_ID
# Add objects to datastore
@ -133,7 +140,7 @@ def test_environment_functions():
def test_environment_source_and_sink():
ind = stix2.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS)
ind = stix2.v20.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS)
env = stix2.Environment(source=stix2.MemorySource([ind]), sink=stix2.MemorySink([ind]))
assert env.get(INDICATOR_ID).labels[0] == 'malicious-activity'
@ -149,7 +156,7 @@ def test_environment_no_datastore():
env = stix2.Environment(factory=stix2.ObjectFactory())
with pytest.raises(AttributeError) as excinfo:
env.add(stix2.Indicator(**INDICATOR_KWARGS))
env.add(stix2.v20.Indicator(**INDICATOR_KWARGS))
assert 'Environment has no data sink to put objects in' in str(excinfo.value)
with pytest.raises(AttributeError) as excinfo:
@ -182,7 +189,7 @@ def test_environment_add_filters():
def test_environment_datastore_and_no_object_factory():
# Uses a default object factory
env = stix2.Environment(store=stix2.MemoryStore())
ind = env.create(stix2.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS)
ind = env.create(stix2.v20.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS)
assert ind.id == INDICATOR_ID
@ -190,17 +197,15 @@ def test_parse_malware():
env = stix2.Environment()
data = """{
"type": "malware",
"spec_version": "2.1",
"id": "malware--fedcba98-7654-3210-fedc-ba9876543210",
"created": "2017-01-01T12:34:56.000Z",
"modified": "2017-01-01T12:34:56.000Z",
"name": "Cryptolocker",
"labels": [
"ransomware"
],
"is_family": false
]
}"""
mal = env.parse(data)
mal = env.parse(data, version="2.0")
assert mal.type == 'malware'
assert mal.id == MALWARE_ID
@ -211,40 +216,40 @@ def test_parse_malware():
def test_creator_of():
identity = stix2.Identity(**IDENTITY_KWARGS)
identity = stix2.v20.Identity(**IDENTITY_KWARGS)
factory = stix2.ObjectFactory(created_by_ref=identity.id)
env = stix2.Environment(store=stix2.MemoryStore(), factory=factory)
env.add(identity)
ind = env.create(stix2.Indicator, **INDICATOR_KWARGS)
ind = env.create(stix2.v20.Indicator, **INDICATOR_KWARGS)
creator = env.creator_of(ind)
assert creator is identity
def test_creator_of_no_datasource():
identity = stix2.Identity(**IDENTITY_KWARGS)
identity = stix2.v20.Identity(**IDENTITY_KWARGS)
factory = stix2.ObjectFactory(created_by_ref=identity.id)
env = stix2.Environment(factory=factory)
ind = env.create(stix2.Indicator, **INDICATOR_KWARGS)
ind = env.create(stix2.v20.Indicator, **INDICATOR_KWARGS)
with pytest.raises(AttributeError) as excinfo:
env.creator_of(ind)
assert 'Environment has no data source' in str(excinfo.value)
def test_creator_of_not_found():
identity = stix2.Identity(**IDENTITY_KWARGS)
identity = stix2.v20.Identity(**IDENTITY_KWARGS)
factory = stix2.ObjectFactory(created_by_ref=identity.id)
env = stix2.Environment(store=stix2.MemoryStore(), factory=factory)
ind = env.create(stix2.Indicator, **INDICATOR_KWARGS)
ind = env.create(stix2.v20.Indicator, **INDICATOR_KWARGS)
creator = env.creator_of(ind)
assert creator is None
def test_creator_of_no_created_by_ref():
env = stix2.Environment(store=stix2.MemoryStore())
ind = env.create(stix2.Indicator, **INDICATOR_KWARGS)
ind = env.create(stix2.v20.Indicator, **INDICATOR_KWARGS)
creator = env.creator_of(ind)
assert creator is None

View File

@ -17,7 +17,7 @@ VERIS = """{
def test_external_reference_veris():
ref = stix2.ExternalReference(
ref = stix2.v20.ExternalReference(
source_name="veris",
external_id="0001AA7F-C601-424A-B2B8-BE6C9F5164E7",
hashes={
@ -36,7 +36,7 @@ CAPEC = """{
def test_external_reference_capec():
ref = stix2.ExternalReference(
ref = stix2.v20.ExternalReference(
source_name="capec",
external_id="CAPEC-550",
)
@ -53,7 +53,7 @@ CAPEC_URL = """{
def test_external_reference_capec_url():
ref = stix2.ExternalReference(
ref = stix2.v20.ExternalReference(
source_name="capec",
external_id="CAPEC-550",
url="http://capec.mitre.org/data/definitions/550.html",
@ -70,7 +70,7 @@ THREAT_REPORT = """{
def test_external_reference_threat_report():
ref = stix2.ExternalReference(
ref = stix2.v20.ExternalReference(
source_name="ACME Threat Intel",
description="Threat report",
url="http://www.example.com/threat-report.pdf",
@ -87,7 +87,7 @@ BUGZILLA = """{
def test_external_reference_bugzilla():
ref = stix2.ExternalReference(
ref = stix2.v20.ExternalReference(
source_name="ACME Bugzilla",
external_id="1370",
url="https://www.example.com/bugs/1370",
@ -103,7 +103,7 @@ OFFLINE = """{
def test_external_reference_offline():
ref = stix2.ExternalReference(
ref = stix2.v20.ExternalReference(
source_name="ACME Threat Intel",
description="Threat report",
)
@ -116,7 +116,7 @@ def test_external_reference_offline():
def test_external_reference_source_required():
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
stix2.ExternalReference()
stix2.v20.ExternalReference()
assert excinfo.value.cls == stix2.ExternalReference
assert excinfo.value.cls == stix2.v20.ExternalReference
assert excinfo.value.properties == ["source_name"]

View File

@ -1,7 +1,8 @@
import pytest
from stix2 import TLP_RED, Malware, markings
from stix2 import markings
from stix2.v20 import Malware, TLP_RED
from stix2.exceptions import MarkingNotFoundError
from .constants import MALWARE_MORE_KWARGS as MALWARE_KWARGS_CONST

View File

@ -18,7 +18,7 @@ EXPECTED = """{
def test_identity_example():
identity = stix2.Identity(
identity = stix2.v20.Identity(
id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c",
created="2015-12-21T19:59:11.000Z",
modified="2015-12-21T19:59:11.000Z",
@ -41,7 +41,7 @@ def test_identity_example():
},
])
def test_parse_identity(data):
identity = stix2.parse(data)
identity = stix2.parse(data, version="2.0")
assert identity.type == 'identity'
assert identity.id == IDENTITY_ID
@ -59,11 +59,11 @@ def test_parse_no_type():
"modified": "2015-12-21T19:59:11.000Z",
"name": "John Smith",
"identity_class": "individual"
}""")
}""", version="2.0")
def test_identity_with_custom():
identity = stix2.Identity(
identity = stix2.v20.Identity(
name="John Smith",
identity_class="individual",
custom_properties={'x_foo': 'bar'}

View File

@ -35,7 +35,7 @@ def test_indicator_with_all_required_properties():
now = dt.datetime(2017, 1, 1, 0, 0, 1, tzinfo=pytz.utc)
epoch = dt.datetime(1970, 1, 1, 0, 0, 1, tzinfo=pytz.utc)
ind = stix2.Indicator(
ind = stix2.v20.Indicator(
type="indicator",
id=INDICATOR_ID,
created=now,
@ -71,9 +71,9 @@ def test_indicator_autogenerated_properties(indicator):
def test_indicator_type_must_be_indicator():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Indicator(type='xxx', **INDICATOR_KWARGS)
stix2.v20.Indicator(type='xxx', **INDICATOR_KWARGS)
assert excinfo.value.cls == stix2.Indicator
assert excinfo.value.cls == stix2.v20.Indicator
assert excinfo.value.prop_name == "type"
assert excinfo.value.reason == "must equal 'indicator'."
assert str(excinfo.value) == "Invalid value for Indicator 'type': must equal 'indicator'."
@ -81,9 +81,9 @@ def test_indicator_type_must_be_indicator():
def test_indicator_id_must_start_with_indicator():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Indicator(id='my-prefix--', **INDICATOR_KWARGS)
stix2.v20.Indicator(id='my-prefix--', **INDICATOR_KWARGS)
assert excinfo.value.cls == stix2.Indicator
assert excinfo.value.cls == stix2.v20.Indicator
assert excinfo.value.prop_name == "id"
assert excinfo.value.reason == "must start with 'indicator--'."
assert str(excinfo.value) == "Invalid value for Indicator 'id': must start with 'indicator--'."
@ -91,26 +91,26 @@ def test_indicator_id_must_start_with_indicator():
def test_indicator_required_properties():
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
stix2.Indicator()
stix2.v20.Indicator()
assert excinfo.value.cls == stix2.Indicator
assert excinfo.value.cls == stix2.v20.Indicator
assert excinfo.value.properties == ["labels", "pattern"]
assert str(excinfo.value) == "No values for required properties for Indicator: (labels, pattern)."
def test_indicator_required_property_pattern():
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
stix2.Indicator(labels=['malicious-activity'])
stix2.v20.Indicator(labels=['malicious-activity'])
assert excinfo.value.cls == stix2.Indicator
assert excinfo.value.cls == stix2.v20.Indicator
assert excinfo.value.properties == ["pattern"]
def test_indicator_created_ref_invalid_format():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Indicator(created_by_ref='myprefix--12345678', **INDICATOR_KWARGS)
stix2.v20.Indicator(created_by_ref='myprefix--12345678', **INDICATOR_KWARGS)
assert excinfo.value.cls == stix2.Indicator
assert excinfo.value.cls == stix2.v20.Indicator
assert excinfo.value.prop_name == "created_by_ref"
assert excinfo.value.reason == "must start with 'identity'."
assert str(excinfo.value) == "Invalid value for Indicator 'created_by_ref': must start with 'identity'."
@ -118,9 +118,9 @@ def test_indicator_created_ref_invalid_format():
def test_indicator_revoked_invalid():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Indicator(revoked='no', **INDICATOR_KWARGS)
stix2.v20.Indicator(revoked='no', **INDICATOR_KWARGS)
assert excinfo.value.cls == stix2.Indicator
assert excinfo.value.cls == stix2.v20.Indicator
assert excinfo.value.prop_name == "revoked"
assert excinfo.value.reason == "must be a boolean value."
@ -134,16 +134,16 @@ def test_cannot_assign_to_indicator_attributes(indicator):
def test_invalid_kwarg_to_indicator():
with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo:
stix2.Indicator(my_custom_property="foo", **INDICATOR_KWARGS)
stix2.v20.Indicator(my_custom_property="foo", **INDICATOR_KWARGS)
assert excinfo.value.cls == stix2.Indicator
assert excinfo.value.cls == stix2.v20.Indicator
assert excinfo.value.properties == ['my_custom_property']
assert str(excinfo.value) == "Unexpected properties for Indicator: (my_custom_property)."
def test_created_modified_time_are_identical_by_default():
"""By default, the created and modified times should be the same."""
ind = stix2.Indicator(**INDICATOR_KWARGS)
ind = stix2.v20.Indicator(**INDICATOR_KWARGS)
assert ind.created == ind.modified
@ -163,7 +163,7 @@ def test_created_modified_time_are_identical_by_default():
},
])
def test_parse_indicator(data):
idctr = stix2.parse(data)
idctr = stix2.parse(data, version="2.0")
assert idctr.type == 'indicator'
assert idctr.id == INDICATOR_ID
@ -176,19 +176,19 @@ def test_parse_indicator(data):
def test_invalid_indicator_pattern():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Indicator(
stix2.v20.Indicator(
labels=['malicious-activity'],
pattern="file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e'",
)
assert excinfo.value.cls == stix2.Indicator
assert excinfo.value.cls == stix2.v20.Indicator
assert excinfo.value.prop_name == 'pattern'
assert 'input is missing square brackets' in excinfo.value.reason
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Indicator(
stix2.v20.Indicator(
labels=['malicious-activity'],
pattern='[file:hashes.MD5 = "d41d8cd98f00b204e9800998ecf8427e"]',
)
assert excinfo.value.cls == stix2.Indicator
assert excinfo.value.cls == stix2.v20.Indicator
assert excinfo.value.prop_name == 'pattern'
assert 'mismatched input' in excinfo.value.reason

View File

@ -27,7 +27,7 @@ EXPECTED = """{
def test_intrusion_set_example():
intrusion_set = stix2.IntrusionSet(
intrusion_set = stix2.v20.IntrusionSet(
id="intrusion-set--4e78f46f-a023-4e5f-bc24-71b3ca22ec29",
created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff",
created="2016-04-06T20:03:48.000Z",
@ -62,7 +62,7 @@ def test_intrusion_set_example():
},
])
def test_parse_intrusion_set(data):
intset = stix2.parse(data)
intset = stix2.parse(data, version="2.0")
assert intset.type == "intrusion-set"
assert intset.id == INTRUSION_SET_ID

View File

@ -11,7 +11,7 @@ LMCO_RECON = """{
def test_lockheed_martin_cyber_kill_chain():
recon = stix2.KillChainPhase(
recon = stix2.v20.KillChainPhase(
kill_chain_name="lockheed-martin-cyber-kill-chain",
phase_name="reconnaissance",
)
@ -26,7 +26,7 @@ FOO_PRE_ATTACK = """{
def test_kill_chain_example():
preattack = stix2.KillChainPhase(
preattack = stix2.v20.KillChainPhase(
kill_chain_name="foo",
phase_name="pre-attack",
)
@ -37,25 +37,25 @@ def test_kill_chain_example():
def test_kill_chain_required_properties():
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
stix2.KillChainPhase()
stix2.v20.KillChainPhase()
assert excinfo.value.cls == stix2.KillChainPhase
assert excinfo.value.cls == stix2.v20.KillChainPhase
assert excinfo.value.properties == ["kill_chain_name", "phase_name"]
def test_kill_chain_required_property_chain_name():
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
stix2.KillChainPhase(phase_name="weaponization")
stix2.v20.KillChainPhase(phase_name="weaponization")
assert excinfo.value.cls == stix2.KillChainPhase
assert excinfo.value.cls == stix2.v20.KillChainPhase
assert excinfo.value.properties == ["kill_chain_name"]
def test_kill_chain_required_property_phase_name():
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
stix2.KillChainPhase(kill_chain_name="lockheed-martin-cyber-kill-chain")
stix2.v20.KillChainPhase(kill_chain_name="lockheed-martin-cyber-kill-chain")
assert excinfo.value.cls == stix2.KillChainPhase
assert excinfo.value.cls == stix2.v20.KillChainPhase
assert excinfo.value.properties == ["phase_name"]

View File

@ -10,29 +10,26 @@ from .constants import FAKE_TIME, MALWARE_ID, MALWARE_KWARGS
EXPECTED_MALWARE = """{
"type": "malware",
"spec_version": "2.1",
"id": "malware--fedcba98-7654-3210-fedc-ba9876543210",
"created": "2016-05-12T08:17:27.000Z",
"modified": "2016-05-12T08:17:27.000Z",
"name": "Cryptolocker",
"labels": [
"ransomware"
],
"is_family": false
]
}"""
def test_malware_with_all_required_properties():
now = dt.datetime(2016, 5, 12, 8, 17, 27, tzinfo=pytz.utc)
mal = stix2.Malware(
mal = stix2.v20.Malware(
type="malware",
id=MALWARE_ID,
created=now,
modified=now,
labels=["ransomware"],
name="Cryptolocker",
is_family=False
name="Cryptolocker"
)
assert str(mal) == EXPECTED_MALWARE
@ -56,9 +53,9 @@ def test_malware_autogenerated_properties(malware):
def test_malware_type_must_be_malware():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Malware(type='xxx', **MALWARE_KWARGS)
stix2.v20.Malware(type='xxx', **MALWARE_KWARGS)
assert excinfo.value.cls == stix2.Malware
assert excinfo.value.cls == stix2.v20.Malware
assert excinfo.value.prop_name == "type"
assert excinfo.value.reason == "must equal 'malware'."
assert str(excinfo.value) == "Invalid value for Malware 'type': must equal 'malware'."
@ -66,9 +63,9 @@ def test_malware_type_must_be_malware():
def test_malware_id_must_start_with_malware():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Malware(id='my-prefix--', **MALWARE_KWARGS)
stix2.v20.Malware(id='my-prefix--', **MALWARE_KWARGS)
assert excinfo.value.cls == stix2.Malware
assert excinfo.value.cls == stix2.v20.Malware
assert excinfo.value.prop_name == "id"
assert excinfo.value.reason == "must start with 'malware--'."
assert str(excinfo.value) == "Invalid value for Malware 'id': must start with 'malware--'."
@ -76,17 +73,17 @@ def test_malware_id_must_start_with_malware():
def test_malware_required_properties():
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
stix2.Malware()
stix2.v20.Malware()
assert excinfo.value.cls == stix2.Malware
assert excinfo.value.properties == ["is_family", "labels", "name"]
assert excinfo.value.cls == stix2.v20.Malware
assert excinfo.value.properties == ["labels", "name"]
def test_malware_required_property_name():
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
stix2.Malware(labels=['ransomware'], is_family=False)
stix2.v20.Malware(labels=['ransomware'])
assert excinfo.value.cls == stix2.Malware
assert excinfo.value.cls == stix2.v20.Malware
assert excinfo.value.properties == ["name"]
@ -99,9 +96,9 @@ def test_cannot_assign_to_malware_attributes(malware):
def test_invalid_kwarg_to_malware():
with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo:
stix2.Malware(my_custom_property="foo", **MALWARE_KWARGS)
stix2.v20.Malware(my_custom_property="foo", **MALWARE_KWARGS)
assert excinfo.value.cls == stix2.Malware
assert excinfo.value.cls == stix2.v20.Malware
assert excinfo.value.properties == ['my_custom_property']
assert str(excinfo.value) == "Unexpected properties for Malware: (my_custom_property)."
@ -110,17 +107,15 @@ def test_invalid_kwarg_to_malware():
EXPECTED_MALWARE,
{
"type": "malware",
"spec_version": "2.1",
"id": "malware--fedcba98-7654-3210-fedc-ba9876543210",
"created": "2016-05-12T08:17:27.000Z",
"modified": "2016-05-12T08:17:27.000Z",
"labels": ["ransomware"],
"name": "Cryptolocker",
"is_family": False
"name": "Cryptolocker"
},
])
def test_parse_malware(data):
mal = stix2.parse(data)
mal = stix2.parse(data, version="2.0")
assert mal.type == 'malware'
assert mal.id == MALWARE_ID
@ -133,7 +128,7 @@ def test_parse_malware(data):
def test_parse_malware_invalid_labels():
data = re.compile('\\[.+\\]', re.DOTALL).sub('1', EXPECTED_MALWARE)
with pytest.raises(ValueError) as excinfo:
stix2.parse(data)
stix2.parse(data, version="2.0")
assert "Invalid value for Malware 'labels'" in str(excinfo.value)
@ -146,7 +141,7 @@ def test_parse_malware_kill_chain_phases():
}
]"""
data = EXPECTED_MALWARE.replace('malware"', 'malware",%s' % kill_chain)
mal = stix2.parse(data)
mal = stix2.parse(data, version="2.0")
assert mal.kill_chain_phases[0].kill_chain_name == "lockheed-martin-cyber-kill-chain"
assert mal.kill_chain_phases[0].phase_name == "reconnaissance"
assert mal['kill_chain_phases'][0]['kill_chain_name'] == "lockheed-martin-cyber-kill-chain"
@ -161,6 +156,6 @@ def test_parse_malware_clean_kill_chain_phases():
"phase_name": 1
}
]"""
data = EXPECTED_MALWARE.replace('2.1"', '2.1",%s' % kill_chain)
mal = stix2.parse(data)
data = EXPECTED_MALWARE.replace('malware"', 'malware",%s' % kill_chain)
mal = stix2.parse(data, version="2.0")
assert mal['kill_chain_phases'][0]['phase_name'] == "1"

View File

@ -4,7 +4,7 @@ import pytest
import pytz
import stix2
from stix2 import TLP_WHITE
from stix2.v20 import TLP_WHITE
from .constants import MARKING_DEFINITION_ID
@ -75,11 +75,11 @@ def test_marking_def_example_with_tlp():
def test_marking_def_example_with_statement_positional_argument():
marking_definition = stix2.MarkingDefinition(
marking_definition = stix2.v20.MarkingDefinition(
id="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9",
created="2017-01-20T00:00:00.000Z",
definition_type="statement",
definition=stix2.StatementMarking(statement="Copyright 2016, Example Corp")
definition=stix2.v20.StatementMarking(statement="Copyright 2016, Example Corp")
)
assert str(marking_definition) == EXPECTED_STATEMENT_MARKING_DEFINITION
@ -87,11 +87,11 @@ def test_marking_def_example_with_statement_positional_argument():
def test_marking_def_example_with_kwargs_statement():
kwargs = dict(statement="Copyright 2016, Example Corp")
marking_definition = stix2.MarkingDefinition(
marking_definition = stix2.v20.MarkingDefinition(
id="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9",
created="2017-01-20T00:00:00.000Z",
definition_type="statement",
definition=stix2.StatementMarking(**kwargs)
definition=stix2.v20.StatementMarking(**kwargs)
)
assert str(marking_definition) == EXPECTED_STATEMENT_MARKING_DEFINITION
@ -99,16 +99,16 @@ def test_marking_def_example_with_kwargs_statement():
def test_marking_def_invalid_type():
with pytest.raises(ValueError):
stix2.MarkingDefinition(
stix2.v20.MarkingDefinition(
id="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9",
created="2017-01-20T00:00:00.000Z",
definition_type="my-definition-type",
definition=stix2.StatementMarking("Copyright 2016, Example Corp")
definition=stix2.v20.StatementMarking("Copyright 2016, Example Corp")
)
def test_campaign_with_markings_example():
campaign = stix2.Campaign(
campaign = stix2.v20.Campaign(
id="campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f",
created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff",
created="2016-04-06T20:03:00Z",
@ -121,7 +121,7 @@ def test_campaign_with_markings_example():
def test_granular_example():
granular_marking = stix2.GranularMarking(
granular_marking = stix2.v20.GranularMarking(
marking_ref="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9",
selectors=["abc", "abc.[23]", "abc.def", "abc.[2].efg"]
)
@ -131,19 +131,19 @@ def test_granular_example():
def test_granular_example_with_bad_selector():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.GranularMarking(
stix2.v20.GranularMarking(
marking_ref="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9",
selectors=["abc[0]"] # missing "."
)
assert excinfo.value.cls == stix2.GranularMarking
assert excinfo.value.cls == stix2.v20.GranularMarking
assert excinfo.value.prop_name == "selectors"
assert excinfo.value.reason == "must adhere to selector syntax."
assert str(excinfo.value) == "Invalid value for GranularMarking 'selectors': must adhere to selector syntax."
def test_campaign_with_granular_markings_example():
campaign = stix2.Campaign(
campaign = stix2.v20.Campaign(
id="campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f",
created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff",
created="2016-04-06T20:03:00Z",
@ -151,7 +151,7 @@ def test_campaign_with_granular_markings_example():
name="Green Group Attacks Against Finance",
description="Campaign by Green Group against a series of targets in the financial services sector.",
granular_markings=[
stix2.GranularMarking(
stix2.v20.GranularMarking(
marking_ref="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9",
selectors=["description"])
])
@ -171,7 +171,7 @@ def test_campaign_with_granular_markings_example():
},
])
def test_parse_marking_definition(data):
gm = stix2.parse(data)
gm = stix2.parse(data, version="2.0")
assert gm.type == 'marking-definition'
assert gm.id == MARKING_DEFINITION_ID
@ -180,9 +180,9 @@ def test_parse_marking_definition(data):
assert gm.definition_type == "tlp"
@stix2.common.CustomMarking('x-new-marking-type', [
('property1', stix2.properties.StringProperty(required=True)),
('property2', stix2.properties.IntegerProperty()),
@stix2.v20.CustomMarking('x-new-marking-type', [
('property1', stix2.v20.properties.StringProperty(required=True)),
('property2', stix2.v20.properties.IntegerProperty()),
])
class NewMarking(object):
def __init__(self, property2=None, **kwargs):
@ -193,7 +193,7 @@ class NewMarking(object):
def test_registered_custom_marking():
nm = NewMarking(property1='something', property2=55)
marking_def = stix2.MarkingDefinition(
marking_def = stix2.v20.MarkingDefinition(
id="marking-definition--00000000-0000-0000-0000-000000000012",
created="2017-01-22T00:00:00.000Z",
definition_type="x-new-marking-type",
@ -218,9 +218,9 @@ def test_registered_custom_marking_raises_exception():
def test_not_registered_marking_raises_exception():
with pytest.raises(ValueError) as excinfo:
# Used custom object on purpose to demonstrate a not-registered marking
@stix2.sdo.CustomObject('x-new-marking-type2', [
('property1', stix2.properties.StringProperty(required=True)),
('property2', stix2.properties.IntegerProperty()),
@stix2.v20.CustomObject('x-new-marking-type2', [
('property1', stix2.v20.properties.StringProperty(required=True)),
('property2', stix2.v20.properties.IntegerProperty()),
])
class NewObject2(object):
def __init__(self, property2=None, **kwargs):
@ -228,7 +228,7 @@ def test_not_registered_marking_raises_exception():
no = NewObject2(property1='something', property2=55)
stix2.MarkingDefinition(
stix2.v20.MarkingDefinition(
id="marking-definition--00000000-0000-0000-0000-000000000012",
created="2017-01-22T00:00:00.000Z",
definition_type="x-new-marking-type2",
@ -241,7 +241,7 @@ def test_not_registered_marking_raises_exception():
def test_marking_wrong_type_construction():
with pytest.raises(ValueError) as excinfo:
# Test passing wrong type for properties.
@stix2.CustomMarking('x-new-marking-type2', ("a", "b"))
@stix2.v20.CustomMarking('x-new-marking-type2', ("a", "b"))
class NewObject3(object):
pass
@ -249,7 +249,7 @@ def test_marking_wrong_type_construction():
def test_campaign_add_markings():
campaign = stix2.Campaign(
campaign = stix2.v20.Campaign(
id="campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f",
created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff",
created="2016-04-06T20:03:00Z",

View File

@ -3,9 +3,9 @@ import shutil
import pytest
from stix2 import (Bundle, Campaign, CustomObject, Filter, Identity, Indicator,
Malware, MemorySource, MemoryStore, Relationship,
properties)
from stix2 import (Filter, MemorySource, MemoryStore, properties)
from stix2.v20 import (Bundle, Campaign, CustomObject, Identity, Indicator,
Malware, Relationship)
from stix2.datastore import make_id
from .constants import (CAMPAIGN_ID, CAMPAIGN_KWARGS, IDENTITY_ID,

View File

@ -1,7 +1,8 @@
import pytest
from stix2 import TLP_AMBER, Malware, exceptions, markings
from stix2 import exceptions, markings
from stix2.v20 import TLP_AMBER, Malware
from .constants import FAKE_TIME, MALWARE_ID
from .constants import MALWARE_KWARGS as MALWARE_KWARGS_CONST

File diff suppressed because it is too large Load Diff

View File

@ -7,7 +7,7 @@ def test_pickling():
"""
Ensure a pickle/unpickle cycle works okay.
"""
identity = stix2.Identity(
identity = stix2.v20.Identity(
id="identity--d66cb89d-5228-4983-958c-fa84ef75c88c",
name="alice",
description="this is a pickle test",

View File

@ -10,7 +10,6 @@ from .constants import (FAKE_TIME, INDICATOR_ID, MALWARE_ID, RELATIONSHIP_ID,
EXPECTED_RELATIONSHIP = """{
"type": "relationship",
"spec_version": "2.1",
"id": "relationship--00000000-1111-2222-3333-444444444444",
"created": "2016-04-06T20:06:37.000Z",
"modified": "2016-04-06T20:06:37.000Z",
@ -23,7 +22,7 @@ EXPECTED_RELATIONSHIP = """{
def test_relationship_all_required_properties():
now = dt.datetime(2016, 4, 6, 20, 6, 37, tzinfo=pytz.utc)
rel = stix2.Relationship(
rel = stix2.v20.Relationship(
type='relationship',
id=RELATIONSHIP_ID,
created=now,
@ -55,9 +54,9 @@ def test_relationship_autogenerated_properties(relationship):
def test_relationship_type_must_be_relationship():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Relationship(type='xxx', **RELATIONSHIP_KWARGS)
stix2.v20.Relationship(type='xxx', **RELATIONSHIP_KWARGS)
assert excinfo.value.cls == stix2.Relationship
assert excinfo.value.cls == stix2.v20.Relationship
assert excinfo.value.prop_name == "type"
assert excinfo.value.reason == "must equal 'relationship'."
assert str(excinfo.value) == "Invalid value for Relationship 'type': must equal 'relationship'."
@ -65,9 +64,9 @@ def test_relationship_type_must_be_relationship():
def test_relationship_id_must_start_with_relationship():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Relationship(id='my-prefix--', **RELATIONSHIP_KWARGS)
stix2.v20.Relationship(id='my-prefix--', **RELATIONSHIP_KWARGS)
assert excinfo.value.cls == stix2.Relationship
assert excinfo.value.cls == stix2.v20.Relationship
assert excinfo.value.prop_name == "id"
assert excinfo.value.reason == "must start with 'relationship--'."
assert str(excinfo.value) == "Invalid value for Relationship 'id': must start with 'relationship--'."
@ -75,27 +74,27 @@ def test_relationship_id_must_start_with_relationship():
def test_relationship_required_property_relationship_type():
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
stix2.Relationship()
assert excinfo.value.cls == stix2.Relationship
stix2.v20.Relationship()
assert excinfo.value.cls == stix2.v20.Relationship
assert excinfo.value.properties == ["relationship_type", "source_ref", "target_ref"]
def test_relationship_missing_some_required_properties():
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
stix2.Relationship(relationship_type='indicates')
stix2.v20.Relationship(relationship_type='indicates')
assert excinfo.value.cls == stix2.Relationship
assert excinfo.value.cls == stix2.v20.Relationship
assert excinfo.value.properties == ["source_ref", "target_ref"]
def test_relationship_required_properties_target_ref():
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
stix2.Relationship(
stix2.v20.Relationship(
relationship_type='indicates',
source_ref=INDICATOR_ID
)
assert excinfo.value.cls == stix2.Relationship
assert excinfo.value.cls == stix2.v20.Relationship
assert excinfo.value.properties == ["target_ref"]
@ -108,15 +107,15 @@ def test_cannot_assign_to_relationship_attributes(relationship):
def test_invalid_kwarg_to_relationship():
with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo:
stix2.Relationship(my_custom_property="foo", **RELATIONSHIP_KWARGS)
stix2.v20.Relationship(my_custom_property="foo", **RELATIONSHIP_KWARGS)
assert excinfo.value.cls == stix2.Relationship
assert excinfo.value.cls == stix2.v20.Relationship
assert excinfo.value.properties == ['my_custom_property']
assert str(excinfo.value) == "Unexpected properties for Relationship: (my_custom_property)."
def test_create_relationship_from_objects_rather_than_ids(indicator, malware):
rel = stix2.Relationship(
rel = stix2.v20.Relationship(
relationship_type="indicates",
source_ref=indicator,
target_ref=malware,
@ -129,7 +128,7 @@ def test_create_relationship_from_objects_rather_than_ids(indicator, malware):
def test_create_relationship_with_positional_args(indicator, malware):
rel = stix2.Relationship(indicator, 'indicates', malware)
rel = stix2.v20.Relationship(indicator, 'indicates', malware)
assert rel.relationship_type == 'indicates'
assert rel.source_ref == 'indicator--00000000-0000-0000-0000-000000000001'
@ -150,7 +149,7 @@ def test_create_relationship_with_positional_args(indicator, malware):
},
])
def test_parse_relationship(data):
rel = stix2.parse(data)
rel = stix2.parse(data, version="2.0")
assert rel.type == 'relationship'
assert rel.id == RELATIONSHIP_ID

View File

@ -28,7 +28,7 @@ EXPECTED = """{
def test_report_example():
report = stix2.Report(
report = stix2.v20.Report(
id="report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3",
created_by_ref="identity--a463ffb3-1bd9-4d94-b02d-74e4f1658283",
created="2015-12-21T19:59:11.000Z",
@ -48,7 +48,7 @@ def test_report_example():
def test_report_example_objects_in_object_refs():
report = stix2.Report(
report = stix2.v20.Report(
id="report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3",
created_by_ref="identity--a463ffb3-1bd9-4d94-b02d-74e4f1658283",
created="2015-12-21T19:59:11.000Z",
@ -69,7 +69,7 @@ def test_report_example_objects_in_object_refs():
def test_report_example_objects_in_object_refs_with_bad_id():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Report(
stix2.v20.Report(
id="report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3",
created_by_ref="identity--a463ffb3-1bd9-4d94-b02d-74e4f1658283",
created="2015-12-21T19:59:11.000Z",
@ -85,7 +85,7 @@ def test_report_example_objects_in_object_refs_with_bad_id():
],
)
assert excinfo.value.cls == stix2.Report
assert excinfo.value.cls == stix2.v20.Report
assert excinfo.value.prop_name == "object_refs"
assert excinfo.value.reason == "must match <object-type>--<guid>."
assert str(excinfo.value) == "Invalid value for Report 'object_refs': must match <object-type>--<guid>."
@ -113,7 +113,7 @@ def test_report_example_objects_in_object_refs_with_bad_id():
},
])
def test_parse_report(data):
rept = stix2.parse(data)
rept = stix2.parse(data, version="2.0")
assert rept.type == 'report'
assert rept.id == REPORT_ID

View File

@ -33,7 +33,7 @@ BAD_SIGHTING = """{
def test_sighting_all_required_properties():
now = dt.datetime(2016, 4, 6, 20, 6, 37, tzinfo=pytz.utc)
s = stix2.Sighting(
s = stix2.v20.Sighting(
type='sighting',
id=SIGHTING_ID,
created=now,
@ -48,7 +48,7 @@ def test_sighting_bad_where_sighted_refs():
now = dt.datetime(2016, 4, 6, 20, 6, 37, tzinfo=pytz.utc)
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Sighting(
stix2.v20.Sighting(
type='sighting',
id=SIGHTING_ID,
created=now,
@ -57,7 +57,7 @@ def test_sighting_bad_where_sighted_refs():
where_sighted_refs=["malware--8cc7afd6-5455-4d2b-a736-e614ee631d99"]
)
assert excinfo.value.cls == stix2.Sighting
assert excinfo.value.cls == stix2.v20.Sighting
assert excinfo.value.prop_name == "where_sighted_refs"
assert excinfo.value.reason == "must start with 'identity'."
assert str(excinfo.value) == "Invalid value for Sighting 'where_sighted_refs': must start with 'identity'."
@ -65,9 +65,9 @@ def test_sighting_bad_where_sighted_refs():
def test_sighting_type_must_be_sightings():
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
stix2.Sighting(type='xxx', **SIGHTING_KWARGS)
stix2.v20.Sighting(type='xxx', **SIGHTING_KWARGS)
assert excinfo.value.cls == stix2.Sighting
assert excinfo.value.cls == stix2.v20.Sighting
assert excinfo.value.prop_name == "type"
assert excinfo.value.reason == "must equal 'sighting'."
assert str(excinfo.value) == "Invalid value for Sighting 'type': must equal 'sighting'."
@ -75,15 +75,15 @@ def test_sighting_type_must_be_sightings():
def test_invalid_kwarg_to_sighting():
with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo:
stix2.Sighting(my_custom_property="foo", **SIGHTING_KWARGS)
stix2.v20.Sighting(my_custom_property="foo", **SIGHTING_KWARGS)
assert excinfo.value.cls == stix2.Sighting
assert excinfo.value.cls == stix2.v20.Sighting
assert excinfo.value.properties == ['my_custom_property']
assert str(excinfo.value) == "Unexpected properties for Sighting: (my_custom_property)."
def test_create_sighting_from_objects_rather_than_ids(malware): # noqa: F811
rel = stix2.Sighting(sighting_of_ref=malware)
rel = stix2.v20.Sighting(sighting_of_ref=malware)
assert rel.sighting_of_ref == 'malware--00000000-0000-0000-0000-000000000001'
assert rel.id == 'sighting--00000000-0000-0000-0000-000000000003'
@ -103,7 +103,7 @@ def test_create_sighting_from_objects_rather_than_ids(malware): # noqa: F811
},
])
def test_parse_sighting(data):
sighting = stix2.parse(data)
sighting = stix2.parse(data, version="2.0")
assert sighting.type == 'sighting'
assert sighting.id == SIGHTING_ID

View File

@ -22,7 +22,7 @@ EXPECTED = """{
def test_threat_actor_example():
threat_actor = stix2.ThreatActor(
threat_actor = stix2.v20.ThreatActor(
id="threat-actor--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f",
created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff",
created="2016-04-06T20:03:48.000Z",
@ -51,7 +51,7 @@ def test_threat_actor_example():
},
])
def test_parse_threat_actor(data):
actor = stix2.parse(data)
actor = stix2.parse(data, version="2.0")
assert actor.type == 'threat-actor'
assert actor.id == THREAT_ACTOR_ID

View File

@ -34,7 +34,7 @@ EXPECTED_WITH_REVOKED = """{
def test_tool_example():
tool = stix2.Tool(
tool = stix2.v20.Tool(
id="tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f",
created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff",
created="2016-04-06T20:03:48.000Z",
@ -61,7 +61,7 @@ def test_tool_example():
},
])
def test_parse_tool(data):
tool = stix2.parse(data)
tool = stix2.parse(data, version="2.0")
assert tool.type == 'tool'
assert tool.id == TOOL_ID
@ -73,13 +73,13 @@ def test_parse_tool(data):
def test_tool_no_workbench_wrappers():
tool = stix2.Tool(name='VNC', labels=['remote-access'])
tool = stix2.v20.Tool(name='VNC', labels=['remote-access'])
with pytest.raises(AttributeError):
tool.created_by()
def test_tool_serialize_with_defaults():
tool = stix2.Tool(
tool = stix2.v20.Tool(
id="tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f",
created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff",
created="2016-04-06T20:03:48.000Z",

View File

@ -105,7 +105,7 @@ def test_deduplicate(stix_objs1):
@pytest.mark.parametrize('object, tuple_to_find, expected_index', [
(stix2.ObservedData(
(stix2.v20.ObservedData(
id="observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf",
created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff",
created="2016-04-06T19:58:16.000Z",

View File

@ -6,7 +6,7 @@ from .constants import CAMPAIGN_MORE_KWARGS
def test_making_new_version():
campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v2 = campaign_v1.new_version(name="fred")
@ -20,7 +20,7 @@ def test_making_new_version():
def test_making_new_version_with_unset():
campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v2 = campaign_v1.new_version(description=None)
@ -34,7 +34,7 @@ def test_making_new_version_with_unset():
def test_making_new_version_with_embedded_object():
campaign_v1 = stix2.Campaign(
campaign_v1 = stix2.v20.Campaign(
external_references=[{
"source_name": "capec",
"external_id": "CAPEC-163"
@ -57,7 +57,7 @@ def test_making_new_version_with_embedded_object():
def test_revoke():
campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v2 = campaign_v1.revoke()
@ -72,7 +72,7 @@ def test_revoke():
def test_versioning_error_invalid_property():
campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS)
with pytest.raises(stix2.exceptions.UnmodifiablePropertyError) as excinfo:
campaign_v1.new_version(type="threat-actor")
@ -81,19 +81,19 @@ def test_versioning_error_invalid_property():
def test_versioning_error_bad_modified_value():
campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS)
with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
campaign_v1.new_version(modified="2015-04-06T20:03:00.000Z")
assert excinfo.value.cls == stix2.Campaign
assert excinfo.value.cls == stix2.v20.Campaign
assert excinfo.value.prop_name == "modified"
assert excinfo.value.reason == "The new modified datetime cannot be before than or equal to the current modified datetime." \
"It cannot be equal, as according to STIX 2 specification, objects that are different " \
"but have the same id and modified timestamp do not have defined consumer behavior."
msg = "Invalid value for {0} '{1}': {2}"
msg = msg.format(stix2.Campaign.__name__, "modified",
msg = msg.format(stix2.v20.Campaign.__name__, "modified",
"The new modified datetime cannot be before than or equal to the current modified datetime."
"It cannot be equal, as according to STIX 2 specification, objects that are different "
"but have the same id and modified timestamp do not have defined consumer behavior.")
@ -101,21 +101,21 @@ def test_versioning_error_bad_modified_value():
def test_versioning_error_usetting_required_property():
campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS)
with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo:
campaign_v1.new_version(name=None)
assert excinfo.value.cls == stix2.Campaign
assert excinfo.value.cls == stix2.v20.Campaign
assert excinfo.value.properties == ["name"]
msg = "No values for required properties for {0}: ({1})."
msg = msg.format(stix2.Campaign.__name__, "name")
msg = msg.format(stix2.v20.Campaign.__name__, "name")
assert str(excinfo.value) == msg
def test_versioning_error_new_version_of_revoked():
campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v2 = campaign_v1.revoke()
with pytest.raises(stix2.exceptions.RevokeError) as excinfo:
@ -127,7 +127,7 @@ def test_versioning_error_new_version_of_revoked():
def test_versioning_error_revoke_of_revoked():
campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v2 = campaign_v1.revoke()
with pytest.raises(stix2.exceptions.RevokeError) as excinfo:
@ -230,8 +230,8 @@ def test_remove_custom_stix_property():
def test_remove_custom_stix_object():
@stix2.CustomObject("x-animal", [
("species", stix2.properties.StringProperty(required=True)),
("animal_class", stix2.properties.StringProperty()),
("species", stix2.v20.properties.StringProperty(required=True)),
("animal_class", stix2.v20.properties.StringProperty()),
])
class Animal(object):
pass
@ -244,7 +244,7 @@ def test_remove_custom_stix_object():
def test_remove_custom_stix_no_custom():
campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS)
campaign_v2 = stix2.utils.remove_custom_stix(campaign_v1)
assert len(campaign_v1.keys()) == len(campaign_v2.keys())

View File

@ -23,13 +23,13 @@ EXPECTED = """{
def test_vulnerability_example():
vulnerability = stix2.Vulnerability(
vulnerability = stix2.v20.Vulnerability(
id="vulnerability--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061",
created="2016-05-12T08:17:27.000Z",
modified="2016-05-12T08:17:27.000Z",
name="CVE-2016-1234",
external_references=[
stix2.ExternalReference(source_name='cve',
stix2.v20.ExternalReference(source_name='cve',
external_id="CVE-2016-1234"),
],
)
@ -54,7 +54,7 @@ def test_vulnerability_example():
},
])
def test_parse_vulnerability(data):
vuln = stix2.parse(data)
vuln = stix2.parse(data, version="2.0")
assert vuln.type == 'vulnerability'
assert vuln.id == VULNERABILITY_ID