From be07c3250014db2d11e03ab660711a9bf3464656 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Fri, 8 Sep 2017 12:39:36 -0400 Subject: [PATCH] Add parse() to Environment layer The Environment layer does not keep its own mapping of custom object types. If we think it likely that users will want to maintain separate lists of custom object types between two or more Environments, we can add this later. --- stix2/core.py | 6 +++--- stix2/environment.py | 5 +++++ stix2/test/test_environment.py | 24 +++++++++++++++++++++++- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/stix2/core.py b/stix2/core.py index be2a53d..0271e34 100644 --- a/stix2/core.py +++ b/stix2/core.py @@ -75,13 +75,13 @@ def parse(data, allow_custom=False): """Deserialize a string or file-like object into a STIX object. Args: - data: The STIX 2 string to be parsed. + data (str, dict, file-like object): The STIX 2 content to be parsed. allow_custom (bool): Whether to allow custom properties or not. Default: False. Returns: An instantiated Python STIX object. - """ + """ obj = get_dict(data) if 'type' not in obj: @@ -96,6 +96,6 @@ def parse(data, allow_custom=False): def _register_type(new_type): """Register a custom STIX Object type. - """ + """ OBJ_MAP[new_type._type] = new_type diff --git a/stix2/environment.py b/stix2/environment.py index 96726a4..8e24c9b 100644 --- a/stix2/environment.py +++ b/stix2/environment.py @@ -1,5 +1,6 @@ import copy +from .core import parse as _parse from .sources import CompositeDataSource, DataSource, DataStore @@ -149,3 +150,7 @@ class Environment(object): except AttributeError: raise AttributeError('Environment has no data sink to put objects in') add.__doc__ = DataStore.add.__doc__ + + def parse(self, *args, **kwargs): + return _parse(*args, **kwargs) + parse.__doc__ = _parse.__doc__ diff --git a/stix2/test/test_environment.py b/stix2/test/test_environment.py index 26fd1b4..0871bb5 100644 --- a/stix2/test/test_environment.py +++ b/stix2/test/test_environment.py @@ -3,7 +3,7 @@ import pytest import stix2 from .constants import (FAKE_TIME, IDENTITY_ID, IDENTITY_KWARGS, INDICATOR_ID, - INDICATOR_KWARGS) + INDICATOR_KWARGS, MALWARE_ID) def test_object_factory_created_by_ref_str(): @@ -164,3 +164,25 @@ def test_environment_datastore_and_no_object_factory(): env = stix2.Environment(store=stix2.MemoryStore()) ind = env.create(stix2.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS) assert ind.id == INDICATOR_ID + + +def test_parse_malware(): + env = stix2.Environment() + data = """{ + "type": "malware", + "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" + ] + }""" + mal = env.parse(data) + + assert mal.type == 'malware' + assert mal.id == MALWARE_ID + assert mal.created == FAKE_TIME + assert mal.modified == FAKE_TIME + assert mal.labels == ['ransomware'] + assert mal.name == "Cryptolocker"