2 # Copyright 2014 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.
7 Unit tests for the contents of device_temp_file.py.
15 from pylib
import constants
16 from pylib
.device
import adb_wrapper
17 from pylib
.device
import device_errors
18 from pylib
.utils
import device_temp_file
19 from pylib
.utils
import mock_calls
21 sys
.path
.append(os
.path
.join(
22 constants
.DIR_SOURCE_ROOT
, 'third_party', 'pymock'))
23 import mock
# pylint: disable=F0401
25 class DeviceTempFileTest(mock_calls
.TestCase
):
28 test_serial
= '0123456789abcdef'
29 self
.adb
= mock
.Mock(spec
=adb_wrapper
.AdbWrapper
)
30 self
.adb
.__str
__ = mock
.Mock(return_value
=test_serial
)
31 self
.watchMethodCalls(self
.call
.adb
)
33 def mockShellCall(self
, cmd_prefix
, action
=''):
34 """Expect an adb.Shell(cmd) call with cmd_prefix and do some action
37 cmd_prefix: A string, the cmd of the received call is expected to have
39 action: If callable, an action to perform when the expected call is
40 received, otherwise a return value.
42 An (expected_call, action) pair suitable for use in assertCalls.
44 def check_and_return(cmd
):
46 cmd
.startswith(cmd_prefix
),
47 'command %r does not start with prefix %r' % (cmd
, cmd_prefix
))
52 return (self
.call
.adb
.Shell(mock
.ANY
), check_and_return
)
54 def mockExistsTest(self
, exists_result
):
59 raise device_errors
.AdbCommandFailedError(
60 cmd
, 'File not found', 1, str(self
.adb
))
61 return self
.mockShellCall('test -e ', action
)
63 def testTempFileNameAlreadyExists(self
):
64 with self
.assertCalls(
65 self
.mockShellCall('test -d /data/local/tmp'),
66 self
.mockExistsTest(True),
67 self
.mockExistsTest(True),
68 self
.mockExistsTest(True),
69 self
.mockExistsTest(False),
70 self
.mockShellCall('touch '),
71 self
.mockShellCall('rm -f ')):
72 with device_temp_file
.DeviceTempFile(self
.adb
) as tmpfile
:
73 logging
.debug('Temp file name: %s' % tmpfile
.name
)
75 def testTempFileLifecycle(self
):
76 with self
.assertCalls(
77 self
.mockShellCall('test -d /data/local/tmp'),
78 self
.mockExistsTest(False),
79 self
.mockShellCall('touch ')):
80 tempFileContextManager
= device_temp_file
.DeviceTempFile(self
.adb
)
81 with mock
.patch
.object(self
.adb
, 'Shell'):
82 with tempFileContextManager
as tmpfile
:
83 logging
.debug('Temp file name: %s' % tmpfile
.name
)
84 self
.assertEquals(0, self
.adb
.Shell
.call_count
)
85 self
.assertEquals(1, self
.adb
.Shell
.call_count
)
86 args
, _
= self
.adb
.Shell
.call_args
87 self
.assertTrue(args
[0].startswith('rm -f '))
89 if __name__
== '__main__':
90 logging
.getLogger().setLevel(logging
.DEBUG
)
91 unittest
.main(verbosity
=2)