Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / native_client / pnacl / driver / tests / driver_test_utils.py
1 #!/usr/bin/python
2 # Copyright (c) 2012 The Native Client Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 import os
7 from os.path import dirname
8 import platform
9 import sys
10 import tempfile
11 import unittest
12
13 import driver_env
14 import driver_log
15 import driver_tools
16
17 def CanRunHost():
18   # Some of the test+tools require running the host binaries, but that
19   # does not work on some bots (e.g., the ARM bots).
20   if platform.machine().startswith('arm'):
21     return False
22   # We also cannot run some of the Windows binaries directly, since
23   # they depend on cygwin DLLs and the cygwin DLLs are only in the
24   # path for the installed drivers bin and not for the binaries.
25   if sys.platform == 'win32':
26     return False
27   return True
28
29 def _SetupLinuxHostDir(env, nacl_dir):
30   # Use the 32-bit path by default, but fall back to 64-bit if the 32-bit does
31   # not exist.
32   dir_template = os.path.join(nacl_dir, 'toolchain', 'pnacl_linux_x86',
33                               'host_%s')
34   dir_32 = dir_template % 'x86_32'
35   dir_64 = dir_template % 'x86_64'
36   driver_tools.AddHostBinarySearchPath(
37     dir_32 if os.path.exists(dir_32) else dir_64)
38
39 def SetupNaClDir(env):
40   test_dir = os.path.abspath(dirname(__file__))
41   nacl_dir = dirname(dirname(dirname(test_dir)))
42   env.set('BASE_NACL', nacl_dir)
43
44 def SetupToolchainDir(env):
45   test_dir = os.path.abspath(dirname(__file__))
46   nacl_dir = dirname(dirname(dirname(test_dir)))
47   toolchain_dir = os.path.join(nacl_dir, 'toolchain')
48   env.set('BASE_TOOLCHAIN', toolchain_dir)
49
50 def SetupHostDir(env):
51   # Some of the tools end up running one of the host binaries. Find the host
52   # dir on the test system and inject it into the search path using the
53   # implementation of -B
54   test_dir = os.path.abspath(dirname(__file__))
55   nacl_dir = dirname(dirname(dirname(test_dir)))
56   if sys.platform == 'darwin':
57     os_shortname = 'mac'
58     host_arch = 'x86_64'
59   elif sys.platform.startswith('linux'):
60     _SetupLinuxHostDir(env, nacl_dir)
61     return
62   elif sys.platform in ('cygwin', 'win32'):
63     os_shortname = 'win'
64     host_arch= 'x86_32'
65   host_dir = os.path.join(nacl_dir, 'toolchain',
66                           'pnacl_%s_x86' % os_shortname,
67                           'host_%s' % host_arch)
68   driver_tools.AddHostBinarySearchPath(host_dir)
69
70 # A collection of override methods that mock driver_env.Environment.
71
72 # One thing is we prevent having to read a driver.conf file,
73 # so instead we have a base group of variables set for testing.
74 def TestEnvReset(self, more_overrides={}):
75   # Call to "super" class method (assumed to be driver_env.Environment).
76   # TODO(jvoung): We may want a different way of overriding things.
77   driver_env.Environment.reset(self)
78   # The overrides.
79   self.set('PNACL_RUNNING_UNITTESTS', '1')
80   SetupNaClDir(self)
81   SetupToolchainDir(self)
82   SetupHostDir(self)
83   for k, v in more_overrides.iteritems():
84     self.set(k, v)
85
86 def ApplyTestEnvOverrides(env, more_overrides={}):
87   """Register all the override methods and reset the env to a testable state.
88   """
89   resetter = lambda self: TestEnvReset(self, more_overrides)
90   driver_env.override_env('reset', resetter)
91   env.reset()
92
93 # Utils to prevent driver exit.
94
95 class DriverExitException(Exception):
96   pass
97
98 def FakeExit(i):
99   raise DriverExitException('Stubbed out DriverExit!')
100
101 # Basic argument parsing.
102
103 def GetPlatformToTest():
104   for arg in sys.argv:
105     if arg.startswith('--platform='):
106       return arg.split('=')[1]
107   raise Exception('Unknown platform')
108
109 # We would like to be able to use a temp file whether it is open or closed.
110 # However File's __enter__ method requires it to be open. So we override it
111 # to just return the fd regardless.
112 class TempWrapper(object):
113   def __init__(self, fd, close=True):
114     self.fd_ = fd
115     if close:
116       fd.close()
117   def __enter__(self):
118     return self.fd_
119   def __exit__(self, exc_type, exc_value, traceback):
120     return self.fd_.__exit__(exc_type, exc_value, traceback)
121   def __getattr__(self, name):
122     return getattr(self.fd_, name)
123
124 class DriverTesterCommon(unittest.TestCase):
125   def setUp(self):
126     super(DriverTesterCommon, self).setUp()
127     self._tempfiles = []
128
129   def tearDown(self):
130     for t in self._tempfiles:
131       if not t.closed:
132         t.close()
133       os.remove(t.name)
134     driver_log.TempFiles.wipe()
135     super(DriverTesterCommon, self).tearDown()
136
137   def getTemp(self, close=True, **kwargs):
138     """ Get a temporary named file object.
139     """
140     # Set delete=False, so that we can close the files and
141     # re-open them.  Windows sometimes does not allow you to
142     # re-open an already opened temp file.
143     t = tempfile.NamedTemporaryFile(delete=False, **kwargs)
144     self._tempfiles.append(t)
145     return TempWrapper(t, close=close)