1# Copyright 2020 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""
5Helpers for running unit, e2e, and screenshot tests.
6"""
7
8import os
9import sys
10from subprocess import Popen
11import signal
12
13# Add the scripts path, so that we can import the devtools_paths
14scripts_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
15sys.path.append(scripts_path)
16import devtools_paths
17
18is_cygwin = sys.platform == 'cygwin'
19
20def check_chrome_binary(chrome_binary):
21    return os.path.exists(chrome_binary) and os.path.isfile(chrome_binary) and os.access(chrome_binary, os.X_OK)
22
23
24def popen(arguments, cwd=devtools_paths.devtools_root_path(), env=os.environ.copy()):
25    process = Popen(arguments, cwd=cwd, env=env)
26    def handle_signal(signum, frame):
27        print('\nSending signal (%i) to process' % signum)
28        process.send_signal(signum)
29        process.terminate()
30
31    # Propagate sigterm / int to the child process.
32    original_sigint = signal.getsignal(signal.SIGINT)
33    original_sigterm = signal.getsignal(signal.SIGTERM)
34    signal.signal(signal.SIGINT, handle_signal)
35    signal.signal(signal.SIGTERM, handle_signal)
36
37    process.communicate()
38
39    # Restore the original sigterm / int handlers.
40    signal.signal(signal.SIGINT, original_sigint)
41    signal.signal(signal.SIGTERM, original_sigterm)
42
43    return process.returncode
44
45
46def to_platform_path_exact(filepath):
47    if not is_cygwin:
48        return filepath
49    output, _ = popen(['cygpath', '-w', filepath]).communicate()
50    # pylint: disable=E1103
51    return output.strip().replace('\\', '\\\\')
52