desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Initialize logging subsystem'
def __init_logging(self, level, filename):
date_format = '%H:%M:%S' if (level == None): level = logging.WARNING logging.basicConfig(level=level) stderr_handler = logging.StreamHandler(sys.stderr) formatter = WrappingLogFormatter(format='%(levelname)s: %(message)s') stderr_handler.setLevel(level) stderr_handler.setFormatter...
'Tests that we can import the module; very basic sanity check.'
def testImport(self):
sqlcmd.Main()
'Return a new PrettyTable instance Arguments: fields - list or tuple of field names caching - boolean value to turn string caching on/off padding width - number of spaces between column lines and content'
def __init__(self, fields=None, caching=True, padding_width=1, left_padding=None, right_padding=None):
self.fields = [] if fields: self.set_field_names(fields) else: self.widths = [] self.aligns = [] self.set_padding_width(padding_width) self.rows = [] self.cache = {} self.html_cache = {} self.hrules = FRAME self.caching = caching self.padding_width = paddi...
'Return a new PrettyTable whose data rows are a slice of this one\'s Arguments: i - beginning slice index j - ending slice index'
def __getslice__(self, i, j):
newtable = copy.deepcopy(self) newtable.rows = self.rows[i:j] return newtable
'Set the names of the fields Arguments: fields - list or tuple of field names'
def set_field_names(self, fields):
if self.fields: self.widths = [len(field) for field in fields] for row in self.rows: for i in range(0, len(row)): if (len(unicode(row[i])) > self.widths[i]): self.widths[i] = len(unicode(row[i])) else: self.widths = [len(field) for field in...
'Set the alignment of a field by its fieldname Arguments: fieldname - name of the field whose alignment is to be changed align - desired alignment - "l" for left, "c" for centre and "r" for right'
def set_field_align(self, fieldname, align):
if (fieldname not in self.fields): raise Exception(('No field %s exists!' % fieldname)) if (align not in ['l', 'c', 'r']): raise Exception(('Alignment %s is invalid, use l, c or r!' % align)) self.aligns[self.fields.index(fieldname)] = align self.cache = ...
'Set the number of empty spaces between a column\'s edge and its content Arguments: padding_width - number of spaces, must be a positive integer'
def set_padding_width(self, padding_width):
try: assert (int(padding_width) >= 0) except AssertionError: raise Exception(('Invalid value for padding_width: %s!' % unicode(padding_width))) self.padding_width = padding_width self.cache = {} self.html_cache = {}
'Set the number of empty spaces between a column\'s left edge and its content Arguments: left_padding - number of spaces, must be a positive integer'
def set_left_padding(self, left_padding):
try: assert ((left_padding == None) or (int(left_padding) >= 0)) except AssertionError: raise Exception(('Invalid value for left_padding: %s!' % unicode(left_padding))) self.left_padding = left_padding self.cache = {} self.html_cache = {}
'Set the number of empty spaces between a column\'s right edge and its content Arguments: right_padding - number of spaces, must be a positive integer'
def set_right_padding(self, right_padding):
try: assert ((right_padding == None) or (int(right_padding) >= 0)) except AssertionError: raise Exception(('Invalid value for right_padding: %s!' % unicode(right_padding))) self.right_padding = right_padding self.cache = {} self.html_cache = {}
'Set the characters to use when drawing the table border Arguments: vertical - character used to draw a vertical line segment. Default is | horizontal - character used to draw a horizontal line segment. Default is - junction - character used to draw a line junction. Default is +'
def set_border_chars(self, vertical='|', horizontal='-', junction='+'):
if ((len(vertical) > 1) or (len(horizontal) > 1) or (len(junction) > 1)): raise Exception('All border characters must be strings of length ONE!') self.vertical_char = vertical self.horizontal_char = horizontal self.junction_char = junction self.cache = {}
'Add a row to the table Arguments: row - row of data, should be a list with as many elements as the table has fields'
def add_row(self, row):
if (len(row) != len(self.fields)): raise Exception(('Row has incorrect number of values, (actual) %d!=%d (expected)' % (len(row), len(self.fields)))) self.rows.append(row) for i in range(0, len(row)): if (len(unicode(row[i])) > self.widths[i]): self.widths...
'Add a column to the table. Arguments: fieldname - name of the field to contain the new column of data column - column of data, should be a list with as many elements as the table has rows align - desired alignment for this column - "l" for left, "c" for centre and "r" for right'
def add_column(self, fieldname, column, align='c'):
if (len(self.rows) in (0, len(column))): if (align not in ['l', 'c', 'r']): raise Exception(('Alignment %s is invalid, use l, c or r!' % align)) self.fields.append(fieldname) self.widths.append(len(fieldname)) self.aligns.append(align) for ...
'Print table in current state to stdout. Arguments: start - index of first data row to include in output end - index of last data row to include in output PLUS ONE (list slice style) fields - names of fields (columns) to include sortby - name of field to sort rows by reversesort - True or False to sort in descending or...
def printt(self, start=0, end=None, fields=None, header=True, border=True, hrules=FRAME, sortby=None, reversesort=False):
print self.get_string(start, end, fields, header, border, hrules, sortby, reversesort)
'Return string representation of table in current state. Arguments: start - index of first data row to include in output end - index of last data row to include in output PLUS ONE (list slice style) fields - names of fields (columns) to include sortby - name of field to sort rows by reversesort - True or False to sort ...
def get_string(self, start=0, end=None, fields=None, header=True, border=True, hrules=FRAME, sortby=None, reversesort=False):
if self.caching: key = cPickle.dumps((start, end, fields, header, border, hrules, sortby, reversesort)) if (key in self.cache): return self.cache[key] hrule = (hrules or self.hrules) bits = [] if (not self.fields): return '' if (not header): old_widths = s...
'Print HTML formatted version of table in current state to stdout. Arguments: start - index of first data row to include in output end - index of last data row to include in output PLUS ONE (list slice style) fields - names of fields (columns) to include sortby - name of field to sort rows by format - should be True or...
def print_html(self, start=0, end=None, fields=None, sortby=None, reversesort=False, format=True, header=True, border=True, hrules=FRAME, attributes=None):
print self.get_html_string(start, end, fields, sortby, reversesort, format, header, border, hrules, attributes)
'Return string representation of HTML formatted version of table in current state. Arguments: start - index of first data row to include in output end - index of last data row to include in output PLUS ONE (list slice style) fields - names of fields (columns) to include sortby - name of border - should be True or False...
def get_html_string(self, start=0, end=None, fields=None, sortby=None, reversesort=False, format=True, header=True, border=True, hrules=FRAME, attributes=None):
if self.caching: key = cPickle.dumps((start, end, fields, format, header, border, hrules, sortby, reversesort, attributes)) if (key in self.html_cache): return self.html_cache[key] if format: tmp_html_func = self._get_formatted_html_string else: tmp_html_func = se...
'Replace obj.attr_name with new_attr. This method is smart and works at the module, class, and instance level while preserving proper inheritance. It will not stub out C types however unless that has been explicitly allowed by the type. This method supports the case where attr_name is a staticmethod or a classmethod of...
def SmartSet(self, obj, attr_name, new_attr):
if (inspect.ismodule(obj) or ((not inspect.isclass(obj)) and obj.__dict__.has_key(attr_name))): orig_obj = obj orig_attr = getattr(obj, attr_name) else: if (not inspect.isclass(obj)): mro = list(inspect.getmro(obj.__class__)) else: mro = list(inspect.getmr...
'Reverses all the SmartSet() calls, restoring things to their original definition. Its okay to call SmartUnsetAll() repeatedly, as later calls have no effect if no SmartSet() calls have been made.'
def SmartUnsetAll(self):
self.stubs.reverse() for args in self.stubs: setattr(*args) self.stubs = []
'Replace child_name\'s old definition with new_child, in the context of the given parent. The parent could be a module when the child is a function at module scope. Or the parent could be a class when a class\' method is being replaced. The named child is set to new_child, while the prior definition is saved away fo...
def Set(self, parent, child_name, new_child):
old_child = getattr(parent, child_name) old_attribute = parent.__dict__.get(child_name) if (old_attribute is not None): if isinstance(old_attribute, staticmethod): old_child = staticmethod(old_child) elif isinstance(old_attribute, classmethod): old_child = classmethod...
'Reverses all the Set() calls, restoring things to their original definition. Its okay to call UnsetAll() repeatedly, as later calls have no effect if no Set() calls have been made.'
def UnsetAll(self):
self.cache.reverse() for (parent, old_child, child_name) in self.cache: setattr(parent, child_name, old_child) self.cache = []
'Init exception. Args: # expected_methods: A sequence of MockMethod objects that should have been # called. expected_methods: [MockMethod] Raises: ValueError: if expected_methods contains no methods.'
def __init__(self, expected_methods):
if (not expected_methods): raise ValueError('There must be at least one expected method') Error.__init__(self) self._expected_methods = expected_methods
'Init exception. Args: # unexpected_method: MockMethod that was called but was not at the head of # the expected_method queue. # expected: MockMethod or UnorderedGroup the method should have # been in. unexpected_method: MockMethod expected: MockMethod or UnorderedGroup'
def __init__(self, unexpected_method, expected):
Error.__init__(self) if (expected is None): self._str = ('Unexpected method call %s' % (unexpected_method,)) else: differ = difflib.Differ() diff = differ.compare(str(unexpected_method).splitlines(True), str(expected).splitlines(True)) self._str = ('Unexpected met...
'Init exception. Args: # unknown_method_name: Method call that is not part of the mocked class\'s # public interface. unknown_method_name: str'
def __init__(self, unknown_method_name):
Error.__init__(self) self._unknown_method_name = unknown_method_name
'Init exception. Args: # expected_mocks: A sequence of MockObjects that should have been # created Raises: ValueError: if expected_mocks contains no methods.'
def __init__(self, expected_mocks):
if (not expected_mocks): raise ValueError('There must be at least one expected method') Error.__init__(self) self._expected_mocks = expected_mocks
'Init exception. Args: # instance: the type of obejct that was created # params: parameters given during instantiation # named_params: named parameters given during instantiation'
def __init__(self, instance, *params, **named_params):
Error.__init__(self) self._instance = instance self._params = params self._named_params = named_params
'Initialize a new Mox.'
def __init__(self):
self._mock_objects = [] self.stubs = stubout.StubOutForTesting()
'Create a new mock object. Args: # class_to_mock: the class to be mocked class_to_mock: class attrs: dict of attribute names to values that will be set on the mock object. Only public attributes may be set. Returns: MockObject that can be used as the class_to_mock would be.'
def CreateMock(self, class_to_mock, attrs={}):
new_mock = MockObject(class_to_mock, attrs=attrs) self._mock_objects.append(new_mock) return new_mock
'Create a mock that will accept any method calls. This does not enforce an interface. Args: description: str. Optionally, a descriptive name for the mock object being created, for debugging output purposes.'
def CreateMockAnything(self, description=None):
new_mock = MockAnything(description=description) self._mock_objects.append(new_mock) return new_mock
'Set all mock objects to replay mode.'
def ReplayAll(self):
for mock_obj in self._mock_objects: mock_obj._Replay()
'Call verify on all mock objects created.'
def VerifyAll(self):
for mock_obj in self._mock_objects: mock_obj._Verify()
'Call reset on all mock objects. This does not unset stubs.'
def ResetAll(self):
for mock_obj in self._mock_objects: mock_obj._Reset()
'Replace a method, attribute, etc. with a Mock. This will replace a class or module with a MockObject, and everything else (method, function, etc) with a MockAnything. This can be overridden to always use a MockAnything by setting use_mock_anything to True. Args: obj: A Python object (class, module, instance, callable...
def StubOutWithMock(self, obj, attr_name, use_mock_anything=False):
attr_to_replace = getattr(obj, attr_name) attr_type = type(attr_to_replace) if ((attr_type == MockAnything) or (attr_type == MockObject)): raise TypeError('Cannot mock a MockAnything! Did you remember to call UnsetStubs in your previous test?') if ((attr_ty...
'Replace a class with a "mock factory" that will create mock objects. This is useful if the code-under-test directly instantiates dependencies. Previously some boilder plate was necessary to create a mock that would act as a factory. Using StubOutClassWithMocks, once you\'ve stubbed out the class you may use the stub...
def StubOutClassWithMocks(self, obj, attr_name):
attr_to_replace = getattr(obj, attr_name) attr_type = type(attr_to_replace) if ((attr_type == MockAnything) or (attr_type == MockObject)): raise TypeError('Cannot mock a MockAnything! Did you remember to call UnsetStubs in your previous test?') if (attr_typ...
'Restore stubs to their original state.'
def UnsetStubs(self):
self.stubs.UnsetAll()
'Initialize a new MockAnything. Args: description: str. Optionally, a descriptive name for the mock object being created, for debugging output purposes.'
def __init__(self, description=None):
self._description = description self._Reset()
'Intercept method calls on this object. A new MockMethod is returned that is aware of the MockAnything\'s state (record or replay). The call will be recorded or replayed by the MockMethod\'s __call__. Args: # method name: the name of the method being called. method_name: str Returns: A new MockMethod aware of MockAnyt...
def __getattr__(self, method_name):
return self._CreateMockMethod(method_name)
'Create a new mock method call and return it. Args: # method_name: the name of the method being called. # method_to_mock: The actual method being mocked, used for introspection. method_name: str method_to_mock: a method object Returns: A new MockMethod aware of MockAnything\'s state (record or replay).'
def _CreateMockMethod(self, method_name, method_to_mock=None):
return MockMethod(method_name, self._expected_calls_queue, self._replay_mode, method_to_mock=method_to_mock, description=self._description)
'Return 1 for nonzero so the mock can be used as a conditional.'
def __nonzero__(self):
return 1
'Provide custom logic to compare objects.'
def __eq__(self, rhs):
return (isinstance(rhs, MockAnything) and (self._replay_mode == rhs._replay_mode) and (self._expected_calls_queue == rhs._expected_calls_queue))
'Provide custom logic to compare objects.'
def __ne__(self, rhs):
return (not (self == rhs))
'Start replaying expected method calls.'
def _Replay(self):
self._replay_mode = True
'Verify that all of the expected calls have been made. Raises: ExpectedMethodCallsError: if there are still more method calls in the expected queue.'
def _Verify(self):
if self._expected_calls_queue: if ((len(self._expected_calls_queue) == 1) and isinstance(self._expected_calls_queue[0], MultipleTimesGroup) and self._expected_calls_queue[0].IsSatisfied()): pass else: raise ExpectedMethodCallsError(self._expected_calls_queue)
'Reset the state of this mock to record mode with an empty queue.'
def _Reset(self):
self._expected_calls_queue = deque() self._replay_mode = False
'Initialize a mock object. This determines the methods and properties of the class and stores them. Args: # class_to_mock: class to be mocked class_to_mock: class attrs: dict of attribute names to values that will be set on the mock object. Only public attributes may be set. Raises: PrivateAttributeError: if a supplie...
def __init__(self, class_to_mock, attrs={}):
MockAnything.__dict__['__init__'](self) self._known_methods = set() self._known_vars = set() self._class_to_mock = class_to_mock try: self._description = class_to_mock.__name__ except (UnknownMethodCallError, AttributeError): try: self._description = type(class_to_moc...
'Intercept attribute request on this object. If the attribute is a public class variable, it will be returned and not recorded as a call. If the attribute is not a variable, it is handled like a method call. The method name is checked against the set of mockable methods, and a new MockMethod is returned that is aware o...
def __getattr__(self, name):
if (name in self._known_vars): return getattr(self._class_to_mock, name) if (name in self._known_methods): return self._CreateMockMethod(name, method_to_mock=getattr(self._class_to_mock, name)) raise UnknownMethodCallError(name)
'Provide custom logic to compare objects.'
def __eq__(self, rhs):
return (isinstance(rhs, MockObject) and (self._class_to_mock == rhs._class_to_mock) and (self._replay_mode == rhs._replay_mode) and (self._expected_calls_queue == rhs._expected_calls_queue))
'Provide custom logic for mocking classes that support item assignment. Args: key: Key to set the value for. value: Value to set. Returns: Expected return value in replay mode. A MockMethod object for the __setitem__ method that has already been called if not in replay mode. Raises: TypeError if the underlying class d...
def __setitem__(self, key, value):
if ('__setitem__' not in dir(self._class_to_mock)): raise TypeError('object does not support item assignment') if self._replay_mode: return MockMethod('__setitem__', self._expected_calls_queue, self._replay_mode)(key, value) return self._CreateMockMethod('__setitem__')(key, va...
'Provide custom logic for mocking classes that are subscriptable. Args: key: Key to return the value for. Returns: Expected return value in replay mode. A MockMethod object for the __getitem__ method that has already been called if not in replay mode. Raises: TypeError if the underlying class is not subscriptable. Une...
def __getitem__(self, key):
if ('__getitem__' not in dir(self._class_to_mock)): raise TypeError('unsubscriptable object') if self._replay_mode: return MockMethod('__getitem__', self._expected_calls_queue, self._replay_mode)(key) return self._CreateMockMethod('__getitem__')(key)
'Provide custom logic for mocking classes that are iterable. Returns: Expected return value in replay mode. A MockMethod object for the __iter__ method that has already been called if not in replay mode. Raises: TypeError if the underlying class is not iterable. UnexpectedMethodCallError if the object does not expect ...
def __iter__(self):
methods = dir(self._class_to_mock) if ('__iter__' not in methods): if (('__getitem__' not in methods) or (not self._replay_mode)): raise TypeError('not iterable object') else: results = [] index = 0 try: while True: ...
'Provide custom logic for mocking classes that contain items. Args: key: Key to look in container for. Returns: Expected return value in replay mode. A MockMethod object for the __contains__ method that has already been called if not in replay mode. Raises: TypeError if the underlying class does not implement __contai...
def __contains__(self, key):
contains = self._class_to_mock.__dict__.get('__contains__', None) if (contains is None): raise TypeError('unsubscriptable object') if self._replay_mode: return MockMethod('__contains__', self._expected_calls_queue, self._replay_mode)(key) return self._CreateMockMethod('__contains__')(...
'Provide custom logic for mocking classes that are callable.'
def __call__(self, *params, **named_params):
callable = hasattr(self._class_to_mock, '__call__') if (not callable): raise TypeError('Not callable') method = None if (type(self._class_to_mock) == types.FunctionType): method = self._class_to_mock else: method = getattr(self._class_to_mock, '__call__') mock_method =...
'Return the class that is being mocked.'
@property def __class__(self):
return self._class_to_mock
'Instantiate and record that a new mock has been created.'
def __call__(self, *params, **named_params):
method = getattr(self._class_to_mock, '__init__') mock_method = self._CreateMockMethod('__init__', method_to_mock=method) if self._replay_mode: if (not self._instance_queue): raise UnexpectedMockCreationError(self._class_to_mock, *params, **named_params) mock_method(*params, **na...
'Verify that all mocks have been created.'
def _Verify(self):
if self._instance_queue: raise ExpectedMockCreationError(self._instance_queue) super(_MockObjectFactory, self)._Verify()
'Creates a checker. Args: # method: A method to check. method: function Raises: ValueError: method could not be inspected, so checks aren\'t possible. Some methods and functions like built-ins can\'t be inspected.'
def __init__(self, method):
try: (self._args, varargs, varkw, defaults) = inspect.getargspec(method) except TypeError: raise ValueError(('Could not get argument specification for %r' % (method,))) if inspect.ismethod(method): self._args = self._args[1:] self._method = method self._has_...
'Mark an argument as being given. Args: # arg_name: The name of the argument to mark in arg_status. # arg_status: Maps argument names to one of _NEEDED, _DEFAULT, _GIVEN. arg_name: string arg_status: dict Raises: AttributeError: arg_name is already marked as _GIVEN.'
def _RecordArgumentGiven(self, arg_name, arg_status):
if (arg_status.get(arg_name, None) == MethodCallChecker._GIVEN): raise AttributeError(('%s provided more than once' % (arg_name,))) arg_status[arg_name] = MethodCallChecker._GIVEN
'Ensures that the parameters used while recording a call are valid. Args: # params: A list of positional parameters. # named_params: A dict of named parameters. params: list named_params: dict Raises: AttributeError: the given parameters don\'t work with the given method.'
def Check(self, params, named_params):
arg_status = dict(((a, MethodCallChecker._NEEDED) for a in self._required_args)) for arg in self._default_args: arg_status[arg] = MethodCallChecker._DEFAULT for i in range(len(params)): try: arg_name = self._args[i] except IndexError: if (not self._has_varargs...
'Construct a new mock method. Args: # method_name: the name of the method # call_queue: deque of calls, verify this call against the head, or add # this call to the queue. # replay_mode: False if we are recording, True if we are verifying calls # against the call queue. # method_to_mock: The actual method being...
def __init__(self, method_name, call_queue, replay_mode, method_to_mock=None, description=None):
self._name = method_name self.__name__ = method_name self._call_queue = call_queue if (not isinstance(call_queue, deque)): self._call_queue = deque(self._call_queue) self._replay_mode = replay_mode self._description = description self._params = None self._named_params = None ...
'Log parameters and return the specified return value. If the Mock(Anything/Object) associated with this call is in record mode, this MockMethod will be pushed onto the expected call queue. If the mock is in replay mode, this will pop a MockMethod off the top of the queue and verify this call is equal to the expected ...
def __call__(self, *params, **named_params):
self._params = params self._named_params = named_params if (not self._replay_mode): if (self._checker is not None): self._checker.Check(params, named_params) self._call_queue.append(self) return self expected_method = self._VerifyMethodCall() if expected_method._s...
'Raise an AttributeError with a helpful message.'
def __getattr__(self, name):
raise AttributeError(('MockMethod has no attribute "%s". Did you remember to put your mocks in replay mode?' % name))
'Raise a TypeError with a helpful message.'
def __iter__(self):
raise TypeError('MockMethod cannot be iterated. Did you remember to put your mocks in replay mode?')
'Raise a TypeError with a helpful message.'
def next(self):
raise TypeError('MockMethod cannot be iterated. Did you remember to put your mocks in replay mode?')
'Pop the next method from our call queue.'
def _PopNextMethod(self):
try: return self._call_queue.popleft() except IndexError: raise UnexpectedMethodCallError(self, None)
'Verify the called method is expected. This can be an ordered method, or part of an unordered set. Returns: The expected mock method. Raises: UnexpectedMethodCall if the method called was not expected.'
def _VerifyMethodCall(self):
expected = self._PopNextMethod() while isinstance(expected, MethodGroup): (expected, method) = expected.MethodCalled(self) if (method is not None): return method if (expected != self): raise UnexpectedMethodCallError(self, expected) return expected
'Test whether this MockMethod is equivalent to another MockMethod. Args: # rhs: the right hand side of the test rhs: MockMethod'
def __eq__(self, rhs):
return (isinstance(rhs, MockMethod) and (self._name == rhs._name) and (self._params == rhs._params) and (self._named_params == rhs._named_params))
'Test whether this MockMethod is not equivalent to another MockMethod. Args: # rhs: the right hand side of the test rhs: MockMethod'
def __ne__(self, rhs):
return (not (self == rhs))
'Returns a possible group from the end of the call queue or None if no other methods are on the stack.'
def GetPossibleGroup(self):
this_method = self._call_queue.pop() assert (this_method == self) group = None try: group = self._call_queue[(-1)] except IndexError: pass return group
'Checks if the last method (a possible group) is an instance of our group_class. Adds the current method to this group or creates a new one. Args: group_name: the name of the group. group_class: the class used to create instance of this new group'
def _CheckAndCreateNewGroup(self, group_name, group_class):
group = self.GetPossibleGroup() if (isinstance(group, group_class) and (group.group_name() == group_name)): group.AddMethod(self) return self new_group = group_class(group_name) new_group.AddMethod(self) self._call_queue.append(new_group) return self
'Move this method into a group of unordered calls. A group of unordered calls must be defined together, and must be executed in full before the next expected method can be called. There can be multiple groups that are expected serially, if they are given different group names. The same group name can be reused if the...
def InAnyOrder(self, group_name='default'):
return self._CheckAndCreateNewGroup(group_name, UnorderedGroup)
'Move this method into group of calls which may be called multiple times. A group of repeating calls must be defined together, and must be executed in full before the next expected mehtod can be called. Args: group_name: the name of the unordered group. Returns: self'
def MultipleTimes(self, group_name='default'):
return self._CheckAndCreateNewGroup(group_name, MultipleTimesGroup)
'Set the value to return when this method is called. Args: # return_value can be anything.'
def AndReturn(self, return_value):
self._return_value = return_value return return_value
'Set the exception to raise when this method is called. Args: # exception: the exception to raise when this method is called. exception: Exception'
def AndRaise(self, exception):
self._exception = exception
'Set the side effects that are simulated when this method is called. Args: side_effects: A callable which modifies the parameters or other relevant state which a given test case depends on. Returns: Self for chaining with AndReturn and AndRaise.'
def WithSideEffects(self, side_effects):
self._side_effects = side_effects return self
'Special equals method that all comparators must implement. Args: rhs: any python object'
def equals(self, rhs):
raise NotImplementedError, 'method must be implemented by a subclass.'
'Initialize IsA Args: class_name: basic python type or a class'
def __init__(self, class_name):
self._class_name = class_name
'Check to see if the RHS is an instance of class_name. Args: # rhs: the right hand side of the test rhs: object Returns: bool'
def equals(self, rhs):
try: return isinstance(rhs, self._class_name) except TypeError: return (type(rhs) == type(self._class_name))
'Initialize IsAlmost. Args: float_value: The value for making the comparison. places: The number of decimal places to round to.'
def __init__(self, float_value, places=7):
self._float_value = float_value self._places = places
'Check to see if RHS is almost equal to float_value Args: rhs: the value to compare to float_value Returns: bool'
def equals(self, rhs):
try: return (round((rhs - self._float_value), self._places) == 0) except TypeError: return False
'Initialize. Args: # search_string: the string you are searching for search_string: str'
def __init__(self, search_string):
self._search_string = search_string
'Check to see if the search_string is contained in the rhs string. Args: # rhs: the right hand side of the test rhs: object Returns: bool'
def equals(self, rhs):
try: return (rhs.find(self._search_string) > (-1)) except Exception: return False
'Initialize. Args: # pattern is the regular expression to search for pattern: str # flags passed to re.compile function as the second argument flags: int'
def __init__(self, pattern, flags=0):
self.regex = re.compile(pattern, flags=flags)
'Check to see if rhs matches regular expression pattern. Returns: bool'
def equals(self, rhs):
return (self.regex.search(rhs) is not None)
'Initialize. Args: # key is any thing that could be in a list or a key in a dict'
def __init__(self, key):
self._key = key
'Check to see whether key is in rhs. Args: rhs: dict Returns: bool'
def equals(self, rhs):
return (self._key in rhs)
'Initialize. Args: # predicate: a Comparator instance.'
def __init__(self, predicate):
assert isinstance(predicate, Comparator), ('predicate %r must be a Comparator.' % predicate) self._predicate = predicate
'Check to see whether the predicate is False. Args: rhs: A value that will be given in argument of the predicate. Returns: bool'
def equals(self, rhs):
return (not self._predicate.equals(rhs))
'Initialize. Args: # key: a key in a dict # value: the corresponding value'
def __init__(self, key, value):
self._key = key self._value = value
'Check whether the given key/value pair is in the rhs dict. Returns: bool'
def equals(self, rhs):
try: return (rhs[self._key] == self._value) except Exception: return False
'Initialize. Args: # key: an attribute name of an object # value: the corresponding value'
def __init__(self, key, value):
self._key = key self._value = value
'Check whether the given attribute has a matching value in the rhs object. Returns: bool'
def equals(self, rhs):
try: return (getattr(rhs, self._key) == self._value) except Exception: return False
'Initialize. Args: expected_seq: a sequence'
def __init__(self, expected_seq):
self._expected_seq = expected_seq
'Check to see whether actual_seq has same elements as expected_seq. Args: actual_seq: sequence Returns: bool'
def equals(self, actual_seq):
try: expected = dict([(element, None) for element in self._expected_seq]) actual = dict([(element, None) for element in actual_seq]) except TypeError: expected = list(self._expected_seq) actual = list(actual_seq) expected.sort() actual.sort() return (expected ...
'Initialize. Args: *args: One or more Comparator'
def __init__(self, *args):
self._comparators = args
'Checks whether all Comparators are equal to rhs. Args: # rhs: can be anything Returns: bool'
def equals(self, rhs):
for comparator in self._comparators: if (not comparator.equals(rhs)): return False return True
'Initialize. Args: *args: One or more Mox comparators'
def __init__(self, *args):
self._comparators = args
'Checks whether any Comparator is equal to rhs. Args: # rhs: can be anything Returns: bool'
def equals(self, rhs):
for comparator in self._comparators: if comparator.equals(rhs): return True return False
'Initialize. Args: func: callable that takes one parameter and returns a bool'
def __init__(self, func):
self._func = func
'Test whether rhs passes the function test. rhs is passed into func. Args: rhs: any python object Returns: the result of func(rhs)'
def equals(self, rhs):
return self._func(rhs)
'Ignores arguments and returns True. Args: unused_rhs: any python object Returns: always returns True'
def equals(self, unused_rhs):
return True
'Add a method to this group. Args: mock_method: A mock method to be added to this group.'
def AddMethod(self, mock_method):
self._methods.append(mock_method)