Like JsonIOStream, but working directly with values stored in memory. Values are round-tripped through JSON serialization. For input, values are read from the supplied sequence or iterator. For output, values are appended to the supplied collection.
| 24 | |
| 25 | |
| 26 | class JsonMemoryStream(object): |
| 27 | """Like JsonIOStream, but working directly with values stored in memory. |
| 28 | Values are round-tripped through JSON serialization. |
| 29 | |
| 30 | For input, values are read from the supplied sequence or iterator. |
| 31 | For output, values are appended to the supplied collection. |
| 32 | """ |
| 33 | |
| 34 | json_decoder_factory = messaging.JsonIOStream.json_decoder_factory |
| 35 | json_encoder_factory = messaging.JsonIOStream.json_encoder_factory |
| 36 | |
| 37 | def __init__(self, input, output, name="memory"): |
| 38 | self.name = name |
| 39 | self.input = iter(input) |
| 40 | self.output = output |
| 41 | |
| 42 | def close(self): |
| 43 | pass |
| 44 | |
| 45 | def _log_message(self, dir, data): |
| 46 | format_string = "{0} {1} " + ( |
| 47 | "{2:indent=None}" if isinstance(data, list) else "{2}" |
| 48 | ) |
| 49 | return log.debug(format_string, self.name, dir, json.repr(data)) |
| 50 | |
| 51 | def read_json(self, decoder=None): |
| 52 | decoder = decoder if decoder is not None else self.json_decoder_factory() |
| 53 | try: |
| 54 | value = next(self.input) |
| 55 | except StopIteration: |
| 56 | raise messaging.NoMoreMessages(stream=self) |
| 57 | value = decoder.decode(json.dumps(value)) |
| 58 | self._log_message("-->", value) |
| 59 | return value |
| 60 | |
| 61 | def write_json(self, value, encoder=None): |
| 62 | encoder = encoder if encoder is not None else self.json_encoder_factory() |
| 63 | value = json.loads(encoder.encode(value)) |
| 64 | self._log_message("<--", value) |
| 65 | self.output.append(value) |
| 66 | |
| 67 | |
| 68 | class TestJsonIOStream(object): |
no outgoing calls
searching dependent graphs…