def test_write_same_stream_callable(self): # streams root = mktemp() output_stream = StringIO() output_stream.name = join(root, 'packed.js') called = [] closed = [] def close(): closed.append(True) output_stream.close = close def f_output_stream(): called.append(True) return output_stream definitions = { 'Node': ( Attr(attr='text'), Text(value=';'), ) } # the program node; attributes are assigned to mimic a real one program = Node() program.text = 'hello' program.sourcepath = join(root, 'program.js') program._token_map = {'hello': [(0, 1, 1)]} unparser = BaseUnparser(definitions) io.write(unparser, [program], f_output_stream, f_output_stream) self.assertEqual(1, len(called)) self.assertEqual(1, len(closed)) output = output_stream.getvalue() self.assertIn('hello', output) self.assertNotIn('program.js', output) # since output stream is a StringIO, default to utf8 encoding self.assertIn('data:application/json;base64;charset=utf8', output) # decode the base64 string self.assertEqual( { "version": 3, "sources": ["program.js"], "names": [], "mappings": "AAAA", "file": "packed.js" }, json.loads( base64.b64decode(output.splitlines()[-1].split(',')[-1].encode( 'utf8')).decode('utf8')))
def test_write_error_handled_callable_closed(self): # streams root = mktemp() output_stream = StringIO() output_stream.name = join(root, 'packed.js') closed = [] def close(): closed.append(True) output_stream.close = close def f_output_stream(): return output_stream def f_error(): raise IOError('some error happened') definitions = { 'Node': ( Attr(attr='text'), Text(value=';'), ) } # the program node; attributes are assigned to mimic a real one program = Node() program.text = 'hello' program.sourcepath = join(root, 'program.js') program._token_map = {'hello': [(0, 1, 1)]} unparser = BaseUnparser(definitions) with self.assertRaises(IOError): io.write(unparser, [program], f_output_stream, f_error) self.assertEqual(1, len(closed)) self.assertEqual('hello;', output_stream.getvalue()) self.assertNotIn('program.js', output_stream.getvalue())