Upstream version 10.38.222.0
[platform/framework/web/crosswalk.git] / src / tools / swarming_client / googletest / tests / trace_test_cases_smoke_test.py
1 #!/usr/bin/env python
2 # Copyright 2013 The Swarming Authors. All rights reserved.
3 # Use of this source code is governed under the Apache License, Version 2.0 that
4 # can be found in the LICENSE file.
5
6 import json
7 import logging
8 import os
9 import re
10 import shutil
11 import subprocess
12 import sys
13 import tempfile
14 import unittest
15
16 BASE_DIR = os.path.dirname(os.path.abspath(__file__))
17 GOOGLETEST_DIR = os.path.dirname(BASE_DIR)
18 ROOT_DIR = os.path.dirname(GOOGLETEST_DIR)
19 sys.path.insert(0, ROOT_DIR)
20 sys.path.insert(0, os.path.join(BASE_DIR, 'gtest_fake'))
21 sys.path.insert(0, os.path.join(ROOT_DIR, 'tests'))
22
23 import gtest_fake_base
24 from utils import file_path
25 import trace_test_util
26
27 FILE_PATH = os.path.realpath(unicode(os.path.abspath(__file__)))
28 TARGET_UTIL_PATH = os.path.join(BASE_DIR, 'gtest_fake', 'gtest_fake_base.py')
29 TARGET_PATH = os.path.join(BASE_DIR, 'gtest_fake', 'gtest_fake_fail.py')
30
31
32 class TraceTestCases(unittest.TestCase):
33   def setUp(self):
34     super(TraceTestCases, self).setUp()
35     self.temp_dir = tempfile.mkdtemp(prefix='trace_test_cases_test')
36
37     self.initial_cwd = GOOGLETEST_DIR
38     if sys.platform == 'win32':
39       # Windows has no kernel mode concept of current working directory.
40       self.initial_cwd = None
41
42     # There's 2 kinds of references to python, self.executable,
43     # self.real_executable. It depends how python was started and on which OS.
44     self.executable = unicode(sys.executable)
45     if sys.platform == 'darwin':
46       # /usr/bin/python is a thunk executable that decides which version of
47       # python gets executed.
48       suffix = '.'.join(map(str, sys.version_info[0:2]))
49       if os.access(self.executable + suffix, os.X_OK):
50         # So it'll look like /usr/bin/python2.7
51         self.executable += suffix
52
53     self.real_executable = file_path.get_native_path_case(self.executable)
54     # Make sure there's no environment variable that could do side effects.
55     os.environ.pop('GTEST_SHARD_INDEX', '')
56     os.environ.pop('GTEST_TOTAL_SHARDS', '')
57
58   def tearDown(self):
59     shutil.rmtree(self.temp_dir)
60     super(TraceTestCases, self).tearDown()
61
62   def assertGreater(self, a, b, msg=None):
63     """Just like self.assertTrue(a > b), but with a nicer default message.
64
65     Added to support python 2.6.
66     """
67     if not a > b:
68       standardMsg = '%r not greater than %r' % (a, b)
69       self.fail(msg or standardMsg)
70
71   @trace_test_util.check_can_trace
72   def test_simple(self):
73     temp_file = os.path.join(self.temp_dir, 'foo_bar')
74     cmd = [
75         sys.executable,
76         os.path.join(GOOGLETEST_DIR, 'trace_test_cases.py'),
77         # Forces 4 parallel jobs.
78         '--jobs', '4',
79         '--out', temp_file,
80     ]
81     if VERBOSE:
82       cmd.extend(['-v'] * 3)
83     cmd.append(TARGET_PATH)
84     logging.debug(' '.join(cmd))
85     proc = subprocess.Popen(
86         cmd,
87         stdout=subprocess.PIPE, stderr=subprocess.PIPE,
88         universal_newlines=True,
89         cwd=GOOGLETEST_DIR)
90     out, err = proc.communicate() or ('', '')  # pylint is confused.
91     self.assertEqual(0, proc.returncode, (out, err))
92     lines = out.splitlines()
93     expected_out_re = [
94       r'Tracing\.\.\.',
95       r'\[0/4\] +\d+\.\d\ds ',
96       r'\[1/4\] +\d+\.\d\ds .+',
97       r'\[2/4\] +\d+\.\d\ds .+',
98       r'\[3/4\] +\d+\.\d\ds .+',
99       r'\[4/4\] +\d+\.\d\ds .+',
100       r'Reading trace logs\.\.\.',
101     ]
102     self.assertEqual(len(expected_out_re), len(lines), lines)
103     for index in range(len(expected_out_re)):
104       self.assertTrue(
105           re.match('^%s$' % expected_out_re[index], lines[index]),
106           '%d: %s\n%r\n%s' % (
107             index, expected_out_re[index], lines[index], out))
108     # Junk is printed on win32.
109     if sys.platform != 'win32' and not VERBOSE:
110       self.assertEqual('', err)
111
112     with open(temp_file, 'r') as f:
113       content = f.read()
114       try:
115         result = json.loads(content)
116       except:
117         print repr(content)
118         raise
119
120     test_cases = {
121       'Baz.Fail': 1,
122       'Foo.Bar1': 0,
123       'Foo.Bar2': 0,
124       'Foo.Bar3': 0,
125     }
126     self.assertEqual(dict, result.__class__)
127     self.assertEqual(sorted(test_cases), sorted(result))
128     for index, test_case in enumerate(sorted(result)):
129       actual = result[test_case]
130       self.assertEqual(
131           [u'duration', u'output', u'returncode', u'trace'], sorted(actual))
132       self.assertGreater(actual['duration'], 0.0000001)
133       self.assertEqual(test_cases[test_case], actual['returncode'])
134       expected_output = (
135           'Note: Google Test filter = %s\n' % test_case +
136           '\n' +
137           gtest_fake_base.get_test_output(test_case, 'Fail' in test_case) +
138           '\n' +
139           gtest_fake_base.get_footer(1, 1) +
140           '\n')
141       # On Windows, actual['output'] is unprocessed so it will contain CRLF.
142       output = actual['output']
143       if sys.platform == 'win32':
144         output = output.replace('\r\n', '\n')
145       self.assertEqual(expected_output, output, repr(output))
146
147       expected_trace = {
148         u'root': {
149           u'children': [],
150           u'command': [
151             self.executable, TARGET_PATH, '--gtest_filter=' + test_case,
152           ],
153           u'executable': file_path.get_native_path_case(
154             unicode(self.executable)),
155           u'initial_cwd': GOOGLETEST_DIR,
156         },
157       }
158       if sys.platform == 'win32':
159         expected_trace['root']['initial_cwd'] = None
160       self.assertGreater(actual['trace']['root'].pop('pid'), 1)
161       self.assertGreater(len(actual['trace']['root'].pop('files')), 10)
162       self.assertEqual(expected_trace, actual['trace'])
163
164
165 if __name__ == '__main__':
166   VERBOSE = '-v' in sys.argv
167   logging.basicConfig(level=logging.DEBUG if VERBOSE else logging.ERROR)
168   # Necessary for the dtrace logger to work around execve() hook. See
169   # trace_inputs.py for more details.
170   os.environ['TRACE_INPUTS_DTRACE_ENABLE_EXECVE'] = '1'
171   unittest.main()