Chromium Code Reviews| Index: src/trusted/validator/x86/testing/tf/utils.py |
| diff --git a/src/trusted/validator/x86/testing/tf/utils.py b/src/trusted/validator/x86/testing/tf/utils.py |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..61d45050c6e46e1c79ba141ecde8bc3244095108 |
| --- /dev/null |
| +++ b/src/trusted/validator/x86/testing/tf/utils.py |
| @@ -0,0 +1,65 @@ |
| +# Copyright (c) 2012 The Native Client Authors. All rights reserved. |
| +# Use of this source code is governed by a BSD-style license that can be |
| +# found in the LICENSE file. |
| + |
| +import os |
| +import subprocess |
| +import tempfile |
| + |
| + |
| +def DataToReadableHex(data): |
| + """Convert string of bytes to string of hexes ('\xde\xad' -> 'de ad'). |
| + |
| + Args: |
| + data: String (used to represent sequence of bytes). |
| + |
| + Returns: |
| + String of space-separated hex codes. |
| + """ |
| + |
| + return ' '.join('%02x' % ord(c) for c in data) |
| + |
| + |
| +def ReadableHexToData(s): |
| + """Convert string of hexes to string of bytes ('be ef' -> '\xbe\xef'). |
| + |
| + Args: |
| + s: String of space-separated two-character hex codes. |
| + |
| + Returns: |
| + String representing sequence of bytes. |
| + """ |
| + |
| + bytes = s.split() |
| + assert all(len(byte) == 2 for byte in bytes) |
| + return ''.join(chr(int(byte, 16)) for byte in bytes) |
| + |
| + |
| +def CheckOutput(args, **kwargs): |
| + # reimplementation of subprocess.check_output from py 2.7 |
| + assert 'stdout' not in kwargs |
| + |
| + process = subprocess.Popen(args, stdout=subprocess.PIPE, **kwargs) |
| + output, _ = process.communicate() |
| + |
| + if process.returncode != 0: |
| + raise subprocess.CalledProcessError(process.returncode, cmd=args[0]) |
| + |
| + return output |
| + |
| + |
| +# Custom context manager that allows temporary file to be reopened |
| +# and deletes it on exit. |
| +# NamedTemporareFile with delete=True won't do the job because |
| +# it can't be reopened on Windows. |
| +class TempFile(object): |
| + def __init__(self, mode='w+b'): |
| + self.file = tempfile.NamedTemporaryFile(mode=mode, delete=False) |
| + |
| + def __enter__(self): |
| + return self.file |
| + |
| + def __exit__(self, exc_type, ext_value, traceback): |
|
Mark Seaborn
2012/09/10 19:38:06
Nit: 'ext_value' -> 'exc_value'
Vlad Shcherbina
2012/09/11 14:26:00
Done.
|
| + self.file.close() |
| + if os.path.exists(self.file.name): |
|
Mark Seaborn
2012/09/10 19:38:06
Nit: can you put a comment in to say which platfor
Vlad Shcherbina
2012/09/11 14:26:00
Done. It's not the platform, but the fact that GNU
|
| + os.remove(self.file.name) |