Performs all eight conversions to verify import/export functionality. 1. cybox.Entity -> dict/list 2. dict/list -> JSON string 3. JSON string -> dict/list 4. dict/list -> cybox.Entity 5. cybox.Entity -> Bindings Object 6. Bindings Object -> XML String 7. XML String -> B
(o, output=False, list_=False)
| 56 | |
| 57 | |
| 58 | def round_trip(o, output=False, list_=False): |
| 59 | """ Performs all eight conversions to verify import/export functionality. |
| 60 | |
| 61 | 1. cybox.Entity -> dict/list |
| 62 | 2. dict/list -> JSON string |
| 63 | 3. JSON string -> dict/list |
| 64 | 4. dict/list -> cybox.Entity |
| 65 | 5. cybox.Entity -> Bindings Object |
| 66 | 6. Bindings Object -> XML String |
| 67 | 7. XML String -> Bindings Object |
| 68 | 8. Bindings object -> cybox.Entity |
| 69 | |
| 70 | It returns the final object, so tests which call this function can check to |
| 71 | ensure it was not modified during any of the transforms. |
| 72 | """ |
| 73 | |
| 74 | klass = o.__class__ |
| 75 | if output: |
| 76 | print("Class: ", klass) |
| 77 | print("-" * 40) |
| 78 | |
| 79 | # 1. cybox.Entity -> dict/list |
| 80 | if list_: |
| 81 | d = o.to_list() |
| 82 | else: |
| 83 | d = o.to_dict() |
| 84 | |
| 85 | # 2. dict/list -> JSON string |
| 86 | json_string = json.dumps(d) |
| 87 | |
| 88 | if output: |
| 89 | print(json_string) |
| 90 | print("-" * 40) |
| 91 | |
| 92 | # Before parsing the JSON, make sure the cache is clear |
| 93 | cybox.utils.cache_clear() |
| 94 | |
| 95 | # 3. JSON string -> dict/list |
| 96 | d2 = json.loads(json_string) |
| 97 | |
| 98 | # 4. dict/list -> cybox.Entity |
| 99 | if list_: |
| 100 | o2 = klass.from_list(d2) |
| 101 | else: |
| 102 | o2 = klass.from_dict(d2) |
| 103 | |
| 104 | # 5. Entity -> Bindings Object |
| 105 | ns_info = NamespaceCollector() |
| 106 | xobj = o2.to_obj(ns_info=ns_info) |
| 107 | |
| 108 | try: |
| 109 | # 6. Bindings Object -> XML String |
| 110 | xml_string = o2.to_xml(encoding=ExternalEncoding) |
| 111 | |
| 112 | if not isinstance(xml_string, text_type): |
| 113 | xml_string = xml_string.decode(ExternalEncoding) |
| 114 | |
| 115 | except KeyError as ex: |