1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3# 4# Copyright 2019 The ChromiumOS Authors 5# Use of this source code is governed by a BSD-style license that can be 6# found in the LICENSE file. 7 8"""Test to ensure we're not touching /dev/ptmx when running commands.""" 9 10 11import os 12import subprocess 13import tempfile 14import time 15import unittest 16 17from cros_utils import command_executer 18 19 20class NoPsuedoTerminalTest(unittest.TestCase): 21 """Test to ensure we're not touching /dev/ptmx when running commands.""" 22 23 _strace_process = None 24 STRACE_TIMEOUT = 10 25 26 def _AttachStraceToSelf(self, output_file): 27 """Attaches strace to the current process.""" 28 args = ["sudo", "strace", "-o", output_file, "-p", str(os.getpid())] 29 print(args) 30 # pylint: disable=bad-option-value, subprocess-popen-preexec-fn 31 self._strace_process = subprocess.Popen(args, preexec_fn=os.setpgrp) 32 # Wait until we see some activity. 33 start_time = time.time() 34 while time.time() - start_time < self.STRACE_TIMEOUT: 35 if os.path.isfile(output_file) and open(output_file).read(1): 36 return True 37 time.sleep(1) 38 return False 39 40 def _KillStraceProcess(self): 41 """Kills strace that was started by _AttachStraceToSelf().""" 42 pgid = os.getpgid(self._strace_process.pid) 43 args = ["sudo", "kill", str(pgid)] 44 if subprocess.call(args) == 0: 45 os.waitpid(pgid, 0) 46 return True 47 return False 48 49 def testNoPseudoTerminalWhenRunningCommand(self): 50 """Test to make sure we're not touching /dev/ptmx when running commands.""" 51 temp_file = tempfile.mktemp() 52 self.assertTrue(self._AttachStraceToSelf(temp_file)) 53 54 ce = command_executer.GetCommandExecuter() 55 ce.RunCommand("echo") 56 57 self.assertTrue(self._KillStraceProcess()) 58 59 strace_contents = open(temp_file).read() 60 self.assertFalse("/dev/ptmx" in strace_contents) 61 62 63if __name__ == "__main__": 64 unittest.main() 65