2 # Copyright (c) 2012 The Chromium 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.
14 SCRIPT_DIR
= os
.path
.dirname(os
.path
.abspath(__file__
))
15 TOOLS_DIR
= os
.path
.dirname(SCRIPT_DIR
)
16 CHROME_SRC
= os
.path
.dirname(os
.path
.dirname(os
.path
.dirname(TOOLS_DIR
)))
17 MOCK_DIR
= os
.path
.join(CHROME_SRC
, 'third_party', 'pymock')
19 sys
.path
.append(TOOLS_DIR
)
20 sys
.path
.append(MOCK_DIR
)
23 from mock
import patch
, Mock
26 class HTTPDTest(unittest
.TestCase
):
28 patcher
= patch('BaseHTTPServer.BaseHTTPRequestHandler.log_message')
30 self
.addCleanup(patcher
.stop
)
32 self
.server
= httpd
.LocalHTTPServer('.', 0)
33 self
.addCleanup(self
.server
.Shutdown
)
36 urllib2
.urlopen(self
.server
.GetURL('?quit=1'))
37 self
.server
.process
.join(10) # Wait 10 seconds for the process to finish.
38 self
.assertFalse(self
.server
.process
.is_alive())
41 class MainTest(unittest
.TestCase
):
42 @patch('httpd.LocalHTTPServer')
43 @patch('sys.stdout', Mock())
44 def testArgs(self
, mock_server_ctor
):
46 mock_server_ctor
.return_value
= mock_server
47 httpd
.main(['-p', '123', '-C', 'dummy'])
48 mock_server_ctor
.assert_called_once_with('dummy', 123)
51 class RunTest(unittest
.TestCase
):
56 if self
.process
and self
.process
.returncode
is None:
60 def _SubprocessThread(process
, queue
):
61 stdout
, stderr
= process
.communicate()
62 queue
.put((process
.returncode
, stdout
, stderr
))
64 def _Run(self
, args
=None, timeout
=None):
66 cmd
= [sys
.executable
, os
.path
.join(TOOLS_DIR
, 'run.py'), '--port=5555']
68 self
.process
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
,
69 stderr
=subprocess
.PIPE
)
71 thread
= threading
.Thread(target
=RunTest
._SubprocessThread
,
72 args
=(self
.process
, queue
))
76 self
.assertFalse(thread
.is_alive(), "Thread still running after timeout")
78 returncode
, stdout
, stderr
= queue
.get(False)
79 return returncode
, stdout
, stderr
83 def _GetChromeMockArgs(page
, http_request_type
, sleep
,
84 expect_to_be_killed
=True):
87 args
.extend(['-P', page
])
89 args
.extend([sys
.executable
, os
.path
.join(SCRIPT_DIR
, 'chrome_mock.py')])
91 args
.append('--' + http_request_type
)
93 args
.extend(['--sleep', str(sleep
)])
94 if expect_to_be_killed
:
95 args
.append('--expect-to-be-killed')
99 args
= self
._GetChromeMockArgs
('?quit=1', 'get', sleep
=10)
100 rtn
, stdout
, _
= self
._Run
(args
, timeout
=20)
101 self
.assertEqual(rtn
, 0)
102 self
.assertIn('Starting', stdout
)
103 self
.assertNotIn('Expected to be killed', stdout
)
105 def testSubprocessDies(self
):
106 args
= self
._GetChromeMockArgs
(page
=None, http_request_type
=None, sleep
=0,
107 expect_to_be_killed
=False)
108 returncode
, stdout
, _
= self
._Run
(args
, timeout
=10)
109 self
.assertNotEqual(-1, returncode
)
110 self
.assertIn('Starting', stdout
)
113 if __name__
== '__main__':