Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(220)

Side by Side Diff: testing_support/super_mox.py

Issue 939523004: Copied files from depot_tools. (Closed) Base URL: https://chromium.googlesource.com/infra/testing/testing_support.git@master
Patch Set: Created 5 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # Copyright (c) 2011 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
5 """Simplify unit tests based on pymox."""
6
7 import os
8 import random
9 import shutil
10 import string
11 import StringIO
12 import subprocess
13 import sys
14
15 sys.path.append(os.path.dirname(os.path.dirname(__file__)))
iannucci 2015/02/19 00:22:39 do we still need this? Can we just guarantee that
pgervais 2015/02/19 00:45:57 Turns out we don't need the file at all...
16 from third_party.pymox import mox
17
18
19 class IsOneOf(mox.Comparator):
20 def __init__(self, keys):
21 self._keys = keys
22
23 def equals(self, rhs):
24 return rhs in self._keys
25
26 def __repr__(self):
27 return '<sequence or map containing \'%s\'>' % str(self._keys)
28
29
30 class TestCaseUtils(object):
31 """Base class with some additional functionalities. People will usually want
32 to use SuperMoxTestBase instead."""
33 # Backup the separator in case it gets mocked
34 _OS_SEP = os.sep
35 _RANDOM_CHOICE = random.choice
36 _RANDOM_RANDINT = random.randint
37 _STRING_LETTERS = string.letters
38
39 ## Some utilities for generating arbitrary arguments.
40 def String(self, max_length):
41 return ''.join([self._RANDOM_CHOICE(self._STRING_LETTERS)
42 for _ in xrange(self._RANDOM_RANDINT(1, max_length))])
43
44 def Strings(self, max_arg_count, max_arg_length):
45 return [self.String(max_arg_length) for _ in xrange(max_arg_count)]
46
47 def Args(self, max_arg_count=8, max_arg_length=16):
48 return self.Strings(max_arg_count,
49 self._RANDOM_RANDINT(1, max_arg_length))
50
51 def _DirElts(self, max_elt_count=4, max_elt_length=8):
52 return self._OS_SEP.join(self.Strings(max_elt_count, max_elt_length))
53
54 def Dir(self, max_elt_count=4, max_elt_length=8):
55 return (self._RANDOM_CHOICE((self._OS_SEP, '')) +
56 self._DirElts(max_elt_count, max_elt_length))
57
58 def SvnUrl(self, max_elt_count=4, max_elt_length=8):
59 return ('svn://random_host:port/a' +
60 self._DirElts(max_elt_count, max_elt_length
61 ).replace(self._OS_SEP, '/'))
62
63 def RootDir(self, max_elt_count=4, max_elt_length=8):
64 return self._OS_SEP + self._DirElts(max_elt_count, max_elt_length)
65
66 def compareMembers(self, obj, members):
67 """If you add a member, be sure to add the relevant test!"""
68 # Skip over members starting with '_' since they are usually not meant to
69 # be for public use.
70 actual_members = [x for x in sorted(dir(obj))
71 if not x.startswith('_')]
72 expected_members = sorted(members)
73 if actual_members != expected_members:
74 diff = ([i for i in actual_members if i not in expected_members] +
75 [i for i in expected_members if i not in actual_members])
76 print >> sys.stderr, diff
77 # pylint: disable=E1101
78 self.assertEqual(actual_members, expected_members)
79
80 def setUp(self):
81 self.root_dir = self.Dir()
82 self.args = self.Args()
83 self.relpath = self.String(200)
84
85 def tearDown(self):
86 pass
87
88
89 class StdoutCheck(object):
90 def setUp(self):
91 # Override the mock with a StringIO, it's much less painful to test.
92 self._old_stdout = sys.stdout
93 stdout = StringIO.StringIO()
94 stdout.flush = lambda: None
95 sys.stdout = stdout
96
97 def tearDown(self):
98 try:
99 # If sys.stdout was used, self.checkstdout() must be called.
100 # pylint: disable=E1101
101 if not sys.stdout.closed:
102 self.assertEquals('', sys.stdout.getvalue())
103 except AttributeError:
104 pass
105 sys.stdout = self._old_stdout
106
107 def checkstdout(self, expected):
108 value = sys.stdout.getvalue()
109 sys.stdout.close()
110 # pylint: disable=E1101
111 self.assertEquals(expected, value)
112
113
114 class SuperMoxTestBase(TestCaseUtils, StdoutCheck, mox.MoxTestBase):
115 def setUp(self):
116 """Patch a few functions with know side-effects."""
117 TestCaseUtils.setUp(self)
118 mox.MoxTestBase.setUp(self)
119 os_to_mock = ('chdir', 'chown', 'close', 'closerange', 'dup', 'dup2',
120 'fchdir', 'fchmod', 'fchown', 'fdopen', 'getcwd', 'lseek',
121 'makedirs', 'mkdir', 'open', 'popen', 'popen2', 'popen3', 'popen4',
122 'read', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'symlink',
123 'system', 'tmpfile', 'walk', 'write')
124 self.MockList(os, os_to_mock)
125 os_path_to_mock = ('abspath', 'exists', 'getsize', 'isdir', 'isfile',
126 'islink', 'ismount', 'lexists', 'realpath', 'samefile', 'walk')
127 self.MockList(os.path, os_path_to_mock)
128 self.MockList(shutil, ('rmtree'))
129 self.MockList(subprocess, ('call', 'Popen'))
130 # Don't mock stderr since it confuses unittests.
131 self.MockList(sys, ('stdin'))
132 StdoutCheck.setUp(self)
133
134 def tearDown(self):
135 StdoutCheck.tearDown(self)
136 TestCaseUtils.tearDown(self)
137 mox.MoxTestBase.tearDown(self)
138
139 def MockList(self, parent, items_to_mock):
140 for item in items_to_mock:
141 # Skip over items not present because of OS-specific implementation,
142 # implemented only in later python version, etc.
143 if hasattr(parent, item):
144 try:
145 self.mox.StubOutWithMock(parent, item)
146 except TypeError, e:
147 raise TypeError(
148 'Couldn\'t mock %s in %s: %s' % (item, parent.__name__, e))
149
150 def UnMock(self, obj, name):
151 """Restore an object inside a test."""
152 for (parent, old_child, child_name) in self.mox.stubs.cache:
153 if parent == obj and child_name == name:
154 setattr(parent, child_name, old_child)
155 break
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698