From bc66db94aa6228572f8b9d949a012e19a7661118 Mon Sep 17 00:00:00 2001 From: Greg Back Date: Fri, 10 Feb 2017 15:58:17 -0600 Subject: [PATCH] Add generic __repr__ to _STIXBase. --- stix2/base.py | 5 +++++ stix2/test/test_stix2.py | 22 ++++++++++++++++------ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/stix2/base.py b/stix2/base.py index 317372c..3adc0e4 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -102,3 +102,8 @@ class _STIXBase(collections.Mapping): # TODO: put keys in specific order. Probably need custom JSON encoder. return json.dumps(self, indent=4, sort_keys=True, cls=STIXJSONEncoder, separators=(",", ": ")) # Don't include spaces after commas. + + def __repr__(self): + props = [(k, self[k]) for k in sorted(self._properties)] + return "{0}({1})".format(self.__class__.__name__, + ", ".join(["{0!s}={1!r}".format(k, v) for k, v in props])) diff --git a/stix2/test/test_stix2.py b/stix2/test/test_stix2.py index ec05a34..03a887b 100644 --- a/stix2/test/test_stix2.py +++ b/stix2/test/test_stix2.py @@ -91,21 +91,31 @@ def relationship(uuid4, clock): EXPECTED_INDICATOR = """{ - "created": "2017-01-01T00:00:00Z", + "created": "2017-01-01T00:00:01Z", "id": "indicator--01234567-89ab-cdef-0123-456789abcdef", "labels": [ "malicious-activity" ], - "modified": "2017-01-01T00:00:00Z", + "modified": "2017-01-01T00:00:01Z", "pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", "type": "indicator", - "valid_from": "1970-01-01T00:00:00Z" + "valid_from": "1970-01-01T00:00:01Z" }""" +EXPECTED_INDICATOR_REPR = "Indicator(" + " ".join(""" + created=datetime.datetime(2017, 1, 1, 0, 0, 1, tzinfo=), + id='indicator--01234567-89ab-cdef-0123-456789abcdef', + labels=['malicious-activity'], + modified=datetime.datetime(2017, 1, 1, 0, 0, 1, tzinfo=), + pattern="[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", + type='indicator', + valid_from=datetime.datetime(1970, 1, 1, 0, 0, 1, tzinfo=) +""".split()) + ")" + def test_indicator_with_all_required_fields(): - now = dt.datetime(2017, 1, 1, 0, 0, 0, tzinfo=pytz.utc) - epoch = dt.datetime(1970, 1, 1, 0, 0, 0, tzinfo=pytz.utc) + now = dt.datetime(2017, 1, 1, 0, 0, 1, tzinfo=pytz.utc) + epoch = dt.datetime(1970, 1, 1, 0, 0, 1, tzinfo=pytz.utc) indicator = stix2.Indicator( type="indicator", @@ -118,6 +128,7 @@ def test_indicator_with_all_required_fields(): ) assert str(indicator) == EXPECTED_INDICATOR + assert repr(indicator) == EXPECTED_INDICATOR_REPR def test_indicator_autogenerated_fields(indicator): @@ -291,7 +302,6 @@ def test_relationship_all_required_fields(): ) assert str(relationship) == EXPECTED_RELATIONSHIP - def test_relationship_autogenerated_fields(relationship): assert relationship.type == 'relationship' assert relationship.id == 'relationship--00000000-0000-0000-0000-000000000001'